所属模块:
M3 · 深度学习基础 (Deep Learning Foundations)| 专题分类:训练稳定性与混合精度 (Training Stability & Mixed Precision)| 难度等级:Medium
一、核心一句话结论 (One-Sentence Summary)
按’先定位首次出现的位置,再分算子/数据/超参’排查:softmax 溢出、除零、lr 过大、脏数据、FP16 上溢。
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 Insights)
- 📌 先定位首个 NaN 的 step 与算子(hook 前向/反向)
- 📌 常见源:softmax 未减 max、LN 方差为 0、lr 过大、FP16 溢出
- 📌 用 BF16、加 ε、降 lr、裁剪、跳过坏批次
English Insights:
– First failure isolation: use torch.autograd.set_detect_anomaly(True) to find the exact operation that produced the first NaN
– Root causes: $0/0$ in normalizations, $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 Principles & Derivation)
$$text{NaN}Leftarrow{0/0, infty/infty, log0, exp(text{large}), sqrt{text{neg}}}$$
数学机理: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。
📖 查看英文严格数学推导 (English Mathematical Derivation)
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 $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}$) or missing, causing division by zero when variance is zero.
– Softmax Exponents: Ensure logits are stabilized with max-subtraction: $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$).
– Check gradient norms before NaN; if norms spiked exponentially over 3 steps, learning rate is too high or warmup was insufficient.
四、工业级落地权衡与工程考量 (Industrial Trade-offs)
深度剖析与工程权衡:① 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’就结束是明显不足。
⚙️ 查看英文落地权衡分析 (English Systems & 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 Pitfalls & Traps)
- ⚠️ 看到 NaN 就直接调 lr(未定位源头,可能反复出现)
- ⚠️ 忽略 mask 全为 −inf 导致的 0/0
English Pitfalls:
– Assuming NaNs are always caused by model architecture when $>70%$ are caused by corrupted input data tokens
– Lowering learning rate blindly without verifying whether a normalization layer divided by zero
六、高频深度面试追问与预测 (Follow-Up Questions)
- 如何用 torch.autograd.set_detect_anomaly 定位?
- How does an all-padding sequence in masked multi-head attention trigger a $0/0$ NaN in softmax?
- 为什么 NaN 会’传染’整个 batch?
- How does
torch.autograd.set_detect_anomalytrace the forward origin of a backward NaN?
七、知识图谱对齐 (Knowledge Graph Anchor)
- 🔗 关联底层卡片:
FP16 / BF16 混合精度训练、GradScaler 动态缩放与数值下溢(AMP Mixed-Precision (FP16/BF16), GradScaler & Underflow) - 🗺️ 知识图谱模块:
AI 基础设施工程导图
🔬 算法科学家与机器学习深度考察全量题库 (Science Depth)
本题收录于 TalentMe 算法科学家深度考察真题库 (Science Depth)。全库共 856 道硬核考点,深度覆盖数学统计、经典ML、深度学习、Transformer、大语言模型、多模态、推荐系统与 MLOps。支持 Jev 面经智能匹配、一键离线单文件 HTML 手册导出并直连 Obsidian 本地记忆。