◆ AI All-in-One

Level 3 In-Depth AI · ML Engineering and Production

Mixed Precision Training

Train with 16-bit numbers where it is safe and 32-bit where it matters. Mixed precision roughly doubles training speed on modern GPUs and halves activation memory, with no loss in accuracy. BF16 versus FP16, loss scaling, autocast, and the memory arithmetic of training.

Level
●●●●● Intermediate
Reading
12 min
To learn it well
45 minutes to read, an afternoon to practise
↗ Plan a path here

Read first

Training Neural Networks in PracticeGPUs and Why AI Needs Them

This leads to

—
The full path from zero — 27 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Tensors and Shapes
  13. NumPy and Array Thinking
  14. GPUs and Why AI Needs Them
  15. Supervised Learning
  16. Linear Regression
  17. Training, Validation and Test Sets
  18. The Perceptron
  19. Logistic Regression
  20. Overfitting and the Bias–Variance Tradeoff
  21. Regularization: L1 and L2
  22. Neural Networks
  23. Backpropagation
  24. Dropout and Regularizing Neural Networks
  25. PyTorch
  26. Optimizers: SGD, Momentum and Adam
  27. Training Neural Networks in Practice
  28. Mixed Precision Training

Read them roughly in this order. See it on the concept map →

Why it matters

Training a large model is expensive in two currencies: time on GPUs and GPU memory. Both depend heavily on how many bits each number uses.

Modern GPUs have tensor cores, units that multiply small blocks of matrices in one step, and they are far faster with 16-bit inputs than with 32-bit ones. As published by NVIDIA, an H100 SXM GPU does about 67 TFLOPS of ordinary FP32 arithmetic, but about 989 TFLOPS of dense BF16 matrix maths on its tensor cores, roughly fifteen times as much (GPUs and Why AI Needs Them). Training entirely in 32-bit leaves most of that hardware idle.

Simply switching everything to 16 bits, though, can make training fail: gradients vanish to zero, sums lose their small updates, or values overflow to infinity. Mixed precision training gets the speed without the failures. It does the heavy matrix multiplications in 16 bits and keeps the few sensitive quantities in 32 bits. In PyTorch it takes about three extra lines. Essentially every large model today, from image classifiers to pretrained LLMs, is trained this way.

The intuition

Think of an accountant who does quick calculations on a pocket calculator with few digits, but keeps the official ledger in full precision. The quick calculations can be slightly rounded without harm. Errors in the ledger would build up over thousands of entries, so the ledger is never rounded.

