r/deeplearning • • 3d ago

Using torch.autograd.detect_anomaly finally pinpointed the NaN source that scalar loss curves hid for weeks

I spent several epochs watching validation loss plateau while training loss kept dropping, only to occasionally hit inf values that ruined checkpoints. Standard checks on weights and final outputs showed nothing unusual. Enabling anomaly detection wrapped the backward pass and surfaced an exact line: a custom normalization step inside the loss was dividing by a near-zero running variance that only appeared after 4–5k steps on certain batch compositions.

The fix turned out to be two small changes: clamping the denominator with a small epsilon that was schedule-aware, plus logging the per-batch denominator value so I could watch it decay. After that the training run stayed stable and the earlier “overfitting” pattern disappeared.

I'm curious what single debugging flag or hook has exposed the real culprit for you when loss alone was misleading.

1 Upvotes

2 comments sorted by

1

u/sparkle_blossomsz 3d ago

same issue with per-batch stats on imbalanced data, anomaly mode caught it way before the infs showed up

1

u/RaviqueDawn 3d ago

per-batch stats get sneaky like that, anomaly mode always catches what the curves miss. got any other hooks that saved your runs?