Mixed Precision: float16 and bfloat16
Every number in a neural network is normally a 32-bit float. Halving that to 16 bits halves the memory for activations and weights, and on modern accelerators 16-bit matrix multiplication runs several times faster. The catch is that 16-bit floats are coarse and have a small range, so a naive switch breaks training: small updates disappear, tiny gradients become zero, large values overflow. Mixed precision keeps the speed and avoids the breakage by doing the heavy matrix arithmetic in 16 bits and everything that needs accuracy in 32 bits. This lesson explains the two 16-bit formats, what goes wrong with them, and how autocasting and loss scaling fix it. It runs on the CPU only: the concepts are the same as on a GPU.
Three floating-point formats
A float stores a sign, an exponent (the range: how large or small a number can be) and a mantissa (the precision: how many significant digits). A value is . With mantissa bits, the gap between 1 and the next representable number, machine epsilon, is (Floating-Point Formats).
| Format | Exponent bits | Mantissa bits | Machine epsilon | Largest value |
|---|---|---|---|---|
| float32 | 8 | 23 | ||
| float16 (IEEE half) | 5 | 10 | ||
| bfloat16 ("brain float") | 8 | 7 |
float16 spends its bits on precision and has a tiny range. bfloat16 is simply the top half of a float32: the same range as float32 and only about 2 to 3 significant decimal digits. NumPy has float16 but no bfloat16, so the next example emulates it by rounding a float32 to its top 16 bits:
import numpy as np
def to_bfloat16(x):
"""Round float32 values to bfloat16 (keep the top 16 bits, round to nearest even)."""
b = np.asarray(x, dtype=np.float32).view(np.uint32).astype(np.uint64)
b = (b + 0x7FFF + ((b >> 16) & 1)) & 0xFFFF0000
return b.astype(np.uint32).view(np.float32)
print(f"{'format':9s} {'bits (exp+mantissa)':>20s} {'machine eps':>12s} {'largest':>10s} {'smallest normal':>16s}")
for name, dt, bits in [("float32", np.float32, "8 + 23"), ("float16", np.float16, "5 + 10")]:
fi = np.finfo(dt)
print(f"{name:9s} {bits:>20s} {float(fi.eps):12.3g} {float(fi.max):10.3g} {float(fi.smallest_normal):16.3g}")
bf_eps = float(to_bfloat16(1 + 2 ** -7)[()] - 1)
bf_max = float(np.array(0x7F7F0000, dtype=np.uint32).view(np.float32))
print(f"{'bfloat16':9s} {'8 + 7':>20s} {bf_eps:12.3g} {bf_max:10.3g} {float(np.finfo(np.float32).smallest_normal):16.3g}")
for v in [1234.567, 0.1, 70000.0]:
with np.errstate(over="ignore"): # 70000 overflows float16
h = float(np.float16(v))
print(f"{v:>9}: float32 {float(np.float32(v)):.7g} float16 {h:.7g} bfloat16 {float(to_bfloat16(v)):.7g}")format bits (exp+mantissa) machine eps largest smallest normal
float32 8 + 23 1.19e-07 3.4e+38 1.18e-38
float16 5 + 10 0.000977 6.55e+04 6.1e-05
bfloat16 8 + 7 0.00781 3.39e+38 1.18e-38
1234.567: float32 1234.567 float16 1235 bfloat16 1232
0.1: float32 0.1 float16 0.09997559 bfloat16 0.1000977
70000.0: float32 70000 float16 inf bfloat16 70144
bfloat16 rounds 1234.567 to 1232 (it can only step by 8 at that size), but it represents 70 000 where float16 overflows to infinity. For training, range matters more than the last digits, which is why bfloat16 has become the default on hardware that supports it.
What breaks in pure 16-bit training
import numpy as np
# 1. Small updates vanish: adding a tiny step to a weight of 1.0
w = np.float16(1.0)
print("float16: 1 + 0.0001 =", w + np.float16(0.0001), " float32:", np.float32(1.0) + np.float32(0.0001))
# 2. Accumulating many small numbers stalls
total16 = np.float16(0.0)
for _ in range(10000):
total16 = total16 + np.float16(0.01)
print("sum of 10000 x 0.01 in float16:", total16, " (exact: 100)")
# 3. Small gradients underflow to zero; loss scaling rescues them
grads = np.array([3e-4, 2e-6, 5e-8, 1e-9], dtype=np.float32)
print("gradients in float16: ", grads.astype(np.float16).astype(np.float32))
scale = np.float32(1024)
scaled = (grads * scale).astype(np.float16) # backward pass on loss * 1024
print("scaled by 1024, then unscaled: ", scaled.astype(np.float32) / scale)float16: 1 + 0.0001 = 1.0 float32: 1.0001
sum of 10000 x 0.01 in float16: 32.0 (exact: 100)
gradients in float16: [2.9993057e-04 2.0265579e-06 5.9604645e-08 0.0000000e+00]
scaled by 1024, then unscaled: [2.9993057e-04 2.0004809e-06 5.0000381e-08 9.8953024e-10]
Three failures, three fixes:
- Lost updates. An update of is smaller than half the float16 spacing near 1 (), so rounds back to 1. A typical step is that small. Fix: keep a float32 master copy of the weights and apply updates there; cast to 16 bits only for the forward and backward pass.
- Stalled sums. Once the running total reaches 32, the spacing of float16 there is , and adding 0.01 rounds away. Reductions (sums in softmax, losses, norms, batch-norm statistics) must therefore accumulate in float32.
- Underflow. Gradients below float16's smallest subnormal (about ) become 0, and those near it lose precision (5e-8 came out as 5.96e-8). Fix: loss scaling. Multiply the loss by a factor (here 1024) before backpropagation; by the chain rule every gradient is multiplied by too and moves into float16's range. Divide by in float32 before the optimizer step (and before gradient clipping). Dynamic loss scaling starts with a large , halves it whenever a gradient overflows to
infornan(that step is skipped), and doubles it after a run of clean steps.
bfloat16 has float32's exponent range, so failure 3 essentially does not happen and no loss scaling is needed. Failures 1 and 2 still apply, and its precision is lower than float16's.
The recipe: automatic mixed precision
Frameworks automate all of this. In PyTorch, torch.autocast runs each operation in the precision that suits it: matrix multiplications and convolutions in 16 bits; softmax, losses, normalisation and reductions in float32. Weights and optimizer state stay in float32. With float16 a GradScaler adds dynamic loss scaling; with bfloat16 it is not needed.
The example trains a small network twice, once in float32 and once with bfloat16 autocast on the CPU (recent CPUs have bfloat16 instructions; nothing here uses a GPU), then runs one trained model in both precisions:
import torch
from torch import nn
torch.manual_seed(0)
X, X_test = torch.randn(512, 16), torch.randn(512, 16)
rule = lambda X: (X[:, :4].sum(dim=1) > 0).long() # a simple rule to learn
y, y_test = rule(X), rule(X_test)
def train(use_bf16, steps=100):
torch.manual_seed(1) # same initial weights for both runs
model = nn.Sequential(nn.Linear(16, 64), nn.ReLU(), nn.Linear(64, 2))
opt = torch.optim.AdamW(model.parameters(), lr=1e-2)
for step in range(steps):
with torch.autocast(device_type="cpu", dtype=torch.bfloat16, enabled=use_bf16):
logits = model(X) # matmuls run in bfloat16
loss = nn.functional.cross_entropy(logits, y) # autocast runs this in float32
opt.zero_grad()
loss.backward()
opt.step() # master weights stay float32
print(f"bf16 autocast {use_bf16!s:5}: logits {logits.dtype}, loss {loss.dtype}, weights {model[0].weight.dtype}")
return model, loss.item()
models = {}
for use_bf16 in (False, True):
model, loss = train(use_bf16)
with torch.no_grad():
acc = (model(X_test).argmax(1) == y_test).float().mean().item()
print(f" final training loss {loss:.4f} test accuracy {acc:.3f}")
models[use_bf16] = model
m = models[False] # one model, two precisions
with torch.no_grad():
full = m(X_test)
with torch.autocast(device_type="cpu", dtype=torch.bfloat16):
half = m(X_test)
print(f"same model, float32 vs bfloat16 logits: max difference {(full - half.float()).abs().max().item():.3f},"
f" typical logit size {full.abs().mean().item():.1f}")bf16 autocast False: logits torch.float32, loss torch.float32, weights torch.float32
final training loss 0.0025 test accuracy 0.939
bf16 autocast True : logits torch.bfloat16, loss torch.float32, weights torch.float32
final training loss 0.0025 test accuracy 0.947
same model, float32 vs bfloat16 logits: max difference 0.089, typical logit size 6.8
Inside autocast the logits come out in bfloat16, but the loss is float32 and the weights stay float32 (the master copy). Both runs reach the same training loss; the test accuracies (0.939 and 0.947 on 512 test points) differ by about one standard error, which is noise from the slightly different arithmetic, not a real gain. Running one model in both precisions changes the logits by at most 0.089 on values of typical size 6.8: about 1 %, consistent with bfloat16's 7-bit mantissa. On this tiny CPU example there is no speed-up to report; the gains appear with large matrices on hardware with fast 16-bit units.
On a GPU with float16 the loop gets a scaler: scaler.scale(loss).backward(), then scaler.unscale_(opt) (before clipping), scaler.step(opt) and scaler.update().
Where precision still matters
- Evaluation and metrics are computed in float32 (or float64).
- Optimizer state (Adam's moments) stays in float32; 8-bit optimizers exist but are a separate technique.
- Inference often goes further: float16/bfloat16 weights, or 8-bit and 4-bit integer quantisation (covered in the deployment and NLP courses).
- Numerically delicate code (custom losses with
expandlog, variance computations) should be checked once in float32 to compare.
Pitfalls
- Casting the whole model with
.half()and training: no master weights, no float32 reductions, lost updates. - float16 without loss scaling: gradients underflow silently and training stalls.
- Clipping scaled gradients: unscale first, or the threshold is wrong by the factor .
- Comparing results bit-for-bit with a float32 run. Expect small differences, as in the example.
Practice
- What is the spacing between consecutive float16 numbers just above 1024, and between consecutive bfloat16 numbers there?
Answer
, so the spacing is for float16 (10 mantissa bits) and for bfloat16 (7 bits). That is why 1234.567 became 1235 and 1232.
- A gradient of is computed in float16 with a loss scale of 65536. Does it survive?
Answer
Scaled, it is , well within float16's normal range (smallest normal about ), so yes; it is divided by 65536 again in float32.
Test yourself
Why does bfloat16 training usually need no loss scaling?
- It has more mantissa bits than float16
- It has the same 8-bit exponent, so the same range, as float32
- It is slower
- It stores gradients as integers
In mixed-precision training, which copy of the weights receives the optimizer updates?
- A float16 copy
- A float32 master copy
- An int8 copy
- None, weights are frozen
What does loss scaling do?
- Normalises the loss to 1
- Multiplies the loss by so that gradients move into the 16-bit range, then divides the gradients by before the update
- Clips the loss
- Averages the loss over the batch
Inside torch.autocast with bfloat16, which ran in float32 in the example?
- The linear layers' matrix multiplications
- The cross-entropy loss
- Nothing
- The input data generation