Skip to content
AI systems and infrastructure Core 27 min read

Mixed precision: FP32, BF16, FP8

Every modern model is trained with most of its arithmetic in 16 or 8 bits, because each halving of the number width roughly doubles tensor-core throughput and halves the bytes moved. It works because different numbers in training need different things: matrix inputs tolerate coarse precision, sums need many bits, gradients need range, and weight updates need both. Mixed precision is the discipline of giving each number exactly what it needs.

10,000 ft

Floating point is a budget of bits split between range (the exponent) and precision (the mantissa). GPU tensor cores are built for narrow formats: on an H100, dense matmul throughput is 495 TFLOP/s in TF32, 989 in BF16 and 1,979 in FP8. Training in FP32 would waste most of the chip, and storing activations in FP32 would double the memory and bandwidth bill computed in compute maths. The 2017 recipe of FP16 compute, FP32 master weights and loss scaling made half precision trainable; BF16, which keeps FP32's range, made it simple and became the default around 2020; FP8 with scaling factors is used for frontier runs as of 2024–2026, and 4-bit formats with block scales are arriving with Blackwell. The same range-versus-precision reasoning, applied to stored weights, is quantisation for inference.

2,000 ft

A mixed-precision training step keeps the state wide and the traffic narrow:

  1. FP32 master weights and optimiser state. Updates are often far smaller than a 16-bit weight's spacing; applied directly they would vanish.
  2. Cast to BF16 (or FP8 with scales) for the matmuls, forward and backward, so the tensor cores run at full speed and activations take half the memory.
  3. Accumulate in FP32 inside every matmul, and run reductions — softmax, normalisation statistics, the loss — in FP32.
  4. Loss scaling, only for FP16: multiply the loss so small gradients do not underflow, unscale before the update, skip steps that overflow.
  5. FP8 needs scale factors on every tensor (or tile), because 8 bits cannot cover the range of real activations and gradients unaided.

One mixed-precision training step
One mixed-precision training step. FP32 master weights + FP32 Adam moments, cast to BF16 (or FP8 + scales), forward matmuls BF16 in, FP32 accumulate, softmax, norms, loss in FP32, backward matmuls BF16 gradients, accumulate and all-reduce gradients (often FP32), optimiser update in FP32, loss × scale if FP16, unscale, skip step on infOne mixed-precision training step. FP32 master weights + FP32 Adam moments, cast to BF16 (or FP8 + scales), forward matmuls BF16 in, FP32 accumulate, softmax, norms, loss in FP32, backward matmuls BF16 gradients, accumulate and all-reduce gradients (often FP32), optimiser update in FP32, loss × scale if FP16, unscale, skip step on inf

Ground level

The formats

A floating-point number is \((-1)^s \times 1.f \times 2^{E-\text{bias}}\): a sign bit, an exponent field \(E\) that sets the range, and a mantissa (fraction) \(f\) that sets the precision — how many distinct values exist between consecutive powers of two. Every format in deep learning is a different split of the same idea:

FP32TF32BF16FP16FP8 E5M2FP8 E4M3FP4 E2M1 32 bits19 bits used (stored in 32)16 bits16 bits8 bits8 bits4 bits signexponent: rangemantissa: precision
BF16 is FP32 with the mantissa cut to 7 bits: same range, less precision. FP16 spends more bits on precision and fewer on range. The FP8 and FP4 formats are so narrow they only work with scale factors.

The emulator in Build it computes the properties that matter (values rounded to three figures; "eps" is the gap between 1 and the next number up):

Format Exponent / mantissa bits Largest value Smallest normal eps Where it is used
FP32 8 / 23 \(3.4\times10^{38}\) \(1.2\times10^{-38}\) \(1.2\times10^{-7}\) master weights, optimiser state, accumulators, reductions
TF32 8 / 10 \(3.4\times10^{38}\) \(1.2\times10^{-38}\) \(9.8\times10^{-4}\) tensor-core mode for FP32 matmuls (Ampere on)
BF16 8 / 7 \(3.4\times10^{38}\) \(1.2\times10^{-38}\) \(7.8\times10^{-3}\) the default for training compute and activations
FP16 5 / 10 65,504 \(6.1\times10^{-5}\) \(9.8\times10^{-4}\) older training (with loss scaling), inference
FP8 E5M2 5 / 2 57,344 \(6.1\times10^{-5}\) 0.25 gradients in hybrid FP8 recipes
FP8 E4M3 4 / 3 448 0.0156 0.125 weights and activations; all tensors in some recipes
FP4 E2M1 2 / 1 6 1 0.5 Blackwell block-scaled formats (MXFP4, NVFP4)

