FP16 OVERFLOW
Sixteen bits, 65,504, and a loss that turns to NaN
Ojaline's ranking model trains in fp16 with PyTorch's dynamic loss scaling. As training goes on, the largest activation in one layer climbs past 65,504. What happens?
fp16 has 5 exponent bits and 10 mantissa bits. Its largest finite value is 65,504, its smallest normal value 2−14, and its subnormals reach down to 2−24 ≈ 5.96 × 10−8. Training sits at both edges at once. Gradients are tiny, so many round to zero. An activation or a scaled gradient can pass 65,504 and round to infinity. One inf in a sum gives inf, inf − inf gives NaN, and NaN spreads to everything it touches.
If floats are new to you, start with money in floating point: the same rounding, with fewer bits.
with torch.autocast('cuda', dtype=torch.float16):
loss = model(batch)
loss.backward() # fp16 grads: < 2^-25 round to 0, > 65504 become inf
optimizer.step() # an inf gradient makes the weights inf, then NaNscaler = torch.amp.GradScaler('cuda') # init_scale 2**16, x0.5 on inf, x2 after 2000 clean
with torch.autocast('cuda', dtype=torch.float16):
loss = model(batch)
scaler.scale(loss).backward() # gradients x scale: tiny ones survive
scaler.step(optimizer) # unscales; skips the step if any grad is inf/NaN
scaler.update() # halves the scale after a skip, grows it after clean steps
# Or, on hardware with bf16: fp32's exponent range, no scaler needed
with torch.autocast('cuda', dtype=torch.bfloat16):
loss = model(batch)
loss.backward(); optimizer.step() Watch the three invariants. FP16, NO LOSS SCALE keeps the weights finite but turns no non-zero gradient rounds to zero red from step 1: two of the eight gradients are too small for fp16 and round to zero, and a third joins them as the gradients shrink. FP16, FIXED LOSS SCALE lifts them, then the bad batch at step 5 overflows (1.5 × 65,536 = 98,304), nothing checks, and the weights go to inf and then NaN. FIX: DYNAMIC LOSS SCALE skips that one step, halves the scale and carries on. FP16 + DYNAMIC, ACTIVATIONS GROW breaks the third invariant: from step 7 the forward pass overflows and every step is skipped. FIX: BF16 holds the same activations.
Micikevicius et al. (ICLR 2018) introduced mixed-precision training with three techniques: an fp32 master copy of the weights, loss scaling, and fp32 accumulation of fp16 products. In their Mandarin speech model about 5% of weight gradients had exponents below −24, and updating fp16 weights directly cost 80% relative accuracy. Their SSD detector diverged without loss scaling and matched fp32 with a scale of 8; across their networks, constant scales from 8 to 32K worked. They state the rule this lesson runs on: a scale is safe as long as it does not cause overflow, and when one is detected you can skip the weight update and move on.
The FIXED LOSS SCALE run multiplies every gradient by one constant. Too small and the tiniest gradients still round to zero; too large and the bad batch at step 5 overflows to inf. Find a fixed scale that gets through all ten steps with no gradient lost and finite weights.
GOAL: all ten steps run, no gradient rounds to zero, weights finite
A fixed scale has to fit a window you do not know in advance. Dynamic loss scaling finds it at run time. PyTorch’s GradScaler (PyTorch 2.15 documentation and source) starts at init_scale=65536.0, multiplies by backoff_factor=0.5 when an iteration has inf or NaN gradients and skips that optimiser step, and multiplies by growth_factor=2.0 after growth_interval=2000 consecutive clean iterations. The sim’s growth interval defaults to 3 so you can see it grow in ten steps. The gradients are unscaled by the scale the backward pass used, in fp32, before clipping or the update.
Write scalerStep(s, grads), one step of a dynamic loss scaler. s is { scale, good, interval }; grads is an array of the scaled gradients from the backward pass (numbers that may be Infinity, -Infinity or NaN). Rules: if any gradient is not finite, return null (skip the step), multiply s.scale by 0.5 and set s.good to 0. Otherwise return a new array of the gradients divided by the scale they were computed with (the scale before this call changes it), add 1 to s.good, and when s.good reaches s.interval, multiply s.scale by 2 and set s.good to 0. The grader checks the returned value and s.scale after every call.
Loss scaling cannot rescue the forward pass. If an activation passes 65,504 every step, the scaler skips every step and the scale keeps halving; PyTorch’s AMP notes warn that models pretrained in bf16 may not fit fp16’s range, and that the scale can then fall below 1. bf16 is the fix for that. It keeps fp32’s 8 exponent bits, so its range is fp32’s (up to about 3.39 × 1038), and pays with 7 mantissa bits: a relative rounding error up to 2−8 ≈ 0.39%, against fp16’s 0.05%. That is too coarse for weight updates (the last row of the sim: 1 + 0.003 is 1 in bf16), so the master weights and the optimiser stay in fp32. BLOOM’s team kept an fp32 copy of the weights and accumulated in fp32 for the same reason. bf16 needs hardware that supports it; they could choose it because they were training on A100s.
What the sim simplifies. Eight numbers stand in for a layer’s gradients and one number for its largest activation; real runs have millions, and one inf among them is enough. The rounding is exact: round to nearest, ties to even, with subnormals and overflow to infinity, which is what a GPU does when it stores fp16 or bf16. Strictly, values at or below 2−25 round to zero and values between that and 2−24 round up to 2−24; Micikevicius et al. say “smaller than 2−24” for short. The activations grow on a fixed schedule here; in a real run they grow with the weights, which is the learning rate lesson’s subject. The fine-tuning chapter loads its model in bf16 for these reasons.
Any training or fine-tuning run with torch.autocast, DeepSpeed or Megatron: a loss that prints NaN, a GradScaler scale that keeps falling (log scaler.get_scale()), many skipped steps, or an fp16 fine-tune of a bf16-pretrained model that diverges at once. GPUs without bf16 support leave you with fp16 and a scaler.
“Your mixed-precision run's loss went to NaN. What do you check?” Say where fp16 runs out: 65,504 at the top, 2^-24 at the bottom. Separate a gradient overflow (the scaler skips the step and backs off; fine if rare) from a forward overflow (every step skips; switch to bf16 or find the layer whose activations grow). Explain loss scaling, unscaling before clipping, the GradScaler defaults, and why weights stay in fp32 even with bf16.