4 Compute and Systems 4 / 5
  1. In this chapter
  2. LLM hardware basics
  3. GPUs and the Roofline Model
  4. GPU kernels
  5. Numerical Precision
  6. Collective Communication
All chapters →

Chapter 4 · Compute and Systems 4.4

Numerical Precision: Three Ways FP16, BF16 and FP8 Training Goes Wrong

Floating-point formats split a few bits between exponent (range) and mantissa (precision). Low-precision training fails in three ways: overflow, underflow (small gradients become 0) and swamping (small terms vanish in sums). Real Qwen2.5-0.5B data shows how large each is and what fixes it.

Intermediate 31 min read Updated Companion code ↓

After this page you will be able to

  • Read the bit layouts of FP32, BF16, FP16 and the two FP8 formats, compute their largest value, smallest normal number and spacing, and explain why the exponent sets the range and the mantissa sets the precision.
  • Tell overflow, underflow and swamping apart, and reproduce each with an experiment.
  • Explain why loss scaling is needed for FP16 but not for BF16, and write out the dynamic loss scaling algorithm (GradScaler).
  • Explain why matrix multiplications accumulate in FP32 and why FP8 training needs block-wise scaling.
  • Explain why softmax, normalization and the loss stay in FP32, and use the roofline to tell at which batch size lower precision pays off.
On this page
  1. How a format spends its bits
  2. Three failures
  3. Overflow: the softmax example
  4. Swamping: small numbers absorbed by big ones
  5. Accumulator precision: why matrix multiplies accumulate in FP32
  6. Underflow and loss scaling
  7. How small real gradients are
  8. Loss scaling: lifting the gradients into the FP16 range
  9. Dynamic loss scaling
  10. BF16: trading precision for range
  11. FP8: making 8 bits work
  12. Two formats and scaling
  13. Measured: how one outlier ruins a whole-tensor scale
  14. Accumulation precision and the DeepSeek-V3 recipe
  15. Operators that stay in FP32
  16. Precision and the roofline
  17. A practical checklist
  18. Common misconceptions
  19. Summary and exercises
  20. Quick self-test
  21. Further reading
  22. FAQ

A floating-point number has to encode both range and precision with a handful of bits: the exponent bits decide how large and how small a number can be, and the mantissa bits decide how far apart two neighbouring numbers are. With fewer bits, training and inference run into three kinds of failure: overflow (beyond the largest value, giving inf or NaN), underflow (below the smallest value, flushed to 0, which is what happens to small gradients in FP16), and swamping (when a small number is added to a large one, the small one is rounded away, worst in sums of thousands of terms). The remedies come in three kinds too: scale the numbers into the format’s useful range (loss scaling, FP8 block scaling), keep accumulators and master weights in a wider format (FP32 accumulation, FP32 master weights), and keep operators with exponentials and sums in FP32 (softmax, normalization, the loss).

The roofline on the previous page says that speed is set by how many bytes you move and how many operations you do per byte, and precision turns both knobs at once: half the bits per number halves the bytes, and the peak of the tensor cores usually doubles (an H100 SXM delivers 1,979 TFLOPS dense in FP8 against 989 TFLOPS in BF16). The price is the topic of this page: with fewer bits, the numbers misbehave. We first look at how a format spends its bits, then measure the three failures one by one on a real model (Qwen2.5-0.5B). Every experiment runs on a CPU, so you can reproduce all of it without a GPU. The page expands the claims in the section “why keep FP32” of Optimizers and Training Stability and lays the groundwork for FP8 and W8A8 in Quantization.

How a format spends its bits

A floating-point number has a sign bit ss, an exponent field ee (EE bits) and a mantissa field ff (MM bits). For a normal number the value is

x=(−1)s×2 e−b×(1+f2M),b=2E−1−1x=(-1)^{s}\times 2^{\,e-b}\times\Bigl(1+\frac{f}{2^{M}}\Bigr),\qquad b=2^{E-1}-1

where bb is the bias (127 for FP32, 15 for FP16, 7 for E4M3). The exponent sets the order of magnitude: each increment doubles the value. The mantissa sets how finely one order of magnitude is divided: between two consecutive powers of two there are 2M2^{M} numbers. When the exponent field is all zeros the number is subnormal: there is no implicit leading 1 and the value is 21−b×f/2M2^{1-b}\times f/2^{M}. Subnormals let values keep shrinking gradually below the smallest normal number, down to the smallest subnormal; anything smaller becomes 0.

Bit layouts of five floating-point formats Five rows of colored blocks whose widths are proportional to the number of bits: one sign bit, and exponent and mantissa widths that depend on the format. FP32 is 1, 8, 23; BF16 is 1, 8, 7 with the same range as FP32; FP16 is 1, 5, 10; FP8 E4M3 is 1, 4, 3; FP8 E5M2 is 1, 5, 2. On the right: the largest value, the smallest normal number and the gap next to 1 for each format. sign s exponent e: sets the range mantissa m: sets the precision FP32 32 bits 1 8 23 max 3.4×10³⁸ min normal 1.2×10⁻³⁸ gap at 1: 1.2×10⁻⁷ BF16 16 bits 1 8 7 max 3.4×10³⁸ min normal 1.2×10⁻³⁸ gap at 1: 7.8×10⁻³ FP16 16 bits 1 5 10 max 65,504 min normal 6.1×10⁻⁵ gap at 1: 9.8×10⁻⁴ FP8 E4M3 8 bits 1 4 3 max 448 min normal 0.0156 gap at 1: 0.125 FP8 E5M2 8 bits 1 5 2 max 57,344 min normal 6.1×10⁻⁵ gap at 1: 0.25
Block widths are proportional to the number of bits. FP16 and E5M2 share the 5-bit exponent, BF16 and FP32 share the 8-bit exponent; E4M3 has only 4 exponent bits and pushes its maximum to 448 by dropping infinities and keeping a single NaN pattern. The numbers on the right come from torch.finfo and match the table above.

The script below reads PyTorch’s torch.finfo to list, for each of the five formats, the largest value, the smallest normal number, the smallest subnormal and the spacing next to 1, and then checks what happens when numbers beyond the range are cast to FP8:

import math
import torch

FORMATS = [  # (name, dtype, sign + exponent + mantissa bits)
    ("FP32", torch.float32, (1, 8, 23)),
    ("BF16", torch.bfloat16, (1, 8, 7)),
    ("FP16", torch.float16, (1, 5, 10)),
    ("FP8 E4M3", torch.float8_e4m3fn, (1, 4, 3)),
    ("FP8 E5M2", torch.float8_e5m2, (1, 5, 2)),
]
print(f"{'format':9s}{'s+e+m':>9s}{'max':>10s}{'min normal':>12s}"
      f"{'min subnormal':>15s}{'gap at 1':>10s}")
for name, dt, (s, e, m) in FORMATS:
    fi = torch.finfo(dt)
    print(f"{name:9s}{f'{s}+{e}+{m}':>9s}{fi.max:10.3g}{fi.tiny:12.3g}"
          f"{fi.tiny * fi.eps:15.3g}{fi.eps:10.3g}")
