M1-033M1: Mathematics & Statistics FundamentalsNumerical StabilityMedium
⚡Flashcard Drill➔Mastery:

Explain Loss Scaling in Mixed Precision (FP16/BF16) Training and How It Prevents Underflow

📐 Mathematical Definition
g~=S⋅g,θ←θ−η g~/S\tilde g=S\cdot g,\qquad \theta\leftarrow\theta-\eta\,\tilde g/S
⚡ One-Sentence Core Answer
Loss scaling multiplies the forward loss by a scale factor SS before backprop, shifting small gradient values into the representable dynamic range of FP16 to prevent them from flushing to zero.

📌 Key Takeaways

  • •
    Dynamic range: FP16 has 5 exponent bits, with minimum positive normal number 2−14≈6.1×10−52^{-14} \approx 6.1 \times 10^{-5} and subnormal 2−24≈5.96×10−82^{-24} \approx 5.96 \times 10^{-8}.
  • •
    Gradient underflow: In deep networks, over 80% of backpropagated gradients have magnitudes below 2−142^{-14}, which flush to zero in naive FP16.
  • •
    Linearity of gradients: ∇W(S⋅L)=S⋅∇WL\nabla_W (S \cdot \mathcal{L}) = S \cdot \nabla_W \mathcal{L}; after backprop, gradients are unscaled by 1/S1/S before optimizer updates.

📐 Mathematical Derivations

By linearity of differentiation, ∂(S⋅L)∂W=S∂L∂W\frac{\partial (S \cdot \mathcal{L})}{\partial W} = S \frac{\partial \mathcal{L}}{\partial W}. Multiplying the scalar loss by scale factor S=216=65536S = 2^{16} = 65536 shifts the entire empirical gradient distribution to the right by 16 binary exponents: log⁡2(∣S⋅g∣)=log⁡2(∣g∣)+16\log_2(|S \cdot g|) = \log_2(|g|) + 16. Gradients that were previously 2−202^{-20} (flushed to zero in FP16) become 2−42^{-4} (comfortably within FP16 normal range). In the optimizer step, gradients are converted to FP32 and unscaled: gFP32=1Sgscaledg_{\text{FP32}} = \frac{1}{S} g_{\text{scaled}}, restoring the exact mathematical gradient value.

🏭 Production Trade-offs

Dynamic Loss Scaling algorithm: (1) Initialize S=216S = 2^{16}. (2) After backward pass, inspect all gradients for inf or NaN. (3) If inf/NaN detected (overflow), skip optimizer step and decrease scale: S←S/2S \leftarrow S / 2. (4) If no overflow occurs for NN consecutive steps (e.g. N=2000N=2000), increase scale: S←2SS \leftarrow 2S. In modern hardware, BF16 (Bfloat16) has 8 exponent bits (identical dynamic range to FP32, up to 103810^{38}), eliminating the need for loss scaling entirely.
⚠️ Common Interview Pitfalls
  • ✕
    Applying optimizer weight decay to scaled gradients before unscaling, which distorts weight regularization by factor SS.
  • ✕
    Failing to skip optimizer step when gradient overflow occurs, contaminating model weights with NaN.
🎯 Interviewer Follow-up Inquiries
  • ?
    Why does BF16 eliminate the need for loss scaling, and what is its precision trade-off compared to FP16?
  • ?
    How does PyTorch torch.cuda.amp.GradScaler automate dynamic loss scaling and optimizer unscaling?
⚡
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-032: Formulate the Log-Sum-Exp (LSE) Trick and Explain What Numerical Instability It Resolves📋Back to BankNext →M1-034: Explain Why Numerically Stable Implementations Use log1p(exp(-|z|)) for Binary Cross-Entropy (BCEWithLogits)
中文速览与面试要点

解释混合精度训练中的 loss scaling,为什么它能防梯度下溢。

FP16 最小正规数很小,梯度易下溢为 0;把 loss 放大 S 倍,梯度同比放大,更新前再除回。

核心要点

  • FP16 的表示范围是 [6.1×10⁻⁵, 65504](正规数),最小正规数约 6×10⁻⁵,低于此的值变为非规格化数(精度骤降)或直接下溢为 0。神经网络的梯度常落在 10⁻⁶–10⁻⁸ 量级(尤其深层或饱和区),直接以 FP16 存储会 整批下溢为 0 ,导致这些参数永远不更新。 Loss scaling 的解法是在反向传播前把 loss 乘以 S(如 2¹⁵=32768),由于反向传播的梯度与 loss 成正比,所有梯度被同比例放大到 FP16 可表示的范围;在优化器更新前再把梯度除以 S 还原。数学上完全等价,因为缩放是线性的。
  • 动态 loss scaling 是工程化的关键:若检测到梯度中出现 inf/NaN(说明 S 过大导致上溢),则跳过该步更新并把 S 减半;若连续若干步没有溢出,则把 S 加倍以充分利用精度。这套机制由 PyTorch AMP 的 GradScaler 自动完成。两个对比点:① BF16 通常不需要 loss scaling ——BF16 的指数位与 FP32 相同(8 位),动态范围约 10⁻³⁸–10³⁸,与 FP32 一致,只是尾数位少(7 位 vs 23 位),故不存在下溢问题,代价是精度略低。这也是大模型训练普遍转向 BF16 的原因。② 必须保留 FP32 主权重副本 ——优化器更新(尤其 Adam 的二阶矩)对精度敏感,若直接在 FP16 权重上更新会因舍入误差累积而损失精度;标准做法是维护 FP32 master weights,每次前向时转为 BF16/FP16。
  • 动态 loss scaling 会检测 inf/NaN 并调整 S
  • BF16 动态范围大,通常不需要 loss scaling

常见陷阱

  • 认为 loss scaling 改变了训练目标(它是线性等价变换)
  • 在 BF16 下也照搬 FP16 的 loss scaling 策略