Algorithms#
An operation's own tolerance says how far a correct implementation's output
can be from the reference, rounded: the exact answer rounded once to the
output format. It covers every implementation that rounds only where the
operation requires, at the steps where every correct implementation has to
round, such as each partial sum or the final rounding to the output format.
When your implementation does not fit that tolerance, describe it with a
named algorithm: one specific way of computing the operation, such as a
fixed order of additions, an accumulator format, the extra roundings of a
fused kernel, or the steps of a GPU's tensor cores.
Algorithms also let you compare ways of computing the same thing. The
reference does not change: an algorithm's bounds measure the distance from
the operation's rounded.
This page covers the algorithms for matmul, for matmul and gemm on tensor
cores, for attention, and for the Fourier transforms. The held-scalar
algorithms, for an add or a multiply that rounds a scalar operand first,
are in
alpha and scalar operands.
matmul algorithms#
The matmul algorithms are accumulation orders, each in a format, with or
without fused multiply-add. They live in er.linalg.products:
Constructor |
How the products of one output element are added |
|---|---|
|
one at a time, in index order |
|
as a balanced binary tree |
|
in order within blocks of |
|
exactly, then rounded once to |
|
rounded, then summed in 16 slots by magnitude |
How much the order matters shows in RMSNorm's sum of squares over one token's 4,096 activations, computed in bfloat16 as a dot product of the row with itself:
import torch
import exactref as er
# The module that holds the matmul algorithms
products = er.linalg.products
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# One token's activations as a 1x4096 row, and the same values as a column
row = torch.randn(1, 4096, generator=g).bfloat16()
col = row.T.contiguous()
# The reference: the exact sum of squares, rounded once to bfloat16
print("reference:", er.matmul(row, col).rounded.tolist())
# Products rounded to bfloat16, then added one at a time in bfloat16
sequential_algorithm = products.matmul_sequential("bfloat16", fma=False)
# run() gives what that implementation computes, emulated exactly
print("sequential:", sequential_algorithm.run(row, col).tolist())
# The same products added in blocks of 64, then the block sums in order
print("blocked:", products.matmul_blocked("bfloat16", 64, fma=False).run(row, col).tolist())
# The same products added as a balanced tree
pairwise_algorithm = products.matmul_pairwise("bfloat16", fma=False)
print("pairwise:", pairwise_algorithm.run(row, col).tolist())
reference: [[3984.0]]
sequential: [[1936.0]]
blocked: [[3920.0]]
pairwise: [[3968.0]]
Added one at a time in bfloat16, the running sum stops growing: once it passes 1024, bfloat16 values are 8 apart and most squares round away. In blocks of 64 each block's sum stays small, and only the block sums meet that problem. Added as a tree, every partial sum stays near the size of its terms, and the answer comes within one bfloat16 step of the reference: values near 4,000 are 16 apart.
With fma=True the exact products are added (a fused multiply-add); with
fma=False each product is first rounded to format. matmul_slots16 sorts
the rounded products into 16 slots, each covering a range of magnitudes.
Each slot adds its values in increasing magnitude, alternating positive and
negative values. Then the slot sums are added from the smallest slot up.
Each constructor also takes an accumulator_rounding, the rounding used
inside the accumulation. It must round to nearest: NEAREST_EVEN (the
default) or NEAREST_AWAY. It is separate from the rounding option of
run() and of the bounds, which is the final rounding to the output format,
as in the operations. A directed accumulator rounding raises ValueError.
Past its largest value, such an accumulator saturates, which can move the
result by up to the size of the terms, and no tolerance bounds that
usefully.
Each algorithm has:
run(A, B): what that implementation computes, emulated exactly, withdtype,rounding,overflow, andworkersoptions.tolerance(A, B),finite_range(A, B),may_be(kind, A, B), andcovers(output, A, B): its bounds, as a result's methods describe them (how far a correct output can be fromrounded, the lowest and highest finite output, where +inf, -inf, or NaN may occur, and whether a correct implementation can produceoutput), withdtype,rounding,overflow,standard,flush_to_zero, andworkersoptions.error_model(k): its error formula forkproducts, which depends only on shapes and formats, for comparing algorithms. Where the formula has no finite bound, as for a sequential bfloat16 sum of 256 products, it raisesValueError.
The error models compare algorithms before any data exists. To choose an order for a float32 kernel whose inner dimension is 4,096:
# Each order's bound on the error of a sum of 4096 rounded float32 products
for name, algorithm in (("sequential", products.matmul_sequential("float32", fma=False)),
("blocked", products.matmul_blocked("float32", 64, fma=False)),
("pairwise", products.matmul_pairwise("float32", fma=False))):
print(f"{name}:", algorithm.error_model(4096))
sequential: 0.000244 * sum over k of |A[i,k] * B[k,j]| + 2.87e-42
blocked: 7.57e-06 * sum over k of |A[i,k] * B[k,j]| + 2.91e-42
pairwise: 7.75e-07 * sum over k of |A[i,k] * B[k,j]| + 5.74e-42
er.accumulation describes the same summation orders on their own, without
a format, for any list of terms: exact, sequential, pairwise, and
blocked. Each gives the most roundings any one term passes through and the
total number of roundings, the numbers the textbook worst-case error bound
is built on (Higham, Accuracy and Stability of Numerical Algorithms,
chapters 3 and 4).
Tensor-core algorithms#
An operation's default tolerance covers normal accumulation, the
order ordinary kernels add in: index order, or SIMD lanes side by side. Its
any-order tolerance, tolerance(standard="any_order"), is wider:
it covers any order of additions at all, as a parallel reduction may use. A
correct kernel that runs on GPU tensor cores can
exceed even the any-order tolerance, because tensor cores do not add the way
the operations' tolerances assume. In each step, a tensor core takes a block
of exact products and its float32 accumulator, aligns them all to the largest
exponent, truncates each to a fixed number of bits below it (the step's
fraction_bits), adds them exactly, and truncates the sum to float32. No
step rounds to nearest. The tensor-core algorithms model these steps
instead.
One step: everything is aligned to the largest exponent, and the bits more
than fraction_bits below it are cut off before the exact addition.
matmul_mma(step, *, reduction=None) and gemm_mma(step, *, reduction=None),
in er.linalg.products, give matmul's and gemm's bounds on tensor cores:
tolerance, finite_range, may_be, and covers. They have no run(),
because kernels split and order the steps as they choose.
A kernel that runs on CUDA cores instead, such as cuBLAS's one-row products, keeps the operation's own tolerance. When you do not know which kernel ran, check against both. The example below uses Blackwell's step for bfloat16 inputs, on a layer of 128 tokens of hidden size 4096 times a 4096 by 1024 weight, with float32 outputs as tensor-core kernels accumulate them; the step's parameters and their values follow below. The tensor-core bound is wider than both the normal and the any-order tolerance:
# The layer's input and weight, in bfloat16
A = torch.randn(128, 4096, generator=g).bfloat16()
B = (torch.randn(4096, 1024, generator=g) / 64).bfloat16()
# Blackwell's tensor-core step for bfloat16 inputs, assuming nothing about splits
step = er.MMAStep(16, 25, -133, 1)
tensor_cores = products.matmul_mma(step)
# The product with float32 outputs
r = er.matmul(A, B, dtype="float32")
# Its largest tolerance for normal accumulation, any order, and tensor cores
normal = max(r.tolerance().scalars())
any_order = max(r.tolerance(standard="any_order").scalars())
mma = max(tensor_cores.tolerance(A, B, dtype="float32").scalars())
print(f"normal: {normal:.3g}")
print(f"any order: {any_order:.3g}")
print(f"tensor cores: {mma:.3g}")
normal: 0.000635
any order: 0.0108
tensor cores: 0.0342
On a GPU, check the kernel's output against it:
# PyTorch's bfloat16 product on a Blackwell GPU, copied back to the CPU
out = (A.cuda() @ B.cuda()).cpu()
# Could a tensor-core kernel with these steps have produced it?
print("covered:", tensor_cores.covers(out, A, B).all())
The step's parameters#
er.MMAStep(products, fraction_bits, exponent_floor, split)
Parameter |
Meaning |
|---|---|
|
how many products one step adds, as a tensor-core instruction does. A kernel may split a sum into pieces. Within each piece, every step except the last adds this many products, counting zero padding |
|
the bits each value keeps below the largest exponent before the exact addition |
|
the lowest exponent the alignment uses |
|
what you can assume about those pieces: every piece but one holds a multiple of |
The values are measured per GPU and input format. A published model (Khattak and Mikaitis, "Accurate Models of NVIDIA Tensor Cores", arXiv 2512.07004) gives these for NVIDIA's Blackwell GPUs, and ExactRef's tests confirm them on NVIDIA's DGX Spark (GB10) against real PyTorch outputs:
Inputs |
|
|
|
|---|---|---|---|
float16 and bfloat16 |
|
|
|
TF32 |
|
|
|
Other GPUs use other values, which ExactRef has not measured. For split,
pass 1 for closed kernels such as cuBLAS's and cuDNN's; FlashAttention-2 and
PyTorch's memory-efficient attention kernel split on multiples of 64.
Inputs and options#
Inputs are float16 or bfloat16, or float32 values that are TF32 values. Round those with
er.round_to_tf32, using the kernel's conversion rounding: cuBLAS on the GB10 rounds to nearest even. A float32AorBmust be an array: an earlier float32 result passed in its place, as in a chain, raisesValueError, because the values an implementation may have stored for it need not be TF32 values. Earlier float16 and bfloat16 results are accepted.reductionis the format of split-K partial sums for a kernel that rounds them to lower precision, as cuBLAS did on an Ampere GPU with float16 and bfloat16 under PyTorch's defaults. On the GB10 they stay in float32.gemm_mmaappliesalphaonce and addsbeta * Cin a float32 step rounded to nearest.alphaandbetamust be float32 values.Cis held in that float32 step, so it must be in a format float32 holds, such as float16, bfloat16, or float32. It may be an earlier result.gemm_mmatakes noreduce_batch: each batch's products are summed on their own.standardmakes no difference:"normal"and"any_order"give the same bound.flush_to_zero=TrueraisesValueError, because tensor-core steps keep subnormal values.
Attention algorithms#
Fused attention kernels round in places the operation itself does not, so a
correct kernel's output can fall outside er.scaled_dot_product_attention's
own tolerance. An er.nn.attention.AttentionAlgorithm describes those extra
roundings, one keyword option for each kernel technique (each a "method"
below), and gives the bounds of any kernel that rounds there:
er.nn.attention.AttentionAlgorithm(
*, online_softmax=False, block_size=None, exp2=False, weights=None,
accumulate=None, bias=None, reciprocal=False, backward_blocks=None,
exp_ulps=None, mma=None, scale_ds=False, rounded_p=False,
grouped_heads=False, split_kv=None, fast_log=False,
)
The methods combine. With none set, the bounds are those of
er.scaled_dot_product_attention itself. With online_softmax, which
processes the keys in blocks with a running maximum and sum, the default
standard="normal" gives the same bound as standard="any_order".
An attention algorithm has tolerance(), finite_range(), may_be(), and
covers(), taking scaled_dot_product_attention's arguments, and their
backward_ forms for the gradients. It has no run(), because kernels
differ in details that the options leave open, and no error model, because
attention's error grows with the size of the logits, which no formula in
shapes and formats alone can bound.
PyTorch's F.scaled_dot_product_attention on the CPU runs a flash kernel.
Here it computes causal attention in bfloat16 for 8 heads, 1,024 positions,
and head dimension 64, and the algorithm that describes it, from
PyTorch's attention kernels below, accepts its
output where the operation's own bounds do not:
# Query, key, and value of shape (batch, heads, positions, head dimension), in bfloat16
q, k, v = (torch.randn(1, 8, 1024, 64, generator=g).bfloat16() for _ in range(3))
# PyTorch's output on the CPU
out = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)
# No methods: the bounds of er.scaled_dot_product_attention itself
plain = er.nn.attention.AttentionAlgorithm()
# PyTorch's CPU flash kernel; exp_ulps=8192 covers its fast exp on every machine
cpu_flash = er.nn.attention.AttentionAlgorithm(
online_softmax=True, block_size=512, reciprocal=True, weights="bfloat16", exp_ulps=8192)
for name, algorithm in (("plain", plain), ("CPU flash", cpu_flash)):
# Does the algorithm cover PyTorch's output? covers() takes attention's
# outputs (output and logsumexp) by name, here just output.
covered = algorithm.covers({"output": out}, q, k, v, is_causal=True).output.all()
# Its largest tolerance on the output, to 3 significant digits
largest = max(algorithm.tolerance(q, k, v, is_causal=True).output.scalars())
print(f"{name}: covered {covered}, largest tolerance {largest:.3g}")
plain: covered False, largest tolerance 0.00781
CPU flash: covered True, largest tolerance 0.0234
Reading complicated tolerances checks an emulated FlashAttention kernel the same way.
Methods#
The compute format in the table is the format a kernel rounds to and
adds in along the way: float32 by default for inputs narrower than float32,
else the input format. In the backward, P is the attention weights and
dS the gradient of the scores, as
Backward defines them.
Method |
What the kernel does |
|---|---|
|
processes the keys in blocks with a running maximum and sum, rescaling earlier partial sums |
|
with |
|
computes the weights as |
|
rounds the weights to this format before the product with V (in the backward, also |
|
does every accumulation in this format instead of the compute format |
|
rounds float-mask values to this format before adding them, as a kernel computing ALiBi biases in lower precision does |
|
normalizes by a rounded reciprocal of the row sum instead of dividing |
|
computes each softmax exponential within |
|
adds up the products in tensor-core steps with these parameters, in float32. It takes float16 or bfloat16 inputs and needs |
|
with |
|
takes the forward logsumexp's log within |
|
in the backward, multiplies |
|
in the backward, forms |
|
in the backward, rounds each query head's |
|
in a fused backward, adds the gradients block by block into gradients held in the output format: |
PyTorch's CPU softmax and its CPU flash kernel normalize by a reciprocal. Any
format can stand in for "bfloat16" above.
PyTorch's attention kernels#
PyTorch's CPU flash kernel, which F.scaled_dot_product_attention runs on the
CPU, is AttentionAlgorithm(online_softmax=True, block_size=512, reciprocal=True) in its forward. For bfloat16 and float16 inputs it also
rounds the weights to the input format, so set weights to it, and it
computes the exponentials with an approximate exp, which needs exp_ulps:
Machine |
|
|---|---|
ARM without SVE, such as Apple's |
|
x86 with AVX2 or AVX-512 |
|
ARM with SVE |
|
Its backward recomputes the weights with an accurate exp and adds the
gradients block by block: describe it with backward_blocks=(32, 512) for
fewer than 192 queries, (64, 512) for fewer than 768, and (256, 512)
beyond. backward_blocks describes a fused backward only, so it needs the
forward's out and logsumexp, and it takes full-size inputs: a broadcast
query, or a key or value broadcast across batch dimensions, raises
ValueError.
PyTorch's CUDA attention backends on the GB10 are described by these methods,
each with weights set to the input format and
mma=er.MMAStep(16, 25, -133, split), plus grouped_heads=True when several
query heads share key and value heads:
Backend |
Methods |
Backward changes |
|
|
|---|---|---|---|---|
FlashAttention-2 |
|
none |
|
|
memory-efficient |
|
|
|
|
cuDNN |
|
|
|
|
exp_ulps=3 bounds the fast exp2 (ex2.approx) these kernels use, checked
over every float32 argument (worst: 2.055 ulps). The call's ulps must be at
least 3, because the rescaling factors and the backward's recomputed P use
the same instruction, and FlashAttention-2 needs 4, for CUDA's documented
error of the fast log (__logf) behind fast_log. cuDNN
is closed source, so its row lists the methods that fit cuDNN outputs
recorded in ExactRef's tests, not methods read from its code.
The backward#
For the backward, backward_tolerance(q, k, v, grad, out=out, logsumexp=logsumexp)
describes a fused backward kernel that is given the forward's out and
logsumexp: it recomputes the weights P from logsumexp and takes D, a
per-row sum that Backward
defines, from out.
Without them, backward_tolerance(q, k, v, grad) describes a backward that
recomputes the softmax, as PyTorch's math backend does. out and
logsumexp may be the forward result's own outputs, fwd["output"] and
fwd["logsumexp"]. er.scaled_dot_product_attention has no exp_ulps
option. So when the kernel's forward needs exp_ulps, a backward check that
takes out and logsumexp from that forward result needs ulps set to the
same value. Passing the kernel's own stored out and logsumexp gives a
tighter check.
Scaling Q and K before the product is not a method: it changes the inputs.
To check such a kernel, pass the pre-scaled values with scale=1.
FFT algorithms#
A Fourier transform's own tolerance covers every way of factoring its length
into radix passes, so it allows for the worst one. A library computes one
factorization, its plan: for each transformed axis, the passes that
compute it, whose lengths multiply to the axis's length. An FFT algorithm
describes a library by its plan. A plan of radix passes gives bounds never
wider than the transform's own. A plan with a Bluestein pass, below, gives a
proven bound where the transform's own is only measured. The algorithms live
in er.fft.dft, one class per transform: FFTAlgorithm, IFFTAlgorithm,
RFFTAlgorithm, IRFFTAlgorithm, HFFTAlgorithm, and IHFFTAlgorithm.
Argument |
Meaning |
|---|---|
|
the passes of the transformed axis, such as |
|
for a real input, or for the real outputs of |
|
the backward's transform: its plan, by default |
An FFT algorithm has tolerance(), finite_range(), may_be(), and
covers(), each with a backward_ form, and error_model(). They take the
transform's own arguments, x, n, axis, and norm: after the output in
covers(), and after the kind in may_be(). There is no run(): no plan
fixes how a library rounds its twiddle factors, so no single output follows
from it.
The libraries' plans#
Two open-source libraries have plans that can be read from their code:
Library |
Run by |
Its plan |
|---|---|---|
pocketfft |
NumPy, and PyTorch's CPU in builds without MKL, such as its ARM builds |
complex passes in the order: 8s, 4s, one 2 moved first, then odd primes. A real input takes real passes: 4s, one 2 moved first, then odd primes. For some lengths with a large prime factor, from 89 for complex transforms and from 191 for real ones, one Bluestein pass of the whole length |
DUCC |
SciPy, and JAX's CPU through XLA |
complex passes as pocketfft's, with a Bluestein pass for each prime factor of 110 or more. Real transforms take real passes, or the packed form when the length is even, more than 1000, and either more than 10000 or with a prime factor above 5 |
PyTorch's x86-64 builds run MKL's FFT, whose plans are not public, so ExactRef gives no plan for it.
NumPy's FFT of 4096 samples runs pocketfft's plan of four passes of radix 8:
import numpy as np
import exactref as er
dft = er.fft.dft
def largest(tolerance):
"""The largest bound of a complex tolerance, over both parts."""
return max(max(t.real, t.imag) for t in tolerance.scalars())
# 64 frames of 4096 samples in float64, and NumPy's spectra
x = np.random.default_rng(67).standard_normal((64, 4096))
spectra = np.fft.fft(x)
# pocketfft's plan for 4096: four passes of radix 8
pocketfft = dft.FFTAlgorithm([8, 8, 8, 8])
print("description:", pocketfft.description)
print("covered:", pocketfft.covers(spectra, x).all())
# The transform's own tolerance, for every factorization, and the plan's
own = largest(er.fft.fft(x).tolerance())
print(f"largest tolerance, the transform's own: {own:.2g}")
print(f"largest tolerance, pocketfft's plan: {largest(pocketfft.tolerance(x)):.2g}")
description: fft by passes 8, 8, 8, 8
covered: True
largest tolerance, the transform's own: 8.2e-11
largest tolerance, pocketfft's plan: 2.3e-11
pocketfft's plan for 4096: four passes of radix 8.
A real input runs real passes. NumPy's rfft of the same frames:
# pocketfft's real passes for 4096: six of radix 4
# The backward's transform is complex, so it takes pocketfft's complex plan
real = dft.RFFTAlgorithm([4, 4, 4, 4, 4, 4], path="real", backward_plan=[8, 8, 8, 8])
print("covered:", real.covers(np.fft.rfft(x), x).all())
covered: True
Over several axes, the plan has one list of passes per axis. NumPy's fft2
over FNet's 512 tokens and 768 features:
# 4 sequences of 512 tokens with 768 features
hidden = np.random.default_rng(67).standard_normal((4, 512, 768))
# pocketfft's plans: 512 as 8, 8, 8, and 768 as 8, 8, 4, 3
two_axes = dft.FFTAlgorithm([[8, 8, 8], [8, 8, 4, 3]])
print("covered:", two_axes.covers(np.fft.fft2(hidden), hidden, axis=(-2, -1)).all())
covered: True
Bluestein passes#
A large prime factor has no small radix to pass through. pocketfft and DUCC
can handle it by Bluestein's algorithm. The transform of a length p becomes
a cyclic convolution, padded to a length of at least 2p - 1 that has only
small factors, and is computed by three ordinary FFTs of that padded length.
Before and after the convolution the values are multiplied by fixed factors
called the chirp. dft.Bluestein(length, padded, radices) is such a pass,
with the radices of the padded length's plan. It may be the whole plan or
one pass of it.
Bluestein's pass for the prime length 4093: the inputs times the chirp, three FFTs of the padded length 8192, then the chirp again.
The transform's own tolerance covers radix passes only. At a length a library computes by Bluestein's algorithm it is not proven, only measured; the Bluestein plan's bound is proven. NumPy at the prime length 4093:
# 64 frames of 4093 samples
xp = np.random.default_rng(67).standard_normal((64, 4093))
# pocketfft's pass: 4093 through a padded length of 8192, by passes 2, 8, 8, 8, and 8
bluestein = dft.FFTAlgorithm([dft.Bluestein(4093, 8192, (2, 8, 8, 8, 8))])
print("covered:", bluestein.covers(np.fft.fft(xp), xp).all())
own = largest(er.fft.fft(xp).tolerance())
print(f"largest tolerance, the transform's own: {own:.2g}")
print(f"largest tolerance, the Bluestein plan: {largest(bluestein.tolerance(xp)):.2g}")
covered: True
largest tolerance, the transform's own: 1.1e-09
largest tolerance, the Bluestein plan: 2.7e-10
The bound's two forms#
An FFT's rounding errors grow with the size of its inputs. The tolerance
measures that size two ways and takes the smaller bound: the inputs' sum of
magnitudes, and sqrt(n) times their 2-norm, the square root of their sum
of squares. With radix passes only, the first is always the smaller. A
Bluestein pass's bound is far smaller in the second form. So for dense
inputs, whose values are all about the same size, a Bluestein plan's
tolerance is below the transform's own from a length of about 1000. For
sparse inputs, with a few nonzero values, it is above it, and not only on
paper: on a single nonzero value, Bluestein's actual error can exceed the
transform's own tolerance. So at a length the library computes by
Bluestein's algorithm, check with the Bluestein plan.
For a plan with a Bluestein pass, the 2-norm's bound is the smaller for dense inputs, and the sum's bound for sparse ones.
# One nonzero value in each of 4 frames of 4093
impulse = np.zeros((4, 4093))
impulse[:, 5] = 1.0
own = largest(er.fft.fft(impulse).tolerance())
print(f"largest tolerance, the transform's own: {own:.2g}")
print(f"largest tolerance, the Bluestein plan: {largest(bluestein.tolerance(impulse)):.2g}")
largest tolerance, the transform's own: 3.2e-13
largest tolerance, the Bluestein plan: 4.1e-12
Comparing plans#
error_model(compute, norm=None) gives a plan's bound as a formula, before
there is data: a relative part times the inputs' sum of magnitudes, plus an
absolute part. It depends on the plan, the compute format, and the norm, and
takes ulps and flush_to_zero as tolerance() does. It is the
sum-of-magnitudes form only, so it compares radix plans well but overstates
a Bluestein plan's bound on dense inputs, where tolerance() takes the far
smaller 2-norm form:
print("radix 8:", pocketfft.error_model("float64"))
print("Bluestein:", bluestein.error_model("float64"))
radix 8: 6.99e-15 * sum over the inputs of |Re x_j| + |Im x_j| + 1.43e-319
Bluestein: 4.06e-12 * sum over the inputs of |Re x_j| + |Im x_j| + 4.63e-317
The FFT backward#
backward_tolerance(x, grad, ...) and the other backward_ methods bound
the backward's transform, by backward_plan and backward_path. The
backward of fft, ifft, rfft, and ihfft is a complex transform of the
same length. On the complex path the forward's plan serves; when the forward
takes real passes or the packed form, give backward_plan. The backward of
irfft and hfft transforms a real gradient, by default by the forward's
plan and path.