x = torch.tensor([1000.0, 1e6])
print("1000 and 1e6 cast to E4M3:", x.to(torch.float8_e4m3fn).tolist())
print("1000 and 1e6 cast to E5M2:", x.to(torch.float8_e5m2).tolist())
format       s+e+m       max  min normal  min subnormal  gap at 1
FP32        1+8+23   3.4e+38    1.18e-38        1.4e-45  1.19e-07
BF16         1+8+7  3.39e+38    1.18e-38       9.18e-41   0.00781
FP16        1+5+10  6.55e+04     6.1e-05       5.96e-08  0.000977
FP8 E4M3     1+4+3       448      0.0156        0.00195     0.125
FP8 E5M2     1+5+2  5.73e+04     6.1e-05       1.53e-05      0.25
1000 and 1e6 cast to E4M3: [nan, nan]
1000 and 1e6 cast to E5M2: [1024.0, inf]

Four things to read from the table:

  • Exponent bits set the range. FP32 and BF16 both have 8 exponent bits: a maximum near 3.4×10383.4\times10^{38} and a smallest normal number near 1.2×10−381.2\times10^{-38}. FP16 and E5M2 both have 5, with maxima of only 65,504 and 57,344. E4M3 has 4 exponent bits and a maximum of 448.
  • Mantissa bits set the precision. Next to 1 the spacing is 2−M2^{-M} (last column), and the largest relative rounding error is 2−(M+1)2^{-(M+1)}. BF16 has 3 fewer mantissa bits than FP16, so it is 8 times less precise, but its range is dozens of orders of magnitude wider.
  • BF16 and E5M2 are “truncations”. BF16 is FP32 with 16 mantissa bits dropped, and E5M2 can be seen as an FP16 with a shorter mantissa (the wording of the FP8 paper), which makes converting to and from the parent format easy.
  • E4M3 gives up infinity. It keeps a single NaN bit pattern and reuses the codes that would have meant infinity and NaN for larger numbers, which lifts the maximum from 240 (under IEEE conventions) to 448. In PyTorch’s float8_e4m3fn the “fn” means finite: casting an out-of-range number to E4M3 gives NaN rather than saturating at 448 (in the output above, both 1000 and 1e6 became NaN). E5M2 follows IEEE and overflows to inf.

As a table (the rounding error bound is 2−(M+1)2^{-(M+1)}, and the number of significant bits is M+1M+1):

FormatMantissa bits MMLargest relative rounding errorSignificant decimal digits
FP32236.0×10−86.0\times10^{-8}7.2
FP16104.9×10−44.9\times10^{-4}3.3
BF1673.9×10−33.9\times10^{-3}2.4
E4M336.25×10−26.25\times10^{-2}1.2
E5M221.25×10−11.25\times10^{-1}0.9

A single rounding in E5M2 can be off by 12.5% and in E4M3 by 6.25%: FP8 is barely precise enough to express an order of magnitude, so it only works together with scaling that places the numbers where the format is most useful. That is the topic of the FP8 section below.

The lab below puts these rules in front of you: type any number and see what each of the five formats stores. Good ones to try first: 0.1 is inexact in all five, with a relative error from 1.5×10−81.5\times10^{-8} (FP32) to 6.25×10−26.25\times10^{-2} (E5M2); 1.001 turns back into 1 in BF16 and both FP8 formats because the gap between neighbours is wider than 0.001, which is the swamping you will meet below; 1000 is NaN in E4M3 and 1024 in E5M2; 65520 just crosses the FP16 limit and becomes inf; 1e-8 underflows to 0 in FP16 and both FP8 formats but is fine in BF16 and FP32; 1e-5 already falls into FP16’s subnormal range, where only a coarse grid with spacing of about 6×10−86\times10^{-8} is left.

Three failures

FailureWhen it happensConsequenceRemedy
OverflowMagnitude above the largest valueinf or NaN; one value can poison a whole tensorScale into range; use a format with more range
UnderflowMagnitude below half the smallest subnormalBecomes 0; information lostLoss scaling; a format with a wider exponent (BF16)
SwampingSmall number added to a large one, below half the spacingThe small number is rounded away; the update or the sum has no effectFP32 accumulator; FP32 master weights

Overflow: the softmax example

Softmax exponentiates every score. The largest FP16 value is 65504: e11≈59874e^{11}\approx59874 still fits, but e12≈162755e^{12}\approx162755 overflows to inf, numerator and denominator are both inf, and inf divided by inf is NaN. The stable form subtracts the maximum first, so that the largest exponential is exactly e0=1e^{0}=1; torch.softmax is implemented this way:

x = torch.tensor([12.0, 11.0, 0.0], dtype=torch.float16)
print("naive exp/sum:", (x.exp() / x.exp().sum()).tolist())
print("torch.softmax:", [round(v, 3) for v in torch.softmax(x, 0).tolist()])
naive exp/sum: [nan, 0.0, 0.0]
torch.softmax: [0.731, 0.269, 0.0]

The naive form returns [nan, 0.0, 0.0] and the whole row of attention is lost; the stable form returns the correct [0.731, 0.269, 0.0] (the third entry is about 4.5×10−64.5\times10^{-6} and shows as 0.0 after rounding to three decimals). Attention scores, logits and the sums of squares inside normalization are where overflow strikes most often.

Swamping: small numbers absorbed by big ones

Floating-point addition aligns the exponents and then rounds. When one number is more than about 2M+12^{M+1} times larger than the other, the small one falls entirely off the end of the mantissa during alignment, and adding it changes nothing. Three small experiments: where does adding 1.0 one at a time stall, what happens when a long series of tiny updates is added to one number, and does the order of summation matter?

def stall(dtype):
    """Add 1.0 one at a time until the sum stops changing; return it."""
    s, one = torch.tensor(0.0, dtype=dtype), torch.tensor(1.0, dtype=dtype)
    while True:
        t = s + one
        if t == s:
            return int(s)
        s = t

for dt in (torch.float16, torch.bfloat16):
    print(f"{dt}: adding 1.0 one at a time stalls at {stall(dt)}")
big = torch.tensor(2.0**24)
print(f"float32: is 2^24 + 1 == 2^24? {bool(big + 1 == big)}")
ones = torch.ones(10_000)
for dt in (torch.float32, torch.float16, torch.bfloat16):
    print(f"torch.sum(10,000 ones, {dt}) = {int(ones.to(dt).sum())}")
w16, w32 = torch.tensor(1.0, dtype=torch.bfloat16), torch.tensor(1.0)
step = torch.tensor(1e-4, dtype=torch.bfloat16)
for _ in range(1000):
    w16 = w16 + step              # the BF16 gap above 1.0 is 2^-7: update lost
    w32 = w32 + 1e-4
print(f"1.0 plus 1000 updates of 1e-4: BF16 {w16.item()}, "
      f"FP32 {w32.item():.4f}")
