| """ |
| Flux LoRA Training - Compatible with both single GPU and DeepSpeed multi-GPU. |
| Uses pre-computed embeddings for maximum GPU efficiency. |
| """ |
| import argparse |
| import os |
| import time |
| from pathlib import Path |
|
|
| import torch |
| import torch.nn.functional as F |
| from torch.utils.data import Dataset, DataLoader |
| from accelerate import Accelerator |
| from accelerate.utils import set_seed |
| from diffusers import FluxTransformer2DModel |
| from diffusers.optimization import get_scheduler |
| from peft import LoraConfig, get_peft_model |
|
|
|
|
| class EmbeddingDataset(Dataset): |
| def __init__(self, embedding_dir): |
| self.embedding_dir = Path(embedding_dir) |
| self.shard_files = sorted(self.embedding_dir.glob("shard-*.pt")) |
| if not self.shard_files: |
| raise ValueError(f"No shard files found in {embedding_dir}") |
|
|
| self.shard_lengths = [] |
| self.cumulative = [0] |
| for sf in self.shard_files: |
| data = torch.load(sf, map_location="cpu", weights_only=False) |
| self.shard_lengths.append(len(data)) |
| self.cumulative.append(self.cumulative[-1] + len(data)) |
| del data |
|
|
| self.total_samples = self.cumulative[-1] |
| self._cache_shard_idx = -1 |
| self._cache_data = None |
| print(f"EmbeddingDataset: {self.total_samples} samples in {len(self.shard_files)} shards") |
|
|
| def __len__(self): |
| return self.total_samples |
|
|
| def _get_shard_and_local_idx(self, idx): |
| for i in range(len(self.shard_files)): |
| if idx < self.cumulative[i + 1]: |
| return i, idx - self.cumulative[i] |
| raise IndexError(f"Index {idx} out of range") |
|
|
| def __getitem__(self, idx): |
| shard_idx, local_idx = self._get_shard_and_local_idx(idx) |
|
|
| if shard_idx != self._cache_shard_idx: |
| self._cache_data = torch.load( |
| self.shard_files[shard_idx], map_location="cpu", weights_only=False |
| ) |
| self._cache_shard_idx = shard_idx |
|
|
| sample = self._cache_data[local_idx] |
| return { |
| "packed_latents": sample["packed_latents"], |
| "pooled_prompt_embeds": sample["pooled_prompt_embeds"], |
| "encoder_hidden_states": sample["encoder_hidden_states"], |
| "img_ids": sample["img_ids"], |
| "txt_ids": sample["txt_ids"], |
| } |
|
|
|
|
| def find_latest_checkpoint(output_dir): |
| output_dir = Path(output_dir) |
| if not output_dir.exists(): |
| return None, 0 |
| checkpoints = sorted( |
| [d for d in output_dir.iterdir() if d.is_dir() and d.name.startswith("checkpoint-")], |
| key=lambda p: int(p.name.split("-")[1]) if p.name.split("-")[1].isdigit() else 0, |
| ) |
| if checkpoints: |
| step = int(checkpoints[-1].name.split("-")[1]) |
| return checkpoints[-1], step |
| return None, 0 |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-schnell") |
| parser.add_argument("--embedding-dir", type=Path, default=Path("/data0/datasets/processed/flux_train/embeddings")) |
| parser.add_argument("--output-dir", type=Path, default=Path("/data0/checkpoints/flux_lora_ds")) |
| parser.add_argument("--cache-dir", default="/data0/models") |
| parser.add_argument("--batch-size", type=int, default=1) |
| parser.add_argument("--gradient-accumulation", type=int, default=8) |
| parser.add_argument("--learning-rate", type=float, default=1e-4) |
| parser.add_argument("--lr-scheduler", default="cosine") |
| parser.add_argument("--lr-warmup-steps", type=int, default=500) |
| parser.add_argument("--max-train-steps", type=int, default=100000) |
| parser.add_argument("--save-steps", type=int, default=5000) |
| parser.add_argument("--lora-rank", type=int, default=128) |
| parser.add_argument("--lora-alpha", type=int, default=128) |
| parser.add_argument("--seed", type=int, default=42) |
| parser.add_argument("--resume-from-checkpoint", default="auto") |
| args = parser.parse_args() |
|
|
| accelerator = Accelerator( |
| mixed_precision="bf16", |
| gradient_accumulation_steps=args.gradient_accumulation, |
| log_with=None, |
| ) |
|
|
| set_seed(args.seed) |
|
|
| if accelerator.is_main_process: |
| args.output_dir.mkdir(parents=True, exist_ok=True) |
| print(f"Process count: {accelerator.num_processes}") |
| print(f"Device: {accelerator.device}") |
|
|
| |
| resume_path = None |
| resume_step = 0 |
| if args.resume_from_checkpoint == "auto": |
| resume_path, resume_step = find_latest_checkpoint(args.output_dir) |
| if resume_path: |
| print(f"Resuming from {resume_path} (step {resume_step})") |
|
|
| |
| if accelerator.is_main_process: |
| print("Loading Flux Transformer...") |
| transformer = FluxTransformer2DModel.from_pretrained( |
| args.model_name, |
| subfolder="transformer", |
| torch_dtype=torch.bfloat16, |
| cache_dir=args.cache_dir, |
| ) |
|
|
| |
| lora_config = LoraConfig( |
| r=args.lora_rank, |
| lora_alpha=args.lora_alpha, |
| target_modules=["to_q", "to_k", "to_v", "to_out.0"], |
| lora_dropout=0.0, |
| ) |
| transformer = get_peft_model(transformer, lora_config) |
|
|
| |
| if resume_path: |
| from peft import set_peft_model_state_dict |
| import safetensors.torch |
| adapter_path = resume_path / "adapter_model.safetensors" |
| if adapter_path.exists(): |
| state_dict = safetensors.torch.load_file(str(adapter_path)) |
| set_peft_model_state_dict(transformer, state_dict) |
| print(f" Loaded LoRA weights from {adapter_path}") |
| else: |
| adapter_bin = resume_path / "adapter_model.bin" |
| if adapter_bin.exists(): |
| state_dict = torch.load(str(adapter_bin), map_location="cpu") |
| set_peft_model_state_dict(transformer, state_dict) |
| print(f" Loaded LoRA weights from {adapter_bin}") |
|
|
| |
| for name, p in transformer.named_parameters(): |
| if p.requires_grad: |
| p.data = p.data.float() |
|
|
| if accelerator.is_main_process: |
| transformer.print_trainable_parameters() |
|
|
| |
| trainable_params = [p for p in transformer.parameters() if p.requires_grad] |
| optimizer = torch.optim.AdamW(trainable_params, lr=args.learning_rate, weight_decay=0.01) |
|
|
| lr_scheduler = get_scheduler( |
| args.lr_scheduler, |
| optimizer=optimizer, |
| num_warmup_steps=args.lr_warmup_steps, |
| num_training_steps=args.max_train_steps, |
| ) |
|
|
| |
| dataset = EmbeddingDataset(args.embedding_dir) |
| dataloader = DataLoader( |
| dataset, |
| batch_size=args.batch_size, |
| shuffle=True, |
| num_workers=2, |
| pin_memory=True, |
| drop_last=True, |
| ) |
|
|
| |
| transformer, optimizer, dataloader, lr_scheduler = accelerator.prepare( |
| transformer, optimizer, dataloader, lr_scheduler |
| ) |
|
|
| |
| global_step = resume_step |
| if resume_step > 0: |
| steps_to_skip = resume_step * args.gradient_accumulation |
| if accelerator.is_main_process: |
| print(f" Skipping {steps_to_skip} dataloader batches...") |
| skipped = 0 |
| skip_dl = iter(dataloader) |
| while skipped < steps_to_skip: |
| try: |
| next(skip_dl) |
| skipped += 1 |
| except StopIteration: |
| skip_dl = iter(dataloader) |
| del skip_dl |
|
|
| |
| t0 = time.time() |
|
|
| if accelerator.is_main_process: |
| print(f"\nStarting training from step {global_step}...") |
| print(f" Batch size/GPU: {args.batch_size}") |
| print(f" Num GPUs: {accelerator.num_processes}") |
| print(f" Grad accumulation: {args.gradient_accumulation}") |
| print(f" Effective batch: {args.batch_size * accelerator.num_processes * args.gradient_accumulation}") |
| print(f" Max steps: {args.max_train_steps}") |
| print(f" Dataset: {len(dataset)} samples") |
|
|
| transformer.train() |
|
|
| while global_step < args.max_train_steps: |
| for batch in dataloader: |
| if global_step >= args.max_train_steps: |
| break |
|
|
| with accelerator.accumulate(transformer): |
| packed_latents = batch["packed_latents"].to(dtype=torch.bfloat16) |
| pooled_prompt_embeds = batch["pooled_prompt_embeds"].to(dtype=torch.bfloat16) |
| encoder_hidden_states = batch["encoder_hidden_states"].to(dtype=torch.bfloat16) |
| img_ids = batch["img_ids"][0] |
| txt_ids = batch["txt_ids"][0] |
|
|
| bs = packed_latents.shape[0] |
|
|
| noise = torch.randn_like(packed_latents) |
| t = torch.rand(bs, device=packed_latents.device, dtype=torch.bfloat16) |
| t_expand = t.view(-1, 1, 1) |
|
|
| noisy_latents = (1 - t_expand) * packed_latents + t_expand * noise |
| timesteps = t |
|
|
| model_pred = transformer( |
| hidden_states=noisy_latents, |
| timestep=timesteps, |
| encoder_hidden_states=encoder_hidden_states, |
| pooled_projections=pooled_prompt_embeds, |
| img_ids=img_ids, |
| txt_ids=txt_ids, |
| return_dict=False, |
| )[0] |
|
|
| target = noise - packed_latents |
| loss = F.mse_loss(model_pred.float(), target.float()) |
|
|
| accelerator.backward(loss) |
|
|
| if accelerator.sync_gradients: |
| accelerator.clip_grad_norm_(trainable_params, 1.0) |
|
|
| optimizer.step() |
| lr_scheduler.step() |
| optimizer.zero_grad() |
|
|
| if accelerator.sync_gradients: |
| global_step += 1 |
|
|
| if global_step % 100 == 0 and accelerator.is_main_process: |
| elapsed = time.time() - t0 |
| steps_done = global_step - resume_step |
| steps_per_sec = steps_done / elapsed if elapsed > 0 else 0 |
| remaining = args.max_train_steps - global_step |
| eta_hours = remaining / steps_per_sec / 3600 if steps_per_sec > 0 else 0 |
| print( |
| f"Step {global_step}/{args.max_train_steps} | " |
| f"Loss: {loss.item():.4f} | " |
| f"LR: {lr_scheduler.get_last_lr()[0]:.2e} | " |
| f"Speed: {steps_per_sec:.2f} steps/s | " |
| f"ETA: {eta_hours:.1f}h" |
| ) |
|
|
| if global_step % args.save_steps == 0: |
| if accelerator.is_main_process: |
| save_path = args.output_dir / f"checkpoint-{global_step}" |
| save_path.mkdir(parents=True, exist_ok=True) |
| unwrapped = accelerator.unwrap_model(transformer) |
| unwrapped.save_pretrained(save_path) |
| print(f"Saved checkpoint: {save_path}") |
| accelerator.wait_for_everyone() |
|
|
| |
| if accelerator.is_main_process: |
| final_path = args.output_dir / "final" |
| final_path.mkdir(parents=True, exist_ok=True) |
| unwrapped = accelerator.unwrap_model(transformer) |
| unwrapped.save_pretrained(final_path) |
| total_time = (time.time() - t0) / 3600 |
| print(f"\nTraining complete! Saved to {final_path}") |
| print(f"Total time: {total_time:.1f} hours") |
|
|
| accelerator.wait_for_everyone() |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|