Check low-precision kernels#
The problem#
You are checking a kernel that works in bfloat16, float16, or an 8-bit float format. Its outputs are far from a float64 reference, as they should be, and you cannot tell a correct low-precision result from a wrong one. Three details make it harder. Some kernels accumulate in float32 and some in the low-precision format itself. The float8 formats without infinity saturate or give NaN past their largest value. And GPUs round float32 inputs to TF32 before a product.
Why the usual approach falls short#
The right tolerance depends on where the kernel rounds and in which format. A tolerance loose enough for a bfloat16 accumulator accepts real bugs in a kernel that accumulates in float32, and one tight enough for float32 accumulation fails every correct bfloat16 accumulator.
The solution#
Tell ExactRef where the kernel rounds and in which format. The sections below take the three details in turn.
bfloat16 accumulators#
By default, for inputs narrower than float32, ExactRef assumes the kernel
adds in float32: that is its compute format, the format it rounds to
and adds in along the way. A kernel that adds in bfloat16 on purpose is judged
with compute="bfloat16", the second argument of covers(), which says per
element whether a correct implementation can produce an output. Some training
setups keep the gradient buffer in bfloat16 to save memory and add each
micro-batch's gradient into it. Here that buffer collects 16 micro-batches of
a 1024 by 1024 weight gradient:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# 16 micro-batches' weight gradients in bfloat16, stacked along the last dimension
micro = (torch.randn(1024, 1024, 16, generator=g) / 1000).bfloat16()
# The training loop's buffer: each micro-batch's gradient added in bfloat16
buffer = torch.zeros(1024, 1024, dtype=torch.bfloat16)
for i in range(16):
buffer += micro[..., i]
# The reference for the sum over the micro-batches
r = er.sum(micro, axis=-1)
# The second argument is the compute format; float32 is the default here
print("covered, float32 accumulation:", r.covers(buffer).all())
print("covered, bfloat16 accumulation:", r.covers(buffer, "bfloat16").all())
covered, float32 accumulation: False
covered, bfloat16 accumulation: True
The same output is wrong for a float32 accumulator and correct for a bfloat16 one, so the check needs to know which kernel it is judging.
Over 16 terms, the bfloat16 tolerance, how far a correct bfloat16 accumulator's output can be from the exact sum rounded once, is a useful bound. Over thousands, it is not. RMSNorm adds the squares of each token's 4,096 activations; here a kernel keeps that running sum in bfloat16:
# 128 tokens of hidden size 4096, and their squares, in bfloat16
x = torch.randn(128, 4096, generator=g).bfloat16()
squares = x * x
# The kernel: each token's sum of squares, kept in bfloat16
acc = torch.zeros(128, dtype=torch.bfloat16)
for i in range(4096):
acc = acc + squares[:, i]
# The reference for each token's sum of squares
r = er.sum(squares, axis=1)
# Token 0: the kernel's sum, and the exact sum rounded once
print("kernel:", acc[0].item())
print("rounded:", r.rounded.scalars()[0])
print("covered, float32 accumulation:", r.covers(acc).all())
print("covered, bfloat16 accumulation:", r.covers(acc, "bfloat16").all())
# The largest tolerance for bfloat16 accumulation, to 2 significant digits
largest = max(r.tolerance("bfloat16").scalars())
print(f"largest bfloat16 tolerance: {largest:.2g}")
kernel: 1872.0
rounded: 3936.0
covered, float32 accumulation: False
covered, bfloat16 accumulation: True
largest bfloat16 tolerance: 3e+11
The kernel's sums are about half the exact ones. Once a running sum passes 256, bfloat16 values are 2 apart, then 4, then 8, and more and more of each square rounds away:
Adding ones in bfloat16, the running sum stops growing at 256. Larger terms stall it later: the sum of squares above stops near 1,900.
The bfloat16 check passes, but it says nothing: the worst case of 4,096 additions in bfloat16 is about 3e11, for sums near 4,000, so every output from -2.5e11 to 2.5e11 passes. At such lengths a bfloat16 accumulator is the bug. Check the kernel with the default float32 accumulation, which fails it here, and fix the accumulator. If the kernel must add in bfloat16, its exact output for a known order is one algorithm away: a named, specific way of computing an operation, which ExactRef can run exactly. This kernel adds the rounded squares one at a time, so the sequential algorithm reproduces it bit for bit:
# Products rounded to bfloat16, then added one at a time in bfloat16
sequential = er.linalg.products.matmul_sequential("bfloat16", fma=False)
# Each token's row times itself, as a batch of 128 products of 1x4096 and 4096x1
emulated = sequential.run(x.unsqueeze(1), x.unsqueeze(2))
# Does the kernel give exactly those values?
print("identical:", emulated.identical(er.asarray(acc.reshape(128, 1, 1))))
identical: True
float8#
ExactRef reads float8 tensors exactly. To convert values to float8 the way
PyTorch does, pass the matching overflow mode. Use "saturate" for
float8_e4m3fn, because PyTorch's conversion to it turns large values and
infinities into the largest value, 448. Use "nan" for the fnuz formats.
Float8 training scales each tensor before converting it. With delayed scaling, the scale comes from an earlier step's largest value, so values that have grown since then land past the format's range. Here a layer's activations have one outlier feature that has grown 4 times since the scale was set:
import math
# A layer's activations: 128 tokens of hidden size 4096, with one large feature
x = torch.randn(128, 4096, generator=g)
x[:, 7] *= 50
# The scale from an earlier step, when the largest value was 4 times smaller
scaled = x / (x.abs().max() / 4 / 448)
print("past 448:", (scaled.abs() > 448).sum().item())
# PyTorch's conversion, and ExactRef's with saturation. identical() is True
# when dtype, shape, and every encoding match.
e4m3fn = scaled.to(torch.float8_e4m3fn)
print("e4m3fn identical:",
er.asarray(scaled, "float8_e4m3fn", overflow="saturate").identical(er.asarray(e4m3fn)))
# The same for float8_e4m3fnuz, which gives NaN past its largest value
fnuz = scaled.to(torch.float8_e4m3fnuz)
print("e4m3fnuz identical:",
er.asarray(scaled, "float8_e4m3fnuz", overflow="nan").identical(er.asarray(fnuz)))
past 448: 52
e4m3fn identical: True
e4m3fnuz identical: True
A float8 matrix product multiplies two float8 tensors, applies their scales,
and writes a wider output. Here is torch._scaled_mm, the product float8
training calls, on the key projection of Llama 3 8B, from 4096 to 1024
features, for the same 128 tokens. The scales are powers of two, as in the MX
formats, so scaling is exact. ExactRef's er.gemm applies the product of the
scales as its alpha:
def power_of_two_scale(t):
"""The power of two that brings t's largest value within e4m3fn's 448."""
return 2.0 ** math.ceil(math.log2(t.abs().max().item() / 448))
# The projection's weight, and both tensors' scales
w = torch.randn(1024, 4096, generator=g) / 64
sx, sw = power_of_two_scale(x), power_of_two_scale(w)
# The activations and the weight, scaled and converted to float8
x8 = (x / sx).to(torch.float8_e4m3fn)
w8 = (w / sw).to(torch.float8_e4m3fn)
# x8 @ w8.T times sx * sw, with a bfloat16 output. _scaled_mm takes its second
# operand column-major, as w8.T is.
out = torch._scaled_mm(x8, w8.T, scale_a=torch.tensor(sx), scale_b=torch.tensor(sw),
out_dtype=torch.bfloat16)
# The reference: alpha * (x8 @ w8.T), with beta = 0 so that C (here 0.0) is not read
r8 = er.gemm(x8, w8.T, 0.0, alpha=sx * sw, beta=0, dtype="bfloat16")
print("covered:", r8.covers(out).all())
covered: True
TF32#
A GPU in TF32 mode rounds each float32 input to TF32 (float32's range with 11 bits of precision) before the product:
A TF32 value keeps a float32's sign, its 8 exponent bits, and its top 10 fraction bits.
er.round_to_tf32(x, rounding) does that rounding on float32 data and returns
float32 values, because every TF32 value is a float32 value. Pass them to
er.matmul, and the reference and tolerance describe a float32 product of
the rounded inputs.
This covers the TF32 conversion of the inputs. The
tensor cores that then multiply them add each block of
products in one adder that truncates, which the plain er.matmul tolerance
does not model. For the product itself, use matmul_mma with TF32's step
parameters (Tensor-core algorithms),
as the GPU example below does.
Kernels round to TF32 in different ways, so rounding is required:
Kernel |
|
|---|---|
NVIDIA's |
|
|
|
cuBLAS's tensor-core kernels on NVIDIA's DGX Spark (GB10), found by measuring them |
|
|
|
When you do not know which rounding your kernel uses, accept all three with
er.any_of, which combines several results into one whose bounds accept an
output of any of them. Here a stand-in for a GPU in TF32 mode computes a
projection of hidden size 1024 for 128 tokens. It drops the low bits of its
inputs, as wgmma does, then multiplies in float32 on the CPU, whose
additions round to nearest:
# A float32 layer: 128 tokens of hidden size 1024, and a 1024 by 1024 weight
A = torch.randn(128, 1024, generator=g)
B = torch.randn(1024, 1024, generator=g) / 32
def drop_low_bits(t):
"""Clear the low 13 of float32's 23 fraction bits, which leaves a TF32 value."""
return (t.view(torch.int32) & ~0x1FFF).view(torch.float32)
# The stand-in kernel's output
out = drop_low_bits(A) @ drop_low_bits(B)
# Judged as a float32 product, the kernel fails: its inputs were rounded
print("float32 check:", er.matmul(A, B).covers(out).all())
def tf32_product(rounding):
"""ExactRef's result for the float32 product of the inputs rounded to TF32."""
return er.matmul(er.round_to_tf32(A, rounding), er.round_to_tf32(B, rounding))
# The three roundings kernels use
toward_zero = tf32_product(er.Rounding.TOWARD_ZERO)
nearest_even = tf32_product(er.Rounding.NEAREST_EVEN)
nearest_away = tf32_product(er.Rounding.NEAREST_AWAY)
# The right rounding passes on its own, and a wrong one fails
print("toward zero:", toward_zero.covers(out).all())
print("nearest even:", nearest_even.covers(out).all())
# Any of the three: covered where a correct product of any of them can give out
either = er.any_of(toward_zero, nearest_even, nearest_away)
print("any of the three:", either.covers(out).all())
float32 check: False
toward zero: True
nearest even: False
any of the three: True
overflow="saturate" matches NVIDIA's .satfinite conversions, which give
the largest TF32 value instead of infinity. NVIDIA does not specify how its
mma instructions treat subnormal inputs.
On a GPU, the product runs on tensor cores, so check it with the TF32 tensor-core step. On the GB10, cuBLAS rounds the inputs to nearest even:
# A float32 product on the GPU with TF32 enabled, copied back to the CPU
torch.backends.cuda.matmul.allow_tf32 = True
out = (A.cuda() @ B.cuda()).cpu()
# The inputs rounded to TF32 as cuBLAS rounds them on the GB10
A_tf32 = er.round_to_tf32(A, er.Rounding.NEAREST_EVEN)
B_tf32 = er.round_to_tf32(B, er.Rounding.NEAREST_EVEN)
# The GB10's tensor-core step for TF32 inputs: 8 products per step
tensor_cores = er.linalg.products.matmul_mma(er.MMAStep(8, 25, -133, 1))
print("covered:", tensor_cores.covers(out, A_tf32, B_tf32).all())