Foundations to Frontier
Tests
C. Programming, Tools and HPC › C5 High-Performance Computing

Mixed-Precision Training

Tensor cores run 8–16 times faster in 16-bit than in 32-bit floating point, and 16-bit values halve memory traffic, so modern training computes most of its arithmetic in FP16 or BF16 (and increasingly FP8) while keeping the numerically delicate parts in FP32. This topic covers the formats (FP32, TF32, FP16, BF16, FP8 E4M3/E5M2: range, precision, subnormals), what goes wrong in low precision (gradient underflow, overflow, rounded-away updates, stalled accumulation), and the standard recipe: autocast, FP32 master weights, FP32 accumulation and reductions, and dynamic loss scaling for FP16 (GradScaler). In the exercises you derive each format's range and precision, implement bfloat16 rounding and a dynamic loss scaler; then you simulate low-precision training to measure gradient underflow, the rescue by loss scaling, BF16's precision floor, stagnation without master weights and stalled accumulation.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Writing numbers with fewer digits

Imagine writing every measurement with only three or four digits instead of eight. You’d write twice as fast and fill half as many pages, and for most things nobody would notice. But some numbers are so tiny they’d round to zero, and adding a tiny amount to a big number might not change it at all. Mixed precision uses short numbers for the bulk of the work and long ones exactly where those problems would bite.

