""" Flux LoRA Training - Flow Matching with correct latent packing. """ from diffusers import FluxPipeline from diffusers.optimization import get_scheduler from peft import LoraConfig, get_peft_model from accelerate import Accelerator import torch import torch.nn.functional as F import webdataset as wds from pathlib import Path from PIL import Image import io import time from torchvision import transforms MODEL_NAME = "black-forest-labs/FLUX.1-schnell" DATA_DIR = "/data0/datasets/processed/flux_train/shards" OUTPUT_DIR = "/data0/checkpoints/flux_lora" CACHE_DIR = "/data0/models" BATCH_SIZE = 1 GRAD_ACCUM = 4 LR = 1e-4 MAX_STEPS = 50000 SAVE_STEPS = 5000 LORA_RANK = 128 Path(OUTPUT_DIR).mkdir(parents=True, exist_ok=True) accelerator = Accelerator( mixed_precision="bf16", gradient_accumulation_steps=GRAD_ACCUM, ) print("Loading Flux...") pipe = FluxPipeline.from_pretrained( MODEL_NAME, torch_dtype=torch.bfloat16, cache_dir=CACHE_DIR, ) transformer = pipe.transformer vae = pipe.vae vae.requires_grad_(False) pipe.text_encoder.requires_grad_(False) pipe.text_encoder_2.requires_grad_(False) lora_config = LoraConfig( r=LORA_RANK, lora_alpha=LORA_RANK, target_modules=["to_q", "to_k", "to_v", "to_out.0"], lora_dropout=0.05, ) transformer = get_peft_model(transformer, lora_config) transformer.print_trainable_parameters() optimizer = torch.optim.AdamW(transformer.parameters(), lr=LR, weight_decay=0.01) lr_scheduler = get_scheduler("cosine", optimizer=optimizer, num_warmup_steps=500, num_training_steps=MAX_STEPS) transform = transforms.Compose([ transforms.Resize(1024, interpolation=transforms.InterpolationMode.LANCZOS), transforms.CenterCrop(1024), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ]) tar_files = sorted(Path(DATA_DIR).glob("*.tar")) print(f"Found {len(tar_files)} tar shards") def preprocess(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} except: return None def ignore_errors(exn): print(f"WebDataset error (skipping): {exn}") return True dataset = ( wds.WebDataset([str(f) for f in tar_files], shardshuffle=True, handler=ignore_errors) .shuffle(1000) .decode("pil", handler=ignore_errors) .map(preprocess) .select(lambda x: x is not None) ) dataloader = torch.utils.data.DataLoader(dataset, batch_size=BATCH_SIZE, num_workers=4, pin_memory=True) transformer, optimizer, dataloader, lr_scheduler = accelerator.prepare( transformer, optimizer, dataloader, lr_scheduler ) vae.to(accelerator.device, dtype=torch.bfloat16) pipe.text_encoder.to(accelerator.device, dtype=torch.bfloat16) pipe.text_encoder_2.to(accelerator.device, dtype=torch.bfloat16) def pack_latents(latents, batch_size, num_channels, height, width): latents = latents.view(batch_size, num_channels, height // 2, 2, width // 2, 2) latents = latents.permute(0, 2, 4, 1, 3, 5) latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels * 4) return latents def prepare_latent_image_ids(height, width, device, dtype): latent_image_ids = torch.zeros(height // 2, width // 2, 3) latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None] latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :] latent_image_ids = latent_image_ids.reshape(height // 2 * width // 2, 3) return latent_image_ids.to(device=device, dtype=dtype) global_step = 0 t0 = time.time() print(f"Starting training... Max steps: {MAX_STEPS}") transformer.train() while global_step < MAX_STEPS: for batch in dataloader: if global_step >= MAX_STEPS: break with accelerator.accumulate(transformer): images = batch["image"].to(accelerator.device, dtype=torch.bfloat16) captions = batch["caption"] bs = images.shape[0] with torch.no_grad(): latents = vae.encode(images).latent_dist.sample() latents = (latents - vae.config.shift_factor) * vae.config.scaling_factor packed_latents = pack_latents(latents, bs, 16, 128, 128) latent_image_ids = prepare_latent_image_ids(128, 128, accelerator.device, torch.bfloat16) prompt_embeds, pooled_prompt_embeds, text_ids = pipe.encode_prompt( prompt=captions if isinstance(captions, list) else [captions], prompt_2=None, device=accelerator.device, ) noise = torch.randn_like(packed_latents) t = torch.rand(bs, device=accelerator.device, dtype=torch.bfloat16) t_expand = t.view(-1, 1, 1) noisy_latents = (1 - t_expand) * packed_latents + t_expand * noise timesteps = (t * 1000).to(dtype=packed_latents.dtype) model_pred = transformer( hidden_states=noisy_latents, timestep=timesteps, encoder_hidden_states=prompt_embeds, pooled_projections=pooled_prompt_embeds, txt_ids=text_ids, img_ids=latent_image_ids, return_dict=False, )[0] target = noise - packed_latents loss = F.mse_loss(model_pred, target) accelerator.backward(loss) if accelerator.sync_gradients: accelerator.clip_grad_norm_(transformer.parameters(), 1.0) optimizer.step() lr_scheduler.step() optimizer.zero_grad() if accelerator.sync_gradients: global_step += 1 if global_step % 100 == 0: elapsed = time.time() - t0 print(f"Step {global_step}/{MAX_STEPS} | Loss: {loss.item():.4f} | LR: {lr_scheduler.get_last_lr()[0]:.2e} | Time: {elapsed/3600:.1f}h") if global_step % SAVE_STEPS == 0: save_path = f"{OUTPUT_DIR}/checkpoint-{global_step}" accelerator.unwrap_model(transformer).save_pretrained(save_path) print(f"Saved: {save_path}") final_path = f"{OUTPUT_DIR}/final" accelerator.unwrap_model(transformer).save_pretrained(final_path) print(f"Training complete! Saved to {final_path}") print(f"Total time: {(time.time()-t0)/3600:.1f} hours")