Read the table as two questions. Range: can the format represent both the largest and the smallest values a tensor will hold? BF16 can represent everything FP32 can (down to \(10^{-38}\)), FP16 cannot represent anything below \(6\times10^{-8}\) even as a subnormal, and E4M3 tops out at 448. Precision: how close is the nearest representable value? With 7 mantissa bits, BF16's relative rounding error is up to \(2^{-8}\approx0.4\%\); FP8 E4M3's is up to 6%. E4M3 follows the FP8 formats paper in giving up infinities and keeping a single NaN pattern to reach 448 rather than 240; E5M2 keeps IEEE-style infinities and NaNs.

Why narrow is fast

Three separate payoffs, all on the GPU page's roofline:

  • Tensor-core throughput doubles per halving. H100 dense: TF32 495, BF16/FP16 989, FP8 1,979 TFLOP/s (Glenn Lockwood's H100 table, from NVIDIA's data sheet). A multiplier's area grows roughly with the square of the mantissa width, which is why Google chose BF16 for TPUs: its multiplier is about half the size of an FP16 one and an eighth of an FP32 one (Wang and Kanwar, 2019).
  • Bytes halve. Every memory-bound kernel — and in a transformer, every element-wise and normalisation kernel is — runs twice as fast on 2-byte data as on 4-byte data.
  • Memory halves. Activations saved for the backward pass usually dominate training memory; storing them in BF16 halves that, allowing larger micro-batches or less recomputation.

What does not shrink: in standard mixed-precision Adam, model state is still 16 bytes per parameter (BF16 weight and gradient, FP32 master weight and two FP32 moments — see compute maths). Mixed precision buys speed and activation memory, not smaller optimiser state.

The recipe, rule by rule

Micikevicius et al. (2017) established the recipe for FP16; each rule fixes one failure you can reproduce in the Build it emulator.

Rule 1: keep FP32 master weights. An update \(\eta g\) is typically \(10^{-3}\) to \(10^{-6}\) of the weight it changes. The spacing of BF16 numbers near 1.0 is \(2^{-7} = 0.0078\), so any update smaller than half that, 0.0039, rounds back to the same weight. In the emulator, a thousand updates of \(10^{-4}\) leave a BF16 weight of 1.0 exactly unchanged, while an FP32 master copy correctly reaches 1.1. Keeping an FP32 master copy, updating it, and casting a fresh BF16 copy for each forward pass solves this for 2 extra bytes per parameter. (Alternatives that avoid the master copy, such as stochastic rounding of the update or Kahan-compensated summation, exist and are used in some low-memory optimisers.)

Rule 2: accumulate in FP32. A matmul's output element is a dot product of length \(K\), often 4,096–16,384. If the running sum were kept in BF16, then once it grows large each new product is smaller than half its spacing and is rounded away — swamping. In the emulator a length-4,096 dot product of positive BF16 numbers, accumulated in BF16, stalls at 256.00 (where the spacing becomes 2) against a true value of 1018.12; accumulated in FP32 it is 1018.11. This is why tensor cores take narrow inputs but accumulate wide, and why softmax, normalisation statistics, the loss and gradient accumulation across micro-batches run in FP32. PyTorch's torch.autocast encodes these rules as lists: on CUDA, matmuls, convolutions and linear layers run in the low-precision type, while softmax, log_softmax, layer_norm, norm, losses such as cross_entropy, and reductions such as sum and exp are autocast to FP32 (AMP documentation).

Rule 3: in FP16, scale the loss. Gradients of a deep network span many orders of magnitude and many of them are tiny. FP16's smallest subnormal is \(6\times10^{-8}\); anything smaller flushes to zero. In the emulator, with gradient magnitudes spread log-normally around \(10^{-6}\), 15.4% become exactly zero in FP16. Because backpropagation is linear in the loss, multiplying the loss by \(S\) multiplies every gradient by \(S\), shifting the whole distribution up into FP16's range: at \(S = 2^{16}\) none underflow. Divide by \(S\) before the update (in FP32) and the mathematics is unchanged. Too large a scale overflows to infinity — at \(2^{24}\), 0.8% of the emulated gradients do — so dynamic loss scaling adjusts \(S\) automatically: if any gradient is inf or NaN, skip the step and halve \(S\); after a run of good steps, double it. PyTorch's GradScaler starts at \(2^{16}\) and doubles after 2,000 clean steps by default.

