memoryai commited on
Commit
11b11fa
·
verified ·
1 Parent(s): 22f612e

Fix NaN: rewrite training loop - proper grad accum, zero_grad before loop, correct loss averaging

Browse files
Files changed (1) hide show
  1. scripts/training/train_flux_lora.py +30 -37
scripts/training/train_flux_lora.py CHANGED
@@ -222,6 +222,7 @@ def main():
222
  # Training loop
223
  global_step = resume_step
224
  accum_loss = 0.0
 
225
  t0 = time.time()
226
 
227
  print(f"\n Starting training from step {global_step}...")
@@ -230,6 +231,8 @@ def main():
230
  print(f" Encode: {encode_device}, Train: {train_device}")
231
  print(f" Save every {args.save_steps} steps")
232
 
 
 
233
  while global_step < args.max_train_steps:
234
  for batch in train_dataloader:
235
  if global_step >= args.max_train_steps:
@@ -255,13 +258,6 @@ def main():
255
  ).input_ids.to(encode_device)
256
  encoder_hidden_states = text_encoder_2(text_ids_2)[0]
257
 
258
- # Debug NaN on first step
259
- if global_step == resume_step:
260
- print(f" DEBUG latents: min={latents.min():.4f} max={latents.max():.4f} nan={latents.isnan().any()}")
261
- print(f" DEBUG pooled: min={pooled_prompt_embeds.min():.4f} max={pooled_prompt_embeds.max():.4f} nan={pooled_prompt_embeds.isnan().any()}")
262
- print(f" DEBUG hidden: min={encoder_hidden_states.min():.4f} max={encoder_hidden_states.max():.4f} nan={encoder_hidden_states.isnan().any()}")
263
- print(f" DEBUG vae_shift={vae_shift} vae_scale={vae_scale}")
264
-
265
  # Move to train device
266
  latents = latents.to(train_device)
267
  pooled_prompt_embeds = pooled_prompt_embeds.to(train_device)
@@ -298,43 +294,40 @@ def main():
298
  return_dict=False,
299
  )[0]
300
 
301
- # Debug NaN on first few steps
302
- if global_step < resume_step + 3:
303
- print(f" DEBUG step {global_step}: pred nan={model_pred.isnan().any()} target nan={target.isnan().any()} pred range=[{model_pred.min():.4f}, {model_pred.max():.4f}]", flush=True)
304
-
305
  loss = F.mse_loss(model_pred.float(), target.float())
306
- loss = loss / args.gradient_accumulation
307
- loss.backward()
 
308
  accum_loss += loss.item()
 
309
 
310
- if (global_step + 1) % args.gradient_accumulation == 0:
311
  torch.nn.utils.clip_grad_norm_(trainable_params, 1.0)
312
  optimizer.step()
313
  lr_scheduler.step()
314
  optimizer.zero_grad()
315
-
316
- global_step += 1
317
-
318
- if global_step % 50 == 0:
319
- elapsed = time.time() - t0
320
- steps_done = global_step - resume_step
321
- steps_per_sec = steps_done / elapsed if elapsed > 0 else 0
322
- avg_loss = accum_loss / 50 * args.gradient_accumulation
323
- print(
324
- f" Step {global_step} | "
325
- f"Loss: {avg_loss:.4f} | "
326
- f"LR: {lr_scheduler.get_last_lr()[0]:.2e} | "
327
- f"Speed: {steps_per_sec:.2f} it/s | "
328
- f"Elapsed: {elapsed/3600:.1f}h",
329
- flush=True,
330
- )
331
- accum_loss = 0.0
332
-
333
- if global_step % args.save_steps == 0:
334
- save_path = args.output_dir / f"checkpoint-{global_step}"
335
- save_path.mkdir(parents=True, exist_ok=True)
336
- transformer.save_pretrained(save_path)
337
- print(f" Saved checkpoint: {save_path}", flush=True)
338
 
339
  # Final save
340
  final_path = args.output_dir / "final"
 
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}...")
 
231
  print(f" Encode: {encode_device}, Train: {train_device}")
232
  print(f" Save every {args.save_steps} steps")
233
 
234
+ optimizer.zero_grad()
235
+
236
  while global_step < args.max_train_steps:
237
  for batch in train_dataloader:
238
  if global_step >= args.max_train_steps:
 
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)
 
294
  return_dict=False,
295
  )[0]
296
 
 
 
 
 
297
  loss = F.mse_loss(model_pred.float(), target.float())
298
+ scaled_loss = loss / args.gradient_accumulation
299
+ scaled_loss.backward()
300
+
301
  accum_loss += loss.item()
302
+ accum_count += 1
303
 
304
+ if accum_count % args.gradient_accumulation == 0:
305
  torch.nn.utils.clip_grad_norm_(trainable_params, 1.0)
306
  optimizer.step()
307
  lr_scheduler.step()
308
  optimizer.zero_grad()
309
+ global_step += 1
310
+
311
+ if global_step % 50 == 0:
312
+ elapsed = time.time() - t0
313
+ steps_done = global_step - resume_step
314
+ steps_per_sec = steps_done / elapsed if elapsed > 0 else 0
315
+ avg_loss = accum_loss / (50 * args.gradient_accumulation)
316
+ print(
317
+ f" Step {global_step} | "
318
+ f"Loss: {avg_loss:.4f} | "
319
+ f"LR: {lr_scheduler.get_last_lr()[0]:.2e} | "
320
+ f"Speed: {steps_per_sec:.2f} steps/s | "
321
+ f"Elapsed: {elapsed/3600:.1f}h",
322
+ flush=True,
323
+ )
324
+ accum_loss = 0.0
325
+
326
+ if global_step % args.save_steps == 0:
327
+ save_path = args.output_dir / f"checkpoint-{global_step}"
328
+ save_path.mkdir(parents=True, exist_ok=True)
329
+ transformer.save_pretrained(save_path)
330
+ print(f" Saved checkpoint: {save_path}", flush=True)
 
331
 
332
  # Final save
333
  final_path = args.output_dir / "final"