g = torch.Generator().manual_seed(0)
x = torch.randn(10**6, generator=g)
exact = x.double().sum().item()
orders = (("original order", x), ("reversed", x.flip(0)),
          ("shuffled", x[torch.randperm(10**6, generator=g)]))
for name, v in orders:
    print(f"float32 sum ({name}) minus exact: {v.sum().item() - exact:+.3e}")
torch.float16: adding 1.0 one at a time stalls at 2048
torch.bfloat16: adding 1.0 one at a time stalls at 256
float32: is 2^24 + 1 == 2^24? True
torch.sum(10,000 ones, torch.float32) = 10000
torch.sum(10,000 ones, torch.float16) = 10000
torch.sum(10,000 ones, torch.bfloat16) = 9984
1.0 plus 1000 updates of 1e-4: BF16 1.0, FP32 1.1000
float32 sum (original order) minus exact: -1.191e-04
float32 sum (reversed) minus exact: +1.251e-04
float32 sum (shuffled) minus exact: -1.191e-04
  • Running sums stall. FP16 stalls at 2048 (2112^{11}) when adding 1.0 one at a time: above that, neighbouring numbers are 2 apart, 2048 + 1 lands exactly halfway between two of them, and round-to-even takes it back to 2048. BF16 stalls at 256 (282^{8}), and FP32 at 2242^{24} (the output shows 224+1=2242^{24}+1=2^{24} is True). The stall point is exactly 2M+12^{M+1}.
  • The sum of ten thousand ones did not stall, and the BF16 value of 9984 is not an accumulation failure. torch.sum accumulates internally at higher precision and rounds once at the end; 9984 appears because between 8192 and 16384 BF16 can only represent multiples of 64, so 10000 itself cannot be stored and the nearest value is 9984. The hand-written FP16 loop (stall above) is what stops at 2048. A library reduction and a loop you write yourself are different things.
  • Small updates vanish completely. Next to 1.0 the BF16 spacing is 2−7≈0.00782^{-7}\approx0.0078, half of it is 0.00390.0039, dozens of times larger than 10−410^{-4}, so a weight of 1.0 plus a thousand updates of 10−410^{-4} is still 1.0, while FP32 reaches 1.1000. This is why optimizers need FP32 master weights: the learning rate times the gradient is usually far smaller than the weight itself and would be rounded away entirely if added to a 16-bit weight (the byte accounting of the model state is in The Compute and Memory Ledger of Training).
  • The order of summation changes the result. For a million random float32 numbers, all three orders are off from the float64 exact value by about 10−410^{-4}, but the reversed sum differs from the original order (the sign even flips), while the shuffled order happens to land on the same value as the original. Floating-point addition is not associative. That is why parallel reductions (threads on a GPU finish in no fixed order) make the loss differ in the last digits between two runs, and why the result of a multi-GPU all-reduce depends on the reduction order; see Collective Communication.

Accumulator precision: why matrix multiplies accumulate in FP32

One output element of a matrix multiply is a sum of KK products, and in a large model KK is the hidden size, thousands. The product of two BF16 numbers is exact in FP32, so any error comes from the summation. The script compares two ways to accumulate: in FP32 throughout and rounding to BF16 once at the end, versus rounding to BF16 after every addition. Errors are normalized by K\sqrt K (the typical size of the sum is about K\sqrt K):

def dot_errors(K, n=2000, seed=0):
    """n dot products of length K: FP32 accumulation then rounding, versus
    rounding to BF16 after every addition."""
    g = torch.Generator().manual_seed(seed)
    a = torch.randn(n, K, generator=g).bfloat16().float()
    b = torch.randn(n, K, generator=g).bfloat16().float()
    prod = a * b                  # BF16 x BF16 is exact in FP32
    ref = prod.double().sum(1)
    fp32 = prod.sum(1).bfloat16().double()
    acc = torch.zeros(n, dtype=torch.bfloat16)
    for k in range(K):
        acc = (acc.float() + prod[:, k]).bfloat16()
    return [((v.double() - ref).abs().mean() / K**0.5).item()
            for v in (fp32, acc)]

print("mean absolute error of a dot product / sqrt(K) (BF16 inputs):")
for K in (64, 256, 1024, 4096):
    e32, e16 = dot_errors(K)
    print(f"  K={K:<5d} FP32 accumulation {e32:.4f}  "
          f"BF16 accumulation {e16:.4f}  ({e16 / e32:.0f}x)")
mean absolute error of a dot product / sqrt(K) (BF16 inputs):
  K=64    FP32 accumulation 0.0011  BF16 accumulation 0.0066  (6x)
  K=256   FP32 accumulation 0.0011  BF16 accumulation 0.0126  (11x)
  K=1024  FP32 accumulation 0.0011  BF16 accumulation 0.0265  (23x)
  K=4096  FP32 accumulation 0.0011  BF16 accumulation 0.0490  (45x)

The FP32 error is a constant 0.0011, which comes only from the final rounding. The BF16-accumulated error grows with KK and is 45 times larger at K=4096K=4096. After normalization it still roughly doubles every time KK grows by 4, so the absolute error is roughly proportional to KK: each step’s rounding error is proportional to the running sum, and KK steps add up. Tensor cores therefore follow the convention of “low-precision inputs, FP32 accumulator”: it is the third technique of mixed-precision training (Micikevicius et al., 2017) and the premise of the BF16 dataflow described by Kalamkar et al. (2019).

This experiment simulates “what if the accumulator were only BF16”; it is not a measurement on a GPU. Hardware accumulators are not always really 32 bits wide: the DeepSeek-V3 paper measured that the FP8 matrix multiply on an H800 keeps only about 14 bits of accumulation precision inside the Tensor Core, a problem the FP8 section below takes up.

The small experiments of this section, recomputed in the browser number by number: where adding 1.0 stops, a hand-written loop against a library reduction for ten thousand 1.0s, how small updates are swallowed, how a dot product’s error grows with KK, and what the summation order does. Pick a format, press the buttons, drag the slider and watch where each printed number comes from.

Underflow and loss scaling

How small real gradients are

Gradients in backpropagation are often much smaller than activations. Micikevicius et al. (2017) measured a Mandarin speech-recognition model and found about 5% of the weight gradients below 2−242^{-24}, which become 0 in FP16; the SSD object detector simply diverged without loss scaling, and scaling the loss by 8 was enough to fix it. Models differ a lot, so measure rather than borrow someone else’s number.

The experiment below does one forward and backward pass of Qwen2.5-0.5B (Apache-2.0 license, released in BF16 and read here as FP32) and counts all 494 million weight gradients. It is an approximation: in real FP16 training the activation gradients underflow in each layer along the way, while here a finished FP32 weight gradient is simply cast to FP16 or BF16 to see how much falls outside the representable range. It estimates how bad underflow is; it does not predict a training outcome. To see the spread, three unrelated English passages are used, one forward and backward pass each.

