memoryai commited on
Commit
5a193ef
·
verified ·
1 Parent(s): 18970a4

Upload scripts/training/train_flux_lora.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/training/train_flux_lora.py +247 -57
scripts/training/train_flux_lora.py CHANGED
@@ -1,10 +1,12 @@
1
  """
2
  Fine-tune Flux with LoRA - 2 GPU split (encode on GPU0, train on GPU1).
3
- Reads webdataset shards directly, no precompute needed.
4
- Supports resume from checkpoint.
5
  """
6
  import argparse
7
  import gc
 
 
8
  import time
9
  from pathlib import Path
10
 
@@ -13,7 +15,7 @@ import torch.nn.functional as F
13
  import webdataset as wds
14
  from PIL import Image
15
  from torchvision import transforms
16
- from peft import LoraConfig, get_peft_model
17
 
18
 
19
  def get_train_transforms(resolution=1024):
@@ -32,7 +34,6 @@ def collate_batch(samples):
32
 
33
 
34
  def create_webdataset(data_dir, resolution=1024, batch_size=1):
35
- import io
36
  transform = get_train_transforms(resolution)
37
 
38
  def preprocess(sample):
@@ -63,13 +64,50 @@ def create_webdataset(data_dir, resolution=1024, batch_size=1):
63
  return dataset, len(tar_files)
64
 
65
 
