M1-035M1: Mathematics & Statistics FundamentalsNumerical StabilityHard
⚡Flashcard Drill➔Mastery:
Enumerate Common Sources of Numerical Instability in Deep Learning and Their Standard Industrial Mitigations
📐 Mathematical Definition
⚡ One-Sentence Core Answer
Numerical instability stems from vanishing/exploding gradients, floating-point overflow/underflow, matrix near-singularity, and precision loss; mitigated by normalization, gradient clipping, log-domain computation, and mixed precision design.
📌 Key Takeaways
- •Gradient explosion/vanishing: Mitigated via Residual connections, LayerNorm/RMSNorm, proper initialization (Xavier/Kaiming), and Gradient Clipping.
- •Exponent overflow/underflow: Mitigated via Log-Sum-Exp tricks, subtracting max in Softmax, and log1p/expm1 formulations.
- •FP16 dynamic range overflow: Mitigated via dynamic loss scaling, FP32 master weights, or upgrading to BF16/FP8 with scaling.
- •Matrix division by zero: Mitigated via numerical guards (epsilon clamping:
x / (norm + eps)).
📐 Mathematical Derivations
Survey of instability equations: (1) Gradient norm explosion in deep RNNs/Transformers: , projecting gradients back into a bounded hypersphere without changing direction. (2) Epsilon placement in normalization: In RMSNorm, , where (FP32) or prevents division by zero when activations collapse. (3) Activation saturation: Sigmoid derivatives , compounding to ; replaced by non-saturating activations like GELU and SwiGLU.
🏭 Production Trade-offs
System design trade-offs: (1) Epsilon magnitude: Setting too small (e.g. in FP16) results in underflow to zero, causing division by zero anyway; setting it too large (e.g. ) distorts normalization variance. (2) BF16 vs FP16: BF16 trades 3 mantissa bits for 3 exponent bits, sacrificing precision ( relative error) for massive dynamic range (), proving vastly superior for large model pretraining stability.
⚠️ Common Interview Pitfalls
- ✕Placing epsilon outside the square root:
torch.sqrt(var) + epsvstorch.sqrt(var + eps)(the former allowssqrt(0)whose gradient isinf). - ✕Clipping gradients element-wise instead of globally by norm, which alters the directional angle of the gradient vector.
🎯 Interviewer Follow-up Inquiries
- ?Why is
torch.sqrt(var + eps)mathematically safe in backward autodiff whiletorch.sqrt(var) + epsproduces NaN gradients at zero? - ?How does weight decay decouple from adaptive gradients in AdamW to prevent numerical divergence?
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
📚
Associated Knowledge Base Guides & Mindmaps
Explore the comprehensive technical article, exam cards, and global architecture tree.
中文速览与面试要点
列举深度学习中常见的数值不稳定来源,以及各自的缓解手段。
来源:指数溢出、除零、log(0)、梯度爆炸/下溢、FP16 范围、方差过小归一化。
核心要点
- 按算子分类更系统:① 指数类 (softmax、sigmoid、exp、log-sum-exp)——溢出/下溢,缓解是减 max、分段计算、log1p;② 除法与归一化 (LayerNorm、BatchNorm、attention 的 1/√d)——除零或方差过小,缓解是加 ε(且 FP16 下 ε 需放大到 1e-3 量级);③ 对数类 (交叉熵、KL、log 概率)——log(0)=−inf,缓解是 clip 概率到 [1e-12, 1−1e-12] 或用 log 域直接计算;④ 梯度类 ——爆炸(连乘 >1)或下溢(连乘 累加类 (大数求和、注意力 logits)——浮点累加误差,缓解是 Kahan 求和、FP32 累加。
- 系统化的排查与预防:① 定位手段 ——用 torch.autograd.set_detect_anomaly(True) 捕获产生 NaN 的具体算子;逐层 hook 监控激活与梯度的 min/max/norm;先看是哪一步(step)开始 NaN,再二分定位层。② 结构性的稳定化 ——残差连接保证梯度至少有恒等通路(+1),归一化层把激活分布拉回稳定尺度,二者共同改善数值条件,这也是深层网络能训练的前提。③ 训练层面的防线 ——梯度裁剪(clip by norm,LLM 常用 1.0)、BF16 替代 FP16、降低学习率、loss scaling 的动态调整。④ 监控指标 ——grad norm 分布、update/param 比值(健康范围约 10⁻³)、loss scale 值的变化趋势,这些指标往往在 loss 变 NaN 之前就已异常。
- 归一化层分母加 ε
- 概率裁剪到 [1e-12, 1-1e-12]
- 监控 grad norm 与 loss scale
- 数值问题常表现为 loss NaN,需逐层定位
常见陷阱
- 只在 loss 变 NaN 后才排查(应监控 grad norm 提前预警)
- FP16 下沿用 FP32 的 ε 值(导致除零)