Environment: Apple M2 Max (CPU, 1 thread), Python 3.14.3, PyTorch 2.10.0, transformers 5.3.0; the script printed identical output in two independent runs.

import os
os.environ["HF_HUB_OFFLINE"] = "1"
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.utils import logging as hf_logging
hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()
torch.set_num_threads(1)
NAME = "Qwen/Qwen2.5-0.5B"      # Apache-2.0; released in BF16, read as FP32
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME, dtype=torch.float32)
params = list(model.parameters())
n = sum(p.numel() for p in params)
TEXTS = [
    "Mixed-precision training runs the forward and backward passes in low "
    "precision while keeping the master weights and optimizer state in FP32. "
    "Gradients are usually tiny, so a fraction of them underflows to zero in "
    "FP16; the loss is therefore multiplied by a scale factor first and the "
    "gradients are divided by it again before the weight update.",
    "Distributed training splits each batch across many GPUs; every GPU "
    "computes its own gradient and the results are averaged with an "
    "all-reduce. The communication volume is proportional to the number of "
    "parameters, so large models often compress their gradients to low "
    "precision before sending them.",
    "A serving system has to handle many requests at once. Each request has "
    "its own KV cache, and the longer the cache, the more data every step has "
    "to read, which is why decoding speed is mostly limited by memory "
    "bandwidth.",
]
acts = []                 # inputs of the 24 down_proj layers (first text only)
hooks = [layer.mlp.down_proj.register_forward_hook(
             lambda mod, args, out: acts.append(args[0].detach()[0]))
         for layer in model.model.layers]

def run(text):
    """One forward + backward pass (loss = mean over positions)."""
    model.zero_grad(set_to_none=True)
    ids = tok(text, return_tensors="pt").input_ids
    loss = model(ids, labels=ids).loss
    loss.backward()
    return ids.shape[1], loss.item()

def flush_fractions():
    """Share of gradients that become 0 in FP16 / BF16, and the share that
    lands in the FP16 subnormal range."""
    z16 = sub16 = z_bf16 = 0
    for p in params:
        g = p.grad.flatten()
        h = g.to(torch.float16)
        z16 += ((h == 0) & (g != 0)).sum().item()
        sub16 += ((h != 0) & (h.abs() < 2.0**-14)).sum().item()
        z_bf16 += ((g.to(torch.bfloat16) == 0) & (g != 0)).sum().item()
    return z16 / n, sub16 / n, z_bf16 / n

print(f"{n / 1e6:.0f}M parameters; one forward + backward pass per text, "
      f"all gradients counted:")
print(f"{'text':>4s}{'tokens':>8s}{'loss':>7s}{'FP16 zero':>11s}"
      f"{'FP16 subnormal':>16s}{'BF16 zero':>11s}")
for i, text in enumerate(TEXTS):
    tokens, loss = run(text)
    z16, sub16, z_bf16 = flush_fractions()
    print(f"{i + 1:4d}{tokens:8d}{loss:7.2f}{z16:11.2%}{sub16:16.2%}"
          f"{z_bf16:11.2%}")
    if i == 0:
        for h in hooks:
            h.remove()
tokens, loss = run(TEXTS[0])     # the analysis below uses the first text
494M parameters; one forward + backward pass per text, all gradients counted:
text  tokens   loss  FP16 zero  FP16 subnormal  BF16 zero
   1      69   3.13     18.26%          15.43%      0.00%
   2      52   3.35     17.72%          15.43%      0.00%
   3      46   3.88     19.00%          13.66%      0.00%

In FP16, all three passages lose about 18% of their gradients to zero, and another 14% to 15% land in the subnormal range (2−242^{-24} to 2−142^{-14}, where precision degrades gradually); in BF16 the underflow share is 0.00%. The three passages differ by little more than a percentage point, so the magnitude is stable. With three short texts and one model, do not extrapolate the numbers to other models; the order of magnitude and the phenomenon are the point.

Loss scaling: lifting the gradients into the FP16 range

Loss scaling uses the linearity of the chain rule: multiply the loss by SS before backpropagation and every gradient is multiplied by SS; divide by SS again before the weight update. The result is mathematically unchanged; only the numbers have been shifted into a range FP16 represents better. The script sweeps S=2kS=2^{k} for the gradients of the first passage:

KS = (0, 4, 8, 10, 12, 13, 14, 16, 20)            # loss scale 2^k
zero = {k: 0 for k in KS}
inf = {k: 0 for k in KS}
gmax = lost_sq = all_sq = back = flushed = 0
for p in params:
    g = p.grad.flatten()
    gmax = max(gmax, g.abs().max().item())
    gone = (g.to(torch.float16) == 0) & (g != 0)
    flushed += gone.sum().item()
    adam = g.abs() / (g.abs() + 1e-8) >= 0.5      # Adam step 1 moves >= 0.5 lr
    back += (gone & adam).sum().item()
    lost_sq += g[gone].double().pow(2).sum().item()
    all_sq += g.double().pow(2).sum().item()
    for k in KS:
        s = (g * 2.0**k).to(torch.float16)
        zero[k] += ((s == 0) & (g != 0)).sum().item()
        inf[k] += torch.isinf(s).sum().item()
print(f"largest |gradient| {gmax:.1f}; largest finite FP16 value is 65504")
print(f"flushed gradients hold {lost_sq / all_sq:.1e} of the squared norm")
print(f"{back / flushed:.1%} of them would move by >= 0.5 lr in Adam step 1")
print(f"{'k':>3s}{'flushed to 0':>14s}{'overflowed to inf':>20s}")
for k in KS:
    print(f"{k:3d}{zero[k] / n:14.4%}{inf[k]:20,d}")
best = max(k for k in KS if inf[k] == 0)
init = int(math.log2(torch.amp.GradScaler("cpu").get_scale()))
print(f"largest scale without overflow: 2^{best}; "
      f"GradScaler default initial scale: 2^{init}")
k, skipped = init, 0       # simulate GradScaler: overflow skips and halves
while gmax * 2.0**k >= 65520:      # values >= 65520 round to inf in FP16
    k, skipped = k - 1, skipped + 1
print(f"if every step had this gradient: from 2^{init}, skip {skipped} steps, "
      f"then settle at 2^{k}")
largest |gradient| 6.8; largest finite FP16 value is 65504
flushed gradients hold 8.7e-13 of the squared norm
20.6% of them would move by >= 0.5 lr in Adam step 1
  k  flushed to 0   overflowed to inf
  0      18.2576%                   0
  4       8.0319%                   0
  8       1.2298%                   0
 10       0.3300%                   0
 12       0.0818%                   0
 13       0.0408%                   0
 14       0.0208%                  45
 16       0.0057%               1,436
 20       0.0004%              45,527
largest scale without overflow: 2^13; GradScaler default initial scale: 2^16
if every step had this gradient: from 2^16, skip 3 steps, then settle at 2^13