Rule 4 (BF16): skip rule 3. BF16 has FP32's exponent, so gradients that fit in FP32 fit in BF16 and no loss scaling is needed; in the emulator, the same gradients lose nothing to underflow in BF16. The price is precision: 7 mantissa bits instead of 10. Empirically that is enough — Kalamkar et al. (2019) matched FP32 results across vision, speech, language and recommendation models with no hyperparameter changes — because stochastic gradient descent already injects far more noise than a 0.4% rounding error. BF16 is the default for training on every accelerator that supports it (TPUs from v2, NVIDIA from Ampere, AMD's Instinct line). FP16 survives mainly for inference and on older GPUs.

What stays in FP32, in practice

A modern BF16 run keeps these wide, and each has a reason:

Kept in FP32 Why
Master weights, Adam moments updates are smaller than BF16 spacing; \(v\) (squared gradients) spans a huge range
Matmul accumulators swamping, as above
Softmax, log-sum-exp, the loss exponentials amplify rounding error; z-loss tracks \(\log Z\)
Norm statistics (mean, variance, RMS) a sum over thousands of elements, then a division
Gradient accumulation and reduction Llama 3 accumulates gradients across micro-batches and reduce-scatters them across data-parallel workers in FP32 (Llama 3 paper, §3.3)
Small parameters: norm gains, biases, router logits cheap to keep wide; sensitive to error

The general principle: narrow for things that are multiplied, wide for things that are summed or that persist across steps.

FP8: when 8 bits need a scale

At 8 bits the trade-off bites. E4M3 spans \(2\times10^{-3}\) to 448 — about five orders of magnitude including subnormals, against BF16's seventy-six. No fixed placement of that window covers both weights (around \(10^{-2}\)), activations (around 1, with outliers in the hundreds) and gradients (around \(10^{-5}\) and below). The emulator shows the blunt version: cast unscaled gradients of size \(10^{-5}\) to E4M3 and 100% become zero.

The fix is a scale factor per tensor: before casting, multiply by \(s = 448/\operatorname{amax}\) so the tensor's largest magnitude lands at the top of the format; carry \(s\) alongside the FP8 data; divide it back out after the matmul (the scales of the two inputs multiply). With that one number per tensor, the same gradients quantise with a 2.6% relative error — the format's own rounding error, and fine for training. The FP8 formats paper trained models up to 175B parameters this way, matching 16-bit results with unchanged hyperparameters, using E4M3 for weights and activations and E5M2 (more range, less precision) for gradients.

How to choose \(s\) is the engineering:

  • Delayed scaling (the original Transformer Engine recipe on Hopper): use the maximum \(|x|\) seen over a window of recent steps, so the scale is known before the tensor is computed and no extra pass is needed. It can be one step late when values jump.
  • Current (just-in-time) scaling: compute amax of the tensor itself, then cast. Exact, but costs an extra reduction over the data.
  • Fine-grained (block) scaling: one scale per small block, so a single outlier only coarsens its own block. DeepSeek-V3 (2024) uses one scale per \(1\times128\) tile of activations (per token, per 128 channels) and per \(128\times128\) block of weights, uses E4M3 for all tensors, and keeps the embedding, output head, MoE gating, normalisation and attention in BF16 or FP32. It reported FP8 training loss within 0.25% of a BF16 baseline.
FP8 matmul with fine-grained scaling (DeepSeek-V3 style)
FP8 matmul with fine-grained scaling (DeepSeek-V3 style). activations BF16 scale per 1×128 tile, weights scale per 128×128 block, quantise to E4M3 value / scale, tensor-core FP8 MMA limited-precision accumulate, every 128 of K: multiply by scales, add into FP32 registers, output BF16, next K chunkFP8 matmul with fine-grained scaling (DeepSeek-V3 style). activations BF16 scale per 1×128 tile, weights scale per 128×128 block, quantise to E4M3 value / scale, tensor-core FP8 MMA limited-precision accumulate, every 128 of K: multiply by scales, add into FP32 registers, output BF16, next K chunk

