M3-073M3: Deep Learning FoundationsTraining Stability & Mixed PrecisionMedium
⚡Flashcard Drill➔Mastery:

Systematic Troubleshooting Workflow When Training Loss Becomes NaN

📐 Mathematical Definition
NaN⇐{0/0, ∞/∞, log⁡0, exp⁡(large), neg}\text{NaN}\Leftarrow\{0/0,\ \infty/\infty,\ \log0,\ \exp(\text{large}),\ \sqrt{\text{neg}}\}
⚡ One-Sentence Core Answer
Isolate the first NaN occurrence via anomaly detection hooks; audit data inputs for corrupted values, inspect operators for division-by-zero or unmasked logits, and check FP16 overflow.

📌 Key Takeaways

  • •
    First failure isolation: use torch.autograd.set_detect_anomaly(True) to find the exact operation that produced the first NaN
  • •
    Root causes: 0/00/0 in normalizations, log⁡(0)=−∞\log(0) = -\infty in CE, attention logit blowups, all-masked attention tokens, unscaled FP16
  • •
    Data sanitization: check for NaNs, Infs, or empty strings in newly loaded data shards

📐 Mathematical Derivations

Systematic Debugging Workflow:
① Step 1: Check Input Data Batches:
Assert torch.isnan(x).any() == False and torch.isinf(x).any() == False. Check for zero-length sequences or attention masks where an entire sequence is masked out with −∞-\infty (which causes softmax(−∞)=0/0=NaN\text{softmax}(-\infty) = 0/0 = \text{NaN}).
② Step 2: Inspect Numerical Operations:
- Normalization Division: Check if ϵ\epsilon in LayerNorm/RMSNorm is too small (<10−8< 10^{-8}) or missing, causing division by zero when variance is zero.
- Softmax Exponents: Ensure logits are stabilized with max-subtraction: softmax(z−max⁡(z))\text{softmax}(z - \max(z)).
- Square Root / Log: Check if variance in custom loss became negative due to precision roundoff: torch.sqrt(torch.clamp(var, min=1e-8)).
③ Step 3: Audit Precision & Learning Rate:
- If training in FP16, switch temporarily to BF16 or FP32. If NaN disappears, root cause is FP16 exponent overflow (>65504> 65504).
- Check gradient norms before NaN; if norms spiked exponentially over 3 steps, learning rate is too high or warmup was insufficient.

🏭 Production Trade-offs

Automated safeguards: In production distributed pre-training frameworks (Megatron-LM, DeepSpeed), configure automatic batch skipping and checkpoint rollback when loss is non-finite.
⚠️ Common Interview Pitfalls
  • ✕
    Assuming NaNs are always caused by model architecture when >70%>70\% are caused by corrupted input data tokens
  • ✕
    Lowering learning rate blindly without verifying whether a normalization layer divided by zero
🎯 Interviewer Follow-up Inquiries
  • ?
    How does an all-padding sequence in masked multi-head attention trigger a 0/00/0 NaN in softmax?
  • ?
    How does torch.autograd.set_detect_anomaly trace the forward origin of a backward NaN?
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔
📚

Associated Knowledge Base Guides & Mindmaps

Explore the comprehensive technical article, exam cards, and global architecture tree.

← PreviousM3-072: Loss Scaling Mechanism and Dynamic Adjustment in Mixed Precision📋Back to BankNext →M3-074: Operators Most Prone to Instability Under Low-Precision (FP16/BF16)
中文速览与面试要点

训练出现 loss NaN 时如何排查?

按'先定位首次出现的位置,再分算子/数据/超参'排查:softmax 溢出、除零、lr 过大、脏数据、FP16 上溢。

核心要点

  • 数学机理:NaN 的产生源头可穷举: 0/0 (如归一化时分母为 0)、 ∞/∞ 、 log(0)=−∞ (交叉熵在预测为 0 时)、 exp(大数)=∞ (softmax/激活未减 max)、 sqrt(负数) (数值误差导致方差略负)。一旦某处产生 NaN,反向传播中的乘法/加法会让 NaN 传染 到所有相关梯度(NaN·x=NaN),进而污染全部参数——故'看到一个 NaN'不等于'源头在那里'。 排查策略 是' 先定位首次出现 ':(1) 记录每步的 loss,找到第一个 NaN 的 step;(2) 用 torch.autograd.set_detect_anomaly(True) 让 PyTorch 在反向遇到 NaN 时抛出异常并打印产生 NaN 的具体算子(代价是速度变慢,仅用于调试);(3) 用 hook 记录每层前向输出与反向梯度的 min/max/是否含 NaN,二分定位到具体层。 定位后按类别修复 :(a) 算子层 ——softmax 加 max-subtraction、LN/BN 的 ε 调大、log 前加 eps、用 stable 的 CE;(b) 超参层 ——降 lr、加长 warmup、加梯度裁剪、增大 Adam 的 ε;(c) 数据层 ——检查异常样本(超长序列、全 padding、重复 token);(d) 精度层 ——从 FP16 换 BF16、关键算子保 FP32。
  • 深度剖析与工程权衡:① NaN vs inf 的区别 ——inf 通常是上溢(大数相乘/exp),NaN 通常是 0/0 或 inf−inf;先区分类型可缩小范围。② 前向 NaN vs 反向 NaN ——前向 NaN 说明激活/损失异常(算子或数据问题);前向正常但反向 NaN 说明梯度计算异常(如除以极小的方差、梯度爆炸)。分别用前向/反向 hook 定位。③ 常见'隐蔽'源 ——(a) attention 的 mask 用 −inf 时若整行被 mask 则 softmax 得 0/0(需用 −1e9 或加保护);(b) 稀疏数据的 LN 方差为 0;(c) 混合精度下 loss scale 未正确 unscale。④ 恢复策略 ——定位并修复后,若已污染参数,需回滚到 NaN 之前的 checkpoint 重训(用坏梯度更新过的参数无法自动恢复)。⑤ 预防性设计 ——使用 BF16、稳定算子、梯度裁剪、skip-nan 机制(检测到 NaN 时跳过该步);这些是现代训练框架的标配。⑥ 面试要点 ——被问'loss 变 NaN 怎么办',应给出' 先定位首个 NaN + 区分前向/反向 + 按算子/超参/数据/精度四类排查 '的结构化流程,并提到 set_detect_anomaly 这一具体工具;回答'调小 lr'就结束是明显不足。
  • 先定位首个 NaN 的 step 与算子(hook 前向/反向)
  • 常见源:softmax 未减 max、LN 方差为 0、lr 过大、FP16 溢出
  • 用 BF16、加 ε、降 lr、裁剪、跳过坏批次

常见陷阱

  • 看到 NaN 就直接调 lr(未定位源头,可能反复出现)
  • 忽略 mask 全为 −inf 导致的 0/0