Reading the table:

  • Underflow falls as kk grows. At k=0k=0, 18.2576% of the gradients become 0; at k=8k=8 it is 1.2298%, at k=12k=12 it is 0.0818% and at k=13k=13 it is 0.0408%.
  • Scale too far and it overflows, and one overflow is already too many. The largest gradient is 6.8, so S gmax⁡<65504S\,g_{\max}<65504 requires SS below about 9630, and the largest power of two that does not overflow is 213=81922^{13}=8192. At k=14k=14 there are already 45 gradients overflowing to inf (out of 494 million), and a single inf contaminates the whole gradient, so the update must be discarded. At k=20k=20 it is 45,527.
  • “Only 8.7×10−138.7\times10^{-13} was lost” does not mean “safe to lose”. The flushed gradients hold only 8.7×10−138.7\times10^{-13} of the squared norm, which barely matters for SGD; but Adam normalizes per coordinate, so the update does not depend on how large the gradient is, and 20.6% of the coordinates flushed to zero would have moved by at least half a learning rate in the first step. Almost every large model trains with an Adam-type optimizer, so these small gradients cannot be written off as noise.

Dynamic loss scaling

The best SS changes during training, so PyTorch’s torch.amp.GradScaler adjusts it automatically. The defaults are init_scale=65536 (2162^{16}), growth_factor=2.0, backoff_factor=0.5 and growth_interval=2000, and the algorithm has four steps:

  1. Multiply the loss by the current SS and backpropagate.
  2. Check the gradients for inf or NaN.
  3. If found: discard the step (no weight update) and halve SS.
  4. If not: divide the gradients by SS and update as usual; after 2000 consecutive clean steps, double SS to probe a larger value.

The last line of the output above simulates this: if every step had the same gradients as this passage, starting from the default 2162^{16} the scaler skips 3 steps (2162^{16}, 2152^{15} and 2142^{14} all overflow) and settles at 2132^{13} from the fourth step on. A few skipped steps at the start cost nothing because the model has not been updated yet; in steady state it probes once every 2000 steps and occasionally skips one more, which is negligible. The advice of Micikevicius et al. (2017) is that a larger factor does no harm as long as nothing overflows.

BF16: trading precision for range

BF16 has the same exponent width as FP32 and its underflow share in the table above is 0.00%, so it needs no loss scaling; Kalamkar et al. (2019) trained image, speech, language and recommendation models in BF16 with no change to any hyperparameter and matched FP32. The price is a 7-bit mantissa: swamping becomes easier, so accumulators, master weights and optimizer state have to stay in FP32, which is exactly the conclusion of the two experiments before.

FP8: making 8 bits work

Two formats and scaling

The FP8 paper (Micikevicius et al., 2022, from NVIDIA, Arm and Intel) defines E4M3 and E5M2 and recommends E4M3 for weights and activations (more precise) and E5M2 for gradients (more range). The range of E4M3 is only about 18 binades (maximum 448, smallest subnormal 2−92^{-9}) against about 40 for FP16, so FP8 cannot be used without scaling: in the paper’s post-training quantization experiments, casting to FP8 without a scaling factor caused a clear loss of accuracy. The principle of scaling is to put the tensor’s largest magnitude near the format’s largest value:

s=max⁡∣x∣xmax⁡FP8,x^=round⁡FP8(x/s)⋅ss=\frac{\max|x|}{x_{\max}^{\text{FP8}}},\qquad \hat{x}=\operatorname{round}_{\text{FP8}}(x/s)\cdot s

The paper also notes that the FP16 habit of skipping the step and halving the scale on overflow is a poor fit for FP8: the range is so narrow that overflows are far more frequent and too many updates would be skipped. So the FP8 scale has to be computed from the data’s maximum at each quantization (some implementations use the history of the last few steps, called delayed scaling) rather than found by trial and error.

Measured: how one outlier ruins a whole-tensor scale

The problem is that the maximum is set by the most extreme value. The experiment below takes the input of down_proj (the output projection of the feed-forward block, so the output of SwiGLU) in each layer of Qwen2.5-0.5B and compares two scaling granularities: one scale for the whole tensor, and one scale per 1x128 values (the granularity DeepSeek-V3 uses for activations). This tensor is exactly the activation that an FP8 forward matrix multiply has to quantize. “err” in the output is the relative RMS error after quantizing and dequantizing, and “0” is the share of non-zero values flushed to 0:

