On this page
A weight sits at 1.0. The optimizer subtracts 0.0001, and in naive 16-bit storage the weight stays 1.0: no exception, no warning, just silently stalled learning. On another batch, an activation near 100,000 crosses FP16's 65,504 ceiling, flips to Inf, and poisons the step.
Mixed precision training avoids both traps by separating compute from persistent state: fast 16-bit Tensor Core matrix multiplications paired with FP32 parameters, optimizer moments, and sensitive reductions.[1] In PyTorch Automatic Mixed Precision (AMP), parameters remain in FP32 while autocast dispatches eligible operations to BF16 or FP16.[2]
A floating-point number has two limits
A finite normal binary float packs a sign bit , exponent , and fraction :
Think of the exponent as picking a ruler and the fraction as its tick marks. Every ruler carries the same number of ticks, so spacing doubles at every power of two. Two independent properties follow: exponent bits set dynamic range (underflow/overflow limits), while fraction bits set nearby resolution (machine epsilon at 1.0). FP16 and BF16 split their 15 remaining bits in opposite ways:
| Format | Sign | Exp (bias) | Frac | Positive normal range | Epsilon ( at 1.0) |
|---|---|---|---|---|---|
| FP32 | 1 | 8 (127) | 23 | ||
| FP16 | 1 | 5 (15) | 10 | (subnormal to ) | |
| BF16 | 1 | 8 (127) | 7 |
BF16 matches FP32's exponent range (some accelerators like Cloud TPU flush BF16 subnormals to zero[3]) at the cost of 8x coarser spacing near 1.0 than FP16 and 65,536x coarser than FP32.

