Guarantees and limits#

What ExactRef promises, what its tolerances cover and what they do not, and the practical limits of using it.

Reference answers#

Every output is the exact result rounded once to the output format, or the call raises er.ReferenceUnavailableError. ExactRef never returns an answer it cannot guarantee.

Most results are decided exactly, with integer arithmetic: sums, products, quotients, square roots, means, variances, and the normalizations built from them. Results that involve transcendental functions, such as exp, log, tanh, softmax, attention, and the matrix exponential, cannot be. For those, ExactRef raises its working precision until it knows which way each exact value rounds, up to a cap. The value of exp, expm1, log, log1p, tanh, sigmoid, softmax, log_softmax, or logsumexp is irrational wherever ExactRef does not know it exactly, so it never sits exactly where the rounding switches, and the precision rises until it settles. Three kinds of call can still reach the cap and raise er.ReferenceUnavailableError:

  • Attention's backward. grad_key and grad_value, and grad_query when it adds up broadcast copies of a query row, each add terms from rows with different softmax denominators. ExactRef can find such a sum exactly only when every term is a rational number. Otherwise, a sum that lies exactly where the rounding switches from one output value to the next, or that is exactly zero because its terms cancel, reaches the cap. So can an element very close to such a switch when the effect of a key with a large negative mask value cancels exactly.

  • logsumexp's backward for complex inputs, where a part of the gradient is exactly zero because its terms cancel.

  • The matrix exponential, its Frechet derivative, and its backward, on an entry that needs more than 8192 bits, a very large matrix, or a matrix of huge norm: see the matrix exponential's limits.

The Fourier transforms have no precision cap. They raise the error only when a transform's exact computation would need more 62-bit primes of a special form than exist.

What a tolerance covers#