Number formats for mixed precision
formatbits (exp/mant)x roundedrelative erroreps
FP328/230.000993458794.0e-81.2e-7
BF168/70.000991821291.6e-37.8e-3
FP165/100.000993728642.7e-49.8e-4
FP8 E5M25/20.000976562501.7e-22.5e-1
FP8 E4M34/30.00195312509.7e-11.3e-1
FP32BF16FP16FP8 E5M2FP8 E4M31e-401e-301e-201e-101e01e101e201e30
blue: normal range · purple: subnormal range (reduced precision) · orange line: |x|
gradients of magnitude 1e-9 … 1e-4 stored in FP16 after scaling by 1e+0: 32% become 0
FP16 has precision but little range: small gradients underflow, so the loss is multiplied by S before backward and the gradients divided by S before the update (dynamic loss scaling picks the largest S that doesn't overflow). BF16 keeps FP32's exponent range, so no scaling is needed, at the cost of about 3 significant digits. FP8 needs per-tensor scale factors for everything.
Why engineers care

Mixed precision roughly halves training time and memory for large models, and lower precision (FP16, INT8, FP8) is what makes networks fit in the power budget of embedded GPUs on robots and satellites. Knowing where precision is lost lets you use it safely for scientific models too, where small quantities (residuals, corrections, gradients of physics losses) matter.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Why train with 16-bit numbers?
  2. 2. A very tiny gradient stored in FP16 can…
  3. 3. In the demo, what does the loss scale do?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The formats

Format exponent / mantissa bits max smallest normal eps (precision)
FP32 8 / 23 3.4·10³⁸ 1.2·10⁻³⁸ 1.2·10⁻⁷
TF32 (tensor-core input) 8 / 10 3.4·10³⁸ 1.2·10⁻³⁸ 9.8·10⁻⁴
BF16 8 / 7 3.4·10³⁸ 1.2·10⁻³⁸ 7.8·10⁻³
FP16 5 / 10 65 504 6.1·10⁻⁵ (subnormals to 6·10⁻⁸) 9.8·10⁻⁴
FP8 E5M2 5 / 2 57 344 6.1·10⁻⁵ 0.25
FP8 E4M3 4 / 3 448 1.6·10⁻² 0.125

BF16 keeps FP32’s range with less precision; FP16 has more precision but a narrow range. On A100 and H100, both run on tensor cores at the same speed.

In PyTorch

scaler = torch.amp.GradScaler("cuda")                      # needed for float16, not for bfloat16
for x, y in loader:
    with torch.autocast("cuda", dtype=torch.float16):       # matmuls/convs in fp16; softmax, norms, losses in fp32
        loss = loss_fn(model(x), y)
    scaler.scale(loss).backward()                           # gradients of loss × S
    scaler.step(opt)                                        # unscale; skip the step if any gradient is inf/NaN
    scaler.update(); opt.zero_grad()                        # grow or shrink S
📝 Quick check (Level 1)
0/3 answered
  1. 1. Largest finite FP16 value?
  2. 2. Which 16-bit format has the same range as FP32?
  3. 3. Which needs a GradScaler?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

What goes wrong in low precision

  1. Underflow: gradients of individual samples are often 10⁻⁶–10⁻⁹; anything below about 6·10⁻⁸ becomes 0 in FP16 (precision is already poor in the subnormal range below 6.1·10⁻⁵).
  2. Overflow: activations or scaled gradients above 65 504 become inf in FP16.
  3. Rounded-away updates: adding an update smaller than half an ulp of the weight changes nothing. Near 1.0, FP16’s ulp is 2⁻¹⁰ ≈ 10⁻³, so typical learning-rate × gradient updates of 10⁻⁵ vanish.
  4. Accumulation: a running sum in FP16 stops growing once each addend is below half its ulp.

The recipe

  • Autocast: matrix multiplications and convolutions in FP16/BF16 (tensor cores); reductions, softmax, normalizations and losses in FP32.
  • FP32 accumulation inside matmul kernels (tensor cores accumulate in FP32).
  • FP32 master weights: the optimizer updates an FP32 copy; the low-precision copy is derived from it.
  • Loss scaling (FP16): multiply the loss by S (e.g. 2¹⁶) so gradients move up into range; divide gradients by S before the update; dynamically halve S and skip the step on overflow, and double it after a run of clean steps.
🐍 Exercise 1: formats, bfloat16 rounding and loss scaling
Derive max, smallest normal and subnormal, eps and decimal digits of a binary format from its exponent and mantissa bits (with the FP8 E4M3 exception), check against NumPy's float16, round float32 to bfloat16 with round-to-nearest-even by bit manipulation, measure gradient underflow in fp16 with and without scaling, and implement a dynamic loss scaler.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A gradient of 10⁻⁸ in FP16 becomes…
  2. 2. On overflow, a dynamic loss scaler…
  3. 3. Why keep FP32 master weights?

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Choosing a precision

  • BF16 is the default on A100/H100/TPUs: no loss scaling, robust; precision is rarely the limit for deep learning.
  • FP16 + GradScaler on older GPUs (V100, consumer cards), or when more mantissa helps.
  • TF32 (torch.backends.cuda.matmul.allow_tf32 = True) speeds up FP32 code’s matmuls with no code change.
  • FP8 (H100+, Transformer Engine): per-tensor scaling factors from running amax statistics; E4M3 for forward, E5M2 for gradients.
  • Scientific models: keep quantities whose small differences matter (residuals, energies, positions in large coordinate frames, long time integrations) in FP32 or FP64; mixed precision is a tool, not a default for every computation.

Memory accounting

With Adam, training stores weights, gradients and two optimizer moments: 16 bytes per parameter in FP32, and still about 16 bytes in mixed precision (2 + 2 bytes of 16-bit weights and gradients, plus 4 + 8 bytes of FP32 master weights and moments). The savings come from activations, which dominate memory for large batches and long sequences, and from tensor-core speed.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Bytes per parameter for mixed-precision Adam training (weights, grads, master, moments)?
  2. 2. BF16 training usually needs loss scaling?
  3. 3. FP8 training relies on…

Level 4: Expert

★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.

Precision failures, measured

Exercise 1. From the bit layout: FP16 max 65 504, smallest normal 2⁻¹⁴, smallest subnormal 2⁻²⁴, eps 2⁻¹⁰ (matching NumPy); BF16 max 3.39·10³⁸ with eps 2⁻⁷; FP8 E4M3 max 448, E5M2 max 57 344. Bit-level BF16 rounding gives π → 3.140625 and rounds ties to even. Of 100 000 gradients drawn from N(0, 10⁻⁶), 2.3% become zero in FP16 and only 0.001% after scaling by 1024. The dynamic scaler halves its scale on an inf and doubles it after 3 clean steps.

Exercise 2: simulated low-precision training. Every intermediate tensor is rounded to the chosen format.

Underflow. Linear regression with tiny targets (scale 10⁻⁴), 300 gradient-descent steps, error of the weights relative to the exact solution:

Precision relative error loss gradients that are exactly 0
FP32 2.1·10⁻⁸ 0%
FP16, no scaling 1.0·10⁻² 99%
FP16 + dynamic loss scaling 2.8·10⁻⁴ 8%
BF16, no scaling 1.4·10⁻³ 35% (residuals rounding to 0, not underflow)

Without scaling, FP16 stalls as soon as the residuals get small; loss scaling recovers about 35× more accuracy; BF16 never underflows but its 8-bit mantissa limits how precisely it can resolve small residuals. (Values are from the browser; on a desktop NumPy build the loss-scaled FP16 error comes out at 2.1·10⁻⁴, because rounding of the summed gradients differs slightly between builds.)

Stagnation. Fine-tuning weights near 1.0–1.5 by small corrections (learning rate 0.02): with FP32 master weights 12% of the initial error remains after 300 steps (FP32 throughout: 0.06%); storing and updating the weights in FP16 leaves 105%: every update was smaller than half an ulp and was rounded away.

Accumulation. Adding 20 000 × 10⁻⁴ (true sum 2.0) gives 2.0002 in FP32, 0.25 in FP16 and 0.03125 in BF16: the low-precision accumulators stop growing once 10⁻⁴ is below half their ulp, which is why kernels accumulate in FP32.

🐍 Exercise 2 (research): what low precision breaks, and what fixes it
Simulate autocast by rounding every tensor to FP16 or BF16; train a tiny-target linear regression in FP32, FP16 without scaling, FP16 with dynamic loss scaling and BF16, measuring error and zero-gradient fractions; fine-tune weights near 1 with and without FP32 master weights; and accumulate many small numbers in each format.

Mixed precision in AI, robotics and aerospace

  • Large-model training: BF16 autocast with FP32 master weights is the standard; FP8 on H100-class hardware for further speed.
  • Edge inference: FP16 and INT8 on Jetson and NPUs (C3.7 covers quantization).
  • Physics-informed and scientific ML: residual losses can be tiny; keep losses and sensitive operations in FP32 and validate against FP64 references.
  • Simulation: mixed-precision iterative refinement solves linear systems in low precision and corrects residuals in high precision, reaching FP64 accuracy faster.

References

  1. P. Micikevicius et al. (2018). “Mixed precision training.” ICLR.
  2. D. Kalamkar et al. (2019). “A study of BFLOAT16 for deep learning training.” arXiv:1905.12322.
  3. P. Micikevicius et al. (2022). “FP8 formats for deep learning.” arXiv:2209.05433.
  4. PyTorch documentation (pytorch.org/docs): Automatic Mixed Precision (torch.amp, GradScaler).
  5. N. J. Higham (2002). Accuracy and Stability of Numerical Algorithms, 2nd ed. SIAM.
  6. S. Rajbhandari et al. (2020). “ZeRO: memory optimizations toward training trillion parameter models.” SC20 (16 bytes per parameter accounting).