Inspect both neighbors before judging an update
Adding 0.0001 to a weight at 1.0 vanishes in both FP16 and BF16 even though both represent 0.0001 standalone. This is swamping: the sum rounds back to the stored weight.
Because grid spacing doubles at 1.0, the rounding cell is asymmetric: the gap below 1.0 is half the gap above 1.0, so subtraction survives at half the magnitude required for addition:
| Format | Gap below 1.0 | Gap above 1.0 | Half-gap down | Half-gap up |
|---|---|---|---|---|
| FP16 | ||||
| BF16 |
Inspect both neighbors with torch.nextafter and verify that 1e-4 disappears in both 16-bit formats while 0.0003 (FP16) and 0.0025 (BF16) cross their downward half-gaps:[4][5]
import torch
for label, dtype, dec in (("FP16", torch.float16, 0.0003), ("BF16", torch.bfloat16, 0.0025)):
one = torch.tensor(1.0, dtype=dtype)
below = torch.nextafter(one, torch.tensor(0.0, dtype=dtype))
above = torch.nextafter(one, torch.tensor(float("inf"), dtype=dtype))
print(f"{label}: down={1.0 - below.item():.6f}, up={above.item() - 1.0:.6f}, "
f"minus_{dec}={(one - torch.tensor(dec, dtype=dtype)).item():.6f}, "
f"minus_1e-4={(one - torch.tensor(1e-4, dtype=dtype)).item():.6f}")FP16: down=0.000488, up=0.000977, minus_0.0003=0.999512, minus_1e-4=1.000000
BF16: down=0.003906, up=0.007812, minus_0.0025=0.996094, minus_1e-4=1.000000
Range decides whether gradients exist at all
Swamping erases updates added to a larger weight; underflow and overflow destroy standalone values outside the exponent range. Casting [1.2e-8, 1.0e5] to FP16 produces [0.0, inf] (1.2e-8 sits below half FP16's smallest subnormal 5.96e-8 and 1e5 > 65,504), whereas BF16 keeps both finite as [1.20e-8, 9.98e4] (with 7-bit rounding), which is why BF16 rarely requires loss scaling.[7]
FP16 uses loss scaling to rescue small gradients
Because differentiation is linear, loss scaling shifts tiny FP16 gradients upward before backpropagation writes them:[1]
Multiplying by adds 10 binary exponent steps, moving into representable FP16 (1.23e-5) before dividing by in FP32 to recover within 0.08% relative error.
Dynamic loss scaling as a feedback controller
torch.amp.GradScaler automates with a feedback loop:[1][8][2]
- Start high () with clean-step counter .
- Run forward under
autocast, then backpropagatescaler.scale(loss). - Call
scaler.unscale_(optimizer)to divide gradients by in FP32 and scan forInf/NaN. - Non-finite gradient found: skip
optimizer.step()atomically (freezing weights and Adam moments), halve , and reset . - All gradients finite: clip norms if needed, apply
optimizer.step(), and increment ; when hitsgrowth_interval(default2000), double and reset .
Watch GradScaler rescue 1.2e-8, skip a spiked step atomically, halve the scale to 512, and double back to 1024 after two clean steps:
import torch
model = torch.nn.Linear(1, 2, bias=False)
with torch.no_grad():
model.weight.fill_(1.0)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
scaler = torch.amp.GradScaler("cpu", init_scale=1024, growth_interval=2)
for name, large_grad in (("quiet", 0.02), ("spike", 100.0), ("quiet_again", 0.02), ("quiet_twice", 0.02)):
optimizer.zero_grad(set_to_none=True)
before = model.weight.detach().clone()
with torch.autocast("cpu", dtype=torch.float16):
loss = (model(torch.ones(1, 1)).float() * torch.tensor([1.2e-8, large_grad])).sum()
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
grad = model.weight.grad.clone()
if torch.isfinite(grad).all():
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(optimizer)
scaler.update()
step = int(optimizer.state[model.weight]["step"])
print(f"{name:<11}: grad={[round(v, 4) if abs(v) > 1e-4 else f'{v:.2e}' for v in grad.flatten().tolist()]}, "
f"updated={not torch.equal(model.weight, before)}, adam_step={step}, next_scale={scaler.get_scale():.0f}")quiet : grad=['1.20e-08', 0.02], updated=True, adam_step=1, next_scale=1024
spike : grad=['1.20e-08', inf], updated=False, adam_step=1, next_scale=512
quiet_again: grad=['1.20e-08', 0.02], updated=True, adam_step=2, next_scale=512
quiet_twice: grad=['1.20e-08', 0.02], updated=True, adam_step=3, next_scale=1024
Deep dive: multiple optimizers and non-finite forward losses
Two GradScaler subtleties matter in complex loops:
- Multiple optimizers skip independently: Each
scaler.step(opt)checks only its own.gradtensors, followed by one sharedscaler.update().[9] If two optimizers require joint atomicity, check finiteness across both explicitly. GradScalerchecks.grad, notloss: An infinite additive constant inlosscan leave finite derivatives, so checktorch.isfinite(loss)before backward.[10]
Compute low, update high
In a CUDA AMP loop, keep weights in FP32, wrap only forward and loss in torch.autocast, keep .backward() outside autocast, and enable GradScaler for FP16 (check torch.isfinite(loss) under BF16 too):[2]
dtype = torch.bfloat16 # or torch.float16 with GradScaler enabled
scaler = torch.amp.GradScaler("cuda", enabled=(dtype == torch.float16))
for batch, target in dataloader:
optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type="cuda", dtype=dtype):
loss = criterion(model(batch.cuda()), target.cuda())
if not torch.isfinite(loss).all().item():
raise FloatingPointError("Non-finite forward loss")
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(optimizer)
scaler.update()Autocast is op-specific: matmuls run in 16-bit while reductions like cross_entropy widen to FP32, backward mirrors forward dtypes, and .grad accumulates in FP32. Never call model.half() with AMP.
GradScaler and gradient accumulation share one optimizer step
Across accumulated micro-batches, hold one constant loss scale: run scaler.scale(micro_loss).backward() per micro-batch, and run unscale_, clip, step, update, and LR scheduler steps once per optimizer boundary (saving scaler.state_dict() in checkpoints).[9]
When micro-batches hold unequal active token counts, divide each micro-batch's summed token loss by the window's total active tokens rather than averaging per-micro-batch means:
import torch
targets = (torch.tensor([0.0]), torch.tensor([2.0, 2.0, 2.0]))
total_tokens = sum(y.numel() for y in targets)
def accumulated_gradient(mode: str) -> float:
w = torch.tensor(1.0, requires_grad=True)
for y in targets:
losses = (w - y).square()
(losses.mean() / len(targets) if mode == "mean_of_means" else losses.sum() / total_tokens).backward()
return w.grad.item()
w = torch.tensor(1.0, requires_grad=True)
(w - torch.cat(targets)).square().mean().backward()
print(f"full_batch={w.grad.item():.1f}, mean_of_means={accumulated_gradient('mean_of_means'):.1f}, "
f"token_weighted={accumulated_gradient('token_weighted'):.1f}")full_batch=-1.0, mean_of_means=0.0, token_weighted=-1.0
Account for memory before claiming savings
Ordinary AMP does not halve total memory: weights (4 B), gradients (4 B), and AdamW moments (8 B) stay FP32 (16 bytes/param, matching the FP32 master-weight recipe's 16 B/param), while only eligible saved activations halve from 4 B to 2 B (and FP32 ops still save FP32 tensors, inspectable via saved_tensors_hooks[11]).
| Component | Pure FP32 | FP32 weights + AMP | FP32 master-weight recipe |
|---|---|---|---|
| Weights + Gradients | 8 B () | 8 B (, FP32) | 4 B 16-bit + 4 B FP32 master |
| AdamW moments () | 8 B () | 8 B (, FP32) | 8 B (, FP32) |
| Static model state | 16 B / param | 16 B / param | 16 B / param (+2 B if FP32 grad replaces 16-bit grad) |
| Eligible saved activations | 4 B / value | 2 B / value | 2 B / value |
With 100M parameters (1.49 GiB static) and 800M saved activation values, halving activation bytes from 2.98 GiB to 1.49 GiB lowers total memory from 4.47 GiB to 2.98 GiB, a 33.3% reduction ((4.47 - 2.98) / 4.47), not 50%. Profile peak allocated memory on real steps,[12][1] and shard persistent FP32 state with ZeRO or FSDP.[13][14]

Distributed jobs add a communication dtype
Distributed reduction dtype (reduce_dtype in FSDP) is independent of compute_dtype.[15] Shipping a 100M-parameter gradient payload drops from 0.37 GiB in FP32 to 0.19 GiB in BF16 (50% less bandwidth), yet watch accumulation precision inside the collective: if three workers contribute [512, 3, -512], adding left-to-right in BF16 rounds 512 + 3 = 515 to 516, yielding 4 instead of 3. Keep the running sum in FP32 before storing the final reduced result, and always log compute_dtype, update_storage_dtype, and reduce_dtype separately.
Choose precision from controlled runs
Hold model, data, seeds, batch shape, evaluation, and hardware fixed when comparing recipes, recording TF32 flags and synchronizing warmed-up GPU timers.[16][17] Watch pure FP16 parameter storage stall at its initial MSE (0.00010000) while FP32 parameters with BF16 autocast track FP32 cleanly:
import torch
def run_steps(mode: str, steps: int = 40) -> float:
torch.manual_seed(0)
x, target = torch.eye(4), torch.full((4, 4), 0.99)
dtype = torch.float16 if mode == "pure_fp16" else torch.float32
w = torch.nn.Parameter(torch.full((4, 4), 1.0, dtype=dtype))
opt = torch.optim.SGD([w], lr=0.05)
for _ in range(steps):
opt.zero_grad()
if mode == "amp_bf16":
with torch.autocast("cpu", dtype=torch.bfloat16):
loss = ((x @ w) - target).float().square().mean()
else:
loss = ((x.to(dtype) @ w) - target.to(dtype)).square().mean()
loss.backward()
opt.step()
return ((x @ w.float()) - target).square().mean().item()
for mode in ("fp32", "amp_bf16", "pure_fp16"):
print(f"{mode:<10} final_mse={run_steps(mode):.8f}")fp32 final_mse=0.00006056
amp_bf16 final_mse=0.00005917
pure_fp16 final_mse=0.00010000RL can expose a BF16 train-inference mismatch
In RL fine-tuning, one inference stack generates rollouts while a training stack recomputes log-probabilities. Because BF16 ticks are 8x wider than FP16, minor kernel rounding differences can push nearby logits across a BF16 tick, shifting token probabilities enough to flip a sampled token under the same random draw. Qi et al. found scaled FP16 reduced this train-inference divergence across their tested RL stacks.[18]
import torch
def policy_gap(dtype: torch.dtype, first: float, second: float) -> float:
p1 = torch.softmax(torch.tensor([first, 1.0]).to(dtype).float(), dim=0)[0]
p2 = torch.softmax(torch.tensor([second, 1.0]).to(dtype).float(), dim=0)[0]
return abs(p1.item() - p2.item())
for first, second in ((1.0038, 1.0040), (1.0004, 1.0006)):
print(f"logits={first},{second}: FP16_gap={policy_gap(torch.float16, first, second):.7f}, "
f"BF16_gap={policy_gap(torch.bfloat16, first, second):.7f}")logits=1.0038,1.004: FP16_gap=0.0000000, BF16_gap=0.0019531
logits=1.0004,1.0006: FP16_gap=0.0002441, BF16_gap=0.0000000
Evaluate FP8 after measuring the lower-precision path
On Hopper/Blackwell GPUs, FP8 halves operand bytes again via two complementary OCP formats:[19][20] E4M3 (max 448, no Inf, favored for forward activations/weights) and E5M2 (max 57,344, keeps Inf, favored for backward gradients).
| FP8 recipe | Scaling mechanism | Trade-off |
|---|---|---|
| Current scaling | Live tensor amax in FP32 | Reduction overhead unless fused |
| Delayed scaling | Predicted from amax history | Sudden spikes saturate before update |
| MXFP8 block scaling | One E8M0 power-of-two scale per 32 values[21] | Tighter outlier isolation; needs native block kernels |
Transformer Engine provides hybrid E4M3/E5M2 and MXFP8 recipes.[22][23] Watch for saturating conversion: overflowing 448 in E4M3 can clamp silently to 448 instead of NaN, so log saturation rates beside throughput and held-out accuracy.[19]

When a precision change goes wrong
- Loss flatlines with finite gradients: Parameters are stored in 16-bit and swamping updates; check
optimizer.param_groupsdtypes. - FP16 trains slower or worse than FP32: Unscaled small gradients underflow; enable
GradScalerand log skipped steps. - Erratic FP16 steps: Clipping happened before
scaler.unscale_(optimizer); always unscale, then clip, then step. - Effective batch collapses:
step()/update()ran inside gradient accumulation; move them to the optimizer boundary. - Scale keeps dropping: Persistent backoff signals oversized values; forward overflows cannot be fixed by smaller loss scales.
- Memory fell <50% or network stayed high: Static FP32 state stays constant under AMP, and BF16 compute can still transmit FP32 gradients; verify
reduce_dtypeexplicitly.