File size: 6,594 Bytes
5187e4e ed16a36 5187e4e ed16a36 5187e4e ed16a36 5187e4e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | """
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")
|