In mixed precision training:

  • The quick calculations are the forward and backward passes: huge matrix multiplications done in 16 bits on tensor cores.
  • The ledger is the master weights: a 32-bit copy of every parameter that receives the updates. An update like "add 0.00001" to a weight of 1.0 would simply vanish in 16-bit (as you'll see in the code), so updates must accumulate in 32 bits.
  • Some operations that sum many numbers or take exponentials (softmax, normalisation, the loss) also stay in 32 bits, because they are the most sensitive to rounding.
Master weightsFP32 · the ledger 16-bit copycast each step Forward passmatmuls in 16-bit Loss in FP32FP16: multiply by S Backward pass16-bit gradients Unscale + updateFP32: θ ← θ − η∇L castto FP32next step kept in FP32: master weights, loss, softmax, normalisation, optimizer state done in 16 bits (BF16 or FP16) on tensor cores: the heavy matrix maths S = loss scale: needed for FP16 (narrow range), unnecessary for BF16 (FP32-sized range)
Fig. 1 One step of mixed precision training. A 32-bit master copy of the weights is cast to 16 bits for the forward and backward passes, which run on tensor cores. The loss is computed in 32 bits and, with FP16, multiplied by a scale factor so small gradients don't underflow. Gradients are unscaled and applied to the 32-bit master weights.

Key idea Do the heavy matrix maths in 16 bits for speed, keep the weights and their updates in 32 bits for accuracy. With BF16 that's all you need. With FP16 you also scale the loss up so tiny gradients don't round to zero.

How it works

Two 16-bit formats

The Quantization chapter shows the bit layouts. For training, two 16-bit formats matter:

  • FP16 (half precision): 5 exponent bits, 10 mantissa bits. Fairly precise, but its range is narrow. The largest value is 65,504. The smallest positive normal value is about 6.1×10−56.1 \times 10^{-5}, and below that precision degrades until values under about 6×10−86 \times 10^{-8} become zero.
  • BF16 (bfloat16): 8 exponent bits, 7 mantissa bits. The same range as FP32 (up to about 3.4×10383.4 \times 10^{38}), but only two or three significant decimal digits.

Two failure modes follow. Underflow is when a number too small for the format becomes zero. Overflow is when a number too large becomes infinity. FP16 is prone to both. BF16 almost never underflows or overflows, but it rounds coarsely: in BF16, 1+0.001=11 + 0.001 = 1.

Gradients are often tiny, typically far smaller than the weights. In FP16 many of them underflow to zero, and the parts of the network they belong to stop learning. That is the problem loss scaling solves. Rounding matters most when you add a small number to a big one, which is exactly what a weight update does. That is the problem master weights solve.

Master weights

Keep the parameters θ\theta in FP32. Each step:

  1. Cast θ\theta to 16 bits for the forward and backward passes.
  2. Compute the gradients in 16 bits.
  3. Convert the gradients to FP32 and update the FP32 master copy: θ←θ−η ∇L\theta \leftarrow \theta - \eta \, \nabla L.

A weight of 1.0 with an update of 10−410^{-4} becomes 1.0001 in FP32. In BF16 the nearest representable numbers to 1 are about 0.996 and 1.008, so the update would be lost entirely. Over thousands of steps, those lost updates are the difference between learning and not learning.

Loss scaling (FP16 only)

Because of the The Chain Rule, every gradient is proportional to the loss. So multiply the loss by a large constant SS before the backward pass. Every gradient is then multiplied by SS too, which lifts small values out of the underflow zone. Before the update, divide the gradients by SS again (in FP32, where small numbers are safe):

∇θL=1S ∇θ(S⋅L)\nabla_\theta L = \frac{1}{S} \, \nabla_\theta (S \cdot L)

Worked example. A gradient of 2×10−82 \times 10^{-8} is below FP16's smallest representable value, so in FP16 it becomes 0. Multiply by S=65,536=216S = 65{,}536 = 2^{16}: it becomes 0.001310.00131, comfortably representable. Convert to FP32 and divide by 65,536: 1.9994×10−81.9994 \times 10^{-8}, the original value to within 0.03%.

Pick SS too large and the biggest gradients overflow to infinity. Dynamic loss scaling adjusts SS automatically. Start high (PyTorch's GradScaler starts at 2162^{16}). If any gradient is infinite or NaN, skip that step and halve SS. After a long run of good steps (2,000 by default), double SS. The scale settles just below the overflow point.

10-12 10-10 10-8 10-6 10-4 10-2 100 102 104 106 magnitude of a number (log scale) FP3210⁻³⁸ to 3×10³⁸ BF16same range FP166×10⁻⁸ to 65,504 reduced precision below this: 0 in FP16 Gradientsillustrative × 2¹⁶loss-scaled red part: lost in FP16
Fig. 2 Where the numbers live, on a logarithmic scale. FP16 covers roughly 10⁻⁸ to 6.5×10⁴, BF16 and FP32 cover about 10⁻³⁸ to 10³⁸. A typical band of gradient values (illustrative) partly falls below FP16's limit. Multiplying the loss by 2¹⁶ shifts the whole band about five orders of magnitude to the right, into FP16's range.

BF16 has FP32's range, so its gradients don't underflow and loss scaling is unnecessary. That simplicity is why BF16 became the default on hardware that supports it: Google TPUs, NVIDIA GPUs from the A100 (2020) onward, and recent CPUs. FP16 with loss scaling remains the choice on older GPUs such as the V100 or T4, which lack fast BF16.

Autocast: who runs in what

You don't decide the precision of each operation by hand. Autocast (in PyTorch, torch.autocast) is a context manager that picks a precision per operation:

  • Matrix multiplications, convolutions and linear layers run in 16 bits (they are fast on tensor cores and tolerate rounding).
  • Reductions and numerically sensitive operations such as softmax, log, normalisation and most loss functions run in FP32.

The model's parameters stay FP32. Autocast casts them on the fly inside the context.

TF32: free speed for FP32 code

NVIDIA's Ampere GPUs (2020) introduced TF32, a tensor-core mode that rounds FP32 inputs to 10 mantissa bits (FP16's precision with FP32's range) inside matrix multiplications, while accumulating in FP32. It speeds up unchanged FP32 code with almost no effect on training. In PyTorch it is switched on with torch.set_float32_matmul_precision("high").

FP8 and beyond

NVIDIA's H100 (2022) added FP8 tensor cores, again doubling peak throughput over BF16. FP8 training needs finer scaling: separate scale factors per tensor or per block, updated as training runs. NVIDIA's Transformer Engine library does this for transformer layers, and DeepSeek-V3 (December 2024) reported training a 671-billion-parameter mixture-of-experts model largely in FP8. As of late 2026, BF16 mixed precision is the safe default, FP8 is used by teams training at the largest scales, and 4-bit training formats such as NVFP4 on Blackwell GPUs are being explored.

The memory arithmetic of training

Mixed precision speeds up training and halves the memory for activations (the intermediate values saved for the backward pass), which often dominate memory for long sequences or large batches. It does not shrink the per-parameter state much. With the Adam optimizer each parameter needs:

Item Pure FP32 BF16 mixed precision
Weights used in forward/backward 4 bytes 2 bytes (BF16 copy)
Gradients 4 bytes 2 bytes
FP32 master weights (the weights above) 4 bytes
Adam first and second moments (FP32) 8 bytes 8 bytes
Total per parameter 16 bytes 16 bytes

So for parameters plus optimizer state alone, before any activations:

Model Inference, BF16 weights Full training with Adam (16 bytes/param)
1B 2 GB 16 GB
7B 14 GB 112 GB
70B 140 GB 1,120 GB

Even a 7B model can't be fully trained on one 80 GB GPU this way. That is why Distributed Training splits this state across GPUs (ZeRO and FSDP), why LoRA and Parameter-Efficient Fine-Tuning trains only a small fraction of the parameters, and why some setups keep Adam's moments in lower precision or use 8-bit optimizers.

In code

Three experiments on a CPU. First, what each format can represent. Second, loss scaling saving a tiny gradient. Third, training the same network with and without BF16 autocast.

import torch

# 1. What each format can represent
for dt in (torch.float32, torch.float16, torch.bfloat16):
    print(f"{str(dt):15} 1 + 0.001 = {(torch.tensor(1.0, dtype=dt) + 0.001).item():.6f}"
          f"   1e-8 -> {torch.tensor(1e-8, dtype=dt).item():.1e}"
          f"   70000 -> {torch.tensor(70000.0, dtype=dt).item():.0f}")

# 2. Loss scaling rescues a tiny gradient from underflow in fp16
g = torch.tensor(2e-8)                        # a typical tiny gradient value
print("fp16:", g.half().item(), "  scaled x65536 in fp16:", (g * 65536).half().item(),
      "  unscaled in fp32:", ((g * 65536).half().float() / 65536).item())

# 3. Autocast on CPU: matmuls run in bf16, the master weights stay fp32
torch.manual_seed(0)
X = torch.randn(2048, 64); y = (X[:, :8].sum(1, keepdim=True) > 0).float()
for use_bf16 in (False, True):
    torch.manual_seed(0)
    model = torch.nn.Sequential(torch.nn.Linear(64, 256), torch.nn.ReLU(), torch.nn.Linear(256, 1))
    opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
    for step in range(300):
        with torch.autocast("cpu", dtype=torch.bfloat16, enabled=use_bf16):
            logits = model(X)
        loss = torch.nn.functional.binary_cross_entropy_with_logits(logits.float(), y)
        opt.zero_grad(); loss.backward(); opt.step()
    print(f"bf16 autocast={use_bf16!s:5}  logits dtype {logits.dtype}  weight dtype "
          f"{model[0].weight.dtype}  final loss {loss.item():.4f}")

# torch.float32   1 + 0.001 = 1.001000   1e-8 -> 1.0e-08   70000 -> 70000
# torch.float16   1 + 0.001 = 1.000977   1e-8 -> 0.0e+00   70000 -> inf
# torch.bfloat16  1 + 0.001 = 1.000000   1e-8 -> 1.0e-08   70000 -> 70144
# fp16: 0.0   scaled x65536 in fp16: 0.0013103485107421875   unscaled in fp32: 1.9994331523776054e-08
# bf16 autocast=False  logits dtype torch.float32  weight dtype torch.float32  final loss 0.0063
# bf16 autocast=True   logits dtype torch.bfloat16  weight dtype torch.float32  final loss 0.0063

The first block shows each format's weakness: FP16 loses 10−810^{-8} and overflows at 70,000, while BF16 keeps both but can't see the 0.001 in 1+0.0011 + 0.001. The third block reaches the same loss either way. Inside autocast the layer outputs are BF16, while the weights the optimizer updates stay FP32. On a CPU, BF16 may not be faster. On a GPU with tensor cores it typically is, often close to twice as fast for large matrix multiplications.

The standard GPU recipe with FP16 adds a GradScaler (with BF16 you can leave the scaler out):

scaler = torch.amp.GradScaler("cuda")
for x, y in loader:
    with torch.autocast("cuda", dtype=torch.float16):
        loss = loss_fn(model(x), y)
    opt.zero_grad()
    scaler.scale(loss).backward()   # backward on loss * S
    scaler.step(opt)                # unscale; skip the step if any grad is inf/NaN
    scaler.update()                 # adjust S for the next step

Common pitfalls

  • Casting the whole model with .half() for training. That makes the master weights 16-bit too, and small updates vanish. Use autocast and keep the parameters FP32. (Calling .half() or .bfloat16() is fine for inference.)
  • FP16 without a GradScaler. Training may run but learn slowly or not at all, because many gradients are silently zero.
  • Clipping scaled gradients. With a GradScaler, call scaler.unscale_(opt) before clip_grad_norm_, or you clip values that are 65,536 times too large (gradient clipping).
  • Custom operations outside autocast's lists. A hand-written softmax or a large sum in 16 bits can lose precision or overflow. Compute such operations in FP32 explicitly.
  • Expecting a big speed-up on small models or CPUs. The gains come from tensor cores on large matrix multiplications. Tiny models are dominated by overheads, and many CPUs lack fast 16-bit units.

Watch out A sudden NaN or inf loss in FP16 training usually means overflow, often in attention scores or a custom layer. A GradScaler skips occasional bad steps, but if the loss scale keeps falling towards 1, something in the model is producing huge values. Switch to BF16 if your hardware supports it, or find the layer that overflows.

Where it leads

A bit of history

Researchers experimented with low-precision training long before it was mainstream, but the recipe used today was set out in Mixed Precision Training (Micikevicius and colleagues at NVIDIA and Baidu, published at ICLR 2018). It introduced the three ingredients: FP16 storage and arithmetic, an FP32 master copy of the weights, and loss scaling. It showed that a range of networks, from image classifiers to speech and translation models, trained to the same accuracy as in FP32. NVIDIA's V100 (2017) had the first tensor cores to make it fast.

Google Brain designed the bfloat16 format and used it in its TPUs, and a 2019 study by Intel and Facebook researchers (Kalamkar et al.) showed that BF16 trained a wide range of models without loss scaling. NVIDIA's A100 (2020) brought BF16 and TF32 to GPUs, and BF16 became the standard for training LLMs. FP8 formats for deep learning were proposed jointly by NVIDIA, Arm and Intel in 2022 and supported by the H100, and by 2025 the frontier was training in FP8 and experimenting with 4-bit formats.

Try it

  1. In the first block, find the smallest positive number that FP16 can store: try torch.tensor(6e-8, dtype=torch.float16) and smaller values.
  2. In BF16, compute 1 + x for x = 0.01, 0.005, 0.004 and 0.003. Where does the addition stop changing the result, and why does that matter for weight updates?
  3. Use the memory table to work out whether you could fully fine-tune a 3B model with Adam on a 24 GB GPU. What if you used LoRA instead?

Hint for 2: BF16 has 7 mantissa bits, so near 1 its steps are 2−7≈0.00782^{-7} \approx 0.0078. Anything smaller than half a step is rounded away.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You train in FP16 without a GradScaler. Training runs but barely learns. What is the likely cause?

  2. Why keep a 32-bit master copy of the weights?

  3. With dynamic loss scaling, a step produces an infinite gradient. What does the scaler do?

  4. Your GPU supports BF16. Do you need loss scaling?

  5. Switching from pure FP32 to BF16 mixed precision with Adam, how does per-parameter memory for weights, gradients and optimizer state change?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Paper

Mixed Precision Training

Micikevicius et al. (NVIDIA & Baidu) · 2017 · Intermediate · Free

The paper that set the standard recipe: FP16 arithmetic, an FP32 master copy of the weights, and loss scaling.

Docs

Train With Mixed Precision

NVIDIA · Intermediate · Free

NVIDIA's practical guide to mixed precision on tensor cores, with explanations of loss scaling and per-framework instructions.

Paper

A Study of BFLOAT16 for Deep Learning Training

Kalamkar et al. (Intel & Facebook) · 2019 · Advanced · Free

Shows across many models that BF16 trains to FP32 accuracy without loss scaling, thanks to its FP32-sized exponent.

Paper

FP8 Formats for Deep Learning

Micikevicius et al. (NVIDIA, Arm & Intel) · 2022 · Advanced · Free

Defines the E4M3 and E5M2 8-bit floating-point formats and shows they can train and run large models.

Book

Machine Learning Engineering Open Book

Stas Bekman · Advanced · Free

A practitioner's open book on the hardware and software of training and serving large models: GPUs, networking, storage and debugging.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/mlops/mixed-precision.md