| """ |
| Pre-compute VAE latents and text embeddings for Flux training. |
| Removes VAE/CLIP/T5 from GPU during training, saving ~10GB VRAM per GPU. |
| """ |
| import argparse |
| import io |
| from pathlib import Path |
|
|
| import torch |
| import webdataset as wds |
| from PIL import Image |
| from torchvision import transforms |
| from tqdm import tqdm |
|
|
|
|
| def get_transform(resolution=1024): |
| return transforms.Compose([ |
| transforms.Resize(resolution, interpolation=transforms.InterpolationMode.LANCZOS), |
| transforms.CenterCrop(resolution), |
| transforms.ToTensor(), |
| transforms.Normalize([0.5], [0.5]), |
| ]) |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Pre-compute embeddings for Flux training") |
| parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-schnell") |
| parser.add_argument("--data-dir", type=Path, default=Path("/data0/datasets/processed/flux_train/shards")) |
| parser.add_argument("--output-dir", type=Path, default=Path("/data0/datasets/processed/flux_train/embeddings")) |
| parser.add_argument("--resolution", type=int, default=1024) |
| parser.add_argument("--batch-size", type=int, default=8) |
| parser.add_argument("--cache-dir", default="/data0/models") |
| parser.add_argument("--device", default="cuda:0") |
| args = parser.parse_args() |
|
|
| args.output_dir.mkdir(parents=True, exist_ok=True) |
| device = torch.device(args.device) |
| transform = get_transform(args.resolution) |
|
|
| |
| print("Loading Flux pipeline components...") |
| from diffusers import FluxPipeline |
| pipe = FluxPipeline.from_pretrained( |
| args.model_name, |
| torch_dtype=torch.bfloat16, |
| cache_dir=args.cache_dir, |
| ) |
|
|
| vae = pipe.vae.to(device).eval() |
| text_encoder = pipe.text_encoder.to(device).eval() |
| text_encoder_2 = pipe.text_encoder_2.to(device).eval() |
| tokenizer = pipe.tokenizer |
| tokenizer_2 = pipe.tokenizer_2 |
|
|
| vae_shift = vae.config.shift_factor |
| vae_scale = vae.config.scaling_factor |
|
|
| |
| tar_files = sorted(args.data_dir.glob("*.tar")) |
| if not tar_files: |
| raise ValueError(f"No tar files found in {args.data_dir}") |
| print(f"Found {len(tar_files)} shards") |
|
|
| def decode_sample(sample): |
| try: |
| img = sample["jpg"] |
| if isinstance(img, bytes): |
| img = Image.open(io.BytesIO(img)).convert("RGB") |
| caption = sample.get("txt", b"") |
| if isinstance(caption, bytes): |
| caption = caption.decode("utf-8") |
| return {"image": transform(img), "caption": caption, "key": sample["__key__"]} |
| except: |
| return None |
|
|
| dataset = ( |
| wds.WebDataset([str(f) for f in tar_files]) |
| .decode("pil") |
| .map(decode_sample) |
| .select(lambda x: x is not None) |
| ) |
|
|
| dataloader = torch.utils.data.DataLoader( |
| dataset, batch_size=None, num_workers=4, pin_memory=True |
| ) |
|
|
| |
| batch_images = [] |
| batch_captions = [] |
| batch_keys = [] |
| sample_idx = 0 |
| shard_idx = 0 |
| shard_data = [] |
| samples_per_shard = 1000 |
|
|
| print(f"Pre-computing embeddings (batch_size={args.batch_size})...") |
|
|
| def save_shard(shard_data, shard_idx): |
| shard_path = args.output_dir / f"shard-{shard_idx:06d}.pt" |
| torch.save(shard_data, shard_path) |
| return shard_idx + 1 |
|
|
| def process_batch(images, captions, keys): |
| imgs = torch.stack(images).to(device, dtype=torch.bfloat16) |
|
|
| with torch.no_grad(): |
| latents = vae.encode(imgs).latent_dist.sample() |
| latents = (latents - vae_shift) * vae_scale |
|
|
| |
| b, c, h, w = latents.shape |
| packed = latents.view(b, c, h // 2, 2, w // 2, 2) |
| packed = packed.permute(0, 2, 4, 1, 3, 5).reshape(b, (h // 2) * (w // 2), c * 4) |
|
|
| |
| text_ids = tokenizer( |
| captions, padding="max_length", max_length=77, |
| truncation=True, return_tensors="pt" |
| ).input_ids.to(device) |
| pooled = text_encoder(text_ids, output_hidden_states=False).pooler_output |
|
|
| text_ids_2 = tokenizer_2( |
| captions, padding="max_length", max_length=256, |
| truncation=True, return_tensors="pt" |
| ).input_ids.to(device) |
| hidden_states = text_encoder_2(text_ids_2)[0] |
|
|
| |
| latent_h, latent_w = h // 2, w // 2 |
| img_ids = torch.zeros(latent_h, latent_w, 3, device=device) |
| img_ids[..., 1] = torch.arange(latent_h)[:, None].float() |
| img_ids[..., 2] = torch.arange(latent_w)[None, :].float() |
| img_ids = img_ids.reshape(latent_h * latent_w, 3) |
|
|
| |
| txt_ids = torch.zeros(hidden_states.shape[1], 3, device=device) |
|
|
| results = [] |
| for i in range(b): |
| results.append({ |
| "key": keys[i], |
| "packed_latents": packed[i].cpu(), |
| "pooled_prompt_embeds": pooled[i].cpu(), |
| "encoder_hidden_states": hidden_states[i].cpu(), |
| "img_ids": img_ids.cpu(), |
| "txt_ids": txt_ids.cpu(), |
| }) |
| return results |
|
|
| total_processed = 0 |
| for sample in dataloader: |
| batch_images.append(sample["image"]) |
| batch_captions.append(sample["caption"]) |
| batch_keys.append(sample["key"]) |
|
|
| if len(batch_images) >= args.batch_size: |
| results = process_batch(batch_images, batch_captions, batch_keys) |
| shard_data.extend(results) |
| total_processed += len(results) |
|
|
| if len(shard_data) >= samples_per_shard: |
| shard_idx = save_shard(shard_data, shard_idx) |
| print(f" Saved shard {shard_idx - 1} ({total_processed} samples total)") |
| shard_data = [] |
|
|
| batch_images = [] |
| batch_captions = [] |
| batch_keys = [] |
|
|
| |
| if batch_images: |
| results = process_batch(batch_images, batch_captions, batch_keys) |
| shard_data.extend(results) |
| total_processed += len(results) |
|
|
| if shard_data: |
| shard_idx = save_shard(shard_data, shard_idx) |
| print(f" Saved shard {shard_idx - 1} ({total_processed} samples total)") |
|
|
| print(f"\nDone! {total_processed} samples saved to {args.output_dir} ({shard_idx} shards)") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|