Chapter 39 of 42 · ~18 min read & lab+75 XP
Chapter 39 · Deep Learning

Mixed Precision Training: FP16 vs. BF16, Dynamic Loss Scaling, Tensor Cores & PyTorch AMP

How to get a free 2×–3× GPU speedup and ~45% VRAM reduction with 3 lines of PyTorch: FP32 vs. FP16 vs. BF16 bit layouts, why BF16 never overflows, FP16 Dynamic Loss Scaling (GradScaler), and FP32 Master Weights!

Why ML Engineers & Data Scientists Actually Need This

Training in pure FP32 leaves 60%–70% of your GPU's Tensor Core throughput idle and burns 2× the activation VRAM!

ML / AI Engineer

Wrapping your forward pass in torch.autocast('cuda', dtype=torch.bfloat16) is the single highest-ROI 1-line speedup in PyTorch.

Data Scientist

Knowing why FP16 overflows at 65,504 saves hours of debugging mysterious NaN gradients on older T4/V100 GPUs!

Interview & Debug Edge

Top ML Systems interview question: 'Explain the bit-level difference between FP16 and BF16, and why FP16 needs Dynamic Loss Scaling while BF16 does not!'

Step 0 · Test Your Gut Before Any Math!

What gives BF16 the exact same massive numeric range (±3.4e38) as FP32 despite using only 16 bits?

What You Will Master in This Chapter
  • Compare FP32, FP16 (5-bit exponent, max 65,504), and BF16 (8-bit exponent, FP32 range 3.4e38) bit layouts
  • Explain why BF16 eliminates overflow/underflow and needs NO GradScaler, while FP16 requires Dynamic Loss Scaling
  • Understand how PyTorch AMP (torch.autocast) keeps FP32 Master Weights and sensitive ops (Softmax, LayerNorm) in FP32 while running Tensor Core GEMMs in 16-bit
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 1
FP16:(1,5,10)   vs.   BF16:(1,8,7)\text{FP16}: (1, 5, 10) \;\text{ vs. }\; \text{BF16}: (1, 8, 7)Say aloud:“FP16 is 1 sign, 5 exponent, 10 mantissa bits versus BF16 1 sign, 8 exponent, 7 mantissa bits”
Plain-English Meaning
Exponent bits control dynamic range (max/min value); mantissa bits control decimal precision.
Everyday Example
FP16 max = 65,504; BF16 max = 3.4 × 10^38 (identical to FP32!).
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Mixed Precision (AMP) is like building a house using a fast framing nailer (BF16/FP16 Tensor Cores) for 95% of the heavy lifting, while keeping a precision laser level (FP32 Master Weights + Softmax/LayerNorm) for the delicate measurements!

1. FP32 vs. FP16 vs. BF16 Bit Layouts

Floating-Point Precision Layout: FP32 vs. FP16 vs. BF16FP32 (32-bit)1s + 8 exp + 23 mantissaFP16 (16-bit)1s + 5 exp (max 65K ⚠) + 10mBF16 (16-bit ✓)1s + 8 exp (FP32 range!) + 7mBF16 eliminates FP16 overflow/underflow — default on A100, H100 & RTX 30/40/50 GPUs!
Bit Layout Showdown: BF16 keeps FP32's full 8-bit exponent (identical dynamic range → zero overflow!), while FP16 only has a 5-bit exponent (overflows at 65,504)!

Modern NVIDIA GPUs (Ampere A100+, Hopper H100, RTX 30/40/50) execute BF16/FP16 matrix multiplies at 2×–4× the FLOPs of FP32 and halve activation memory bandwidth! Prefer BF16 on any Ampere+ GPU; use FP16 + GradScaler on older Volta/Turing (V100/T4) GPUs.

Animated Mini-Lab • Mixed Precision

FP32 vs. FP16 vs. BF16 Dynamic Range & Speed

BF16 (2 bytes): Max 3.4e38 (same range as FP32!) · ZERO GradScaler needed · 2–3× speed ✓