DeepSeek-V3 also found a hardware subtlety worth knowing: on its H800s, FP8 tensor-core accumulation retains only about 14 bits, which for a \(K = 4096\) inner dimension gave errors of nearly 2% in a preliminary test. Their kernels therefore promote partial sums to FP32 registers every 128 elements of \(K\) — Rule 2 again, enforced by hand.

Reading DeepSeek-V3 §3.3 for the FP8 recipe

Read the framework figure and the two subsections on fine-grained quantisation and accumulation precision. The useful habit to copy is the ablation at scale: they validated FP8 against BF16 on two model sizes for about a trillion tokens before committing the full run. Skip the communication details on first reading; they belong to distributed training.

Long runs surface problems short ones miss. Fishman et al. (2024) trained FP8 models on up to 2 trillion tokens and found divergence late in training, which they traced to SwiGLU amplifying outliers once its weights align; a modified "Smooth-SwiGLU" fixed it, and they also quantised both Adam moments to FP8.

Block-scaled formats: MX and NVFP4

Blackwell GPUs put block scaling into hardware. The Open Compute Project's microscaling (MX) formats (Rouhani et al., 2023) attach one shared 8-bit power-of-two scale (E8M0) to every block of 32 elements: MXFP8 (E4M3 or E5M2 elements), MXFP6, MXFP4 (E2M1) and MXINT8. In that paper a 1.5B-parameter GPT trained with MXFP6 weights, activations and gradients reached a loss of 2.75 against 2.74 for FP32. NVIDIA's NVFP4 (NVIDIA, 2025) uses smaller blocks of 16 with a finer FP8 (E4M3) scale per block plus one FP32 scale per tensor, about 4.5 bits per value in all.

Why the blocks must be small at 4 bits is the last experiment in the emulator. FP4 E2M1 has only the magnitudes 0, 0.5, 1, 1.5, 2, 3, 4 and 6 — a dynamic range of 12. Give a Gaussian tensor one outlier 100× its typical size and a single per-tensor scale maps every ordinary value below 0.25 after scaling: all of them round to zero. With a scale per 16 values, only the outlier's own block suffers and the relative error is 9.5%. (E4M3, with its dynamic range of about \(2\times10^5\), shrugs off the same outlier with either scaling.)

As of 2026 the evidence for training in these formats is real but young: Mishra et al. (2025) report MXFP8-E4M3 runs matching BF16 for models up to 8B parameters on up to 15T tokens, and NVIDIA's NVFP4 pretraining study trained a 12B model on 10T tokens to loss and accuracy comparable to an FP8 baseline, using random Hadamard transforms to spread outliers, two-dimensional block quantisation, stochastic rounding for gradients and a few layers kept in higher precision.

History

Training in reduced precision is older than the boom — fixed-point and 16-bit experiments date to the early 1990s — but the modern story starts with hardware. NVIDIA's Volta tensor cores (2017) offered FP16 matmuls with FP32 accumulation, and Micikevicius et al. (NVIDIA and Baidu) published the master-weights-plus-loss-scaling recipe the same year. Google Brain's bfloat16, used in TPU v2 and v3 matrix units, avoided loss scaling by keeping FP32's exponent; Intel's 2019 study made the empirical case, and NVIDIA's Ampere (2020) brought BF16 (and TF32) to GPUs, after which BF16 became the default for large-model training. Hopper (2022) added FP8, with the FP8 formats paper co-authored by NVIDIA, Arm and Intel; DeepSeek-V3 (December 2024) was the most visible frontier-scale FP8 training run with a public recipe. Blackwell (2024–2025) added MX and NVFP4 block-scaled formats, and 4-bit pretraining results followed in 2025.

First principles

Precision is relative, range is absolute. A float with \(m\) mantissa bits represents any number in its range with relative error at most \(u = 2^{-(m+1)}\) (the unit roundoff): 0.4% for BF16, 6% for E4M3. That error is the same at \(10^{-30}\) as at \(10^{30}\). So a format fails in exactly two ways: a value falls outside its range (overflow to inf, underflow to zero), or a computation needs more relative precision than \(u\) provides. Mixed precision is the practice of diagnosing which failure each tensor is exposed to.

Why multiplication tolerates few bits and addition does not. The relative error of a product is the sum of the relative errors of its factors: two BF16 inputs give a product accurate to about 0.8%, independent of size. Addition is different: adding a small number to a large one loses the small number's low bits, and adding many numbers loses information steadily, with error growing with the number of terms (bounded in the worst case by about \(nu\) times the sum of magnitudes). Matmuls are mostly multiplications fed into long sums — so narrow inputs, wide accumulators.

