Tutorial: training in 8-bit floating point#
Since the Hopper and Ada generations, NVIDIA GPUs multiply matrices in two 8-bit floating-point formats: E4M3 (four exponent bits, three mantissa bits) and E5M2 (five and two). These are also the formats of the Open Compute Project’s FP8 specification, and AMD and Intel accelerators implement the same pair. The standard recipe for training in them is E4M3 for the forward pass, E5M2 for the gradients, 32-bit accumulation, and a scale per tensor. It was worked out on hardware that already had the tensor cores. MPTorch lets you take that recipe apart on a GPU without them (or on a CPU), change any one ingredient, and see what it does to a training run.
This tutorial builds up from the formats to a trained network. Every code
block is a file under docs/snippets/tutorial/, and every output is
recorded from a run. The training script of the last section took about
three minutes on a laptop GPU.
1. The formats#
An FP8 number is a sign, an exponent and a mantissa, like any binary float (Formats and rounding has the general form). With the OCP biases:
E4M3 spends its bits on precision: eight values per binade, a largest finite value of 448 and a smallest subnormal of \(2^{-9}\). E5M2 spends them on range: four values per binade, up to 57344 and down to \(2^{-16}\), the same exponent range as float16.
In MPTorch the nearest spellings are BinaryK(8, 4, bias=7) and
BinaryK(8, 3, bias=15). The bias has to be given, because a BinaryK
otherwise takes IEEE P3109’s, which is one larger: BinaryK(8, 4) is
P3109’s Binary8p4, not OCP’s E4M3. Only the first spelling is exact:
E4M3 already spends its top exponent field on numbers, as P3109 does, so
BinaryK(8, 4, bias=7)has exactly its finite values.E5M2 is laid out the IEEE 754 way, with that field kept for infinities and NaNs. No P3109 format keeps it, so no BinaryK format is E5M2, for the same reason that none is float16, bfloat16 or float32 (Formats and rounding).
PyTorch’s own torch.float8_e4m3fn and torch.float8_e5m2 dtypes serve
as the reference. The run tabulates the ranges from both sides. It then
rounds every one of the \(2^{32}\) float32 values with both and
counts where they disagree:
"""E4M3 and E5M2 spelled as BinaryK formats, checked against torch's native FP8 dtypes."""
import torch
from mptorch import BinaryK
from mptorch.quant import Quant
# The OCP / NVIDIA FP8 formats. torch's own dtypes are the reference. E4M3's
# finite values are exactly its spelling's; E5M2 keeps its top exponent field
# for infinities and NaNs, which no BinaryK format does, so its spelling is only
# the nearest one and has three more values at the top.
e4m3 = BinaryK(8, 4, bias=7) # torch.float8_e4m3fn
e5m2 = BinaryK(8, 3, bias=15) # nearest to torch.float8_e5m2
print(f"{'':<22}{'E4M3':>14}{'torch e4m3fn':>14}{'E5M2':>14}{'torch e5m2':>14}")
rows = {
"largest finite": lambda f, fi: (
(2 - 2 ** (2 - f.P)) * 2.0 ** (2 ** (f.K - f.P) - 1 - f.bias),
fi.max,
),
"smallest normal": lambda f, fi: (2.0 ** (1 - f.bias), fi.tiny),
"smallest subnormal": lambda f, fi: (
2.0 ** (1 - f.bias - f.man_bits),
fi.smallest_normal * 2.0**-f.man_bits,
),
"spacing at 1": lambda f, fi: (2.0**-f.man_bits, fi.eps),
}
for name, fn in rows.items():
a, ta = fn(e4m3, torch.finfo(torch.float8_e4m3fn))
b, tb = fn(e5m2, torch.finfo(torch.float8_e5m2))
print(f"{name:<22}{a:>14g}{ta:>14g}{b:>14g}{tb:>14g}")
# Exhaustive check: every one of the 2**32 float32 bit patterns, rounded to
# nearest-even by both. Chunked so it fits a laptop GPU (or runs on a CPU).
# The two overflow conventions differ, so the count is split at the largest
# finite value the torch dtype has: below it the two must agree exactly.
device = "cuda" if torch.cuda.is_available() else "cpu"
chunk = 2**24
inside = {"E4M3": 0, "E5M2": 0}
beyond = {"E4M3": 0, "E5M2": 0}
first = {}
for start in range(0, 2**32, chunk):
bits = torch.arange(start, start + chunk, dtype=torch.int64, device=device).to(torch.int32)
x = bits.view(torch.float32)
for name, fmt, dt in (("E4M3", e4m3, torch.float8_e4m3fn), ("E5M2", e5m2, torch.float8_e5m2)):
ours = Quant(fmt)(x)
theirs = x.to(dt).to(torch.float32)
# NaN != NaN, so compare NaN-ness separately from values.
differ = torch.isfinite(x) & (ours != theirs) & ~(torch.isnan(ours) & torch.isnan(theirs))
in_range = x.abs() <= torch.finfo(dt).max
inside[name] += int((differ & in_range).sum())
beyond[name] += int((differ & ~in_range).sum())
if (differ & ~in_range).any() and name not in first:
i = int((differ & ~in_range).nonzero()[0])
first[name] = (x[i].item(), ours[i].item(), theirs[i].item())
print(f"\nfinite float32 inputs on which BinaryK and torch disagree ({device}):")
for name, dt in (("E4M3", torch.float8_e4m3fn), ("E5M2", torch.float8_e5m2)):
x0, ours, theirs = first[name]
print(
f" {name}: |x| <= {torch.finfo(dt).max:g}: {inside[name]:,} beyond it: {beyond[name]:,}"
f" (first at |x| = {abs(x0):g}: BinaryK {ours:g}, torch {theirs:g})"
)
E4M3 torch e4m3fn E5M2 torch e5m2
largest finite 448 448 98304 57344
smallest normal 0.015625 0.015625 6.10352e-05 6.10352e-05
smallest subnormal 0.00195312 0.00195312 1.52588e-05 1.52588e-05
spacing at 1 0.125 0.125 0.25 0.25
finite float32 inputs on which BinaryK and torch disagree (cuda):
E4M3: |x| <= 448: 0 beyond it: 1,999,634,430 (first at |x| = 464: BinaryK inf, torch 448)
E5M2: |x| <= 57344: 0 beyond it: 12,582,914 (first at |x| = 61440: BinaryK 65536, torch inf)
Up to each dtype’s largest finite value, the two agree in value on every
input. The count compares with !=, which cannot see the sign of a zero.
PyTorch keeps that sign. A BinaryK format has one unsigned zero, so it
returns \(+0.0\) for \(-0.0\) and for a negative input that rounds
to zero. Beyond the largest finite value the two differ, in a different way
for each format:
For E4M3 only the overflow convention differs. PyTorch saturates to \(\pm 448\), infinite inputs included. A BinaryK format under its default
SAT_NONEpolicy produces \(\pm\infty\). UnderSAT_FINITEit clamps to 480, because the finite domain spends the top code on a number.SAT_FINITE_EXTENDED, which is P3109’sSatFinitein the extended domain, is PyTorch’s convention: it clamps to 448, infinities included.For E5M2 the value set differs. The first table’s largest finite values, 98304 against 57344, show it.
BinaryK(8, 3, bias=15)spends the top exponent field, which E5M2 reserves, on three more numbers: 65536, 81920 and 98304. So 61440 rounds to 65536 where PyTorch overflows. It is the nearest BinaryK to E5M2, not E5M2.
A model that keeps its values in range sees neither difference, and the sign of a zero changes the value of no sum or product.
2. What rounding to FP8 costs#
Rounding a tensor to a format with a few mantissa bits replaces each value by one within half a spacing of it. The spacing in \([2^q, 2^{q+1})\) is \(2^{q-3}\) for E4M3 and \(2^{q-2}\) for E5M2. The relative error per element is therefore bounded by \(2^{-4}\) and \(2^{-3}\), and its root mean square over a Gaussian tensor is near 2.7 % and 5.3 %. The rounding mode decides the sign of the error: round-to-nearest is unbiased, truncation is biased toward zero, rounding up is biased upward, and stochastic rounding is unbiased with more variance.
"""What rounding a Gaussian tensor to FP8 costs, mode by mode."""
import torch
from mptorch import BinaryK, RoundMode
from mptorch.quant import Quant
torch.manual_seed(0)
x = torch.randn(1_000_000)
e4m3 = BinaryK(8, 4, bias=7, prng_bits=8)
e5m2 = BinaryK(8, 3, bias=15, prng_bits=8)
print(f"{'format, rounding':<20}{'mean error':>12}{'RMS error':>12}{'rel. RMS':>10}")
for fmt, label in ((e4m3, "E4M3"), (e5m2, "E5M2")):
for mode in (RoundMode.RNE, RoundMode.RZ, RoundMode.RU, RoundMode.SR):
err = Quant(fmt, mode)(x) - x
print(
f"{label + ', ' + mode.name:<20}{err.mean():>12.2e}{err.pow(2).mean().sqrt():>12.4f}"
f"{(err.norm() / x.norm()):>10.4f}"
)
# Where each format stops working: relative error across nine decades.
print(f"\n{'|x|':>10}{'E4M3 rel. err':>16}{'E5M2 rel. err':>16}")
for e in range(-7, 6):
v = torch.full((10000,), 10.0**e) * (1 + 0.5 * torch.rand(10000))
for_row = []
for fmt in (e4m3, e5m2):
q = Quant(fmt)(v)
rel = ((q - v).abs() / v).mean().item()
for_row.append("overflow" if torch.isinf(q).any() else f"{rel:.4f}")
print(f"{10.0**e:>10.0e}{for_row[0]:>16}{for_row[1]:>16}")
format, rounding mean error RMS error rel. RMS
E4M3, RNE 6.19e-06 0.0266 0.0266
E4M3, RZ 6.46e-05 0.0511 0.0511
E4M3, RU 3.60e-02 0.0531 0.0531
E4M3, SR 1.30e-05 0.0375 0.0375
E5M2, RNE 1.37e-06 0.0528 0.0528
E5M2, RZ 1.28e-04 0.0983 0.0983
E5M2, RU 7.19e-02 0.1064 0.1064
E5M2, SR 2.72e-05 0.0751 0.0751
|x| E4M3 rel. err E5M2 rel. err
1e-07 1.0000 1.0000
1e-06 1.0000 1.0000
1e-05 1.0000 0.2375
1e-04 1.0000 0.0483
1e-03 0.5844 0.0501
1e-02 0.0429 0.0429
1e-01 0.0231 0.0509
1e+00 0.0255 0.0506
1e+01 0.0202 0.0404
1e+02 0.0215 0.0504
1e+03 overflow 0.0521
1e+04 overflow 0.0377
1e+05 overflow overflow
The second table shows why there are two formats. It covers nine decades of magnitude:
E4M3 keeps its 2.5 % accuracy only between about \(10^{-2}\) and \(10^{2}\). Below that its subnormals run out of digits and then flush to zero (a relative error of 1.0 means the value became zero). Above 448 it overflows.
E5M2 is twice as coarse everywhere but keeps its 5 % accuracy from \(10^{-4}\) to \(10^{4}\).
Weights and activations stay within a couple of decades of one. Gradients shrink layer by layer and step by step, and do not. That is the argument for E4M3 forward and E5M2 backward.
3. One matrix product, several arithmetics#
An FP8 tensor core takes two 8-bit operands and multiplies them exactly: the product of two 4-bit significands has 8 bits, which any format wider than E4M3 holds. It adds the product to a running sum kept in a wider format. On Hopper that accumulator is nominally float32, though it has been measured to keep only about 14 mantissa bits for FP8 inputs. On other hardware it may be float16 or bfloat16.
In MPTorch’s vocabulary (Dot-product arithmetic) this is a SplitMac.
Its mul is any format wide enough to hold the product exactly, and its
acc is the accumulator being studied:
The run quantizes the operands of a \(512 \times 1024 \times 512\) product to E4M3 once, then computes the product in eight arithmetics and measures each against a float64 reference:
"""One matmul, several arithmetics: what an FP8 tensor core does and does not round."""
import warnings
import torch
from mptorch import BinaryK, FormatRangeWarning, RoundMode
from mptorch.quant import FusedMac, Quant, SplitMac, qmatmul
torch.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"
M, K, N = 512, 1024, 512
x = torch.randn(M, K, device=device)
w = torch.randn(K, N, device=device) / K**0.5
exact = (x.double() @ w.double()).float()
e4m3 = Quant(BinaryK(8, 4, bias=7))
xq, wq = e4m3(x), e4m3(w) # what an FP8 tensor core is fed
# An 8-exponent-bit binaryK reaches below 2**-126, where the casts cannot tell
# one input from another, so building one warns (concepts, "What float32 can
# carry"). Nothing here goes anywhere near that small.
warnings.simplefilter("ignore", FormatRangeWarning)
bf16 = BinaryK(16, 8) # 8 exponent + 7 mantissa bits: holds an E4M3 x E4M3 product exactly
fp22 = BinaryK(23, 15) # 8 exponent + 14 mantissa bits: a reduced-precision accumulator
fp16 = BinaryK(16, 11)
e4m3_fmt = BinaryK(8, 4, bias=7)
def rel(out):
return f"{((out - exact).norm() / exact.norm()).item():.2e}"
print(f"{'operands':<10}{'arithmetic':<52}{'rel. error':>12}")
print(f"{'float32':<10}{'torch.matmul':<52}{rel(x @ w):>12}")
print(f"{'E4M3':<10}{'torch.matmul (float32 products and sums)':<52}{rel(xq @ wq):>12}")
fused32 = qmatmul(xq, wq, FusedMac(None))
print(f"{'E4M3':<10}{'FusedMac(None): sequential fp32 FMAs':<52}{rel(fused32):>12}")
configs = {
"SplitMac(bf16, fp22): exact products, 14-bit sums": SplitMac(bf16, fp22),
"SplitMac(bf16, fp16): exact products, fp16 sums": SplitMac(bf16, fp16),
"SplitMac(bf16, bf16): exact products, bf16 sums": SplitMac(bf16, bf16),
"SplitMac(bf16, bf16) with stochastic sums": SplitMac(
BinaryK(16, 8, prng_bits=8), BinaryK(16, 8, prng_bits=8), rounding=RoundMode.SR
),
"SplitMac(E4M3, fp22): products rounded to E4M3 too": SplitMac(e4m3_fmt, fp22),
"FusedMac(E4M3): everything in E4M3": FusedMac(e4m3_fmt),
}
for name, mac in configs.items():
print(f"{'E4M3':<10}{name:<52}{rel(qmatmul(xq, wq, mac)):>12}")
operands arithmetic rel. error
float32 torch.matmul 2.25e-07
E4M3 torch.matmul (float32 products and sums) 3.89e-02
E4M3 FusedMac(None): sequential fp32 FMAs 3.89e-02
E4M3 SplitMac(bf16, fp22): exact products, 14-bit sums 3.89e-02
E4M3 SplitMac(bf16, fp16): exact products, fp16 sums 3.92e-02
E4M3 SplitMac(bf16, bf16): exact products, bf16 sums 5.37e-02
E4M3 SplitMac(bf16, bf16) with stochastic sums 6.45e-02
E4M3 SplitMac(E4M3, fp22): products rounded to E4M3 too 4.76e-02
E4M3 FusedMac(E4M3): everything in E4M3 4.22e-01
The 16-bit formats are named after the dtypes whose field widths they have:
fp16 is P3109’s Binary16p11 and bf16 its Binary16p8. They
are not those dtypes. With P3109’s bias, each stops one code short of the
dtype’s largest value, which is its \(+\infty\), and reaches a binade
below the dtype’s smallest value (Formats and rounding, “The IEEE 754 dtypes are
not P3109 formats”). Neither end matters in this product. The E4M3 operands
are multiples of \(2^{-9}\), so every product and sum is a multiple of
\(2^{-18}\), and the sums stay many binades below 65472. The rows
therefore measure the widths and nothing else.
Reading down the table:
Rounding the operands to E4M3 costs 3.9 % relative error, and nothing the accumulator does above float16’s width changes that. The float32 and 14-bit sums give the same number, and the float16-width one is very slightly worse.
A bfloat16-width accumulator (7 mantissa bits, for a sum of 1024 terms) adds visibly to the error.
Stochastic rounding of that sum adds variance and removes no bias, because the terms have random signs.
Rounding the products to E4M3 as well costs a further point.
Accumulating in E4M3 no longer gives a usable matrix product.
This is the experiment to run when a new accelerator’s accumulator width is
in question: change acc and read the row.
4. One layer, the FP8 recipe#
A linear layer has four signals and three matrix products (Layers), and the standard FP8 training recipe assigns them so:
Everything the forward pass reads is in E4M3, every gradient is in E5M2, and
the products are exact with a wide sum. As a QAffineFormats this is one
factory call for the arithmetic and six quantizer assignments:
"""An FP8 training recipe for one layer: E4M3 forward, E5M2 backward, and scaling."""
import warnings
import torch
from mptorch import BinaryK, FormatRangeWarning, SaturationMode
from mptorch.quant import QAffineFormats, QLinear, Quant, binaryK_gemm_formats
# An 8-exponent-bit binaryK reaches below 2**-126, where the casts cannot tell
# one input from another, so naming one warns (concepts, "What float32 can
# carry"). Nothing here goes anywhere near that small.
warnings.simplefilter("ignore", FormatRangeWarning)
torch.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"
E4M3 = BinaryK(8, 4, bias=7)
E5M2 = BinaryK(8, 3, bias=15)
def fp8_formats(*, gemm_acc: BinaryK | None, loss_scale: float = 1.0) -> QAffineFormats:
"""Forward signals in E4M3, backward signals in E5M2, matmuls with the given accumulator.
Products of two FP8 numbers are exact in a bfloat16-wide multiplier, so
``mul_K=16, mul_P=8`` rounds nothing a tensor core would keep; ``gemm_acc`` is what
the running sum is rounded to (``None``: float32).
"""
formats = binaryK_gemm_formats(
mul_K=16,
mul_P=8,
acc_K=gemm_acc.K if gemm_acc else None,
acc_P=gemm_acc.P if gemm_acc else None,
accumulate_quant=gemm_acc is not None,
)
fwd, bwd = Quant(E4M3), Quant(E5M2)
formats.input_quant, formats.weight_quant, formats.bias_quant = fwd, fwd, fwd
formats.igrad_quant, formats.wgrad_quant, formats.bgrad_quant = bwd, bwd, bwd
return formats
layer = QLinear(784, 128, formats=fp8_formats(gemm_acc=None), device=device)
ref = torch.nn.Linear(784, 128, device=device)
ref.load_state_dict(layer.state_dict())
x = torch.randn(64, 784, device=device, requires_grad=True)
x_ref = x.detach().clone().requires_grad_(True)
g = torch.randn(64, 128, device=device) * 1e-3 # a gradient of realistic size
layer(x).backward(g)
ref(x_ref).backward(g)
cos = torch.nn.functional.cosine_similarity
print("cosine similarity to the float32 layer")
print(f" output {cos(layer(x).flatten(), ref(x_ref).flatten(), dim=0):.5f}")
print(f" input grad {cos(x.grad.flatten(), x_ref.grad.flatten(), dim=0):.5f}")
print(f" weight grad {cos(layer.weight.grad.flatten(), ref.weight.grad.flatten(), dim=0):.5f}")
# Why gradients get E5M2 and not E4M3: their range. Rounded to E4M3 (smallest
# subnormal 2**-9 ~ 0.002) most of this gradient is simply zero.
for name, fmt in (("E4M3", E4M3), ("E5M2", E5M2)):
zeroed = (Quant(fmt)(g) == 0).float().mean().item()
print(f"\n{name}: {zeroed:.1%} of a gradient of size ~1e-3 rounds to zero")
# The usual remedy is a scale: multiply into range, round, divide back out.
# A quantizer slot takes any callable, so this is a few lines.
class ScaledQuant:
"""Per-tensor scaling to the format's largest finite value (like an FP8 'amax' scale)."""
def __init__(self, fmt: BinaryK, max_finite: float):
self.q = Quant(BinaryK(fmt.K, fmt.P, bias=fmt.bias, saturation=SaturationMode.SAT_FINITE))
self.max_finite = max_finite
def __call__(self, t: torch.Tensor) -> torch.Tensor:
scale = self.max_finite / t.abs().amax().clamp_min(1e-30)
return self.q(t * scale) / scale
for name, fmt, mx in (("E4M3", E4M3, 448.0), ("E5M2", E5M2, 57344.0)):
sq = ScaledQuant(fmt, mx)
zeroed = (sq(g) == 0).float().mean().item()
print(
f"scaled {name}: {zeroed:.1%} of the same gradient rounds to zero, "
f"cos to unrounded {cos(sq(g).flatten(), g.flatten(), dim=0):.5f}"
)
cosine similarity to the float32 layer
output 0.99917
input grad 0.99814
weight grad 0.99830
E4M3: 67.1% of a gradient of size ~1e-3 rounds to zero
E5M2: 0.6% of a gradient of size ~1e-3 rounds to zero
scaled E4M3: 0.0% of the same gradient rounds to zero, cos to unrounded 0.99965
scaled E5M2: 0.0% of the same gradient rounds to zero, cos to unrounded 0.99861
The output has three blocks:
The first confirms that the layer is close to its float32 twin in all three directions.
The second makes the range argument of section 2 concrete on a gradient of realistic size: two thirds of it vanishes in E4M3, and almost none in E5M2.
The third shows the last ingredient of the recipe, scaling. A tensor is multiplied into the format’s range before rounding and divided back afterwards. Its largest element then uses the top of the range, and its smallest elements are not lost at the bottom. Hardware FP8 keeps one such scale per tensor (Transformer Engine’s “amax” scaling). Here it is eight lines of Python, because a quantizer slot takes any callable. With it, even E4M3 holds the gradient.
5. Training the network#
The last script trains a 784-128-96-10 multilayer perceptron on MNIST. This is the example of the original MPTorch tutorial, on the current interface. It trains nine configurations from the same initial weights and the same shuffles, with plain SGD, for five epochs each. Three things vary:
The signals: float32, or E4M3 on everything the forward pass reads and E5M2 on every gradient. The logits are rounded by a
Quantizer(E4M3 forward, E5M2 backward), because there is nooutput_quantslot.The matmuls: float32 (no math hooks), or a
binaryK_gemm_formatscore with exact products (mul_K=16, mul_P=8, wide enough to hold any FP8 product) and a running sum in one of four accumulators: 14 bits; bfloat16’s widths (Binary16p8, which is not bfloat16 itself, as section 3 says); the same with stochastic rounding; or E4M3.The master weights: float32, or rounded to E4M3 after every optimizer step, with round-to-nearest or stochastic rounding. The update \(w \leftarrow Q(w - \eta\, g)\), with learning rate \(\eta\) and gradient \(g\), is applied by hand after
opt.step(). A low-precision master copy is nothing more than that.
One configuration also scales the loss by 1024 (and the gradients back down), the classic remedy for gradient underflow.
"""Training an MLP on MNIST in FP8: the signals, the matmuls, and the weights.
Every configuration below trains the same 784-128-96-10 network from the same
initialisation, and differs only in what is rounded, to what, and where:
signals what the layer's inputs, weights, biases and gradients are
rounded to before each matmul (the *_quant slots)
matmuls the arithmetic *inside* the three GEMMs of each layer
(the *_math hooks, via binaryK_gemm_formats)
weights the format the master copy of the weights is rounded to after
every optimizer step, and how
Run: python3 fp8_05_mlp_mnist.py [--epochs N] [--only name,name]
"""
import argparse
import time
import warnings
from collections.abc import Callable
from dataclasses import dataclass
import torch
import torch.nn.functional as F
from torch import nn
from torchvision import datasets
from mptorch import BinaryK, FormatRangeWarning, RoundMode
from mptorch.quant import QAffineFormats, QLinear, Quant, Quantizer, binaryK_gemm_formats
E4M3 = BinaryK(8, 4, bias=7)
E5M2 = BinaryK(8, 3, bias=15)
# An 8-exponent-bit binaryK reaches below 2**-126, where the casts cannot tell
# one input from another, so building one warns (concepts, "What float32 can
# carry"). Nothing here goes anywhere near that small.
warnings.simplefilter("ignore", FormatRangeWarning)
BF16 = BinaryK(16, 8) # 8 exponent, 7 mantissa bits
FP22 = BinaryK(23, 15) # 8 exponent, 14 mantissa bits: a reduced-precision accumulator
BF16_SR = BinaryK(16, 8, prng_bits=8)
E4M3_SR = BinaryK(8, 4, bias=7, prng_bits=8)
def fp8_signals(formats: QAffineFormats) -> QAffineFormats:
"""E4M3 on everything the forward pass reads, E5M2 on every gradient."""
fwd, bwd = Quant(E4M3), Quant(E5M2)
formats.input_quant, formats.weight_quant, formats.bias_quant = fwd, fwd, fwd
formats.igrad_quant, formats.wgrad_quant, formats.bgrad_quant = bwd, bwd, bwd
return formats
def gemm(acc: BinaryK | None, rounding: RoundMode = RoundMode.RNE) -> QAffineFormats:
"""Products exact (bf16 holds an FP8 x FP8 product), running sums in `acc`."""
return binaryK_gemm_formats(
mul_K=16,
mul_P=8,
accumulate_quant=acc is not None,
acc_K=acc.K if acc else None,
acc_P=acc.P if acc else None,
acc_prng_bits=acc.prng_bits if acc else 0,
rounding_mode=rounding,
)
@dataclass
class Config:
name: str
formats: Callable[[], QAffineFormats]
weight_quant: Callable[[torch.Tensor], torch.Tensor] | None = None # master weights
loss_scale: float = 1.0
CONFIGS = [
Config("float32", QAffineFormats),
Config("fp8 signals, fp32 matmuls", lambda: fp8_signals(QAffineFormats())),
Config(
"fp8 signals, fp32 matmuls, loss scale 1024",
lambda: fp8_signals(QAffineFormats()),
loss_scale=1024.0,
),
Config("fp8 signals, fp22-accumulated matmuls", lambda: fp8_signals(gemm(FP22))),
Config("fp8 signals, bf16-accumulated matmuls", lambda: fp8_signals(gemm(BF16))),
Config(
"fp8 signals, bf16-accumulated matmuls, SR",
lambda: fp8_signals(gemm(BF16_SR, RoundMode.SR)),
),
Config("fp8 signals, E4M3-accumulated matmuls", lambda: fp8_signals(gemm(E4M3))),
Config(
"fp8 signals, E4M3 master weights (RNE)",
lambda: fp8_signals(QAffineFormats()),
weight_quant=Quant(E4M3),
),
Config(
"fp8 signals, E4M3 master weights (SR)",
lambda: fp8_signals(QAffineFormats()),
weight_quant=Quant(E4M3_SR, RoundMode.SR),
),
]
def load_mnist(device: str):
"""The whole dataset as normalised [N, 784] tensors on the device."""
out = []
for train in (True, False):
ds = datasets.MNIST("data", train=train, download=True)
x = (ds.data.float() / 255 - 0.1307) / 0.3081
out += [x.reshape(len(ds), -1).to(device), ds.targets.to(device)]
return out
def make_model(cfg: Config, device: str) -> nn.Sequential:
torch.manual_seed(0) # same initial weights for every configuration
return nn.Sequential(
QLinear(784, 128, formats=cfg.formats()),
nn.ReLU(),
QLinear(128, 96, formats=cfg.formats()),
nn.ReLU(),
QLinear(96, 10, formats=cfg.formats()),
# There is no output_quant slot: rounding the logits is a Quantizer,
# here E4M3 forward with the gradient passed through in E5M2.
Quantizer(E4M3, E5M2) if cfg.name != "float32" else nn.Identity(),
).to(device)
def accuracy(model, x, y, batch=1000) -> float:
model.eval()
with torch.no_grad():
correct = sum(
(model(x[i : i + batch]).argmax(1) == y[i : i + batch]).sum().item()
for i in range(0, len(x), batch)
)
return correct / len(x)
def train(cfg: Config, data, device: str, epochs: int, batch: int = 64, lr: float = 0.1):
x_tr, y_tr, x_te, y_te = data
model = make_model(cfg, device)
opt = torch.optim.SGD(model.parameters(), lr=lr)
if cfg.weight_quant: # start from weights the master format can hold
with torch.no_grad():
for p in model.parameters():
p.copy_(cfg.weight_quant(p))
g = torch.Generator(device=device).manual_seed(0)
accs, t0 = [], time.perf_counter()
for _ in range(epochs):
model.train()
perm = torch.randperm(len(x_tr), generator=g, device=device)
for i in range(0, len(x_tr), batch):
idx = perm[i : i + batch]
opt.zero_grad()
(F.cross_entropy(model(x_tr[idx]), y_tr[idx]) * cfg.loss_scale).backward()
if cfg.loss_scale != 1.0:
for p in model.parameters():
p.grad /= cfg.loss_scale
opt.step()
if cfg.weight_quant: # w <- Q(w - lr * g): the master copy lives in this format
with torch.no_grad():
for p in model.parameters():
p.copy_(cfg.weight_quant(p))
accs.append(accuracy(model, x_te, y_te))
return accs, time.perf_counter() - t0
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--epochs", type=int, default=5)
ap.add_argument("--only", default="")
args = ap.parse_args()
device = "cuda" if torch.cuda.is_available() else "cpu"
data = load_mnist(device)
configs = [
c for c in CONFIGS if not args.only or any(o in c.name for o in args.only.split(","))
]
print(f"MNIST, 784-128-96-10 MLP, SGD lr 0.1, batch 64, {args.epochs} epochs, on {device}")
print(
f"{'configuration':<48}"
+ "".join(f"{'ep ' + str(e + 1):>8}" for e in range(args.epochs))
+ f"{'time':>8}"
)
for cfg in configs:
accs, dt = train(cfg, data, device, args.epochs)
print(f"{cfg.name:<48}" + "".join(f"{a:>8.4f}" for a in accs) + f"{dt:>7.0f}s", flush=True)
if __name__ == "__main__":
main()
MNIST, 784-128-96-10 MLP, SGD lr 0.1, batch 64, 5 epochs, on cuda
configuration ep 1 ep 2 ep 3 ep 4 ep 5 time
float32 0.9593 0.9606 0.9749 0.9724 0.9705 11s
fp8 signals, fp32 matmuls 0.9588 0.9614 0.9735 0.9708 0.9669 16s
fp8 signals, fp32 matmuls, loss scale 1024 0.9595 0.9595 0.9715 0.9729 0.9742 21s
fp8 signals, fp22-accumulated matmuls 0.9597 0.9637 0.9686 0.9717 0.9723 18s
fp8 signals, bf16-accumulated matmuls 0.9598 0.9606 0.9733 0.9669 0.9744 16s
fp8 signals, bf16-accumulated matmuls, SR 0.9594 0.9627 0.9709 0.9565 0.9714 16s
fp8 signals, E4M3-accumulated matmuls 0.9173 0.9258 0.8982 0.9481 0.0980 16s
fp8 signals, E4M3 master weights (RNE) 0.9111 0.9053 0.9415 0.9355 0.9363 18s
fp8 signals, E4M3 master weights (SR) 0.9547 0.9476 0.9531 0.9599 0.9636 18s
From epoch to epoch, the test accuracy of any one run moves by a few tenths of a percent, so differences of that size between rows are noise. The table shows three things:
FP8 signals cost almost nothing here. Rounding every activation, weight and gradient of this network to eight bits, with float32 products and sums, trains to the same accuracy as float32. Loss scaling changes nothing on this problem. An MLP three layers deep has no gradient small enough to underflow E5M2, as section 4 already suggested.
The accumulator has a threshold, and it is low. A 14-bit accumulator is indistinguishable from float32. So is a bfloat16-width one, for this network, whose longest dot product has 784 terms, even though section 3 measured a visibly larger error for it on a single product. Stochastic rounding of the sums neither helps nor hurts. An E4M3 accumulator is different: it trains to about 92-95 % for four epochs and then collapses to chance. The run looks as if it is working until it stops working.
Master weights are where stochastic rounding matters. The update \(\eta g\) is small compared with the weight it is added to. With the weights held in E4M3 and rounded to nearest after every step, any update below half a spacing (\(2^{-4}\) of the weight’s magnitude) is lost entirely, and the network trains three to four points worse. The same master copy rounded stochastically keeps those updates in expectation and recovers most of the gap. This is the accumulator effect of Formats and rounding, in a network. It is why every FP8 training recipe keeps its master weights in a wider format or rounds them stochastically.
Where to go from here#
Attention. The two matrix products of an attention head are
QMatmulmodules over aQMatmulFormats(Calling the kernels shows one). This puts the same recipe inside a transformer block, including theq @ k.mTshape with no copy.Convolutions.
QConv2dtakes the same formats, andconv_formats()runs its three passes in the recipe’s arithmetic (Layers, “Convolutions”).Block formats. The next generation of the recipe shares a scale per block of 32 or 16 elements: OCP’s MXFP8 and MXFP4, and NVIDIA’s NVFP4.
block_gemm_formats()trains the same network in them (Block formats, Block matrix products).Per-element formats. A
Palettelets the first rows of a product run in E5M2 and the rest in E4M3, or any assignment that aprec_idxmap describes.Other formats. Everything above uses
BinaryK.SuperFPis a second family with a different trade-off. Any other width is one constructor call away:BinaryK(6, 3),BinaryK(4, 2), or a format nobody has built.Wider arithmetic. Everything above runs in float32, whose binary32 arithmetic carries every format used here.
model.double()moves the same model into binary64, where formats of up to 53 bits of precision are simulated exactly. That gives a reference for measuring what an 8-bit accumulator really costs.carrier=torch.float64gives the float32 model binary64’s products and sums while it keeps its dtype (Layers).Other roundings. Each format in a
SplitMachas its own saturation and subnormal policy, and eachSplitMacits own rounding mode. The scripts in this tutorial take those as arguments and are meant to be edited.