tolerance() gives, per element, how far a correct implementation's output can be from the reference, on these inputs. It covers every implementation that loses precision only at the operation's required rounding steps, the steps where every correct implementation has to round, rounding to nearest there:

  • one rounding in the compute format, the format the implementation adds in (by default float32 for inputs narrower than float32, else the input format), at each required step,

  • the additions in normal accumulation (index order, or 2 or 4 SIMD-style lanes, and for softmax, log_softmax, and logsumexp also the wider orders of PyTorch's kernels), or with standard="any_order" in any order that does not overflow,

  • library functions such as exp within ulps units in the last place, by default 1 for most operations (Results lists each default),

  • and the final rounding to the output format.

The rounding argument of an operation sets the rounding of the reference and of that final step, not of the steps inside the computation.

An output within tolerance() is no worse than normal accumulation can be. Beyond it but within the any-order tolerance, it is correct but worse than normal accumulation can be. Beyond the any-order tolerance, no implementation that rounds only at the required steps, without overflowing, could produce it. Where an overflow is possible, may_be() says which infinities or NaN a correct implementation may produce, erring on the side of yes.

The Fourier transforms have no order of additions that every FFT library shares, and no normal answer. Their tolerance covers every library that computes by radix passes, for any factorization of the length, with each twiddle factor within ulps times the compute format's unit roundoff of its exact value (by default 2 for float32 and narrower compute formats, and 10 for float64). It is the same under both standards. At a length a library computes by Bluestein's algorithm, the tolerance is not proven, only measured; an FFT algorithm with a Bluestein pass gives a proven bound.

What a tolerance does not cover#

  • Roundings an implementation adds beyond the required ones, such as FlashAttention's cast of the weights to bfloat16, or an intermediate result stored in its dtype. Such an implementation can exceed tolerance(). Algorithms, each one specific way of computing an operation with its own bounds, and chains, which pass an earlier result in place of an array, allow for these.

  • Rounded attention weights: PyTorch's math backend (SDPBackend.MATH) computes the attention weights P, normalized and rounded, before multiplying them by V. No tolerance allows for that rounding.

  • Tensor-core accumulation, unless you describe it with a tensor-core algorithm. The operations' tolerances, the any-order one included, assume each rounding in the compute format is to nearest. GPU tensor cores add each block of products in one adder that truncates, so a correct tensor-core kernel can exceed them, most likely on inputs that cancel heavily or span a wide range of exponents. The tensor-core algorithms model those steps, from the GPU's measured parameters.

  • Every bug. A wrong formula can still produce an output within the bounds, for example when its effect is smaller than the rounding allowed on those inputs. A tolerance says whether rounding can explain a difference.

Matrix exponential#

matrix_exp has no rounding step that every algorithm shares, so its tolerance is a backward error instead: a correct result is exp(A + dA), rounded to the compute format and then to the output format, with

||dA||_inf <= ulps * (n + 16) * u * max(||A||_inf, 1)

for n x n matrices, where u is the compute format's unit roundoff (2**-24 for float32, 2**-53 for float64) and ulps defaults to 1. The n and the 16 count the roundings of an algorithm's inner products and its other steps (short sums, scalings, the linear solve), and the floor of 1 covers the rounding of the identity part of exp(A). matrix_exp_frechet and matrix_exp's backward use 2n + 16 for their 2n x 2n block matrix. There is no normal answer.

The allowance is an assumption about what correct implementations do. It was measured on random Gaussian, symmetric, non-normal, and skew-symmetric matrices, with n from 2 to 64 and ||A||_inf from 0.03 to 512. On those, Higham's 2005 scaling and squaring method with its degree-13 Pade approximant, and PyTorch's matrix_exp, stay within half of the allowance. Some results fall outside it:

  • Matrices near a multiple of the identity, with eigenvalues near +-5.37 * 2**s for a whole number s. There the rounding of that Pade method itself exceeds the allowance by up to about 3 times. For negative eigenvalues, PyTorch's float32 results exceed it by up to about 6 times.

  • PyTorch's own results at small norms: in float64 near ||A||_inf 0.03, and in float32 up to ||A||_inf 1.

  • SciPy 1.18.1's expm, for some float64 matrices with ||A||_inf of 4 or more.

In all these cases, ExactRef's reference agrees with mpmath at high precision. A larger ulps raises the allowance.

Formats without infinity#

float8_e4m3fn and the fnuz formats have no infinity. A finite exact result beyond the format's largest value rounds to that largest value. Under a directed rounding that points away from zero, it rounds to NaN instead, because the format has no value further out. PyTorch's finite float8_e4m3fn results agree. PyTorch also turns infinities into the largest value, which overflow="saturate" reproduces; its conversions into the fnuz formats give NaN instead, which overflow="nan" reproduces. exact keeps the exact value of every element, so behind a NaN it shows whether the true value was a finite number too large for the format, an infinity, or NaN.

Special values#

Infinities, NaN, and signed zeros follow IEEE 754 applied to the exact expression. Where mathematics leaves the answer open, ExactRef follows PyTorch; where mathematics gives an answer, ExactRef gives it, even when PyTorch differs. Each operation's reference page states its rules.

Threads#

Every operation, and every method that computes bounds, takes workers: the number of threads it computes on. By default it is the number of cores PyTorch would use: the performance cores on Apple Silicon, else the physical cores. No result depends on it. Several Python threads can call ExactRef at once.

The floating-point environment#

ExactRef computes in the default floating-point environment. When the calling thread flushes subnormals, for example after torch.set_flush_denormal(True), every ExactRef operation, and every method call on a result or algorithm, such as tolerance() or covers(), turns flushing off and turns it back on before returning. Where the platform offers no way to do that, the call raises ReferenceUnavailableError.

Proofs#

Every guarantee and tolerance is proven in plain-text Markdown files in the repository:

ExactRef's answers are also tested against independent references: MPFR and MPC (through gmpy2), FLINT (through python-flint), SymPy, NumPy, and the Python standard library. The inf and NaN conventions that ExactRef takes from PyTorch, where mathematics leaves the answer open, are tested against PyTorch.

Where to go next#