Why gradients need range. Gradient magnitudes vary by layer, by parameter and over training, across many orders of magnitude, and the important updates are often the small ones. What matters is that a gradient of \(10^{-9}\) is represented as roughly \(10^{-9}\), not that it has 10 correct digits. That is exactly what an 8-bit exponent offers.

Why noise tolerance makes this possible. A mini-batch gradient is itself a noisy estimate of the true gradient, and for individual coordinates the sampling noise is often as large as the signal. A rounding error of 0.4% per operation, unbiased on average, is small next to that, so it barely changes the trajectory. Systematic (biased) errors are the dangerous ones: swamping, underflow to exactly zero, saturation. Each rule in the recipe removes one source of bias; stochastic rounding, which rounds up or down with probability proportional to proximity, removes the bias of rounding itself.

The maths

A normal float with sign \(s\), exponent field \(E\), bias \(b = 2^{e-1}-1\) and \(m\)-bit fraction \(f\) encodes

\[ x = (-1)^s\left(1 + \frac{f}{2^m}\right)2^{E-b}. \]

The spacing between consecutive numbers in \([2^k, 2^{k+1})\) is \(2^{k-m}\), so round-to-nearest satisfies

\[ \mathrm{fl}(x) = x(1+\delta),\qquad |\delta| \le u = 2^{-(m+1)}. \]

The smallest normal is \(2^{1-b}\), the smallest subnormal \(2^{1-b-m}\), and (for IEEE-like formats) the largest finite value \((2-2^{-m})\,2^{2^e-2-b}\). Check FP16: \(e=5\), \(b=15\), \(m=10\) gives \(2^{-14}\approx6.1\times10^{-5}\), \(2^{-24}\approx6.0\times10^{-8}\) and \((2-2^{-10})\,2^{15}=65{,}504\).

Derivation: when an update is swallowed, and why accumulation stalls

Let \(w\in[2^k,2^{k+1})\) be stored with \(m\) mantissa bits; its neighbours are \(2^{k-m}\) away. Round-to-nearest maps \(w+\Delta\) back to \(w\) whenever \(|\Delta| < 2^{k-m-1}\). Relative to the weight, the update is lost if

\[ \frac{|\Delta|}{|w|} < \frac{2^{k-m-1}}{2^{k+1}} = 2^{-(m+2)}\ \text{(worst case, at the top of the binade)}. \]

For BF16 (\(m=7\)) that is \(2^{-9}\approx0.2\%\) in the worst case and up to \(2^{-8}\) at the bottom of a binade. Adam's updates are of order the learning rate, \(10^{-4}\) to \(10^{-3}\) relative, so in BF16 most would be partly or wholly lost. With an FP32 master (\(m=23\)) the threshold is \(\sim10^{-7}\).

The same inequality explains the stalled dot product: summing positive terms of average size \(\bar p\), the running sum \(S\) stops growing once \(\bar p < 2^{\lfloor\log_2 S\rfloor-m-1}\), i.e. once \(S \gtrsim \bar p\,2^{m+1}\). With \(\bar p\approx0.25\) and \(m=7\), \(S\) stalls near \(0.25\times256 = 64\) for the average term; larger terms keep it moving until the spacing reaches 2 at \(S=256\), where nearly every term (all below 1) is rounded away. The emulator stalls at exactly 256.00.

Loss scaling is exact. Backpropagation computes \(\nabla_\theta(S\mathcal L) = S\nabla_\theta \mathcal L\), because every step of the chain rule is linear in the upstream gradient. So scaling the loss by a power of two (which changes only exponents, not mantissas) and dividing the result by the same power is exact, provided nothing overflows.

Choosing an FP8 scale. For a tensor \(X\) and format maximum \(q_{\max}\) (448 for E4M3), \(s = q_{\max}/\max|X|\) maps the largest magnitude to the top of the range; the smallest magnitude that survives as a normal number is then \(\max|X|\cdot 2^{-6}/448\) for E4M3. Anything much below \(\max|X|/10^{4.5}\) falls into subnormals or zero. A block scale replaces the tensor's \(\max|X|\) with the block's, which is why blocks protect ordinary values from distant outliers.

Build it