66
- def pack_latents(latents):
67
- b, c, h, w = latents.shape
68
- latents = latents.reshape(b, c, h // 2, 2, w // 2, 2)
69
- latents = latents.permute(0, 2, 4, 1, 3, 5).reshape(b, (h // 2) * (w // 2), c * 4)
70
  return latents
71
 
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  def find_latest_checkpoint(output_dir):
74
  output_dir = Path(output_dir)
75
  if not output_dir.exists():
@@ -84,6 +122,53 @@ def find_latest_checkpoint(output_dir):
84
  return None, 0
85
 
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  def main():
88
  parser = argparse.ArgumentParser()
89
  parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-schnell")
@@ -94,16 +179,22 @@ def main():
94
  parser.add_argument("--batch-size", type=int, default=1)
95
  parser.add_argument("--gradient-accumulation", type=int, default=8)
96
  parser.add_argument("--learning-rate", type=float, default=1e-4)
97
- parser.add_argument("--lr-scheduler", default="cosine")
98
- parser.add_argument("--lr-warmup-steps", type=int, default=500)
99
  parser.add_argument("--max-train-steps", type=int, default=999999999)
100
  parser.add_argument("--save-steps", type=int, default=2000)
 
101
  parser.add_argument("--lora-rank", type=int, default=128)
102
- parser.add_argument("--lora-alpha", type=int, default=128)
103
  parser.add_argument("--seed", type=int, default=42)
104
  parser.add_argument("--encode-device", default="cuda:0")
105
  parser.add_argument("--train-device", default="cuda:1")
106
  parser.add_argument("--resume-from-checkpoint", default="auto")
 
 
 
 
 
107
  args = parser.parse_args()
108
 
109
  args.output_dir.mkdir(parents=True, exist_ok=True)
@@ -112,7 +203,6 @@ def main():
112
  encode_device = torch.device(args.encode_device)
113
  train_device = torch.device(args.train_device)
114
 
115
- # Check if only 1 GPU available
116
  if torch.cuda.device_count() < 2:
117
  print(" Only 1 GPU, using same device for encode + train")
118
  encode_device = torch.device("cuda:0")
@@ -153,6 +243,7 @@ def main():
153
 
154
  vae_shift = vae.config.shift_factor
155
  vae_scale = vae.config.scaling_factor
 
156
 
157
  # Load transformer on train_device
158
  print(f" Loading Flux transformer on {train_device}...")
@@ -161,18 +252,28 @@ def main():
161
  args.model_name, subfolder="transformer", torch_dtype=torch.bfloat16, cache_dir=args.cache_dir
162
  )
163
 
164
- # LoRA
 
 
 
 
 
 
 
 
 
 
 
165
  lora_config = LoraConfig(
166
  r=args.lora_rank,
167
  lora_alpha=args.lora_alpha,
168
- target_modules=["to_q", "to_k", "to_v", "to_out.0"],
169
  lora_dropout=0.0,
170
  )
171
  transformer = get_peft_model(transformer, lora_config)
172
 
173
  # Load checkpoint weights if resuming
174
  if resume_path:
175
- from peft import set_peft_model_state_dict
176
  adapter_path = resume_path / "adapter_model.safetensors"
177
  if adapter_path.exists():
178
  import safetensors.torch
@@ -186,18 +287,13 @@ def main():
186
  set_peft_model_state_dict(transformer, state_dict)
187
  print(f" Loaded LoRA weights from checkpoint")
188
 
189
- # Cast LoRA params to fp32 to prevent NaN in bf16 backward pass
190
- for name, p in transformer.named_parameters():
191
- if p.requires_grad:
192
- p.data = p.data.float()
193
-
194
  transformer.to(train_device)
195
  transformer.print_trainable_parameters()
196
  transformer.train()
197
 
198
  # Optimizer + scheduler
199
  trainable_params = [p for p in transformer.parameters() if p.requires_grad]
200
- optimizer = torch.optim.AdamW(trainable_params, lr=args.learning_rate, weight_decay=0.01)
201
 
202
  from diffusers.optimization import get_scheduler
203
  lr_scheduler = get_scheduler(
@@ -216,20 +312,37 @@ def main():
216
  print(f" Loading dataset from {args.data_dir}")
217
  train_dataset, num_shards = create_webdataset(args.data_dir, args.resolution, args.batch_size)
218
  train_dataloader = torch.utils.data.DataLoader(
219
- train_dataset, batch_size=None, num_workers=0
220
  )
221
 
 
 
 
 
 
 
 
 
222
  # Training loop
223
  global_step = resume_step
224
  accum_loss = 0.0
 
225
  accum_count = 0
 
226
  t0 = time.time()
227
 
228
- print(f"\n Starting training from step {global_step}...")
 
 
229
  print(f" Batch size: {args.batch_size}, Grad accum: {args.gradient_accumulation}")
230
  print(f" Effective batch: {args.batch_size * args.gradient_accumulation}")
 
 
 
231
  print(f" Encode: {encode_device}, Train: {train_device}")
232
- print(f" Save every {args.save_steps} steps")
 
 
233
 
234
  optimizer.zero_grad()
235
 
@@ -240,54 +353,81 @@ def main():
240
 
241
  images = batch["image"].to(encode_device, dtype=torch.bfloat16)
242
  captions = batch["caption"]
 
243
 
244
- # Encode on encode_device
245
  with torch.no_grad():
 
246
  latents = vae.encode(images).latent_dist.sample()
247
  latents = (latents - vae_shift) * vae_scale
 
 
 
248
 
 
249
  text_ids = tokenizer(
250
  captions, padding="max_length", max_length=77,
251
  truncation=True, return_tensors="pt"
252
  ).input_ids.to(encode_device)
253
  pooled_prompt_embeds = text_encoder(text_ids, output_hidden_states=False).pooler_output
254
 
 
255
  text_ids_2 = tokenizer_2(
256
- captions, padding="max_length", max_length=256,
257
  truncation=True, return_tensors="pt"
258
  ).input_ids.to(encode_device)
259
  encoder_hidden_states = text_encoder_2(text_ids_2)[0]
260
 
261
- # Move to train device
262
  latents = latents.to(train_device)
263
  pooled_prompt_embeds = pooled_prompt_embeds.to(train_device)
264
  encoder_hidden_states = encoder_hidden_states.to(train_device)
265
 
266
- # Flow matching
267
  noise = torch.randn_like(latents)
268
- t = torch.rand(latents.shape[0], device=train_device, dtype=torch.bfloat16)
269
- t_expand = t.view(-1, 1, 1, 1)
270
- noisy_latents = (1 - t_expand) * latents + t_expand * noise
271
 
272
- noisy_packed = pack_latents(noisy_latents)
273
- target = pack_latents(noise - latents)
 
 
 
 
 
274
 
275
- # Flux expects raw timestep 0-1
276
- timesteps = t
277
 
278
- b, seq_len, _ = noisy_packed.shape
279
- h_patches = w_patches = int(seq_len ** 0.5)
280
- img_ids = torch.zeros(seq_len, 3, device=train_device, dtype=torch.bfloat16)
281
- img_ids[:, 1] = torch.arange(h_patches, device=train_device).repeat_interleave(w_patches).to(torch.bfloat16)
282
- img_ids[:, 2] = torch.arange(w_patches, device=train_device).repeat(h_patches).to(torch.bfloat16)
283
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  txt_ids = torch.zeros(encoder_hidden_states.shape[1], 3, device=train_device, dtype=torch.bfloat16)
285
 
286
- # Forward with autocast for numerical stability
 
 
 
 
 
 
 
 
287
  with torch.amp.autocast("cuda", dtype=torch.bfloat16):
288
  model_pred = transformer(
289
- hidden_states=noisy_packed,
290
- timestep=timesteps,
 
291
  encoder_hidden_states=encoder_hidden_states,
292
  pooled_projections=pooled_prompt_embeds,
293
  img_ids=img_ids,
@@ -295,12 +435,19 @@ def main():
295
  return_dict=False,
296
  )[0]
297
 
298
- # Compute loss in fp32
299
- loss = F.mse_loss(model_pred.float(), target.float())
 
 
 
 
 
 
 
300
 
301
- # Check for NaN and skip batch if needed
302
- if torch.isnan(loss):
303
- print(f" WARNING: NaN loss at accum_count={accum_count}, skipping batch", flush=True)
304
  optimizer.zero_grad()
305
  accum_count += 1
306
  continue
@@ -311,36 +458,79 @@ def main():
311
  accum_loss += loss.item()
312
  accum_count += 1
313
 
 
314
  if accum_count % args.gradient_accumulation == 0:
315
- torch.nn.utils.clip_grad_norm_(trainable_params, 1.0)
 
 
316
  optimizer.step()
317
  lr_scheduler.step()
318
  optimizer.zero_grad()
319
  global_step += 1
320
 
321
- if global_step % 50 == 0:
 
322
  elapsed = time.time() - t0
323
  steps_done = global_step - resume_step
324
  steps_per_sec = steps_done / elapsed if elapsed > 0 else 0
325
- avg_loss = accum_loss / (50 * args.gradient_accumulation) if accum_loss != 0 else float('nan')
326
- cur_loss = loss.item()
 
327
  print(
328
- f" Step {global_step} | "
329
- f"Loss(avg): {avg_loss:.4f} | "
330
- f"Loss(cur): {cur_loss:.4f} | "
331
- f"LR: {lr_scheduler.get_last_lr()[0]:.2e} | "
332
- f"Speed: {steps_per_sec:.2f} steps/s | "
333
  f"Elapsed: {elapsed/3600:.1f}h",
334
  flush=True,
335
  )
336
  accum_loss = 0.0
 
337
 
 
338
  if global_step % args.save_steps == 0:
339
  save_path = args.output_dir / f"checkpoint-{global_step}"
340
  save_path.mkdir(parents=True, exist_ok=True)
341
  transformer.save_pretrained(save_path)
 
 
 
 
 
 
342
  print(f" Saved checkpoint: {save_path}", flush=True)
343
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  # Final save
345
  final_path = args.output_dir / "final"
346
  final_path.mkdir(parents=True, exist_ok=True)
 
1
  """
2
  Fine-tune Flux with LoRA - 2 GPU split (encode on GPU0, train on GPU1).
3
+ Reads webdataset shards directly. Supports resume from checkpoint.
4
+ Follows diffusers reference implementation for correct flow matching.
5
  """
6
  import argparse
7
  import gc
8
+ import io
9
+ import math
10
  import time
11
  from pathlib import Path
12
 
 
15
  import webdataset as wds
16
  from PIL import Image
17
  from torchvision import transforms
18
+ from peft import LoraConfig, get_peft_model, set_peft_model_state_dict
19
 
20
 
21
  def get_train_transforms(resolution=1024):
 
34
 
35
 
36
  def create_webdataset(data_dir, resolution=1024, batch_size=1):
 
37
  transform = get_train_transforms(resolution)
38
 
39
  def preprocess(sample):
 
64
  return dataset, len(tar_files)
65
 
66
 
67
+ def pack_latents(latents, batch_size, num_channels, height, width):
68
+ latents = latents.view(batch_size, num_channels, height // 2, 2, width // 2, 2)
69
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
70
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels * 4)
71
  return latents
72
 
73
 
74
+ def unpack_latents(latents, height, width, num_channels):
75
+ batch_size = latents.shape[0]
76
+ latents = latents.reshape(batch_size, height // 2, width // 2, num_channels, 2, 2)
77
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
78
+ latents = latents.reshape(batch_size, num_channels, height, width)
79
+ return latents
80
+
81
+
82
+ def prepare_latent_image_ids(height, width, device, dtype):
83
+ latent_image_ids = torch.zeros(height, width, 3, device=device, dtype=dtype)
84
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height, device=device, dtype=dtype)[:, None]
85
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width, device=device, dtype=dtype)[None, :]
86
+ return latent_image_ids.reshape(height * width, 3)
87
+
88
+
89
+ def compute_density_for_timestep_sampling(weighting_scheme, batch_size, logit_mean=0.0, logit_std=1.0):
90
+ if weighting_scheme == "logit_normal":
91
+ u = torch.normal(mean=logit_mean, std=logit_std, size=(batch_size,))
92
+ u = torch.sigmoid(u)
93
+ elif weighting_scheme == "mode":
94
+ u = torch.rand(batch_size)
95
+ u = 1 - u - 0.2 * (torch.cos(math.pi * u / 2) ** 2 - 1 + u)
96
+ else:
97
+ u = torch.rand(batch_size)
98
+ return u
99
+
100
+
101
+ def compute_loss_weighting(weighting_scheme, sigmas):
102
+ if weighting_scheme == "sigma_sqrt":
103
+ weighting = (sigmas ** -2.0)
104
+ return weighting.clamp(max=10.0)
105
+ elif weighting_scheme == "cosmap":
106
+ return 2.0 / (math.pi * (1 - 2 * sigmas + 2 * sigmas ** 2))
107
+ else:
108
+ return torch.ones_like(sigmas)
109
+
110
+
111
  def find_latest_checkpoint(output_dir):
112
  output_dir = Path(output_dir)
113
  if not output_dir.exists():
 
122
  return None, 0
123
 
124
 
125
+ @torch.no_grad()
126
+ def generate_samples(
127
+ transformer, vae, text_encoder, text_encoder_2,
128
+ tokenizer, tokenizer_2,
129
+ prompts, output_dir, global_step,
130
+ encode_device, train_device,
131
+ num_inference_steps=4, guidance_scale=0.0,
132
+ ):
133
+ from diffusers import FluxPipeline
134
+ import numpy as np
135
+
136
+ output_dir = Path(output_dir) / "samples"
137
+ output_dir.mkdir(parents=True, exist_ok=True)
138
+
139
+ transformer.eval()
140
+
141
+ try:
142
+ pipe = FluxPipeline.from_pretrained(
143
+ "black-forest-labs/FLUX.1-schnell",
144
+ transformer=transformer,
145
+ vae=vae,
146
+ text_encoder=text_encoder,
147
+ text_encoder_2=text_encoder_2,
148
+ tokenizer=tokenizer,
149
+ tokenizer_2=tokenizer_2,
150
+ torch_dtype=torch.bfloat16,
151
+ )
152
+ pipe = pipe.to(train_device)
153
+
154
+ for i, prompt in enumerate(prompts):
155
+ image = pipe(
156
+ prompt=prompt,
157
+ num_inference_steps=num_inference_steps,
158
+ guidance_scale=guidance_scale,
159
+ height=512,
160
+ width=512,
161
+ ).images[0]
162
+ image.save(output_dir / f"step_{global_step:06d}_sample_{i}.png")
163
+
164
+ del pipe
165
+ except Exception as e:
166
+ print(f" WARNING: Sample generation failed: {e}")
167
+
168
+ transformer.train()
169
+ torch.cuda.empty_cache()
170
+
171
+
172
  def main():
173
  parser = argparse.ArgumentParser()
174
  parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-schnell")
 
179
  parser.add_argument("--batch-size", type=int, default=1)
180
  parser.add_argument("--gradient-accumulation", type=int, default=8)
181
  parser.add_argument("--learning-rate", type=float, default=1e-4)
182
+ parser.add_argument("--lr-scheduler", default="constant")
183
+ parser.add_argument("--lr-warmup-steps", type=int, default=100)
184
  parser.add_argument("--max-train-steps", type=int, default=999999999)
185
  parser.add_argument("--save-steps", type=int, default=2000)
186
+ parser.add_argument("--sample-steps", type=int, default=2000)
187
  parser.add_argument("--lora-rank", type=int, default=128)
188
+ parser.add_argument("--lora-alpha", type=int, default=64)
189
  parser.add_argument("--seed", type=int, default=42)
190
  parser.add_argument("--encode-device", default="cuda:0")
191
  parser.add_argument("--train-device", default="cuda:1")
192
  parser.add_argument("--resume-from-checkpoint", default="auto")
193
+ parser.add_argument("--guidance-scale", type=float, default=1.0)
194
+ parser.add_argument("--weighting-scheme", default="none", choices=["none", "logit_normal", "mode", "sigma_sqrt", "cosmap"])
195
+ parser.add_argument("--logit-mean", type=float, default=0.0)
196
+ parser.add_argument("--logit-std", type=float, default=1.0)
197
+ parser.add_argument("--max-grad-norm", type=float, default=1.0)
198
  args = parser.parse_args()
199
 
200
  args.output_dir.mkdir(parents=True, exist_ok=True)
 
203
  encode_device = torch.device(args.encode_device)
204
  train_device = torch.device(args.train_device)
205
 
 
206
  if torch.cuda.device_count() < 2:
207
  print(" Only 1 GPU, using same device for encode + train")
208
  encode_device = torch.device("cuda:0")
 
243
 
244
  vae_shift = vae.config.shift_factor
245
  vae_scale = vae.config.scaling_factor
246
+ print(f" VAE config: shift_factor={vae_shift}, scaling_factor={vae_scale}")
247
 
248
  # Load transformer on train_device
249
  print(f" Loading Flux transformer on {train_device}...")
 
252
  args.model_name, subfolder="transformer", torch_dtype=torch.bfloat16, cache_dir=args.cache_dir
253
  )
254
 
255
+ # Check guidance
256
+ has_guidance = getattr(transformer.config, "guidance_embeds", False)
257
+ print(f" Model has guidance_embeds: {has_guidance}")
258
+
259
+ # LoRA - comprehensive target modules for Flux MMDiT
260
+ lora_target_modules = [
261
+ "attn.to_q", "attn.to_k", "attn.to_v", "attn.to_out.0",
262
+ "attn.add_k_proj", "attn.add_q_proj", "attn.add_v_proj", "attn.to_add_out",
263
+ "ff.net.0.proj", "ff.net.2",
264
+ "ff_context.net.0.proj", "ff_context.net.2",
265
+ ]
266
+
267
  lora_config = LoraConfig(
268
  r=args.lora_rank,
269
  lora_alpha=args.lora_alpha,
270
+ target_modules=lora_target_modules,
271
  lora_dropout=0.0,
272
  )
273
  transformer = get_peft_model(transformer, lora_config)
274
 
275
  # Load checkpoint weights if resuming
276
  if resume_path:
 
277
  adapter_path = resume_path / "adapter_model.safetensors"
278
  if adapter_path.exists():
279
  import safetensors.torch
 
287
  set_peft_model_state_dict(transformer, state_dict)
288
  print(f" Loaded LoRA weights from checkpoint")
289
 
 
 
 
 
 
290
  transformer.to(train_device)
291
  transformer.print_trainable_parameters()
292
  transformer.train()
293
 
294
  # Optimizer + scheduler
295
  trainable_params = [p for p in transformer.parameters() if p.requires_grad]
296
+ optimizer = torch.optim.AdamW(trainable_params, lr=args.learning_rate, weight_decay=0.01, betas=(0.9, 0.999))
297
 
298
  from diffusers.optimization import get_scheduler
299
  lr_scheduler = get_scheduler(
 
312
  print(f" Loading dataset from {args.data_dir}")
313
  train_dataset, num_shards = create_webdataset(args.data_dir, args.resolution, args.batch_size)
314
  train_dataloader = torch.utils.data.DataLoader(
315
+ train_dataset, batch_size=None, num_workers=2, prefetch_factor=4
316
  )
317
 
318
+ # Sample prompts for monitoring
319
+ sample_prompts = [
320
+ "a beautiful mountain landscape at sunset, 4k, highly detailed",
321
+ "a cute cat sitting on a windowsill, natural lighting",
322
+ "a futuristic city skyline at night with neon lights",
323
+ "portrait of a woman with flowers in her hair, oil painting style",
324
+ ]
325
+
326
  # Training loop
327
  global_step = resume_step
328
  accum_loss = 0.0
329
+ accum_grad_norm = 0.0
330
  accum_count = 0
331
+ log_interval = 50
332
  t0 = time.time()
333
 
334
+ print(f"\n === Training Config ===")
335
+ print(f" Model: {args.model_name}")
336
+ print(f" LoRA rank: {args.lora_rank}, alpha: {args.lora_alpha}, scaling: {args.lora_alpha/args.lora_rank:.2f}")
337
  print(f" Batch size: {args.batch_size}, Grad accum: {args.gradient_accumulation}")
338
  print(f" Effective batch: {args.batch_size * args.gradient_accumulation}")
339
+ print(f" LR: {args.learning_rate}, Scheduler: {args.lr_scheduler}, Warmup: {args.lr_warmup_steps}")
340
+ print(f" Weighting: {args.weighting_scheme}")
341
+ print(f" Guidance: {args.guidance_scale if has_guidance else 'N/A (Schnell)'}")
342
  print(f" Encode: {encode_device}, Train: {train_device}")
343
+ print(f" Save every {args.save_steps} steps, Sample every {args.sample_steps} steps")
344
+ print(f" Starting from step {global_step}")
345
+ print(f" ========================\n")
346
 
347
  optimizer.zero_grad()
348
 
 
353
 
354
  images = batch["image"].to(encode_device, dtype=torch.bfloat16)
355
  captions = batch["caption"]
356
+ bs = images.shape[0]
357
 
358
+ # === Encode on encode_device ===
359
  with torch.no_grad():
360
+ # VAE encode
361
  latents = vae.encode(images).latent_dist.sample()
362
  latents = (latents - vae_shift) * vae_scale
363
+ # latents shape: [B, 16, H/8, W/8]
364
+
365
+ _, num_channels, latent_h, latent_w = latents.shape
366
 
367
+ # Text encode - CLIP (pooled)
368
  text_ids = tokenizer(
369
  captions, padding="max_length", max_length=77,
370
  truncation=True, return_tensors="pt"
371
  ).input_ids.to(encode_device)
372
  pooled_prompt_embeds = text_encoder(text_ids, output_hidden_states=False).pooler_output
373
 
374
+ # Text encode - T5 (sequence)
375
  text_ids_2 = tokenizer_2(
376
+ captions, padding="max_length", max_length=512,
377
  truncation=True, return_tensors="pt"
378
  ).input_ids.to(encode_device)
379
  encoder_hidden_states = text_encoder_2(text_ids_2)[0]
380
 
381
+ # === Move to train device ===
382
  latents = latents.to(train_device)
383
  pooled_prompt_embeds = pooled_prompt_embeds.to(train_device)
384
  encoder_hidden_states = encoder_hidden_states.to(train_device)
385
 
386
+ # === Flow matching setup ===
387
  noise = torch.randn_like(latents)
 
 
 
388
 
389
+ # Sample timesteps using density function
390
+ u = compute_density_for_timestep_sampling(
391
+ args.weighting_scheme, bs, args.logit_mean, args.logit_std
392
+ )
393
+ # u is in [0, 1], use as sigmas directly (linear schedule)
394
+ sigmas = u.to(device=train_device, dtype=torch.bfloat16)
395
+ sigmas_expand = sigmas.view(-1, 1, 1, 1)
396
 
397
+ # Noisy latents: linear interpolation
398
+ noisy_latents = (1.0 - sigmas_expand) * latents + sigmas_expand * noise
399
 
400
+ # Target: velocity = noise - clean
401
+ target = noise - latents
 
 
 
402
 
403
+ # === Pack latents for transformer ===
404
+ packed_noisy = pack_latents(noisy_latents, bs, num_channels, latent_h, latent_w)
405
+ packed_target = pack_latents(target, bs, num_channels, latent_h, latent_w)
406
+
407
+ # === Prepare positional IDs ===
408
+ # img_ids: spatial positions for packed patches
409
+ # packed dims are latent_h//2, latent_w//2
410
+ img_ids = prepare_latent_image_ids(
411
+ latent_h // 2, latent_w // 2, train_device, torch.bfloat16
412
+ )
413
+
414
+ # txt_ids: zeros for text tokens
415
  txt_ids = torch.zeros(encoder_hidden_states.shape[1], 3, device=train_device, dtype=torch.bfloat16)
416
 
417
+ # === Timesteps for transformer (divide by 1000) ===
418
+ timesteps = (sigmas * 1000.0)
419
+
420
+ # === Guidance ===
421
+ guidance = None
422
+ if has_guidance:
423
+ guidance = torch.full((bs,), args.guidance_scale, device=train_device, dtype=torch.bfloat16)
424
+
425
+ # === Forward pass ===
426
  with torch.amp.autocast("cuda", dtype=torch.bfloat16):
427
  model_pred = transformer(
428
+ hidden_states=packed_noisy,
429
+ timestep=timesteps / 1000,
430
+ guidance=guidance,
431
  encoder_hidden_states=encoder_hidden_states,
432
  pooled_projections=pooled_prompt_embeds,
433
  img_ids=img_ids,
 
435
  return_dict=False,
436
  )[0]
437
 
438
+ # === Loss computation in fp32 ===
439
+ weighting = compute_loss_weighting(args.weighting_scheme, sigmas)
440
+ # weighting shape: [B], need to expand for sequence dim
441
+ weighting = weighting.view(-1, 1, 1).to(model_pred.device)
442
+
443
+ loss = torch.mean(
444
+ (weighting * (model_pred.float() - packed_target.float()) ** 2).reshape(bs, -1),
445
+ dim=1,
446
+ ).mean()
447
 
448
+ # NaN check
449
+ if torch.isnan(loss) or torch.isinf(loss):
450
+ print(f" WARNING: Invalid loss at step {global_step}, skipping batch", flush=True)
451
  optimizer.zero_grad()
452
  accum_count += 1
453
  continue
 
458
  accum_loss += loss.item()
459
  accum_count += 1
460
 
461
+ # === Optimizer step ===
462
  if accum_count % args.gradient_accumulation == 0:
463
+ grad_norm = torch.nn.utils.clip_grad_norm_(trainable_params, args.max_grad_norm)
464
+ accum_grad_norm += grad_norm.item()
465
+
466
  optimizer.step()
467
  lr_scheduler.step()
468
  optimizer.zero_grad()
469
  global_step += 1
470
 
471
+ # === Logging ===
472
+ if global_step % log_interval == 0:
473
  elapsed = time.time() - t0
474
  steps_done = global_step - resume_step
475
  steps_per_sec = steps_done / elapsed if elapsed > 0 else 0
476
+ avg_loss = accum_loss / (log_interval * args.gradient_accumulation)
477
+ avg_grad = accum_grad_norm / log_interval
478
+ cur_lr = lr_scheduler.get_last_lr()[0]
479
  print(
480
+ f" Step {global_step:6d} | "
481
+ f"Loss: {avg_loss:.4f} | "
482
+ f"GradNorm: {avg_grad:.3f} | "
483
+ f"LR: {cur_lr:.2e} | "
484
+ f"Speed: {steps_per_sec:.2f} st/s | "
485
  f"Elapsed: {elapsed/3600:.1f}h",
486
  flush=True,
487
  )
488
  accum_loss = 0.0
489
+ accum_grad_norm = 0.0
490
 
491
+ # === Save checkpoint ===
492
  if global_step % args.save_steps == 0:
493
  save_path = args.output_dir / f"checkpoint-{global_step}"
494
  save_path.mkdir(parents=True, exist_ok=True)
495
  transformer.save_pretrained(save_path)
496
+ # Save optimizer state for proper resume
497
+ torch.save({
498
+ "optimizer": optimizer.state_dict(),
499
+ "lr_scheduler": lr_scheduler.state_dict(),
500
+ "global_step": global_step,
501
+ }, save_path / "training_state.pt")
502
  print(f" Saved checkpoint: {save_path}", flush=True)
503
 
504
+ # Cleanup old checkpoints (keep last 3)
505
+ all_ckpts = sorted(
506
+ [d for d in args.output_dir.iterdir() if d.is_dir() and d.name.startswith("checkpoint-")],
507
+ key=lambda p: int(p.name.split("-")[1]),
508
+ )
509
+ if len(all_ckpts) > 3:
510
+ for old_ckpt in all_ckpts[:-3]:
511
+ import shutil
512
+ shutil.rmtree(old_ckpt)
513
+ print(f" Removed old checkpoint: {old_ckpt.name}")
514
+
515
+ # === Generate samples ===
516
+ if global_step % args.sample_steps == 0:
517
+ print(f" Generating samples at step {global_step}...")
518
+ generate_samples(
519
+ transformer=transformer,
520
+ vae=vae,
521
+ text_encoder=text_encoder,
522
+ text_encoder_2=text_encoder_2,
523
+ tokenizer=tokenizer,
524
+ tokenizer_2=tokenizer_2,
525
+ prompts=sample_prompts,
526
+ output_dir=args.output_dir,
527
+ global_step=global_step,
528
+ encode_device=encode_device,
529
+ train_device=train_device,
530
+ num_inference_steps=4,
531
+ guidance_scale=0.0,
532
+ )
533
+
534
  # Final save
535
  final_path = args.output_dir / "final"
536
  final_path.mkdir(parents=True, exist_ok=True)