All courses

Mixed-precision training

Explain bf16 matmuls with fp32 master weights and fp32 accumulation, and why fp16 also needs loss scaling. Identify which operations (softmax, norms, loss) are kept in higher precision.

Builds on: Floating point: fp32, fp16, bf16, int8, The LLM training loop

▶ Watch this lesson Start the whole course

What the animation says

Why not all 16-bit?

Sixteen-bit numbers take half the memory of thirty-two-bit ones, and move half the data. GPU matrix units also run bf16 matrix multiplies many times faster, and those multiplies are nearly all of training's arithmetic. So why not store and compute everything in bf16? Because things break. Tiny weight updates vanish, and long sums lose precision. With fp16, tiny gradients even underflow to zero. Mixed precision patches each weak spot right where it breaks.

Updates that vanish

Take one weight, exactly 1.0, nudged down by 0.00005 every step. In fp32, the nudge lands and the weight ticks down. But bf16 keeps only about eight significant bits. Just below 1, its neighbouring values are about 0.004 apart. A nudge of 0.00005 is far less than half that gap, so it rounds back to 1.0. After a thousand steps, where does the bf16 weight end up?

Sums that stall

The bf16 weight never moved: still exactly 1.0. The fp32 weight reached about 0.95. So updates go to fp32 master weights. Sums break the same way. Add 0.01 to a bf16 running total, 4096 times. The true sum is 40.96. The bf16 total stalls at 4.0. At 4, bf16 values are 0.031 apart, more than twice 0.01, so every addition rounds away. That's why matrix hardware adds its products in an fp32 accumulator, and rounds only the final output.

One mixed-precision step

Here is one mixed-precision step. First, cast the fp32 master weights down to bf16. Forward and backward: matmuls read bf16, accumulate in fp32, and write bf16. Softmax, the norm layers and the loss are upcast to fp32. Their exps, logs and long sums amplify rounding error. Then the gradient is converted to fp32, and the update is applied to the master weights. Now the colours are gone. Tap the two boxes that run in fp32.

fp16 needs loss scaling

bf16 reaches about ten to the minus thirty-eight, so it needs no help. fp16 is narrower. Its smallest positive value is about six times ten to the minus eight. Its largest is 65504. A gradient of two times ten to the minus eight stores as zero. So multiply the loss by S, here 65536. By the chain rule, every gradient scales too: now about 0.0013. Divide by S in fp32 before the update, and the tiny value is back. Same S, but now a gradient of 4. What happens?

Skip, halve, retry

It overflows: 262144 is past 65504, so the gradient is inf. Whenever any gradient is inf or NaN, skip the step and halve S. S becomes two to the fifteenth. Four times that is 131072, still inf. Skip again. Keep halving until four times S fits. Once steps succeed, raise S again slowly. Tap the first scale where the step goes through.

Why not train entirely in 16 bits?

16-bit numbers halve memory and data movement. GPU matrix units also run bf16/fp16 matmuls many times faster than fp32, and matmuls are nearly all of training's arithmetic. So why not store and compute *everything* in bf16? Because three things break. Tiny weight updates vanish. Long sums lose precision. With fp16 only, tiny gradients underflow to zero. Mixed precision fixes each problem exactly where it occurs.

Cheap precision for bulk, high where it counts

Use bf16 for the bulk of the work: matmul inputs and stored activations. Then patch the weak spots: 1. Keep fp32 **master weights**. The update is applied there, because $\eta g$ is often far smaller than a bf16 weight's rounding step. 2. Matmul hardware adds the products in an **fp32 accumulator** and rounds only the final output. 3. Compute softmax, norm statistics and the loss in fp32. Their exps, logs and sums over $T$, $d$ or $V$ terms amplify rounding error.

One mixed-precision training step

- Cast the fp32 master weights: $\theta_{16}=\text{bf16}(\theta)$. - Forward and backward: matmuls read bf16, accumulate in fp32 and write bf16. Softmax, LayerNorm/RMSNorm, log-softmax and $\mathcal L$ are upcast to fp32. - Update in fp32: $g=\text{fp32}(\nabla_\theta\mathcal L)$, then $\theta\leftarrow\theta-\eta g$. - **fp16 only, loss scaling:** backprop $S\mathcal L$, then compute $g=\nabla_\theta(S\mathcal L)/S$ in fp32. If any $g$ is inf or NaN, skip the step and halve $S$. Otherwise raise $S$ slowly.

Loss scaling with real fp16 numbers

fp16's smallest positive value is $\approx6\times10^{-8}$ and its largest is 65504. A gradient of $2\times10^{-8}$ therefore stores as 0. Scale the loss by $S=2^{16}=65536$. By the chain rule every gradient is also scaled by $S$: $2\times10^{-8}\cdot65536\approx1.3\times10^{-3}$, which fp16 can represent. Unscaling in fp32 gives $1.3\times10^{-3}/65536=2\times10^{-8}$ again. The risk runs the other way too. A gradient of 4 becomes $262144>65504$, which is inf. So you skip that step and halve $S$ to $2^{15}$. That still overflows ($4\cdot2^{15}=131072$), so the next step skips again and halves $S$ again. This repeats until $4S\le65504$, at $S=2^{13}$. bf16 reaches $\sim10^{-38}$, so it needs no scaling.

Watch bf16 lose updates and sums

numpy has no bf16, so `bf16()` rounds fp32 to bf16's 8 significant bits. - **Weight updates:** a weight of 1.0 gets −5e−5 per step. Near 1, bf16's rounding step is about 0.004, so every update rounds away. The fp32 master weight moves to ≈0.95. - **Long sums:** a bf16 running sum of 0.01s stalls at 4.0, where the rounding step (0.031) is more than twice 0.01. The true sum is 40.96.
import numpy as np
def bf16(x):  # round fp32 to nearest bf16
    b = np.asarray(x, np.float32).view(np.uint32)
    b = (b + 0x7FFF + ((b >> 16) & 1)) & 0xFFFF0000
    return b.astype(np.uint32).view(np.float32)
w16, w32, s16 = bf16(1.0), np.float32(1.0), bf16(0.0)
for _ in range(1000):                     # 1000 steps of -5e-5
    w16 = bf16(w16 - np.float32(5e-5))    # bf16 weight
    w32 = w32 - np.float32(5e-5)          # fp32 master weight
for _ in range(4096):                     # 4096 terms of 0.01
    s16 = bf16(s16 + np.float32(0.01))    # bf16 accumulator
print(w16, w32, s16)                      # 1.0  ~0.95  4.0

What to remember

Do matmuls with bf16 inputs and fp32 accumulation. Keep fp32 master weights for the update, and compute softmax, norms and the loss in fp32. fp16 also needs loss scaling: multiply the loss by $S$ so tiny gradients don't underflow, unscale in fp32, and skip the step and shrink $S$ whenever an inf appears.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.