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
⚡ One-Sentence Core Answer
Loss scaling multiplies the forward loss by a scale factor 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 and subnormal .
- •Gradient underflow: In deep networks, over 80% of backpropagated gradients have magnitudes below , which flush to zero in naive FP16.
- •Linearity of gradients: ; after backprop, gradients are unscaled by before optimizer updates.
📐 Mathematical Derivations
By linearity of differentiation, . Multiplying the scalar loss by scale factor shifts the entire empirical gradient distribution to the right by 16 binary exponents: . Gradients that were previously (flushed to zero in FP16) become (comfortably within FP16 normal range). In the optimizer step, gradients are converted to FP32 and unscaled: , restoring the exact mathematical gradient value.
🏭 Production Trade-offs
Dynamic Loss Scaling algorithm: (1) Initialize . (2) After backward pass, inspect all gradients for
inf or NaN. (3) If inf/NaN detected (overflow), skip optimizer step and decrease scale: . (4) If no overflow occurs for consecutive steps (e.g. ), increase scale: . In modern hardware, BF16 (Bfloat16) has 8 exponent bits (identical dynamic range to FP32, up to ), 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 .
- ✕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.GradScalerautomate 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.
📚
Associated Knowledge Base Guides & Mindmaps
Explore the comprehensive technical article, exam cards, and global architecture tree.
中文速览与面试要点
解释混合精度训练中的 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 策略