Mixed Precision Training Explained: FP16 vs BF16, Loss Scaling, and PyTorch Autocast
Why training in 16-bit floats can silently zero your gradients, how loss scaling and FP32 master weights fix it, and when bfloat16 lets you skip the scaler entirely.

Most deep learning frameworks default to 32-bit floats, and most modern accelerators can do far more arithmetic per second on 16-bit numbers. Halving the width of every tensor also halves the bytes moved through memory, and memory traffic is often what limits training speed. The catch is that 16 bits leave much less room for numbers, and a training run can lose information without any error message. Mixed precision training is the set of techniques that captures the speed while keeping the model's accuracy where it would be in full precision.
This explainer walks through the two common 16-bit formats, the three failure modes they introduce, the fixes that the original mixed precision paper proposed, and the way PyTorch packages those fixes into autocast and GradScaler. A short script at the end reproduces each failure on a laptop CPU.
Three formats, one trade-off
Every floating point number spends its bits on a sign, an exponent and a mantissa. Exponent bits decide how large and how small a value can be. Mantissa bits decide how finely values are spaced near any given magnitude. The formats differ only in how they split the budget:
- FP32 (single precision): 1 sign, 8 exponent, 23 mantissa bits. Huge range and fine spacing; the safe baseline.
- FP16 (IEEE half precision): 1 sign, 5 exponent, 10 mantissa bits. The largest finite value is 65,504, the smallest normal value is 2^-14 (about 6.1e-5), and subnormals reach down to 2^-24 (about 6e-8). Anything smaller in magnitude rounds to zero.
- BF16 (bfloat16, from Google Brain): 1 sign, 8 exponent, 7 mantissa bits. It keeps the FP32 exponent width, so its range matches FP32, but its spacing is about eight times coarser than FP16's.
Put simply, FP16 buys precision at the cost of range, and BF16 buys range at the cost of precision. Google's TPU team chose the BF16 split because, in their experience, networks are more sensitive to exponent width than to mantissa width. That single design decision explains almost every practical difference you will see between the two.
What actually goes wrong in 16 bits
1. Small gradients underflow to zero
Gradients for activations deep in a network are frequently tiny. In the mixed precision paper by Micikevicius and colleagues, a histogram of activation gradients from an SSD object detector showed that a meaningful slice of values sat below what FP16 can represent, including a band between 2^-27 and 2^-24 that the model actually needed. Training that detector in plain FP16 diverged. Those values were not wrong; they simply vanished when stored in half precision.
2. Small updates disappear when added to large weights
Even when a gradient survives, the optimizer adds learning rate times gradient to the weight. With a 10-bit mantissa, the gap between adjacent FP16 values near 1.0 is about 0.001. Add 0.0001 to a weight of 1.0 and the result rounds straight back to 1.0. The paper frames this as a ratio: once a weight is more than about 2,048 times larger than its update, the update is shifted out of the mantissa during addition. On a Mandarin speech model, updating FP16 weights directly cost roughly 80 percent relative accuracy compared with the FP32 baseline. BF16, with only 7 mantissa bits, is even more exposed to this problem than FP16.
3. Large values overflow
At the other end, FP16 cannot hold anything above 65,504. Large activations, unnormalized sums, or the exponent inside a softmax can overflow to infinity, and one infinity quickly turns into NaN across the whole step. BF16 rarely hits this wall because its range matches FP32.
The three fixes from the original paper
- Keep an FP32 master copy of the weights. Forward and backward passes use a 16-bit copy, but the optimizer applies updates to the 32-bit master, so tiny updates accumulate instead of rounding away. This adds memory for the weights, but activations usually dominate training memory, so the total still drops substantially.
- Scale the loss before backpropagation. Multiplying the loss by a factor S multiplies every gradient by S through the chain rule, lifting small values into FP16's representable range. Gradients are divided by S again before clipping and before the weight update, so the math is unchanged.
- Accumulate in FP32. Matrix multiplies take 16-bit inputs but sum their products in 32 bits, and large reductions such as softmax sums and normalization statistics run in FP32 as well, even though the tensors stored between layers stay in 16 bits.
Picking S by hand works: the paper's networks used factors from 8 up to 32,768, and the SSD detector matched its FP32 accuracy with a factor of just 8. The rule of thumb is that S times the largest gradient magnitude should stay below 65,504. In practice almost everyone uses dynamic scaling instead, which NVIDIA's training guide describes as a simple feedback loop: start with a large scale, and if any gradient comes back as infinity or NaN, skip that update and shrink the scale; after a long run of clean steps, try a larger scale again.
How PyTorch packages this: autocast and GradScaler
PyTorch implements fix 3 and parts of fix 1 with torch. autocast, and fix 2 with torch. amp. GradScaler. Model parameters stay in FP32, which gives you master weights for free. Inside an autocast region, each operation is cast according to a per-op list. On CUDA, matrix-heavy ops such as linear, matmul, bmm and the conv layers run in FP16, while numerically sensitive ops such as softmax, log_softmax, layer_norm, exp, sum and cross_entropy run in FP32. On CPU, the default autocast dtype is bfloat16 rather than float16.
GradScaler implements dynamic loss scaling. Its documented defaults start the scale at 65,536, multiply it by 2 after 2,000 consecutive clean steps, and halve it whenever an infinity or NaN appears. Calling scaler. step(optimizer) unscales the gradients and runs the optimizer only if they are all finite; otherwise that step is skipped. The loop below runs as written on CPU with BF16 and on a CUDA GPU with FP16:
import torch
from torch import nn
device = "cuda" if torch.cuda.is_available() else "cpu"
amp_dtype = torch.float16 if device == "cuda" else torch.bfloat16
model = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10)).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
loss_fn = nn.CrossEntropyLoss()
# Scaling only matters for float16 gradients; disabled, the scaler is a pass-through.
scaler = torch.amp.GradScaler(device, enabled=(amp_dtype == torch.float16))
for step in range(100):
x = torch.randn(32, 64, device=device)
y = torch.randint(0, 10, (32,), device=device)
optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type=device, dtype=amp_dtype):
logits = model(x) # linear layers run in the low-precision dtype
loss = loss_fn(logits, y) # cross_entropy is autocast to float32
scaler.scale(loss).backward() # backward runs outside autocast
scaler.unscale_(optimizer) # real gradient values, needed before clipping
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(optimizer) # skips the step if any gradient is inf/NaN
scaler.update() # grows or shrinks the scale for next time
if step % 25 == 0:
print(step, logits.dtype, loss.dtype, round(loss.item(), 4))
On a CPU run, the printed dtypes confirm the per-op policy: the logits come out as torch. bfloat16 while the loss is torch. float32. Note the order of the gradient calls. Clipping must see unscaled gradients, otherwise a max_norm of 1.0 would be compared against values inflated by tens of thousands, so unscale_ comes first. Calling unscale_ twice before a step raises an error, and scaler. step will not unscale a second time.
A worked example you can run
The three failure modes are easy to reproduce with scalar tensors. The script below stores a tiny gradient of 1e-8, the same gradient multiplied by a loss scale of 1,024, and the result of adding an update of 1e-4 to a weight of 1.0, in each format:
import torch
grad = 1e-8 # a tiny activation gradient
scale = 1024.0 # a loss-scale factor (2**10)
update = 1e-4 # learning rate times gradient, added to a weight of 1.0
for dt in (torch.float32, torch.float16, torch.bfloat16):
raw = torch.tensor(grad, dtype=dt).item()
scaled = torch.tensor(grad * scale, dtype=dt).item()
stepped = (torch.tensor(1.0, dtype=dt) + torch.tensor(update, dtype=dt)).item()
print(f"{str(dt):15} raw={raw:.3e} scaled={scaled:.3e} "
f"1.0+1e-4={stepped:.6f} max={torch.finfo(dt).max:.4g}")
torch.float32 raw=1.000e-08 scaled=1.024e-05 1.0+1e-4=1.000100 max=3.403e+38
torch.float16 raw=0.000e+00 scaled=1.025e-05 1.0+1e-4=1.000000 max=6.55e+04
torch.bfloat16 raw=1.001e-08 scaled=1.025e-05 1.0+1e-4=1.000000 max=3.39e+38
Read the output column by column. In FP16 the raw gradient becomes exactly zero, and scaling by 1,024 rescues it. In BF16 the raw gradient survives without any scaling, thanks to the FP32-sized exponent. In both 16-bit formats, the weight update vanishes, which is precisely why the optimizer must update an FP32 copy of the weights no matter which format you pick.
FP16 or BF16: a decision checklist
- Your hardware has fast BF16 math: prefer BF16. Range matches FP32, so you can usually drop the GradScaler. Google describes BF16 on TPUs as close to a drop-in replacement for FP32 that needs no loss scaling.
- Your hardware only accelerates FP16: use FP16 with dynamic loss scaling through GradScaler. Do not skip the scaler.
- You are fine-tuning a model that was pretrained in BF16: be careful with FP16. The PyTorch docs warn that such models can produce values beyond FP16's 65,504 limit, which can push the loss scale below 1 and stall training.
- Your task needs fine numerical resolution in stored activations: FP16's extra mantissa bits can matter, so benchmark both formats against an FP32 baseline.
- You want the Tensor Core speedup on NVIDIA GPUs: keep matrix dimensions such as hidden sizes, channel counts, vocabulary size and batch size at multiples of 8, as NVIDIA's guide recommends.
Common mistakes
- Calling model. half() and calling it mixed precision. That stores the weights in 16 bits, removes the FP32 master copy, and reintroduces the vanishing-update problem. Let autocast handle casts instead.
- Running backward inside the autocast block. PyTorch recommends wrapping only the forward pass and the loss; backward ops automatically run in the dtype their forward ops used.
- Clipping gradients before unscaling them, which silently turns clipping into a no-op or an extreme clamp.
- Using nn. BCELoss or binary_cross_entropy under autocast. PyTorch raises an error for these; switch to BCEWithLogitsLoss, which is numerically safer.
- Unscaling and stepping on every micro-batch during gradient accumulation. The scale should stay fixed while gradients accumulate, with unscale_, step and update called only at the accumulation boundary.
- Never comparing against a full-precision run. A short FP32 baseline is the only way to know whether a small accuracy gap comes from precision or from something else.
When not to bother
Mixed precision pays off when large matrix multiplies and memory bandwidth dominate the step. A tiny model, a data loader that is already the bottleneck, or hardware without fast 16-bit units may see little gain while still taking on the debugging cost of skipped steps and dtype surprises. Some numerically delicate workloads, such as certain linear algebra or long cumulative sums, belong in FP32 regardless, which is why autocast keeps those ops there. Measure step time and final accuracy before and after; if neither improves, the simpler FP32 setup wins.
The core idea fits in one line: do the heavy arithmetic in 16 bits, but keep anything that accumulates, reduces or updates in 32 bits. FP16 needs loss scaling to protect small gradients; BF16 trades that requirement for coarser spacing. Either way, the FP32 master weights are not optional.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter