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
缓解: log⁡-sum-exp, ϵ 平滑, clipping, BF16, LN/RMSNorm\text{缓解}:\ \log\text{-sum-exp},\ \epsilon\ \text{平滑},\ \text{clipping},\ \text{BF16},\ \text{LN/RMSNorm}
⚡ 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: g←g⋅min⁡(1,clip_norm∥g∥2)g \leftarrow g \cdot \min\left(1, \frac{\text{clip\_norm}}{\|g\|_2}\right), projecting gradients back into a bounded hypersphere without changing direction. (2) Epsilon placement in normalization: In RMSNorm, RMS(x)=1d∑i=1dxi2+ϵ\text{RMS}(x) = \sqrt{\frac{1}{d}\sum_{i=1}^d x_i^2 + \epsilon}, where ϵ=10−5\epsilon = 10^{-5} (FP32) or 10−610^{-6} prevents division by zero when activations collapse. (3) Activation saturation: Sigmoid derivatives σ′(z)=σ(z)(1−σ(z))≤0.25\sigma'(z) = \sigma(z)(1-\sigma(z)) \le 0.25, compounding to 0.25L→00.25^L \to 0; replaced by non-saturating activations like GELU and SwiGLU.

🏭 Production Trade-offs

System design trade-offs: (1) Epsilon magnitude: Setting ϵ\epsilon too small (e.g. 10−1210^{-12} in FP16) results in underflow to zero, causing division by zero anyway; setting it too large (e.g. 10−210^{-2}) distorts normalization variance. (2) BF16 vs FP16: BF16 trades 3 mantissa bits for 3 exponent bits, sacrificing precision (10−310^{-3} relative error) for massive dynamic range (103810^{38}), proving vastly superior for large model pretraining stability.
⚠️ Common Interview Pitfalls
  • ✕
    Placing epsilon outside the square root: torch.sqrt(var) + eps vs torch.sqrt(var + eps) (the former allows sqrt(0) whose gradient 120\frac{1}{2\sqrt{0}} is inf).
  • ✕
    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 while torch.sqrt(var) + eps produces 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.
🎯 Drill This Card Now➔
📚

Associated Knowledge Base Guides & Mindmaps

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

← PreviousM1-034: Explain Why Numerically Stable Implementations Use log1p(exp(-|z|)) for Binary Cross-Entropy (BCEWithLogits)📋Back to BankNext →M1-036: Define Maximum Likelihood Estimation (MLE) with a Complete End-to-End Derivation
中文速览与面试要点

列举深度学习中常见的数值不稳定来源,以及各自的缓解手段。

来源:指数溢出、除零、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 的 ε 值(导致除零)