def blocks(x, bh, bw):
    """Cut a matrix into bh x bw tiles, one flattened tile per row."""
    h, w = x.shape
    return (x.reshape(h // bh, bh, w // bw, bw)
             .permute(0, 2, 1, 3).reshape(-1, bh * bw))

def quantize(x, dt, bh, bw):
    """One scale per tile (amax / FP8 max); quantize, then dequantize.
    Returns the relative RMS error and the share of non-zero values that
    were flushed to zero."""
    xb = blocks(x, bh, bw)
    s = xb.abs().amax(1, keepdim=True) / torch.finfo(dt).max
    q = (xb / s.clamp(min=1e-30)).to(dt).float() * s
    err = ((q - xb).pow(2).sum() / xb.pow(2).sum()).sqrt().item()
    return err, ((q == 0) & (xb != 0)).float().mean().item()

E4M3, E5M2 = torch.float8_e4m3fn, torch.float8_e5m2
rows = []
for i, x in enumerate(acts):
    h, w = x.shape
    ratio = (x.abs().max() / x.abs().median()).item()
    whole, tile = quantize(x, E4M3, h, w), quantize(x, E4M3, 1, 128)
    rows.append((i, ratio, *whole, *tile))
print("inputs of the 24 down_proj layers, E4M3. whole: one scale for the")
print("tensor; tile: one scale per 1x128 values; zero: share flushed to 0.")
print(f"{'layer':>5s}{'amax/median':>13s}{'whole err':>11s}{'whole 0':>9s}"
      f"{'tile err':>10s}{'tile 0':>8s}")
worst = sorted(rows, key=lambda r: -r[1])[:3]
for i, ratio, et, ft, eb, fb in [rows[12]] + worst:
    print(f"{i:5d}{ratio:13.0f}{et:11.4f}{ft:9.2%}{eb:10.4f}{fb:8.2%}")
for i, *_ in worst:
    x = acts[i]
    t, c = divmod(x.abs().argmax().item(), x.shape[1])
    print(f"layer {i}: the largest value is at token {t}, channel {c}, "
          f"|x| = {x.abs().max():.0f}")
rest = [r for r in rows if r not in worst]
lo, hi = min(r[3] for r in rest), max(r[3] for r in rest)
top = max(r[1] for r in rest)
print(f"the other {len(rest)} layers: amax/median at most {top:.0f},")
print(f"  whole-tensor zero share {lo:.2%} to {hi:.2%}, tile at most "
      f"{max(r[5] for r in rest):.2%}")
wgt = model.model.layers[12].mlp.down_proj.weight.detach()
print("layer 12 down_proj, one scale per tensor, relative RMS error:")
for name, x in (("activations", acts[12]), ("weights", wgt)):
    rel = ((x.bfloat16().float() - x).pow(2).sum() / x.pow(2).sum()).sqrt()
    h, w = x.shape
    print(f"  {name} {h}x{w}: BF16 {rel:.4f}  E4M3 "
          f"{quantize(x, E4M3, h, w)[0]:.4f}  E5M2 "
          f"{quantize(x, E5M2, h, w)[0]:.4f}")
print(f"128x128 tiles (weights, E4M3): {quantize(wgt, E4M3, 128, 128)[0]:.4f}")
inputs of the 24 down_proj layers, E4M3. whole: one scale for the
tensor; tile: one scale per 1x128 values; zero: share flushed to 0.
layer  amax/median  whole err  whole 0  tile err  tile 0
   12           82     0.0263    0.04%    0.0224   0.01%
    2        34771     0.0015    7.33%    0.0010   0.01%
    3        21245     0.0126    4.74%    0.0013   0.01%
   21        12740     0.0084    2.63%    0.0027   0.03%
layer 2: the largest value is at token 0, channel 813, |x| = 1418
layer 3: the largest value is at token 0, channel 2247, |x| = 1026
layer 21: the largest value is at token 0, channel 567, |x| = 1527
the other 21 layers: amax/median at most 879,
  whole-tensor zero share 0.03% to 0.20%, tile at most 0.02%
layer 12 down_proj, one scale per tensor, relative RMS error:
  activations 69x4864: BF16 0.0017  E4M3 0.0263  E5M2 0.0527
  weights 896x4864: BF16 0.0000  E4M3 0.0265  E5M2 0.0527
128x128 tiles (weights, E4M3): 0.0265
  • Most layers are fine with one scale. Layer 12 has a maximum 82 times its median, E4M3 has a relative error of 0.0263 and only 0.04% of the values are flushed to zero; the other 21 layers all have a maximum at most 879 times the median and flush between 0.03% and 0.20%.
  • A few layers have “massive activations”. The maxima in layers 2, 3 and 21 are 34771, 21245 and 12740 times the median: in every one of them a single channel (813, 2247 and 567) of token 0 reaches an absolute value above 1000. This is consistent with the “massive activations” described by Sun et al. (2024): a handful of activations are tens of thousands of times larger than the median and sit in a few fixed channels at the starting token (they measured the residual stream; here we measure the input of the projection that writes into it). With one whole-tensor scale, these three layers flush 7.33%, 4.74% and 2.63% of their values to zero; block scaling confines the outlier to one block and every other block has its own scale, which brings the flushed share down to 0.01%, 0.01% and 0.03%.
  • RMS error can mislead. Layer 2 has a whole-tensor RMS error of only 0.0015, smaller than a typical layer: the error is normalized by the norm, and the norm is dominated by the single huge value, which is quantized very accurately. What suffers is the other 7.33% of the values. When you evaluate a quantization scheme, look at the distribution (the share flushed to zero), not only at the overall error.
  • Weights have no outliers. For the layer-12 down_proj weight, the whole-tensor scale and 128x128 blocks give the same error, 0.0265. The weights were released in BF16, so converting back to BF16 has an error of 0.0000.
  • Each mantissa bit removed doubles the error. E4M3 has an error of 0.0263 and E5M2 0.0527, while BF16 has only 0.0017: FP8 rounding error is more than ten times that of BF16. That is one reason E5M2 is used only for gradients, where range matters, and not for activations and weights.

Limitations of the experiment: one model and one passage of 69 tokens; the “whole-tensor” scale uses the current tensor’s maximum (some real systems use the history of the last few steps); quantize-then-dequantize simulates rounding error only, not the accumulation precision of an FP8 matrix multiply, and it is not a training experiment.

The price of tiles is one extra scale per tile: with one FP32 scale per 128 elements, each element costs 0.25 bits more on average.

Accumulation precision and the DeepSeek-V3 recipe

DeepSeek-V3 published a complete FP8 training recipe in which the findings above all have a counterpart: activations are scaled in 1×1281\times128 tiles and weights in 128×128128\times128 blocks, with scales computed online; every tensor uses E4M3, and fine-grained scaling makes up for the dynamic range; the FP8 matrix multiply on an H800 keeps only about 14 bits of accumulation precision inside the Tensor Core, so every 128 elements the partial sum is promoted into FP32 registers on the CUDA cores; embeddings, the output head, MoE gating, normalization and attention operators stay in BF16 or FP32, the master weights and weight gradients are FP32, and the two AdamW moments are BF16. Details and the ablations are in the DeepSeek-V3 paper walkthrough. The factor of 45 in the accumulation experiment above is why the accumulation precision has to be raised there.

Building “one scale per block” into the hardware format gives the microscaling (MX) formats (Rouhani et al., 2023): every 32 elements share one 8-bit E8M0 scale (a power of two), and the elements can be FP8, FP6, FP4 or INT8 (MXFP8, MXFP6, MXFP4, MXINT8). Each element costs 0.25 bits more on average, the same overhead as one FP32 scale per 128 elements, with a 4 times finer granularity.

Operators that stay in FP32

Not every operator is suited to low precision. PyTorch’s autocast converts linear layers and convolutions to FP16 or BF16 while a list of operators is automatically cast back to FP32, including softmax, log_softmax, layer_norm, cross_entropy, exp, log, sum, norm and cumsum (see the PyTorch documentation); the documentation’s reason is that such operators (reductions) often need the dynamic range of FP32. They share a trait: they contain exponentials (overflow) or sums (swamping), and on the roofline they are bandwidth-bound and barely use any compute, so FP32 hardly slows the whole down.

  • Softmax and attention. The example above makes the case; the online softmax of FlashAttention also subtracts the current maximum (see Efficient Attention).
  • Normalization. RMSNorm sums squares over the hidden dimension, which is a long sum of thousands of terms.
  • The loss. The logsumexp in cross-entropy is the same story as softmax; when VV is large the logits themselves deserve FP32 (see the logits item in The Compute and Memory Ledger of Training).
  • Optimizer state and master weights. The second moment is a running average of squared gradients, much smaller than the gradient itself, and the experiments above show that master weights have to be FP32.

Precision and the roofline

Back to the roofline of the previous page. The arithmetic intensity of a linear layer is about I≈2B/wI\approx2B/w (BB is the batch size, ww the bytes per weight, ignoring activation traffic for large matrices), and the batch size at which it becomes compute-bound is B∗≈ridge×w/2B^{*}\approx\text{ridge}\times w/2. An H100 SXM has 3.35 TB/s of bandwidth:

Configurationww (bytes)Dense peakRidge (FLOP/byte)Batch size where it turns compute-bound
BF16 weights and activations2989 TFLOPS295about 295
FP8 weights and activations11,979 TFLOPS591about 295
Weight-only INT4, BF16 compute (W4A16)0.5989 TFLOPS295about 74

FP8 halves the bytes and doubles the peak at the same time, so the ridge and the arithmetic intensity double together: the batch size at which the layer becomes compute-bound does not change, but both sides run twice as fast. Weight-only quantization changes the bytes only: it shortens the time to read the weights at small batch sizes, the range where it helps most, but beyond a batch of about 74 the layer is compute-bound and weight quantization no longer speeds anything up, which is why Quantization says prefill does not necessarily get faster. (The scale factors of INT4 take about 3% more bytes, ignored here.)

A practical checklist

Tensor or operatorCommon precisionWhy
Inputs to forward and backward matmulsBF16; or FP8 (needs block scaling)Enough range, fewer bytes, faster tensor cores
Matmul accumulatorFP32 (on H100, FP8 must be promoted to FP32 periodically)Swamping: BF16 accumulation error grows with KK
Master weightsFP32Updates below half the spacing are absorbed
Optimizer stateFP32 (DeepSeek-V3 keeps the moments in BF16)The second moment is small and a long running average
Gradients (cross-GPU reduction of weight gradients)FP32 or BF16A reduction is a sum; Llama 3’s reduce-scatter runs in FP32
Softmax, normalization, lossFP32Exponentials and sums: overflow and swamping
Loss in FP16 trainingDynamic loss scalingSmall gradients underflow
KV cache and inference weightsBF16, FP8, INT8, INT4Bytes set capacity and bandwidth, see Quantization

Common misconceptions

  1. “BF16 is more precise than FP16.” The opposite: BF16 has a 7-bit mantissa and FP16 a 10-bit one. BF16’s advantage is range, not precision. It is easier to train with because gradients rarely underflow and no loss scaling is needed.
  2. “With mixed precision, everything is 16-bit.” Master weights, moments, accumulators, softmax and normalization are in FP32, which is why the model state costs 16 bytes per parameter rather than 4 (see The Compute and Memory Ledger of Training).
  3. “FP8 just means casting the tensor to FP8.” Without scaling, numbers above 448 are NaN in E4M3 and numbers below 2−92^{-9} are 0; and with a single scale for the whole tensor one outlier can wipe out the rest (7.33% in this page’s experiment).
  4. “A NaN loss means the learning rate is too high.” It may be an FP16 overflow or an exp overflow inside softmax. The order of checks is in Optimizers and Training Stability.
  5. “The overall error tells you whether a quantization is good.” Massive activations make the overall error look tiny (0.0015 in layer 2) while a large share of the remaining values is flushed to zero; look at the share flushed to zero and at the distribution too.

Summary and exercises

  • The exponent bits set the range and the mantissa bits set the precision; BF16 has the range of FP32, FP16 has a narrow range, and E4M3 and E5M2 have only 8 bits and must be scaled.
  • Three failures: overflow (scale into range), underflow (loss scaling, a wider exponent), swamping (FP32 accumulators and master weights).
  • Small FP16 gradients underflow in bulk (about 18% measured); loss scaling lifts them into range, and dynamic scaling finds the largest usable factor by skipping a step and halving on overflow; BF16 does not need it.
  • Matrix multiplies accumulate in FP32: BF16 accumulation error grows with KK and is 45 times the FP32 error at K=4096K=4096.
  • FP8 needs block-wise scaling: the massive activations of a few layers make whole-tensor scaling flush 2.63% to 7.33% of the values, and 1x128 tiles bring that down to about 0.01% to 0.03%.
  • Softmax, normalization and the loss stay in FP32; FP8 doubles the ridge and the arithmetic intensity together, so the batch-size threshold stays put.

Quick self-test

1. Which statement about FP16 and BF16 is correct?

  • BF16 has a longer mantissa, so it is more precise
  • BF16 has the same 8 exponent bits as FP32, hence the same range, but only a 7-bit mantissa, less precise than FP16’s 10 bits
  • FP16 has the same range as FP32, so it needs no loss scaling
  • Both are 16-bit, so their numerical properties are the same

In the table the largest FP16 value is 65,504 and for BF16 it is 3.4×10383.4\times10^{38}; the spacing next to 1 is 0.000977 for FP16 and 0.00781 for BF16. BF16 traded precision for range, so gradients almost never underflow and no loss scaling is needed.

2. In the experiment, multiplying the gradients by 2132^{13} cut the share flushed to zero from 18.2576% to 0.0408%. Why not multiply by 2202^{20} to make it even lower?

  • Because 2202^{20} is not representable in FP16
  • Because the largest gradient is 6.8, multiplying by 2202^{20} pushes it far beyond 65504, 45,527 gradients overflow to inf, and the update has to be discarded
  • Because the larger the factor, the higher the share that underflows
  • Because loss scaling can only use 2132^{13}

Overflow is worse than underflow: one inf contaminates the whole gradient. The largest allowed factor is set by the largest gradient, S<65504/6.8≈9630S<65504/6.8\approx9630, so 2132^{13}; at k=14k=14 there are already 45 overflowing gradients.

3. What does GradScaler do when it finds inf or NaN in a step’s gradients?

  • Replace inf with 65504 and continue the update
  • Discard the step (no weight update), halve the scale factor, and double it again after 2000 consecutive clean steps
  • Stop training with an error
  • Recompute the step in FP32

The defaults are init_scale=65536, backoff_factor=0.5 and growth_interval=2000. In the simulation above, starting at 2162^{16} it skips 3 steps and settles at 2132^{13}. The FP8 paper points out that this strategy is a poor fit for FP8, whose narrower range would skip too many updates.

4. How does the error of a dot product that rounds to BF16 after every addition (BF16 accumulation) change with KK?

  • It does not depend on KK and stays around 0.0011
  • It grows with KK: normalized by K\sqrt K it rises from 0.0066 at K=64K=64 to 0.0490 at K=4096K=4096, 45 times the FP32 accumulation (0.0011)
  • It shrinks with KK because the errors cancel
  • It only matters for KK below 256

Each step’s rounding error is proportional to the running sum and KK steps accumulate, so the absolute error is roughly proportional to KK. The FP32-accumulated error comes only from the last rounding and does not depend on KK.

5. The down_proj input of layer 2, quantized to E4M3 with one scale for the whole tensor, has a relative RMS error of only 0.0015, yet 7.33% of its values become 0. How should you read that?

  • The RMS error is tiny, so the quantization is fine
  • A value of about 1418 at token 0 sets the scale; the RMS error is normalized by the norm and dominated by that value, while the rest of the values are scaled below E4M3’s smallest value and flushed to zero, so overall error alone is not a good check
  • The 7.33% is E4M3’s own rounding error and does not depend on the scaling
  • Storing the FP32 scale in BF16 would fix it

With the same E4M3 but one scale per 1x128 values, the share flushed to zero falls to 0.01%, so the problem is the granularity of the scale, not the format.

6. On an H100, if the weights and activations of a linear layer both become FP8 (peak doubled, bytes halved), what happens to the batch size at which the layer turns compute-bound?

  • It doubles, to about 591
  • It stays about the same, near 295: halving the bytes doubles the arithmetic intensity, which cancels the doubled ridge
  • It halves, to about 148
  • It does not depend on precision and is always 153

B∗≈ridge×w/2B^{*}\approx\text{ridge}\times w/2: for BF16 it is 295×2/2=295295\times2/2=295, for FP8 it is 591×1/2≈295591\times1/2\approx295. 153 is the ridge of the A100.

Exercises:

  1. A gradient has the value 10−810^{-8}. What is it stored as in FP16? What if it is multiplied by 2122^{12} first and then stored in FP16? And in BF16? (The smallest FP16 subnormal is 2−24≈5.96×10−82^{-24}\approx5.96\times10^{-8}.)
  2. DeepSeek-V3 scales activations in 1×1281\times128 tiles, one scale per tile. Assume the scale is stored in FP32. How many scales does a 4096-dimensional activation vector need, and how many extra bits does each FP8 element carry on average? What if it were an MX format (one 8-bit E8M0 scale per 32 elements)?
  3. For an H100 SXM (BF16 dense 989 TFLOPS, FP8 dense 1,979 TFLOPS, bandwidth 3.35 TB/s), use B∗≈ridge×w/2B^{*}\approx\text{ridge}\times w/2 to estimate the batch size at which a linear layer turns compute-bound in BF16, in FP8, and with weight-only INT4 (W4A16, computing on BF16 tensor cores, ignoring the scale factors).
Reference answers
  1. FP16: 10−810^{-8} is below 2−25≈2.98×10−82^{-25}\approx2.98\times10^{-8} (half the smallest subnormal), so it rounds to 0. Multiplied by 2122^{12} it is 4.096×10−54.096\times10^{-5}, below the smallest normal number 2−14≈6.1×10−52^{-14}\approx6.1\times10^{-5}, so it lands in the subnormal range with spacing 2−242^{-24} and is stored as 687×2−24≈4.095×10−5687\times2^{-24}\approx4.095\times10^{-5}, a relative error of about 0.03%; dividing by 2122^{12} before the update recovers the gradient. BF16: the range reaches down to 10−3810^{-38}, so it is stored as about 1.0012×10−81.0012\times10^{-8}, a relative error of about 0.12%, below 2−82^{-8}.
  2. 4096/128=324096/128=32 scales, 32×32=102432\times32=1024 bits in total, 1024/4096=0.251024/4096=0.25 bits per element, so about 8.25 bits per element. An MX format has one 8-bit scale per 32 elements: 8/32=0.258/32=0.25 bits, the same 0.25 bits but with a 4 times finer granularity.
  3. BF16: the ridge is 989/3.35≈295989/3.35\approx295, so B∗≈295×2/2=295B^{*}\approx295\times2/2=295. FP8: the ridge is 1979/3.35≈5911979/3.35\approx591, so B∗≈591×1/2≈295B^{*}\approx591\times1/2\approx295, the same as BF16. W4A16: w=0.5w=0.5, the ridge is still 295, so B∗≈295×0.5/2≈74B^{*}\approx295\times0.5/2\approx74. Conclusion: FP8 doubles both sides without moving the threshold; weight-only quantization lowers the threshold to about 74, and beyond that batch size it no longer speeds anything up.

Further reading

FAQ

What is the difference between FP16, BF16 and FP32, and which should I train with?
They differ in how the bits are split. FP32 has 8 exponent and 23 mantissa bits. FP16 has 5 exponent and 10 mantissa bits: its largest value is only 65504, its smallest normal number is about 6.1e-5, and small gradients underflow to 0. BF16 has 8 exponent and 7 mantissa bits: the same range as FP32 but less precision than FP16. Because the range is wide enough, BF16 training usually needs no loss scaling, so large-model pretraining today usually uses BF16 as its baseline; FP16 needs loss scaling but has a longer mantissa and is still common for inference. Whichever you pick, keep the master weights, the optimizer state and the matrix-multiply accumulators in FP32.
What is loss scaling, and why does BF16 not need it?
Loss scaling multiplies the loss by a factor S before the backward pass, which scales every gradient by S, and divides by S again before the weight update. It lifts small gradients that fall below the FP16 range back into it so they are not flushed to zero. Measured here on Qwen2.5-0.5B: about 18% of the 494 million gradients underflow to 0 in FP16; multiplying by 2^13 brings that down to 0.04%, and one more doubling overflows 45 gradients to inf. BF16 has the same exponent width as FP32, so the same gradients underflow 0.00% of the time and no scaling is needed. Dynamic loss scaling (PyTorch's GradScaler) starts at 2^16, skips the step and halves the factor whenever it sees inf or NaN, and doubles it after 2000 consecutive clean steps.
Why does FP8 training need block-wise scaling, and how do E4M3 and E5M2 differ?
E4M3 (4 exponent bits, 3 mantissa bits, maximum 448) is more precise; E5M2 (5 exponent bits, 2 mantissa bits, maximum 57344) has more range. The FP8 paper by NVIDIA and others recommends E4M3 for weights and activations and E5M2 for gradients. FP8 has so little range that with one scale for the whole tensor a single outlier sets the scale and pushes everything else below the smallest value, where it becomes 0. Measured on the 24 down_proj inputs of Qwen2.5-0.5B: three layers have a maximum more than 10,000 times the median (all at token 0), and whole-tensor scaling flushes 2.63% to 7.33% of their values to zero; one scale per 1x128 values brings that down to about 0.01% to 0.03%. DeepSeek-V3 trains this way: 1x128 tiles for activations and 128x128 blocks for weights.
Why do matrix multiplications accumulate in FP32?
One output element is a sum of K products, and K is in the thousands in large models. If the accumulator is only BF16, every addition rounds, the rounding error grows with the running sum, and big terms swallow small ones. In the simulation here, for K=4096 a dot product that rounds to BF16 after every addition has 45 times the error of FP32 accumulation, and the error grows with K, while the FP32-accumulated error does not depend on K. Tensor cores therefore take low-precision inputs and accumulate in FP32. FP8 is the exception: DeepSeek-V3 reports that the FP8 matrix multiply on H800 keeps only about 14 bits of accumulation precision inside the Tensor Core, so every 128 elements the partial sum is promoted into FP32 registers on the CUDA cores.
Which tensors must stay in FP32 in mixed-precision training, and what goes wrong with softmax in FP16?
Keep in FP32: the master weights (an update far smaller than the weight is rounded away in BF16; in the experiment here adding 1e-4 to 1.0 a thousand times leaves BF16 at 1.0 and FP32 at 1.1000), the optimizer state (DeepSeek-V3 is a rare exception that stores the moments in BF16), the matrix-multiply accumulators, and operators with exponentials or sums such as softmax, normalization and the loss. The largest FP16 value is 65504, exp(12) = 162755 already overflows, and a naive exp divided by the sum returns NaN; the stable form subtracts the maximum first. PyTorch autocast puts softmax, log_softmax, layer_norm, cross_entropy and others on its list of operators that run in FP32.