Fix NaN: autocast forward, NaN skip, show cur_loss for debug
Browse files
scripts/training/train_flux_lora.py
CHANGED
|
@@ -283,18 +283,28 @@ def main():
|
|
| 283 |
|
| 284 |
txt_ids = torch.zeros(encoder_hidden_states.shape[1], 3, device=train_device, dtype=torch.bfloat16)
|
| 285 |
|
| 286 |
-
# Forward
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
|
|
|
|
|
|
| 297 |
loss = F.mse_loss(model_pred.float(), target.float())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
scaled_loss = loss / args.gradient_accumulation
|
| 299 |
scaled_loss.backward()
|
| 300 |
|
|
@@ -312,10 +322,12 @@ def main():
|
|
| 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",
|
|
|
|
| 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,
|
| 294 |
+
txt_ids=txt_ids,
|
| 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
|
| 307 |
+
|
| 308 |
scaled_loss = loss / args.gradient_accumulation
|
| 309 |
scaled_loss.backward()
|
| 310 |
|
|
|
|
| 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",
|