ExactRef
Exact reference answers, with proven error bounds, for testing numerical code#
For an operation and its inputs, ExactRef gives you the exact answer rounded once to the output format, and a per-element tolerance: how far the output of a correct finite-precision implementation can be from that answer, on those inputs. Use it to check PyTorch operations, custom kernels, and numerical libraries.
Install#
pip install exactref
ExactRef needs CPython 3.10 or newer with the GIL (free-threaded builds are not supported) and has no dependencies: its arithmetic is its own C extension. NumPy and PyTorch are not needed, but ExactRef reads their arrays and tensors directly when you have them.
Quick start#
A linear layer of a language model, in bfloat16: 128 tokens of hidden size 4096 through a 4096 by 4096 weight. Is PyTorch's output correct, element by element?
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The layer's input and weight, scaled as in a trained model
x = torch.randn(128, 4096, generator=g).bfloat16()
w = (torch.randn(4096, 4096, generator=g) / 64).bfloat16()
# PyTorch's output for the layer
y = torch.nn.functional.linear(x, w)
# ExactRef's reference for the same product: the exact answer, rounded once
r = er.matmul(x, w.T)
# Could a correct implementation produce every element of y?
print("covered:", r.covers(y).all())
covered: True
Yes. Each element passes only if a correct implementation could have produced
it on these inputs: one that rounds where the product requires, such as at
each partial sum and at the final result. A kernel with a bug that
torch.testing.assert_close accepts fails this check:
Find a bug in a matmul backend shows one.
The check has a limit. To accept every implementation that adds in an ordinary order, it allows for all of a sum's roundings going the same way, so an error of a few dozen units in the last place can pass. When you know the order your kernel adds in, compare it bit for bit with ExactRef's exact emulation of that order, which catches an error of one unit in the last place: Check exactly when you know the order.
What every call returns#
Every operation returns a Result:
r.rounded: the exact answer, rounded once to the output format.r.tolerance(): per element, how far a correct implementation's finite output can be fromrounded.r.covers(output): per element, whether a correct implementation can produceoutput.r.normal(): the normal answer, what an ordinary implementation that adds in index order computes, emulated exactly.r.exact: per element, an interval guaranteed to contain the exact answer, for example to grade an implementation more precise than the output format or to measure an error exactly.
Results describes each of them and their options.
How to read a tolerance#
A sum's rounding error depends on the order its terms are added in, so ExactRef gives two tolerances:
tolerance()covers normal accumulation, the order ordinary kernels add in: index order, or a few SIMD lanes side by side.tolerance(standard="any_order")covers any order of additions at all, as a parallel reduction or atomic adds on a GPU may use. It is wider.
The reference, rounded, with the normal tolerance around it and the wider
any-order tolerance beyond.
An implementation's output, element by element:
Within
tolerance(): no worse than normal accumulation can be.Beyond it, but within
tolerance(standard="any_order"): still correct, but worse than normal accumulation can be, for example from a poor order of additions.Beyond both: no correct implementation could produce it. A correct implementation here is one that does not overflow and rounds only at the steps the operation needs, such as each partial sum and the final result.
r.covers(output) tells you, per element, whether the output is in the first
case, and r.covers(output, standard="any_order") whether it is in the first
or second. Both also judge infinities and NaN.
How tolerance works shows each case in a few lines of
Python.
Multi-step computations#
An implementation with several steps, such as a network layer, stores each step's output, and that stored value is uncertain: it can be any value ExactRef's result for that step allows. To check the whole computation, pass each result in as the input of the next operation. The next result's bounds then cover every such value, so the uncertainty carries through step by step. Chains and any_of shows how.
What you can do with it#
Find a bug in a matmul backend that
assert_closepasses, and name what the kernel does wrong.Replace hand-picked test tolerances with bounds computed from your inputs.
Accept nondeterministic reductions that differ from run to run.
Find the step that loses accuracy in a multi-step computation.
Solutions has these and more, each with code.
Operations#
Operation |
Call |
Inputs |
Backward |
Normal answer |
|---|---|---|---|---|
Matrix product |
|
real, complex, integer |
yes |
yes |
Matrix product added to a matrix (gemm) |
|
real, complex, integer |
yes |
yes |
Matrix exponential |
|
real, complex |
yes |
no |
Its Frechet derivative |
|
real, complex |
no |
no |
Elementwise sum, difference, and product |
|
real, complex, integer |
yes |
yes |
Elementwise quotient and reciprocal |
|
real, complex, integer, bool |
yes |
yes |
Square root and its reciprocal |
|
real, complex, integer, bool |
yes |
yes |
Exponential and logarithm |
|
real, complex, integer, bool |
yes |
yes |
Hyperbolic tangent and sigmoid |
|
real, complex, integer, bool |
yes |
yes |
Sum over dimensions |
|
real, complex, integer, bool |
yes |
yes |
Log of a sum of exponentials |
|
real, complex, integer, bool |
yes |
yes |
Running sum |
|
real, complex, integer, bool |
yes |
yes |
Mean, variance, and standard deviation |
|
real, complex |
yes |
yes |
Adding values into indexed positions |
|
real, complex, integer |
yes |
yes |
Scaled dot-product attention |
|
real |
yes |
yes |
Convolution |
|
real |
yes |
yes |
Softmax and its logarithm |
|
real |
yes |
yes |
Layer, RMS, and batch normalization |
|
real |
yes |
yes |
Fourier transforms |
|
real but not float8, complex, integer, bool |
yes |
no |
Half spectra of real inputs |
|
real but not float8, integer, bool |
yes |
no |
Real outputs from half spectra |
|
real but not float8, complex, integer, bool |
yes |
no |
Conversion to another floating-point format |
|
real, complex |
yes |
yes |
Formats: float64, float32, float16, bfloat16, and the float8 formats; complex32, complex64, and complex128; the signed and unsigned integer formats; and bool, with all five IEEE rounding modes.
Why trust it#
Every guarantee and every tolerance has a written proof, in the proofs folder on GitHub, and so does the exactness of the C code that computes them.
When it cannot be sure of an exact answer, ExactRef raises
ReferenceUnavailableErrorinstead of guessing.Its answers are tested against independent references: MPFR and MPC, FLINT, SymPy, NumPy, and the Python standard library. For infinities and NaN, where mathematics leaves the answer open, ExactRef follows PyTorch's conventions, and its tests check those cases against PyTorch.