TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Mixed Precision: float16 and bfloat16

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 ±1.m×2e\pm 1.m \times 2^{e}. With pp mantissa bits, the gap between 1 and the next representable number, machine epsilon, is 2−p2^{-p} (Floating-Point Formats).

Format Exponent bits Mantissa bits Machine epsilon Largest value
float32 8 23 2−23≈1.2×10−72^{-23} \approx 1.2 \times 10^{-7} 3.4×10383.4 \times 10^{38}
float16 (IEEE half) 5 10 2−10≈9.8×10−42^{-10} \approx 9.8 \times 10^{-4} 6550465504
bfloat16 ("brain float") 8 7 2−7≈7.8×10−32^{-7} \approx 7.8 \times 10^{-3} 3.4×10383.4 \times 10^{38}

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:

python · try it yourself
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

python · try it yourself
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:

  1. Lost updates. An update of 10−410^{-4} is smaller than half the float16 spacing near 1 (2−11≈4.9×10−42^{-11} \approx 4.9 \times 10^{-4}), so 1+10−41 + 10^{-4} rounds back to 1. A typical step ηg\eta g 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.
  2. Stalled sums. Once the running total reaches 32, the spacing of float16 there is 2−5=0.031252^{-5} = 0.03125, and adding 0.01 rounds away. Reductions (sums in softmax, losses, norms, batch-norm statistics) must therefore accumulate in float32.
  3. Underflow. Gradients below float16's smallest subnormal (about 6×10−86 \times 10^{-8}) 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 SS (here 1024) before backpropagation; by the chain rule every gradient is multiplied by SS too and moves into float16's range. Divide by SS in float32 before the optimizer step (and before gradient clipping). Dynamic loss scaling starts with a large SS, halves it whenever a gradient overflows to inf or nan (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:

python · try it yourself
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 exp and log, 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 SS.
  • Comparing results bit-for-bit with a float32 run. Expect small differences, as in the example.

Practice

  1. What is the spacing between consecutive float16 numbers just above 1024, and between consecutive bfloat16 numbers there?
Answer

1024=2101024 = 2^{10}, so the spacing is 210⋅2−10=12^{10} \cdot 2^{-10} = 1 for float16 (10 mantissa bits) and 210⋅2−7=82^{10} \cdot 2^{-7} = 8 for bfloat16 (7 bits). That is why 1234.567 became 1235 and 1232.

  1. A gradient of 3×10−93 \times 10^{-9} is computed in float16 with a loss scale of 65536. Does it survive?
Answer

Scaled, it is 3×10−9⋅65536≈2×10−43 \times 10^{-9} \cdot 65536 \approx 2 \times 10^{-4}, well within float16's normal range (smallest normal about 6.1×10−56.1 \times 10^{-5}), so yes; it is divided by 65536 again in float32.

Test yourself

Why does bfloat16 training usually need no loss scaling?

  1. It has more mantissa bits than float16
  2. It has the same 8-bit exponent, so the same range, as float32
  3. It is slower
  4. It stores gradients as integers

In mixed-precision training, which copy of the weights receives the optimizer updates?

  1. A float16 copy
  2. A float32 master copy
  3. An int8 copy
  4. None, weights are frozen

What does loss scaling do?

  1. Normalises the loss to 1
  2. Multiplies the loss by SS so that gradients move into the 16-bit range, then divides the gradients by SS before the update
  3. Clips the loss
  4. Averages the loss over the batch

Inside torch.autocast with bfloat16, which ran in float32 in the example?

  1. The linear layers' matrix multiplications
  2. The cross-entropy loss
  3. Nothing
  4. The input data generation