2. FP16 Dynamic Loss Scaling (`GradScaler`)

FP16 Dynamic Loss Scaling (torch.cuda.amp.GradScaler)1. Scale Loss × SShift tiny grads into FP162. loss.backward()No underflow to 0 ✓3. Unscale ÷ SSkip step if inf/NaN!
FP16 Dynamic Loss Scaling multiplies the loss by S (e.g., 65,536) before .backward() so tiny gradients survive FP16 underflow, then unscales by 1/S before optimizer.step()!

Small gradients like 1e-6 round straight to 0.0 in FP16 (underflow!). GradScaler multiplies the loss by a large factor SS (e.g., 65,536) before .backward(), shifting gradients into FP16's representable zone, then divides by SS before optimizer.step() — automatically halving SS if any inf/NaN appears!

3. FP32 Master Weights & PyTorch `torch.autocast`

PyTorch AMP Mixed Precision: Fast Tensor Cores + FP32 Master WeightsFP32 Master WeightsAccurate small updatesBF16/FP16 Forward2×–3× Tensor Core GEMMFP32 Softmax/NormAuto-kept in FP32 ✓
PyTorch AMP Mixed Precision keeps FP32 Master Weights for accurate tiny updates while running Tensor-Core Forward & Backward GEMMs in 2× faster BF16/FP16!

Never cast the whole model blindly with model.half()! Small updates like 1e-4 disappear when added to 1.0 in 16-bit. PyTorch AMP keeps weights in FP32, casts GEMMs to BF16/FP16 automatically, and keeps reductions (Softmax, LayerNorm, CrossEntropy) safely in FP32!

Pause & Check · Quick Intuition Pulse

Why should you use torch.autocast('cuda', dtype=torch.bfloat16) instead of blindly calling model.half()?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

No! Because BF16 has the exact same 8-bit exponent range as FP32, gradients don't underflow or overflow like FP16 — GradScaler is only needed for torch.float16!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS PyTorch AMP Mixed Precision pipeline run Tensor Core GEMMs with FP32 master weights.
Interactive Animation • PyTorch AMP Deep Lab

Mixed Precision Training: BF16/FP16 Tensor Cores + FP32 Master Weights

See how PyTorch autocast speeds up GEMMs 2–3× while protecting numerical stability.

Step 1 / 4
1. Cast FP32 Master Weights → BF16/FP16 for Tensor Core forward pass
2. Autocast automatically keeps Softmax, LayerNorm & Loss in safe FP32
3. Backward pass computes fast 16-bit gradients (with GradScaler for FP16)
4. Update FP32 Master Weights cleanly — 2.5× faster, ~45% less VRAM ✓
0%
Stage 1 / 4
Intuition Takeaway: Use BF16 torch.autocast (or FP16 + GradScaler on older GPUs) to unlock 2×–3× Tensor Core speed and ~45% lower VRAM while keeping Master Weights and Softmax/Norm safely in FP32.
Where This Powers Real ML, Deep Learning & Generative AI

Every Modern GPU Training & Fine-Tuning Script

BF16 AMP is enabled by default in PyTorch Lightning, Hugging Face Accelerate, and all frontier LLM/ViT training runs.

Production NumPy & PyTorch Code Patterns
# Modern BF16 AMP on Ampere/Hopper+ GPUs (zero GradScaler needed!)
for x, y in train_loader:
    optimizer.zero_grad(set_to_none=True)
    with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
        logits = model(x)
        loss = criterion(logits, y)
    loss.backward()
    optimizer.step()
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Putting loss.backward() INSIDE the with torch.autocast(): block.
Best Practice: PyTorch officially recommends exiting autocast BEFORE calling loss.backward() — backward ops automatically use the matching forward precision!
Chapter Mastery Check (+75 XP)
Score: 0 / 1
1Why does BF16 avoid the gradient underflow/overflow problems of FP16?

Apply What You Learned — Solve Matching Coding Problems