A float-format emulator in NumPy: it rounds float64 values to the nearest number representable in any of the formats above (with subnormals, round-half-to-even, and overflow to infinity or saturation). Every claim on this page is reproduced below.

import numpy as np

# (exponent bits, mantissa bits, largest finite value, overflow -> inf?)
FMT = {"FP32": (8, 23, 3.4028235e38, True), "TF32": (8, 10, 3.40e38, True),
       "BF16": (8, 7, 3.3895e38, True),     "FP16": (5, 10, 65504.0, True),
       "E5M2": (5, 2, 57344.0, True),       "E4M3": (4, 3, 448.0, False),
       "E2M1": (2, 1, 6.0, False)}

def to_fmt(x, name):
    """Round float64 values to the nearest value of a float format (round-half-even),
    with subnormals; overflow becomes inf (IEEE-like) or saturates (FP8 E4M3, FP4)."""
    e, m, vmax, inf = FMT[name]
    x = np.asarray(x, dtype=np.float64)
    emin = 2 - 2 ** (e - 1)                          # exponent of smallest normal
    ex = np.floor(np.log2(np.maximum(np.abs(x), 1e-300)))
    step = 2.0 ** (np.maximum(ex, emin) - m)         # spacing of representable values
    y = np.round(x / step) * step                    # np.round is round-half-to-even
    big = np.abs(y) > vmax
    return np.where(big, np.sign(x) * (np.inf if inf else vmax), y)

print(f"{'format':6s}{'max':>11s}{'min normal':>12s}{'min subnorm':>13s}{'eps (1+eps)':>13s}")
for n, (e, m, vmax, _) in FMT.items():
    emin = 2 - 2 ** (e - 1)
    print(f"{n:6s}{vmax:11.4g}{2.0**emin:12.3g}{2.0**(emin - m):13.3g}{2.0**-m:13.3g}")

# 1. Why master weights: tiny updates are swallowed by a BF16 weight
w16, w32 = to_fmt(1.0, "BF16"), 1.0
for _ in range(1000):
    w16 = to_fmt(w16 + 1e-4, "BF16")                 # update applied in BF16
    w32 = w32 + 1e-4                                 # update applied to FP32 master
print(f"\n1000 updates of 1e-4 to w=1: BF16 weight {w16:.4f}, FP32 master {w32:.4f}")

# 2. Why loss scaling for FP16: small gradients underflow to zero
rng = np.random.default_rng(0)
g = 10.0 ** rng.normal(-6, 1.5, 100_000) * rng.choice([-1, 1], 100_000)
for scale in (1, 2**10, 2**16, 2**24):
    q = to_fmt(g * scale, "FP16")
    print(f"FP16, loss scale 2^{int(np.log2(scale)):2d}: {np.mean(q == 0):6.1%} zero, "
          f"{np.mean(np.isinf(q)):6.1%} inf")
print(f"BF16, no scale:      {np.mean(to_fmt(g, 'BF16') == 0):6.1%} zero")
format        max  min normal  min subnorm  eps (1+eps)
FP32    3.403e+38    1.18e-38      1.4e-45     1.19e-07
TF32      3.4e+38    1.18e-38     1.15e-41     0.000977
BF16    3.389e+38    1.18e-38     9.18e-41      0.00781
FP16     6.55e+04     6.1e-05     5.96e-08     0.000977
E5M2    5.734e+04     6.1e-05     1.53e-05         0.25
E4M3          448      0.0156      0.00195        0.125
E2M1            6           1          0.5          0.5

1000 updates of 1e-4 to w=1: BF16 weight 1.0000, FP32 master 1.1000
FP16, loss scale 2^ 0:  15.4% zero,   0.0% inf
FP16, loss scale 2^10:   0.1% zero,   0.0% inf
FP16, loss scale 2^16:   0.0% zero,   0.0% inf
FP16, loss scale 2^24:   0.0% zero,   0.8% inf
BF16, no scale:        0.0% zero

Continue in the same session (it reuses to_fmt, FMT and rng):

# 3. Why FP32 accumulation: a length-4096 dot product of BF16 inputs
x = to_fmt(rng.random(4096), "BF16"); y = to_fmt(rng.random(4096), "BF16")
exact, acc16 = float(x @ y), 0.0
for p in x * y:                                   # round the running sum after every add
    acc16 = float(to_fmt(acc16 + p, "BF16"))
