ExactRef
Exact reference answers, with proven error bounds, for testing numerical code.
When a kernel's output differs from a reference computed in float64, is that a bug, or ordinary rounding? ExactRef answers per element. For an operation and its inputs, it computes the exact answer, rounds it once to the output format, and gives a tolerance: how far the output of a correct finite-precision implementation can be from that answer, on those inputs. An output beyond the tolerance cannot come from a correct implementation. When you know how your kernel adds, ExactRef can also emulate that exact sequence of roundings, so you can check its output bit for bit.
- Documentation: https://exactref.ai
- Source and bug reports: https://github.com/TorchCTS/ExactRef
- Proofs of every guarantee: https://github.com/TorchCTS/ExactRef/tree/main/proofs
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, as well as Python lists and any object with the buffer protocol.
Quick start
A sum where the order of additions matters:
>>> import exactref as er
>>> r = er.sum(er.asarray([1e16, 1.0, -1e16], "float64"))
>>> r.rounded.tolist() # the exact sum, rounded once to float64
1.0
>>> r.normal().tolist() # what adding in index order in float64 gives
0.0
>>> r.tolerance().tolist() # how far a correct float64 implementation can be from 1.0
1.1102230246251574
The exact sum is 1.0. Adding left to right in float64 loses the 1.0 and gives 0.0, which is still correct: a correct implementation can be up to 1.11 away. An implementation that returned 8.0 would not be.
Checking PyTorch's matrix product:
import torch
import exactref as er
A, B = torch.randn(64, 256), torch.randn(256, 32)
r = er.matmul(A, B)
assert r.covers(A @ B).all() # every element is one a correct implementation can produce
What a check tells you
The tolerance describes an implementation that rounds only where the operation requires, such as each partial sum of a matrix product and the final rounding to the output format, and that adds in an ordinary order: index order, or the lanes of a SIMD loop. ExactRef calls this normal accumulation. Each output then falls into one of three cases:
- 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 the any-order tolerance: no implementation that rounds only where the operation requires, without overflowing, could produce it.
r.covers(output) makes that judgment for every element at once, including infinities and NaN. A kernel that rounds
more than the operation requires, such as FlashAttention when it casts the attention weights to bfloat16, can fall
outside tolerance() without a bug. Describe such a kernel with a named algorithm (below), whose tolerance includes
its extra roundings.
Because the tolerance has to cover every correct implementation, it allows for all of a sum's roundings going the
same way. For a float32 dot product of 1024 random terms that is typically several hundred ulps of the result, while a
real library lands within a few percent of it. So covers() never rejects a correct implementation, and catches
gross and structural bugs, but a bug that adds a few dozen ulps can pass it. When you know the order your kernel adds
in, check it exactly instead.
Checking exactly, when you know the order
ExactRef can emulate a specific sequence of roundings exactly. If your kernel adds the products of a matrix product left to right in float32, its output must equal ExactRef's emulation bit for bit:
import numpy as np
import exactref as er
rng = np.random.default_rng(0)
A = rng.standard_normal((8, 1024)).astype(np.float32)
B = rng.standard_normal((1024, 8)).astype(np.float32)
# Your kernel: each product rounded to float32, then added left to right in float32
def my_matmul(A, B):
out = np.zeros((A.shape[0], B.shape[1]), np.float32)
for i in range(A.shape[0]):
for j in range(B.shape[1]):
acc = np.float32(0)
for a, b in zip(A[i], B[:, j]):
acc = acc + a * b
out[i, j] = acc
return out
C = my_matmul(A, B)
# ExactRef emulates that exact sequence of roundings
expected = er.linalg.products.matmul_sequential("float32", fma=False).run(A, B)
assert expected.tolist() == C.tolist()
# A one-ulp error passes the worst-case check, and the exact check catches it
C[3, 5] = np.nextafter(C[3, 5], np.float32(np.inf))
print(er.matmul(A, B).covers(C).all()) # True
print(expected.tolist() == C.tolist()) # False
The emulations available:
r.normal()on any result that has a normal answer (see the table below): the operation in index order, with each product and each partial sum rounded to the compute format.- The matmul named algorithms'
run(), for examplematmul_sequential(left to right),matmul_pairwise(a balanced tree), andmatmul_blocked(left to right within blocks of a given size, then the block sums), each in an accumulator format you choose, with or without fused multiply-add (fma); andmatmul_exact_accumulation(the exact sum, rounded once).
Use the exact check when you control or know the order of additions. Use tolerance() and covers() when you do not,
as with BLAS libraries, multithreaded kernels, and GPUs, whose orders vary.
Reading a result
Every operation returns a Result:
r = er.matmul(A, B)
r.rounded # the exact answer, correctly rounded once to the output format
r.exact # certified enclosures of the exact answer (an ExactArray)
r.exact.value((0, 1)) # Enclosure(midpoint, radius): the true value lies within radius of midpoint
r.guarantee # "correctly_rounded"
r.tolerance() # per element: max |implementation - r.rounded| over finite outputs, for normal accumulation
r.tolerance(standard="any_order") # the same for any order of additions that does not overflow
r.tolerance("bfloat16") # if implementations compute in bfloat16
r.tolerance(flush_to_zero=True) # if they flush subnormals to zero
r.finite_range() # (low, high): the lowest and highest finite output of a correct implementation
r.may_be("+inf") # where a correct implementation may output +inf (or "-inf", "nan")
r.covers(output) # where a correct implementation can produce the values in output
r.normal() # the output of normal accumulation in index order (computed when asked for)
r.boundaries # the operation's rounding boundaries
Where an overflow is possible, may_be() tells you which infinities or NaN a correct implementation may produce, and
it errs on the side of yes. An infinite tolerance marks an element with no bound at all, and a NaN tolerance an element
whose exact answer is not finite. For complex outputs, tolerance() is complex128 with one bound per part, and
may_be() and covers() have a last axis of 2: the real part and the imaginary part.
Operations
| Operation | Shortcut | Inputs | Backward | normal() |
|---|---|---|---|---|
linalg.products.matmul |
er.matmul |
real, complex, integer | yes | yes |
linalg.products.gemm (beta C + alpha A @ B) |
er.gemm |
real, complex, integer | yes | yes |
arithmetic.basic.add, arithmetic.basic.multiply |
er.add, er.multiply |
real, complex, integer | yes | yes |
arithmetic.basic.subtract |
er.subtract |
real, complex, integer | yes | yes |
foundations.conversion.convert_float_format |
er.convert_float_format |
real, complex | yes | yes |
arithmetic.basic.divide, arithmetic.basic.reciprocal |
er.divide, er.reciprocal |
real, complex, integer, bool | yes | yes |
elementary.power.sqrt, elementary.power.rsqrt |
er.sqrt, er.rsqrt |
real, complex, integer, bool | yes | yes |
elementary.exp_log.exp, expm1, log, log1p |
er.exp, er.expm1, er.log, er.log1p |
real, complex, integer, bool | yes | real inputs |
elementary.hyperbolic.tanh |
er.tanh |
real, complex, integer, bool | yes | real inputs |
elementary.logistic.sigmoid |
er.sigmoid |
real, complex, integer, bool | yes | real inputs |
array.indexing.scatter.scatter_add |
er.scatter_add |
real, complex, integer | yes | yes |
reduction.arithmetic.sum |
er.sum |
real, complex, integer, bool | yes | yes |
reduction.arithmetic.logsumexp |
er.logsumexp |
real, complex, integer, bool | yes | real inputs |
scan.cumulative.cumulative_sum |
er.cumulative_sum |
real, complex, integer, bool | yes | yes |
statistics.descriptive.location.mean |
er.mean |
real, complex | yes | yes |
statistics.descriptive.dispersion.var (outputs var, mean) |
er.var |
real, complex | yes | yes |
statistics.descriptive.dispersion.std (outputs std, mean) |
er.std |
real, complex | yes | yes |
linalg.matrix_function.matrix_exp |
er.matrix_exp |
real, complex | yes | no |
linalg.matrix_function.matrix_exp_frechet |
er.matrix_exp_frechet |
real, complex | no | no |
nn.attention.scaled_dot_product_attention |
er.scaled_dot_product_attention |
real | yes | yes |
nn.conv.convolution (and its transposed form) |
er.convolution |
real | yes | yes |
nn.softmax.softmax, nn.softmax.log_softmax |
er.softmax, er.log_softmax |
real | yes | yes |
nn.normalization.rms_norm, nn.normalization.layer_norm, nn.normalization.batch_norm |
er.rms_norm, er.layer_norm, er.batch_norm |
real | yes | yes |
fft.dft.fft, fft.dft.ifft |
none: er.fft.fft, er.fft.ifft |
real (not float8), complex, integer, bool | yes | no |
fft.dft.rfft, fft.dft.ihfft |
none: er.fft.rfft, er.fft.ihfft |
real (not float8), integer, bool | yes | no |
fft.dft.irfft, fft.dft.hfft |
none: er.fft.irfft, er.fft.hfft |
real (not float8), complex, integer, bool | yes | no |
Backward operations take floating-point and complex inputs. Formats run from the float8 variants through float16, bfloat16, float32, and float64 to complex and integer formats, and the reference can round in any of the five IEEE rounding modes.
Beyond one operation
- Chains. Pass a result where an array goes. The next operation's tolerance then carries the uncertainty of the stored intermediate, so a computation with several steps, such as a transformer layer, is checked step by step.
- Named algorithms. These give tolerances for specific implementations: fixed orders of additions (whose
run()also emulates them exactly, as above), NVIDIA tensor cores (with your GPU's measured parameters), fused attention kernels and PyTorch's attention math path, Fourier transforms by the passes a library runs (tighter bounds for a known factorization, and a proven bound for Bluestein's algorithm, which libraries use for lengths with a large prime factor), and anaddor amultiplythat rounds a scalar operand to a format first, as PyTorch's CPU kernels do when you writex * 0.1.
Guarantees and limits
- The reference is exact or the call raises. Every element of
roundedis the exact answer rounded once, or the call raisesReferenceUnavailableError. ExactRef raises its working precision until it knows which way each exact value rounds, up to a cap. Two kinds of call can reach the cap:- attention's backward, where
grad_key,grad_value, andgrad_querysummed over broadcast copies of a query row add terms from rows with different softmax denominators. Unless every term is rational, such a sum that lands exactly on a rounding boundary, or cancels to exactly zero, reaches the cap, and so can an element very close to a rounding boundary where the effect of a heavily masked key cancels exactly; - the matrix exponential, its Frechet derivative, and its backward, for an entry that needs more than 8192 bits, a
very large matrix (from about 6600 x 6600 real or 3300 x 3300 complex), or a matrix that is not diagonal with
||A||_infof 2**60 or more. Their docstrings give the limits exactly.
- attention's backward, where
- What the tolerance covers. Every implementation that loses precision only at the operation's rounding boundaries
and rounds to nearest there. The
roundingargument sets the rounding of the reference and of the final rounding to the output format. - The matrix exponential is different. No rounding step is shared by every algorithm (Taylor or Pade, any number of
squarings), so its tolerance bounds a backward error: the output is
exp(A + dA)with||dA||_inf <= ulps * (n + 16) * u * max(||A||_inf, 1)(2n + 16formatrix_exp_frechetandmatrix_exp's backward, on their 2n x 2n block matrix), whereuis the compute format's unit roundoff. That allowance is an assumption, measured on random matrices up to 64 x 64, where Higham's scaling and squaring and PyTorch'smatrix_expmostly stay within half of it. The guide lists the cases measured outside it (matrices near a multiple of the identity, and PyTorch's results at small norms), andulpsraises the allowance. - Formats without infinity (
float8_e4m3fnand thefnuzformats). A finite result too large for the format rounds to its largest value, or to NaN where a directed rounding points away from zero. PyTorch's conversions turn infinities into the largest value forfloat8_e4m3fn(overflow="saturate"reproduces this) and give NaN for thefnuzformats (overflow="nan"). - Flushing subnormals. Some code sets the CPU to flush subnormal numbers, the tiny values below the normal range,
to zero, for example
torch.set_flush_denormal(True). ExactRef turns that off during each call and restores it afterwards. Where the platform offers no way to do that, the call raisesReferenceUnavailableError. - Threads. Operations, and the methods that compute bounds, take
workers, the number of threads to use, by default as many as PyTorch uses: the physical cores, or the performance cores on Apple Silicon. No result depends on it.
Documentation
The guide at https://exactref.ai/guide/ covers how tolerances work and how to read complicated ones, results, data in
and out, backward operations, chains and any_of, named algorithms, and the guarantees and limits. Each operation's
reference page gives its rules (shapes, promotion, special values, and the roundings its tolerance allows for), and the
reference maps PyTorch's calls onto ExactRef's.
How ExactRef is tested
The tests are developed separately. They check ExactRef's answers against independent references: MPFR and MPC
(through gmpy2), FLINT (through python-flint), SymPy, NumPy (for integer wraparound), and the Python standard library.
PyTorch is never a reference there: it is an implementation whose outputs the tests check against ExactRef's bounds.
Each operation's guarantees and tolerances are proven in proofs/.
License
ExactRef is released under the MIT License.
Metadata
Release files for exactref 0.2.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| exactref-0.2.1.tar.gz | 808.4 kB | Without provenance | Details for exactref-0.2.1.tar.gz |
Built distributions (wheels)
| File | Actions Reset | |||
|---|---|---|---|---|
| exactref-0.2.1-cp310-abi3-win_amd64.whl | CPython 3.10 | abi3 | Windows x86-64 | Details for exactref-0.2.1-cp310-abi3-win_amd64.whl |
| exactref-0.2.1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl | CPython 3.10 | abi3 | Linux glibc 2.17+ x86-64, Linux glibc 2.28+ x86-64 | Details for exactref-0.2.1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl |
| exactref-0.2.1-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl | CPython 3.10 | abi3 | Linux glibc 2.28+ ARM64, Linux glibc 2.17+ ARM64 | Details for exactref-0.2.1-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl |
| exactref-0.2.1-cp310-abi3-macosx_14_0_arm64.whl | CPython 3.10 | abi3 | macOS 14.0+ ARM64 | Details for exactref-0.2.1-cp310-abi3-macosx_14_0_arm64.whl |
Total release size: 9.7 MB
Release files / exactref-0.2.1.tar.gz
| Download URL | exactref-0.2.1.tar.gz |
|---|---|
| Size | 808.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d46f5750c3f082534dc7e0ca6ed46cd1a29aa2465de82af8d9984fdd9980c022
|
|
BLAKE2b-256 checksum How to use checksums |
931eac2e552645993b8e250386f0d42a49ec63455cdab6df289ca6d41ca86751
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.0
|
Release files / exactref-0.2.1-cp310-abi3-win_amd64.whl
| Download URL | exactref-0.2.1-cp310-abi3-win_amd64.whl |
|---|---|
| Size | 1.3 MB |
| Tags | CPython 3.10 Windows x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
8ca656c74afa8e9ff736297f1e250cd37d5550cf4be45899fc4c9f4794a704c8
|
|
BLAKE2b-256 checksum How to use checksums |
abe72354af83ad0b85101fe6c6448794204ef22121e396fa5e267ee98318a900
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.0
|
Release files / exactref-0.2.1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl
| Download URL | exactref-0.2.1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl |
|---|---|
| Size | 3.4 MB |
| Tags | CPython 3.10 Linux glibc 2.17+ x86-64 Linux glibc 2.28+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
493bd2d2287b3ab5bc5ee5e100d52a8b8b1c32dcf682e087fe3c02fd0e750779
|
|
BLAKE2b-256 checksum How to use checksums |
ebe40f24bdf29bddacedd0470d0f7517fe98a8434c4e2cdf257afadb41fe9cf0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.0
|
Release files / exactref-0.2.1-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl
| Download URL | exactref-0.2.1-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl |
|---|---|
| Size | 3.3 MB |
| Tags | CPython 3.10 Linux glibc 2.17+ ARM64 Linux glibc 2.28+ ARM64 abi3 |
|
SHA-256 checksum How to use checksums |
438b345929e38d31c79faa1ccf5de0af21b90895e95a428a8c0bb4ead4593829
|
|
BLAKE2b-256 checksum How to use checksums |
7268dd5f1bb42f486bde2ed1d4da7557d85edf94929c07efa518b72fd9996fbf
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.0
|
Release files / exactref-0.2.1-cp310-abi3-macosx_14_0_arm64.whl
| Download URL | exactref-0.2.1-cp310-abi3-macosx_14_0_arm64.whl |
|---|---|
| Size | 915.2 kB |
| Tags | CPython 3.10 abi3 macOS 14.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
c7d0cd59da0f3b49132439e8f768f5c629c25e145a7596ae3cceaf1d0ad10cfd
|
|
BLAKE2b-256 checksum How to use checksums |
819f33eb18aed8e83e6f9d702a7cd15607aaffa288195deb05ebea29159dc158
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.0
|
Security for exactref 0.2.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.