How tolerance works#
Finite-precision arithmetic rounds, so a correct implementation rarely returns the exact answer. ExactRef gives you the reference, the exact answer rounded once to the output format, and a tolerance: how far from the reference a correct implementation can land, for the inputs you actually have. ExactRef works it out from the rounding steps any implementation of the operation has to take, so it is not a fixed number per dtype.
Each section below shows one mechanism, where it shows up in real code, and how the tolerance accounts for it. Some use a few hand-picked values, where the mechanism is easiest to see.
One rounding leaves no room#
An elementwise product rounds once, as in the gate of a SwiGLU MLP, which multiplies two projections of the same tokens:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# A SwiGLU gate and up projection: 128 tokens of width 11008, in bfloat16
gate = torch.nn.functional.silu(torch.randn(128, 11008, generator=g)).bfloat16()
up = torch.randn(128, 11008, generator=g).bfloat16()
# ExactRef's result for their elementwise product
r = er.multiply(gate, up)
# The largest tolerance of the 1,409,024 elements
print("largest tolerance:", max(r.tolerance().scalars()))
# PyTorch's product, compared bit for bit with the reference
print("identical:", r.rounded.identical(er.asarray(gate * up)))
largest tolerance: 0.0
identical: True
Every correct implementation rounds the same exact product the same way, so the tolerance is 0 everywhere and PyTorch's output is the reference, bit for bit.
The order of additions changes the answer#
A sum depends on the order of its additions. That is why a parallel reduction on a GPU, or a sum over activations with a few huge outliers, can differ from a plain loop. Three values show it most clearly:
# ExactRef's result for the float64 sum of 1e16, 1.0, and -1e16
r = er.sum([1e16, 1.0, -1e16])
# The exact sum, rounded once
print("rounded:", r.rounded.tolist())
# What a loop that adds in index order returns
print("normal:", r.normal().tolist())
# How far a correct implementation's output can be from rounded
print("tolerance:", r.tolerance().tolist())
# Could a correct implementation return 0.0? And 8.0?
print("0.0 covered:", r.covers(0.0).all())
print("8.0 covered:", r.covers(8.0).all())
rounded: 1.0
normal: 0.0
tolerance: 1.1102230246251574
0.0 covered: True
8.0 covered: False
The exact sum is 1.0. Adding in index order, 1e16 + 1.0 rounds back to
1e16, because float64 values that large are 2 apart, and the loop ends
at 0.0. An implementation that adds -1e16 first keeps the 1.0. Both are
correct, so the tolerance has to allow both: 0.0 passes and 8.0 does not.
Kernels add in many orders. A loop goes in index order, SIMD code keeps a few running sums side by side, one per lane, and pairwise summation adds neighbors first, as a tree:
Three orders for the same eight terms. Each addition rounds, so each order can give a different answer.
The tolerance comes from the inputs#
Two rows of 4,096 activations in float64, the second with one outlier of the kind language models produce:
import random
# Seeded, so every run uses the same values
rng = random.Random(67)
# A row of activations, and the same row with an outlier in front
row = [rng.gauss(0, 1) for _ in range(4096)]
spiky = [3e4] + row[1:]
# The tolerance of each row's sum, worked out from its own values
print("plain row:", er.sum(row).tolerance().tolist())
print("with an outlier:", er.sum(spiky).tolerance().tolist())
plain row: 3.8056668927310966e-11
with an outlier: 1.367880031466484e-08
The rows differ in one value, but the outlier makes every partial sum large, and each addition then rounds at that size. A fixed tolerance per dtype would be far too loose for the first row or would fail correct implementations of the second.
normal() is what an ordinary loop computes#
# Add the row in index order, rounding to float64 after each addition
total = 0.0
for v in row:
total += v
print("loop:", total)
# ExactRef's emulation of that loop for the same values
print("normal:", er.sum(row).normal().tolist())
loop: 199.93407568471048
normal: 199.93407568471048
normal() emulates, exactly, an implementation that adds in index order in
the compute format: the format it rounds each addition to, float64
here, as in the loop above. Use it to see what an ordinary implementation
gets, next to the reference.
The compute format matters#
A kernel that adds bfloat16 values, such as RMSNorm's sum of squares over a hidden dimension, has to choose where to keep its running sum. Adding 300 ones shows what happens when it stays in bfloat16:
# ExactRef's result for the sum of 300 bfloat16 ones
r = er.sum(er.asarray([1.0] * 300, "bfloat16"))
# The exact sum, rounded once to bfloat16
print("rounded:", r.rounded.tolist())
# The tolerance when the additions happen in float32, the default here
print("tolerance:", r.tolerance().tolist())
# The tolerance when they happen in bfloat16
print("bfloat16 tolerance:", r.tolerance("bfloat16").tolist())
rounded: 300.0
tolerance: 0.0
bfloat16 tolerance: 566.0
For bfloat16 inputs, ExactRef assumes by default that the additions happen
in float32. float32 holds every partial sum here exactly, so the tolerance
is 0. An implementation that keeps its running sum in bfloat16 gets stuck at
256, because bfloat16 values from 256 to 512 are 2 apart and 256 + 1
rounds back down:
A running sum kept in bfloat16 stops growing at 256.
Judged as such an implementation, with tolerance("bfloat16"), 256 is a
correct answer:
# Is 256 correct for an implementation that adds in float32, the default?
print("float32 covered:", r.covers(er.asarray(256.0, "bfloat16")).all())
# And for one that adds in bfloat16, named by the second argument?
print("bfloat16 covered:", r.covers(er.asarray(256.0, "bfloat16"), "bfloat16").all())
float32 covered: False
bfloat16 covered: True
Over the 4,096 terms of a real hidden dimension, a bfloat16 running sum's
worst case is so large that tolerance("bfloat16") says almost nothing;
that is why kernels keep it in float32.
Operations also take a rounding argument. It sets how the reference is
rounded and how the final result is rounded into the output format. It does
not change the roundings in the compute format along the way: the tolerance
always assumes those are to nearest. A named algorithm, one
specific way of computing the operation with its own bounds, sets its own
rounding for those steps.
Normal and any-order: three verdicts#
tolerance() covers normal accumulation, the way ordinary kernels add: in
index order, or in 2 or 4 interleaved running sums as SIMD code keeps them
(softmax also allows wider ones, as its kernels use).
tolerance(standard="any_order") covers every order of additions that does
not overflow. Between them, an output gets one of three verdicts:
Within
tolerance(): no worse than normal accumulation can be.Outside it, but within the any-order tolerance: correct, but worse than normal accumulation can be.
Outside both: wrong; no correct implementation could produce it.
Values chosen so that the order matters a great deal show all three:
# 1e16 and -1e16, padded with zeros, then 96 ones
xs = [1e16, 0.0, 0.0, 0.0, -1e16, 0.0, 0.0, 0.0] + [1.0] * 96
# ExactRef's result for their float64 sum
r = er.sum(xs)
# The exact sum, rounded once
print("rounded:", r.rounded.tolist())
# The tolerance for normal accumulation, the default standard
print("normal tolerance:", r.tolerance().tolist())
# The tolerance for any order of additions that does not overflow
print("any-order tolerance:", r.tolerance(standard="any_order").tolist())
rounded: 96.0
normal tolerance: 3.330669073876024
any-order tolerance: 228.70594307278597
Three implementations of this sum:
# Adds the values one at a time, in index order
def index_order(xs):
total = 0.0
for x in xs:
total += x
return total
# Adds element i to running sum i % 8, then adds up the 8 sums
def eight_lanes(xs):
lanes = [0.0] * 8
for i, x in enumerate(xs):
lanes[i % 8] += x
return index_order(lanes)
# Buggy: counts xs[0] twice
def first_twice(xs):
return index_order([xs[0]] + xs)
for f in (index_order, eight_lanes, first_twice):
# The implementation's output
out = f(xs)
# Whether it passes the normal tolerance, and the any-order one
normal = r.covers(out).all()
any_order = r.covers(out, standard="any_order").all()
print(f"{f.__name__}: {out}, normal: {normal}, any_order: {any_order}")
index_order: 96.0, normal: True, any_order: True
eight_lanes: 72.0, normal: False, any_order: True
first_twice: 1e+16, normal: False, any_order: False
index_order is exact here: no worse than normal accumulation can be.
eight_lanes keeps 8 running sums, as 8-wide SIMD code does. Lanes 0 and 4 start at
1e16and-1e16and swallow every 1.0 added to them, so it is off by 24. That is correct, because some order of additions gives it, but worse than normal accumulation can be.first_twice adds the first element twice: a bug, and no order of additions explains it.
Both tolerances allow for all of a sum's roundings going the same way: the
default over every normal accumulation, the any-order one over every order.
So an error smaller than that worst case passes. The verdicts suit an
implementation whose order you do not know, as with BLAS libraries,
multithreaded kernels, and GPUs. When you know the order, check exactly
instead: an implementation that adds in index order must match normal()
bit for bit, and for a matrix product the matmul algorithms' run() gives
the exact output of other fixed orders.
# index_order adds in index order, so it must equal normal() exactly
print("index_order matches normal():", index_order(xs) == r.normal().tolist())
# eight_lanes adds in another order, so it does not
print("eight_lanes matches normal():", eight_lanes(xs) == r.normal().tolist())
index_order matches normal(): True
eight_lanes matches normal(): False
Check exactly when you know the order
shows both checks on a layer's product, where an error of a few dozen
ulps passes covers() and fails the exact check.
What a tolerance cannot tell you#
A tolerance says whether rounding can explain a difference. A bug that does not show on your test inputs passes. A common one: a kernel that adds in blocks of 64 and forgets the last, partial block. Test data whose length is a multiple of 64 hides it:
def blocked_sum(xs, block=64):
"""Buggy: adds the full blocks of 64 and skips a last, partial block."""
total = 0.0
for start in range(0, len(xs) - block + 1, block):
# Each full block's sum, added in index order, then added to the total
part = 0.0
for v in xs[start:start + block]:
part += v
total += part
return total
for n in (4096, 4100):
# n activations, and whether the buggy sum passes for them
data = [rng.gauss(0, 1) for _ in range(n)]
print(f"{n} values, covered:", er.sum(data).covers(blocked_sum(data)).all())
4096 values, covered: True
4100 values, covered: False
With 4,096 values there is no partial block, so the bug never runs. Test lengths that are not a multiple of your kernel's block sizes, and inputs where a mistake would show.
Where to go next#
Reading complicated tolerances: whole tensors, overflow, infinities and NaN, several outputs, complex outputs, and kernels that round in more places than the operation requires.
Results: everything a result holds and every option of
tolerance().