acc32 = float(np.sum((x * y).astype(np.float32), dtype=np.float32))
print(f"\ndot product of 4096: exact {exact:.2f}, BF16 accumulator {acc16:.2f}, "
      f"FP32 accumulator {acc32:.2f}")

# 4. Why narrow formats need scales, and why small blocks help
def quant(t, fmt, block=None):
    """Scale each group so its largest |value| maps to the format's max, round, unscale."""
    t = t.reshape(-1, block) if block else t.reshape(1, -1)
    s = FMT[fmt][2] / np.abs(t).max(axis=1, keepdims=True)
    return (to_fmt(t * s, fmt) / s).reshape(-1)

rel = lambda q, t: np.sqrt(np.mean((q - t) ** 2) / np.mean(t ** 2))
grad = rng.standard_normal(1 << 17) * 1e-5               # gradients are tiny
print(f"E4M3 gradients, no scale: {np.mean(to_fmt(grad, 'E4M3') == 0):.0%} zero; "
      f"per-tensor scale: rel. error {rel(quant(grad, 'E4M3'), grad):.3f}")
act = rng.standard_normal(1 << 17); act[12345] = 100.0  # one outlier activation
ok = np.arange(act.size) != 12345
for fmt, blk in (("E4M3", 128), ("E2M1", 16)):
    for b in (None, blk):
        q = quant(act, fmt, b)
        print(f"{fmt} {'per-tensor' if b is None else f'blocks of {b}':12s}: rel. error "
              f"{rel(q[ok], act[ok]):.3f}, {np.mean(q[ok] == 0):5.1%} of values -> 0")
dot product of 4096: exact 1018.12, BF16 accumulator 256.00, FP32 accumulator 1018.11
E4M3 gradients, no scale: 100% zero; per-tensor scale: rel. error 0.026
E4M3 per-tensor  : rel. error 0.026,  0.0% of values -> 0
E4M3 blocks of 128: rel. error 0.026,  0.0% of values -> 0
E2M1 per-tensor  : rel. error 1.000, 100.0% of values -> 0
E2M1 blocks of 16: rel. error 0.095,  6.8% of values -> 0

Every rule of the recipe is visible: updates vanish without master weights, a BF16 accumulator stalls, FP16 loses gradients without a loss scale and overflows with too large a one, FP8 needs a scale, and FP4 needs small blocks.

Things to try

  • Make the dot-product experiment use values centred on zero (rng.standard_normal). Does the BF16 accumulator still fail? Why is cancellation kinder to it than a sum of positive numbers?
  • Implement stochastic rounding in to_fmt (round up with probability equal to the fractional position between neighbours) and repeat the 1,000-update experiment in pure BF16. Does the expected weight now reach 1.1?
  • Implement dynamic loss scaling: start at \(2^{16}\), halve on any inf, double after 20 clean steps, and feed it gradients whose scale drifts downward over 1,000 steps.
  • Change the outlier from 100 to \(10^5\) and find where E4M3 per-tensor scaling starts to lose ordinary values. Compare with the dynamic-range estimate in The maths.
  • Train a tiny MLP from the deep learning track with every matmul input passed through to_fmt(..., "E4M3") with per-tensor scales, and compare its loss curve with FP32.

In practice

  • Default to BF16 autocast on any GPU from Ampere onwards: in PyTorch, with torch.autocast("cuda", dtype=torch.bfloat16): around the forward pass and loss, no GradScaler. Keep the model's parameters in FP32 (they are the master weights) unless you use an FSDP mixed-precision policy, which handles the casting for you.
  • FP32 matmuls can silently use TF32. On Ampere and later, PyTorch lets FP32 matmuls run on tensor cores in TF32 if you set torch.set_float32_matmul_precision("high"); nanoGPT does the equivalent. It is fast and almost always fine for training, but surprising when you compare outputs bit for bit.
  • FP16 only with GradScaler, and watch for models pretrained in BF16 overflowing FP16's 65,504 maximum at inference (activations of some models exceed it).
  • FP8 through a library. Use NVIDIA's Transformer Engine or PyTorch's torchao float8 training rather than hand-rolled casts; start from their recipes, keep the first and last layers in BF16, and run an A/B against BF16 long enough to see late-training divergence.
  • When a run diverges, check the numerics before the hyperparameters: loss-scale collapse (FP16), attention or output logit growth (see numerical computing), Adam's \(\epsilon\) dominating tiny second moments, an FP8 scale that saturated.

