Topic 34 of 62 · Training at scale
FP16, BF16, and mixed precision
MediumHow do FP16 and BF16 divide their 16 bits differently, and why does FP16 require dynamic loss scaling?
1 · Start with the intuition
Every 16-bit floating-point format has to split 15 non-sign bits between exponent (dynamic range: how large or small a number can be) and mantissa/fraction (precision: how finely spaced two nearby numbers are). FP16 uses 5 exponent bits and 10 fraction bits, giving good precision near 1.0 but a tiny dynamic range that overflows above 65,504 and loses small gradients: below 2⁻¹⁴ ≈ 6.1 × 10⁻⁵ values become subnormal with fewer significant bits, and below about 3 × 10⁻⁸ they round to zero. BF16 keeps the exact 8-bit exponent of FP32 and leaves 7 fraction bits—matching FP32’s huge dynamic range so gradients almost never underflow, removing the need for FP16-style loss scaling.
2 · How the mechanism works
Mechanism step 1 of 3 · no question to answer
Run matmuls in 16-bit
Execute tensor-core matrix multiplications in BF16 or FP16 while accumulating dot products in FP32.
Next, we will look at: Keep sensitive state in FP32. Move on when this operation makes sense.
Visualizing the behavior
Bit layouts: sign · exponent · mantissa
Spec- Sign
- Exponent → range
- Mantissa → precision
Range vs precision
SpecLargest finite value
Gap between 1.0 and the next value (smaller = finer)
3 · The governing equation
FP32: 1 sign + 8 exponent + 23 fraction bits BF16: 1 sign + 8 exponent + 7 fraction bits (same range as FP32, coarser precision) FP16: 1 sign + 5 exponent + 10 fraction bits (max finite = 65,504; smallest normal 2⁻¹⁴; smallest subnormal 2⁻²⁴) Loss scaling (FP16): ∇θ(s · L) = s · ∇θL ⇒ g_true = ∇θ(s · L) / s
Notation: s is the dynamic loss-scaling factor (e.g., 2¹⁶), which is increased over clean steps and halved whenever an Inf/NaN gradient is detected (skipping that step).
Why keep an FP32 master copy of the weights even when using BF16? Because a typical parameter update −η·g is thousands of times smaller than the weight θ itself. With only 7 fraction bits in BF16 (a relative spacing of 2⁻⁷ ≈ 0.78%), adding a 10⁻⁴ update directly to a weight of 1.0 in BF16 rounds straight back to 1.0, stalling training. Accumulating updates into FP32 master weights preserves those small steps.
4 · Put concrete numbers on it
Worked numbers (from stated assumptions)5 · Common misconception to avoid
Saying “switching to mixed precision cuts total training memory in half” or clipping gradients before unscaling in FP16. Persistent model state does not shrink: pure FP32 Adam holds weights 4 + gradients 4 + two moments 8 = 16 bytes/param, and the common BF16 setup holds BF16 weights 2 + BF16 gradients 2 + FP32 master weights 4 + two FP32 moments 8 = 16 bytes/param. Setups that keep FP32 gradients alongside a 16-bit weight copy need 18 bytes/param. The memory saving comes from 2-byte activations.
In practice · implementation & engineering rule of thumb
On Ampere/Hopper+ GPUs, prefer bfloat16 autocast (no GradScaler needed). If running float16, always call scaler.unscale_(optimizer) before clip_grad_norm_.
with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
loss = model(input_ids, labels=labels).loss
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()Go one level deeper
Follow-ups that often come after a correct first answer.
- What stays in FP32
- Typical mixed precision keeps FP32 master weights and optimizer states, runs matmuls in BF16/FP16 with FP32 accumulation, and lets autocast run precision-sensitive ops (softmax, log-softmax, norms, losses) in FP32.
- Dynamic loss scaling (FP16)
- PyTorch’s GradScaler starts at a scale of 65,536. On inf/NaN it skips that optimizer step and halves the scale; after 2,000 clean steps it doubles the scale. BF16 usually needs no scaling because its range matches FP32.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumWhy must you unscale FP16 gradients before calling clip_grad_norm_?
Show follow-up reasoning
While scaled by s, the gradient norm is s · ‖g‖₂. If you clip against threshold c before dividing by s, you are actually clipping the true gradient against c / s—which shrinks your effective clip threshold by thousands of times and changes whenever the dynamic loss scaler adjusts s.