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
- Builds on
- 27 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 27 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- NumPy and Array Thinking
- GPUs and Why AI Needs Them
- Supervised Learning
- Linear Regression
- Training, Validation and Test Sets
- The Perceptron
- Logistic Regression
- Overfitting and the Bias–Variance Tradeoff
- Regularization: L1 and L2
- Neural Networks
- Backpropagation
- Dropout and Regularizing Neural Networks
- PyTorch
- Optimizers: SGD, Momentum and Adam
- Training Neural Networks in Practice
- 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.
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 , and below that precision degrades until values under about become zero.
- BF16 (bfloat16): 8 exponent bits, 7 mantissa bits. The same range as FP32 (up to about ), 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, .
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 in FP32. Each step:
- Cast to 16 bits for the forward and backward passes.
- Compute the gradients in 16 bits.
- Convert the gradients to FP32 and update the FP32 master copy: .
A weight of 1.0 with an update of 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 before the backward pass. Every gradient is then multiplied by too, which lifts small values out of the underflow zone. Before the update, divide the gradients by again (in FP32, where small numbers are safe):
Worked example. A gradient of is below FP16's smallest representable value, so in FP16 it becomes 0. Multiply by : it becomes , comfortably representable. Convert to FP32 and divide by 65,536: , the original value to within 0.03%.
Pick too large and the biggest gradients overflow to infinity. Dynamic loss scaling adjusts automatically. Start high (PyTorch's GradScaler starts at ). If any gradient is infinite or NaN, skip that step and halve . After a long run of good steps (2,000 by default), double . The scale settles just below the overflow point.
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 and overflows at 70,000, while BF16 keeps both but can't see the 0.001 in . 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)beforeclip_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
NaNorinfloss 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
- Distributed Training: once each GPU is efficient, spread training across many of them, and shard the 16 bytes per parameter.
- Quantization: going further down in bits, mainly for inference.
- AI Hardware: GPUs, TPUs and Accelerators: how each GPU generation added lower-precision tensor cores, from FP16 (V100) to BF16 and TF32 (A100), FP8 (H100) and FP4 (Blackwell).
- LoRA and Parameter-Efficient Fine-Tuning: QLoRA combines a 4-bit frozen model with BF16 adapters.
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
- In the first block, find the smallest positive number that FP16 can store: try
torch.tensor(6e-8, dtype=torch.float16)and smaller values.- In BF16, compute
1 + xforx= 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?- 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 . Anything smaller than half a step is rounded away.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
PyTorch: Automatic Mixed Precision (torch.amp)
Reference for autocast and GradScaler, including which operations run in 16-bit and which stay in 32-bit.
Mixed Precision Training
The paper that set the standard recipe: FP16 arithmetic, an FP32 master copy of the weights, and loss scaling.
Train With Mixed Precision
NVIDIA's practical guide to mixed precision on tensor cores, with explanations of loss scaling and per-framework instructions.
A Study of BFLOAT16 for Deep Learning Training
Shows across many models that BF16 trains to FP32 accuracy without loss scaling, thanks to its FP32-sized exponent.
FP8 Formats for Deep Learning
Defines the E4M3 and E5M2 8-bit floating-point formats and shows they can train and run large models.
Machine Learning Engineering Open Book
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