Common misconceptions

\"Mixed precision halves the memory of training.\"

It halves activation memory and the bytes moved by matmuls, but standard mixed-precision Adam still holds 16 bytes per parameter of state: the FP32 master weights and moments are extra, not replaced. Memory savings on state come from sharding (ZeRO/FSDP), 8-bit optimisers or parameter-efficient fine-tuning.

\"BF16 is just a worse FP16.\"

It has three fewer mantissa bits but three more exponent bits: the same range as FP32. For training, range is what fails first (gradients underflow, activations overflow), so BF16 is the more robust choice. FP16's extra precision helps mainly inference and some precision-sensitive kernels.

\"FP8 training is FP8 everywhere.\"

Only the large matmuls run in FP8. Embeddings, output heads, normalisations, attention softmax, routers, master weights, optimiser state and gradient reductions stay in BF16 or FP32 in every published recipe.

Check yourself

Why does BF16 not need loss scaling while FP16 does?

Loss scaling exists to keep small gradients above the format's smallest representable value. FP16's 5-bit exponent bottoms out at about \(6\times10^{-8}\) (subnormal); BF16's 8-bit exponent reaches \(10^{-38}\) like FP32, so the gradients that fit in FP32 fit in BF16.

A weight of 3.0 is stored in BF16. What is the smallest update that changes it?

3.0 lies in \([2,4)\), where BF16 spacing is \(2^{1-7} = 2^{-6} = 0.0156\). Round-to-nearest changes the stored value only if the update exceeds half the spacing, 0.0078 (ties go to even). An Adam step of \(10^{-3}\times\) the weight (0.003) is lost entirely — hence FP32 master weights.

Why accumulate in FP32 but multiply in BF16?

A product's relative error is just the sum of its inputs' relative errors, bounded and independent of magnitude. A long sum loses the low bits of each small addend once the running total is large; with 7 mantissa bits, the sum stalls when it reaches about \(2^8\) times the typical term. The emulator's BF16 dot product stalls at 256 against a true 1,018.

What does dynamic loss scaling do when it sees an inf in the gradients, and why is skipping the step safe?

It skips the optimiser step (the gradients are invalid) and halves the scale, then retries on the next batch. Skipping occasional steps is like dropping a mini-batch: SGD is robust to that, and with a growth interval of thousands of steps it happens rarely.

In FP8 E4M3 with a per-tensor scale, a tensor's amax is 300 and a typical value is 0.01. Roughly how many significant bits does the typical value get?

The scale maps 300 to 448, so 0.01 becomes about 0.015, just under E4M3's smallest normal (0.0156) — it becomes subnormal, with spacing \(2^{-9}\approx0.002\), so only about 3 bits of resolution, a relative error up to ~7%. Values ten times smaller lose almost everything. A per-block scale (if the outlier is elsewhere) restores the full 3-bit mantissa.

Hard: why did DeepSeek-V3 need to promote FP8 partial sums to FP32 every 128 elements, if the tensor core already accumulates in 'FP32'?

On their H800s, the FP8 tensor-core accumulation path retains only about 14 bits, not full FP32. Over a long inner dimension (\(K=4096\)) the swamping effect builds up, giving relative errors near 2% in their test. Copying partial sums out to true FP32 registers every 128 elements (after scaling) bounds the length of any low-precision summation chain.

Hard: why must 4-bit formats use blocks of 16–32 values, while FP8 can often work with one scale per tensor?

E2M1 has a dynamic range of 12 (0.5 to 6), so a scale chosen for a group's largest value rounds everything more than ~12× smaller to zero. Real tensors have outliers 100× typical values, so a per-tensor scale destroys most of the tensor; a block of 16 contains an outlier rarely, and when it does only 15 neighbours suffer. E4M3's dynamic range is about \(2\times10^5\), so a 100× outlier still leaves ordinary values in its normal range.

Go deeper

Papers

Articles and documentation

Code

Where this leads

  • Distributed training — the 16 bytes per parameter that mixed precision does not remove, sharded across GPUs.
  • Quantisation — the same range-versus-precision trade applied to stored weights for inference: INT8, INT4, GPTQ, AWQ.
  • Kernels — where scale factors and FP32 accumulators actually live inside a matmul.
  • Compute maths — how bytes per parameter feed into memory and cost estimates.