PyTorch equivalents#

ExactRef's operations are mathematical operations, not a copy of PyTorch's API. Each returns a result r: its reference r.rounded is the exact answer rounded once to the output format, r.tolerance() gives per element how far a correct implementation's output can be from r.rounded, and r.covers(output) says per element whether a correct implementation can produce output.

This page lists the ExactRef call that checks each common PyTorch call, and where PyTorch rounds more often than the operation requires. Those extra roundings are described with:

  • a chain: an earlier result passed in place of an array, so the next result's bounds cover every value the earlier result allows;

  • any_of: one result whose bounds accept an output of any of several expressions an implementation may compute;

  • an algorithm: a named way of computing an operation, such as a fused kernel's extra roundings or tensor-core steps, with its own bounds;

  • or an option.

In-place and out= variants map the same way as the plain call.

Matrix products#

PyTorch

ExactRef

A @ B

er.matmul(A, B)

torch.matmul(A, B)

torch.mm(A, B)

torch.bmm(A, B)

torch.mv(A, B)

torch.dot(A, B)

torch.addmm(C, A, B, beta=b, alpha=a)

er.gemm(A, B, C, alpha=a, beta=b)

torch.addmv(C, A, B, beta=b, alpha=a)

torch.baddbmm(C, A, B, beta=b, alpha=a)

torch.addr(C, v, w, beta=b, alpha=a)

er.gemm(v.reshape((m, 1)), w.reshape((1, n)), C, alpha=a, beta=b)

torch.addbmm(C, A, B, beta=b, alpha=a)

a loop of er.gemm calls, below

er.matmul follows NumPy's batching and 1-D promotion, as torch.matmul does. er.gemm takes alpha and beta exactly and broadcasts C to the output's shape; with beta = 0 it does not read C, and with alpha = 0 neither A nor B, as in PyTorch and BLAS. For addr, v and w are ExactRef arrays or earlier results, which have reshape.

Where PyTorch rounds more#

addbmm rounds each batch's product before adding the next one. That is a loop of gemm calls on earlier results:

Code
y = C
for i in range(batches):
    # Add batch i's product to the stored result, rounding once; beta scales
    # only C, in the first call
    y = er.gemm(A[i], B[i], y, alpha=alpha, beta=beta if i == 0 else 1)

er.gemm(A, B, C, alpha=alpha, beta=beta, reduce_batch=True) is the reference without those roundings: every element is one sum over all batches, rounded once.

Scaling an operand first. An implementation that scales and stores an operand before the product is a chain:

Code
# alpha * A stored first
er.gemm(er.multiply(A, alpha), B, C)

# beta * C stored first
er.gemm(A, B, er.multiply(C, beta), alpha=alpha)

addmv in bfloat16 and float16 may store beta * C in the dtype before the addition. With the matrix stored transposed, it may also store alpha * (A @ x). Write each of these two ways of computing as a chain of er.multiply, er.gemm with beta=0, and er.add. Then cover both with er.any_of.

addr in bfloat16 and float16 computes in the dtype itself. Check it with covers(out, "bfloat16") or covers(out, "float16"): the second argument is the compute format, the format an implementation rounds to and adds in along the way, which is float32 by default for these inputs.

Batched products in the backward. When both operands keep batch dimensions that broadcast against each other, PyTorch rounds each batch's product before summing the copies. The default tolerance does not allow for that.

TF32. A GPU in TF32 mode rounds float32 inputs to TF32 before the product. Round the inputs with er.round_to_tf32 and pass those to er.matmul: TF32 values are float32 values. Check low-precision kernels says which rounding matches which kernel.

Tensor cores. On a CUDA GPU, PyTorch runs float16 and bfloat16 matrix products, and float32 ones in TF32 mode, on tensor cores, whose block additions truncate. Check matmul, mm, and bmm with matmul_mma, and addmm with gemm_mma: tensor-core algorithms built from the GPU's MMAStep, what one tensor-core instruction does to a block of products. Algorithms lists Blackwell's values. One-row products run on CUDA cores and keep the operation's own tolerance.

Parameters with no ExactRef argument#

Some kernels and lower-level APIs take parameters that ExactRef's operations do not have. Each can be expressed with the inputs ExactRef already takes:

In the kernel or API

Express it as

an operand in a compressed storage form, such as sparse or 2:4 semi-structured

the same operand as an ordinary matrix

offs of torch._grouped_mm (grouped products)

one call per group

BLAS's transa and transb

the operand already transposed or conjugate-transposed; an earlier result has transpose

BLAS's uplo in syrk and herk (one triangle of the output)

a full product, comparing only the triangle the implementation computes

Elementwise arithmetic and conversions#

PyTorch

ExactRef

x * y

er.multiply(x, y)

torch.mul(x, y)

x * s, with s a Python scalar or a tensor of shape ()

er.arithmetic.basic.multiply_held_scalar(held), with held as below

x + y

er.add(x, y)

torch.add(x, y)

x + s

er.arithmetic.basic.add_held_scalar(held), with held as below

torch.add(x, y, alpha=a)

add_held_scalar(held) with alpha=a; in float16 and bfloat16, as below

x - y

er.subtract(x, y)

torch.sub(x, y)

x - s, torch.sub(x, y, alpha=a)

add_held_scalar(held) with -s in place of s, or with alpha=-a, as for torch.add

torch.rsub(x, y, alpha=a)

torch.sub(y, x, alpha=a): the operands swapped

x / y

er.divide(x, y)

torch.div(x, y), torch.true_divide(x, y)

x / s on a CPU, with s a Python scalar

er.divide(x, s), with s rounded to the compute format first

x / s on CUDA

er.multiply(x, r), with r the scalar's reciprocal rounded to the compute format: that kernel multiplies by it

s / x

er.multiply(er.reciprocal(x), s), with s rounded to the compute format first: PyTorch multiplies the reciprocal by s

torch.div(x, y, rounding_mode="floor") or "trunc"

not covered: another operation

torch.reciprocal(x)

er.reciprocal(x)

torch.reciprocal(x) on a Linux ARM CPU, bfloat16

er.arithmetic.basic.reciprocal_estimate(): that kernel computes some elements with Arm's reciprocal estimate (below)

its gradient there

reciprocal_estimate().backward_covers(output, x, grad)

x.to(d), x.half(), x.bfloat16(), x.float(), x.double(), between floating-point dtypes or between complex ones

er.convert_float_format(x, d)

x.to(d) from float64 to bfloat16 or a float8 dtype

er.convert_float_format(er.convert_float_format(x, "float32"), d): PyTorch goes through float32

x.to(torch.float8_e4m3fn)

er.convert_float_format(x, "float8_e4m3fn", overflow="saturate"): PyTorch clamps a value past the range, an infinity too

x.to(d) to float8_e4m3fnuz or float8_e5m2fnuz

er.convert_float_format(x, d, overflow="nan"): PyTorch gives NaN past the range

their gradients

er.add.backward, er.subtract.backward, er.multiply.backward, er.divide.backward, er.reciprocal.backward, and er.convert_float_format.backward; for divide and reciprocal in float16 and bfloat16, with compute= the dtype

Broadcasting follows NumPy, and mixed formats are promoted as PyTorch promotes them (bfloat16 with float16 gives float32). An operand of shape () takes part in the promotion only when every operand has shape (). Beside an operand with dimensions it is a scalar operand, as a Python scalar is: ExactRef takes it exactly, and it does not change the format. PyTorch rounds a scalar operand first, so the table checks it with the held-scalar algorithms, which round the scalar to the format held before the operation (alpha and scalar operands), or with the scalar rounded by hand. In a division PyTorch rounds a Python scalar to the compute format: float32 for float32, float16, and bfloat16 tensors.

Where PyTorch rounds more#

Scalar operands and alpha are rounded before the operation. PyTorch's CPU add rounds them to the tensor's dtype: held="operand". For bfloat16 and complex32 it converts them through float32 or complex64 first, held=("float32", "operand") or ("complex64", "operand"), and for float16 too except on aarch64, ("float32", "operand"). Its CPU mul rounds a scalar that is its second argument (x * s, or s * x with a Python scalar s) to float32 for float16 and bfloat16, the format it computes in, held="compute", and any other scalar as add does. Its CUDA kernels round alpha to the compute type (float32 for float16 and bfloat16): held="compute".

With alpha other than 1, the CPU add of complex32 and float16, and of bfloat16 on ARM, may also store alpha * y in the dtype before adding x, which add_held_scalar does not model. Write that way of computing as a chain, with a the rounded alpha:

dtype

ExactRef

float32

add_held_scalar("operand")

bfloat16 on ARM (macOS, Linux ARM)

er.add(x, er.multiply(y, a, dtype="bfloat16")), with alpha * y stored first

bfloat16 on x86

er.add(x, y, alpha=a): one rounding

complex32

er.add(x, er.multiply(y, a, dtype="complex32")), with alpha * y stored first

float16

er.any_of of both ways of computing, because some elements are computed each way

For example, a residual branch scaled by 0.3 and added in float16, over 128 tokens of hidden size 1024:

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The residual stream and the branch's output, in float16
x = torch.randn(128, 1024, generator=g).half()
y = torch.randn(128, 1024, generator=g).half()

# Alpha as the CPU kernel uses it: 0.3 rounded to float16
a = torch.tensor(0.3, dtype=x.dtype).item()
print("alpha:", a)

# x + a * y, rounded once to float16
plain = er.add(x, y, alpha=a)
# a * y rounded to float16 first, then added to x
stored = er.add(x, er.multiply(y, a, dtype="float16"))

# er.any_of accepts an output of either way of computing, element by element
print("covered:", er.any_of(plain, stored).covers(torch.add(x, y, alpha=0.3)).all())
Output
alpha: 0.300048828125
covered: True
any_of: the smallest range holding both center's rounded alternative center

Per element, er.any_of(plain, stored) accepts any output in the smallest range that holds both ways' ranges of correct outputs. plain is the center, whose rounded it keeps, and stored the alternative.

Broadcast operands in the backward. In the backward of add and multiply with a broadcast operand, PyTorch may round each product before summing the copies, an extra rounding the default tolerance does not allow for.

bfloat16 reciprocal and rsqrt on a Linux ARM CPU. PyTorch's Linux ARM build computes these two in bfloat16 less accurately than the operations allow. Over every finite bfloat16 input, torch.reciprocal is up to 1.18 steps from the exact value and differs from the correctly rounded value on 17,250 of 65,278 inputs. torch.rsqrt is up to 1.70 steps off and differs on 11,723 of 32,639. er.reciprocal and er.rsqrt reject those outputs. That build's kernel computes each element one of two ways, depending on its position, the tensor's strides, and the threads. One rounds as er.reciprocal and er.rsqrt do. The other takes Arm's reciprocal estimate, a hardware approximation accurate to about 8 bits, of x or of its rounded square root. er.arithmetic.basic.reciprocal_estimate() and er.elementary.power.rsqrt_estimate() accept the output of either way, and their backward_covers accepts the gradient PyTorch computes from either output. They take bfloat16 only and no ulps; with flush_to_zero=True they describe a CPU set to flush subnormals to zero. This page's other rows cover that build's bfloat16 division of two tensors, exp, log, sqrt, tanh, and sigmoid, its float16 reciprocal and rsqrt, and both kernels on macOS.

Special values#

Complex special values follow IEEE rules in each part, as in PyTorch: (inf + 0j) * (1 + 0j) is inf + nanj. Where mathematics gives an answer, ExactRef gives it even when PyTorch does not: er.add(x, y, alpha=1j) with x holding 1+1j and y holding inf+1j is infj, where PyTorch, multiplying alpha * y out in complex arithmetic, gives nan+infj.

Square roots#

PyTorch

ExactRef

torch.sqrt(x), x.pow(0.5), x ** 0.5 on an ARM CPU or CUDA

er.sqrt(x)

the same on MPS

er.sqrt(x) with flush_to_zero=True: MPS reads a subnormal input as 0

torch.sqrt(x) on an x86 CPU build with MKL, float32

er.sqrt(x) with ulps=Fraction(9, 16): that build uses MKL's routine, which is within 0.5601 steps of the exact root on every float32

torch.sqrt(x) on an x86 CPU build with MKL, float64

er.sqrt(x) with ulps=1: either value next to the exact root

torch.rsqrt(x) on a CPU, float32 and float64

er.rsqrt(x)

torch.rsqrt(x) on an ARM CPU, float16, and on macOS, bfloat16

er.rsqrt(x) with compute= the dtype: that kernel rounds both steps in the dtype

torch.rsqrt(x) on a Linux ARM CPU, bfloat16

er.elementary.power.rsqrt_estimate(): that kernel computes some elements with Arm's reciprocal estimate ([Elementwise arithmetic](#elementwise-arithmetic-and-conversions))

torch.rsqrt(x) on an x86 CPU, float16 and bfloat16

er.rsqrt(x): that kernel works in float32

torch.rsqrt(x) on MPS

er.rsqrt(x) with flush_to_zero=True

torch.rsqrt(x) and x.pow(-0.5) on CUDA

er.elementary.power.rsqrt_direct(): one library function

x.pow(-0.5) on a CPU, float64, float32, and bfloat16

as torch.rsqrt on that CPU

x.pow(-0.5) on a CPU, float16

er.rsqrt(x): that kernel works in float32

complex torch.sqrt(z) and torch.rsqrt(z) on a CPU

er.sqrt(z) and er.rsqrt(z)

complex torch.sqrt(z) on CUDA

er.elementary.power.sqrt_polar(): CUDA goes through an angle, and its smaller part is only as accurate as its larger one

complex torch.sqrt(z) on MPS

not covered: MPS uses a formula that subtracts

complex torch.rsqrt(z) on CUDA

not covered: CUDA computes it as a complex power

their gradients, float32, float64, and complex

er.sqrt.backward(z, grad) and er.rsqrt.backward(x, grad), with the forward's ulps; complex torch.sqrt's on CUDA, sqrt_polar().backward_covers(output, z, grad)

their gradients, float16 and bfloat16

the same with compute= the dtype; torch.rsqrt's on a Linux ARM CPU in bfloat16, rsqrt_estimate().backward_covers(output, x, grad)

torch.rsqrt's gradient on a CPU, float16

a chain on the forward's output y: er.multiply(-0.5 * grad, er.convert_float_format(er.multiply(er.multiply(y, y, dtype="float32"), y, dtype="float32"), "float16")), since that kernel cubes y in float32

er.rsqrt is the square root followed by its reciprocal, each rounded; rsqrt_direct is one library function, as CUDA's rsqrtf is. sqrt and rsqrt explains both. Here RMSNorm's reciprocal root is checked for 2,048 tokens of width 4,096:

Code
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The activations of 2048 tokens, and per token the mean of their squares
# plus eps, as RMSNorm computes it before the root
h = torch.randn(2048, 4096, generator=g)
ms = h.pow(2).mean(-1) + 1e-6

# torch.rsqrt on a CPU: the square root and then its reciprocal, each rounded
print("covered:", er.rsqrt(ms).covers(torch.rsqrt(ms)).all())
Output
covered: True

Elementary functions#

PyTorch

ExactRef

torch.exp(x), torch.expm1(x), torch.log(x), torch.log1p(x), torch.tanh(x), torch.sigmoid(x) on a CPU, real x

er.exp(x), er.expm1(x), er.log(x), er.log1p(x), er.tanh(x), er.sigmoid(x)

the same on CUDA

the same with ulps=2

the same on MPS, but expm1

the same with ulps=4 and flush_to_zero=True

torch.expm1(x) on MPS, real x

er.elementary.exp_log.expm1_algorithm(difference=True) with ulps=2 and flush_to_zero=True

their gradients, float32 and float64

er.exp.backward(x, grad) and the others, with the forward's ulps

their gradients, float16 and bfloat16

the same with compute= the dtype on CUDA, and on a CPU for expm1, log1p, and float16 sigmoid; the default elsewhere

complex torch.exp(z), torch.expm1(z), torch.sigmoid(z) on a Linux or macOS CPU

er.exp(z), er.expm1(z), er.sigmoid(z)

complex torch.log(z), torch.log1p(z), torch.tanh(z) on a Linux CPU

er.log(z), er.log1p(z), er.tanh(z) with ulps=2

complex torch.log(z), torch.log1p(z), torch.tanh(z) on a macOS CPU

log_algorithm(hypot=True), log1p_algorithm(squares=True), tanh_algorithm(double_angle=True)

complex z on a Windows CPU

exp_algorithm(fused=True), er.expm1(z), log_algorithm(norm_log1p=True), log1p_algorithm(norm_log1p=True), sigmoid_algorithm(fused=True), and tanh_algorithm(sinh_beta=True), with ulps=3

complex z on CUDA

er.exp(z), er.expm1(z), log_algorithm(hypot=True), log1p_algorithm(squares=True), and sigmoid_algorithm(scaled=True) with ulps=2; tanh_algorithm(kahan=True) with ulps=4

complex z on MPS

exp_algorithm(products=True), expm1_algorithm(difference=True), log_algorithm(sqrt_sum=True), log1p_algorithm(direct=True), sigmoid_algorithm(divided=True), and tanh_algorithm(quotient=True), with ulps=4 and flush_to_zero=True, and for complex32 also compute="float16", since MPS runs that kernel in float16; expm1 of a value whose imaginary part is 0 is not covered

The algorithms are in er.elementary.exp_log, er.elementary.hyperbolic, and er.elementary.logistic. By default the tolerance lets each library function be 1 step of the compute format from the exact value, and 1.0001 steps for log1p and tanh, whose CPU functions return the value one full step from an exact value that lies just beside a float. PyTorch's CPU functions stay within that. CUDA's are within 2 steps and MPS's within 4, hence their rows' ulps. MPS computes a real expm1 as exp(x) - 1 from 0.1 in magnitude, which expm1_algorithm(difference=True) describes.

For complex inputs the kernels call real functions such as cos, sinh, and atan2 from the C library or the device. glibc's atan2, sinh, and cosh are up to 1.9 steps off on some inputs. So on a Linux CPU a complex log or log1p is outside the default on about one input in 3,000, and a complex tanh on a few in a thousand; ulps=2 accepts them all. On a Windows CPU they come from Microsoft's C runtime, whose functions are up to 2.8 steps off, so that row takes ulps=3. At special inputs such as infinities, Metal's formulas can pass through a NaN; there MPS's algorithms accept a NaN part as well as the reference. MPS's complex expm1 of a value on the real axis is off by up to thousands of steps, and no setting accepts it.

Here is the tanh inside GPT-2's GELU, for 1,024 tokens of 3,072 features:

Code
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The values the GELU passes to tanh
u = torch.randn(1024, 3072, generator=g) * 2
t = er.tanh(u)
print("covered:", t.covers(torch.tanh(u)).all())

# The largest tolerance by default, and with ulps=2 as for a CUDA kernel
print("largest tolerance:", max(t.tolerance().scalars()))
print("with ulps=2:", max(t.tolerance(ulps=2).scalars()))
Output
covered: True
largest tolerance: 5.960464477539063e-08
with ulps=2: 1.1920928955078125e-07

Sums and means#

PyTorch

ExactRef

torch.sum(x, dim, keepdim=k)

er.sum(x, dim, keepdims=k)

torch.sum(x, dtype=d), d of the same kind (floating point, complex, integer, or bool) as x, such as float32 for a bfloat16 x

er.sum(er.multiply(x, 1, dtype=d))

torch.sum(x, dtype=d), d of another kind, such as float32 for an integer x

er.sum(er.asarray(x, d))

torch.mean(x, dim, keepdim=k) on a CPU

er.mean(x, dim, keepdims=k)

torch.mean(x, dim) on CUDA

er.multiply(er.sum(x, dim, dtype=c), r, dtype=d), with c the compute format, r the count's reciprocal rounded to c, and d the dtype: that kernel multiplies by it

torch.cumsum(x, dim) on a CPU, float32

er.cumulative_sum(x, dim) with compute="float64": that kernel keeps the running sum in float64

torch.cumsum(x, dim) on a CPU, float64, float16, and bfloat16

er.cumulative_sum(x, dim)

torch.cumsum(x, dim) on CUDA

er.cumulative_sum(x, dim) with standard="any_order": a parallel scan

base.scatter_add(dim, index, src)

er.scatter_add(base, index, src, axis=dim)

base.index_add(dim, rows, src, alpha=a)

er.scatter_add(base, index, src, axis=dim, alpha=a), with index the row index written out along the axis (rows[:, None].expand_as(src) for dim=0); in float16 and bfloat16 with compute= the dtype

an embedding's backward

er.scatter_add of the gradient rows into a zero table, as index_add

base.index_put(indices, values, accumulate=True), base.put_(index, source, accumulate=True)

er.scatter_add with the positions written out as its index, and standard="any_order": those kernels add in an order of their own

any of these scatters on CUDA

the same with standard="any_order": the adds arrive in no fixed order

their gradients

er.sum.backward, er.mean.backward, er.cumulative_sum.backward with the forward's compute, and er.scatter_add.backward

Integer and bool inputs to sum and cumsum give int64, as in PyTorch. torch.sum(x, dtype=d) converts x first. When d is of the same kind as x (both floating point, for example), the conversion is er.multiply(x, 1, dtype=d). When it is of another kind, such as an integer x summed in float32, the conversion is er.asarray.

The compute format matters for a running sum, because each element carries the roundings of all the elements before it. Here are the cumulative probabilities that top-p sampling takes, over a vocabulary of 50,257 tokens:

Code
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The next-token probabilities of 8 sequences, sorted from the largest
logits = torch.randn(8, 50257, generator=g) * 4
p = torch.softmax(logits, -1).sort(-1, descending=True).values

# PyTorch's CPU kernel keeps the running sum in float64
r = er.cumulative_sum(p, -1)
print("covered:", r.covers(torch.cumsum(p, -1), "float64").all())

# The last element's tolerance for a float32 running sum, and for a float64 one
print("float32 running sum:", r.tolerance().tolist()[0][-1])
print("float64 running sum:", r.tolerance("float64").tolist()[0][-1])
Output
covered: True
float32 running sum: 0.0025721192359924316
float64 running sum: 0.0

Variance and standard deviation#

PyTorch

ExactRef

torch.var(x) and torch.var_mean(x), reduced to one output, float32 and float64, on a CPU

er.var(x): its var and mean outputs

torch.std(x) and torch.std_mean(x), reduced to one output, float32 and float64, on a CPU

er.std(x): its std and mean outputs

torch.var(x, dim), and the variance of torch.var_mean(x, dim), with several outputs, and every float16 and bfloat16 variance, on a CPU

er.statistics.descriptive.dispersion.var_welford() with compute="float64": that kernel is Welford's method with float64 accumulators

torch.std(x, dim) with several outputs, and every float16 and bfloat16 standard deviation, on a CPU

std_welford() with compute="float64"

torch.var and torch.std on CUDA

var_welford() and std_welford(): Welford's method with float32 accumulators for float32 and narrower dtypes

correction=c, unbiased=False

correction=c; unbiased=False is correction=0

their gradients

er.var.backward(x, grad, axis=dim, correction=c, keepdims=k) and er.std.backward, the same way; in float16 and bfloat16 with compute= the dtype

er.var and er.std describe the two-pass method: the mean first, then the squared deviations from it. Welford's method updates a running mean and a running sum of squared deviations instead. Its error grows with the mean over the spread, so its bounds are wider, most of all for data far from 0. Here are the variances of 1,024 tokens' hidden states of width 4,096, whose mean is 8:

Code
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
h = torch.randn(1024, 4096, generator=g) + 8

# One variance per token is several outputs: Welford's method in float64
welford = er.statistics.descriptive.dispersion.var_welford()
print("per token covered:", welford.covers(torch.var(h, -1), h, -1, compute="float64").all())

# The variance of all the values is one output: the two-pass method
print("overall covered:", er.var(h)["var"].covers(torch.var(h)).all())
Output
per token covered: True
overall covered: True

Softmax, log_softmax, and logsumexp#

PyTorch

ExactRef

torch.softmax(x, -1) on a CPU

er.nn.softmax.softmax_algorithm(reciprocal=True)

torch.softmax(x, dim) on a CPU, another dimension

er.softmax(x, dim) with standard="any_order"; for float16 and bfloat16, softmax_algorithm(stored_exp=True) with standard="any_order"

torch.softmax(x, dim) on CUDA

er.softmax(x, dim) with ulps=2 and standard="any_order"

torch.softmax(x, dim) on MPS

softmax_algorithm(reciprocal=True) with ulps=4

torch.log_softmax(x, -1) on a CPU

er.log_softmax(x); for float16 and bfloat16, er.nn.softmax.log_softmax_algorithm(stored_sum=True)

torch.log_softmax(x, dim) on a CPU, another dimension

er.log_softmax(x, dim) with standard="any_order"

torch.log_softmax(x, dim) on CUDA

er.log_softmax(x, dim) with ulps=2 and standard="any_order"

torch.logsumexp(x, dim) on a CPU

er.logsumexp(x, dim) with standard="any_order"; for float16 and bfloat16, also compute= the dtype

torch.logsumexp(x, dim) on CUDA

the same with ulps=2

complex torch.logsumexp(z, dim) on a Linux CPU

er.logsumexp(z, dim)

complex torch.logsumexp(z, dim) on a macOS CPU and on CUDA

er.reduction.arithmetic.logsumexp_algorithm(hypot=True); with ulps=2 on CUDA

their gradients on a CPU

er.softmax.backward(x, grad, dim) and the others, with the forward's arguments

torch.softmax's gradient on CUDA

softmax_algorithm(products=True).backward_covers(...) with ulps=2 and standard="any_order"

er.softmax divides each exponential by the row's sum. PyTorch's CPU kernel for the last dimension multiplies by a rounded reciprocal of the sum instead, which reciprocal=True describes. stored_exp and stored_sum describe 16-bit kernels that round the exponentials, or the sum and its logarithm, to the output's dtype first. The default covers a row added in index order or in 2, 4, 8, or 16 lanes, which includes PyTorch's CPU kernels on ARM and on x86 with AVX2 or AVX-512, and for bfloat16 and float16 the orders of PyTorch's 16-bit kernels (softmax and log_softmax). standard="any_order" is for a sum that a kernel splits its own way, across threads along a long dimension or in a GPU's tree. Softmax algorithms gives the algorithms in full. Here are a language model's next-token probabilities for 8 sequences, over a vocabulary of 50,257 tokens:

Code
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
logits = torch.randn(8, 50257, generator=g) * 4

# torch.softmax over the last dimension on a CPU: a rounded reciprocal of the sum
cpu_softmax = er.nn.softmax.softmax_algorithm(reciprocal=True)
print("softmax covered:", cpu_softmax.covers(torch.softmax(logits, -1), logits).all())
# log_softmax, the first step of cross-entropy
print("log_softmax covered:", er.log_softmax(logits).covers(torch.log_softmax(logits, -1)).all())
Output
softmax covered: True
log_softmax covered: True

Normalizations#

PyTorch

ExactRef

F.layer_norm(x, shape, weight, bias, eps) on a CPU, float32 and float64

er.layer_norm(x, shape, weight, bias, eps)

F.layer_norm on a CPU, float16 and bfloat16

er.nn.normalization.layer_norm_algorithm(folded=True)

F.layer_norm on CUDA

layer_norm_algorithm(welford=True, rsqrt_ulps=2.5)

F.rms_norm(x, shape, weight, eps) on a CPU

er.rms_norm(x, shape, weight, eps)

F.rms_norm on CUDA

er.nn.normalization.rms_norm_algorithm(rsqrt_ulps=2.5)

F.batch_norm(x, running_mean, running_var, weight, bias, training, momentum, eps) on a CPU, contiguous or channels-last

er.batch_norm(...) with the same arguments

F.batch_norm on a CPU, a strided input

er.nn.normalization.batch_norm_algorithm(centered=True)

F.batch_norm in training on a CPU, float16 and bfloat16, and its gradients there

er.batch_norm(...) and er.batch_norm.backward(...) with compute= the dtype

F.batch_norm on CUDA

batch_norm_algorithm(centered=True, welford=True, rsqrt_ulps=2.5)

F.batch_norm on CUDA, evaluation of a channels-last input

er.batch_norm(...)

their gradients on a CPU

er.layer_norm.backward(x, grad, shape, weight, bias, eps), er.rms_norm.backward(x, grad, shape, weight, eps), and er.batch_norm.backward(x, grad, running_mean, running_var, weight, bias, training, eps)

F.layer_norm's gradients on a CPU, float16 and bfloat16

er.layer_norm.backward with compute= the dtype

er.layer_norm, er.rms_norm, and er.batch_norm follow the steps of PyTorch's CPU kernels for contiguous inputs. The algorithms describe the other kernels: folded computes x * r + (-r * mean) before the weight and the bias, welford takes the statistics by Welford's method, centered subtracts the mean first, and rsqrt_ulps takes the reciprocal square root as one library function. NVIDIA documents CUDA's rsqrtf as within 2 steps of the correctly rounded value, which is 2.5 steps of the exact one. Here is a ViT-Base layer norm, over 2 images of 197 tokens of width 768:

Code
import torch.nn.functional as F

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The tokens, and the layer's weight and bias
x = torch.randn(2, 197, 768, generator=g)
w = torch.rand(768, generator=g) + 0.5
b = torch.randn(768, generator=g) / 10
print("float32 covered:", er.layer_norm(x, (768,), w, b).covers(F.layer_norm(x, (768,), w, b)).all())

# The CPU kernel for bfloat16 folds the mean into the shift
xb, wb, bb = x.bfloat16(), w.bfloat16(), b.bfloat16()
folded = er.nn.normalization.layer_norm_algorithm(folded=True)
print("bfloat16 covered:", folded.covers(F.layer_norm(xb, (768,), wb, bb), xb, (768,), wb, bb).all())
Output
float32 covered: True
bfloat16 covered: True

Convolution#

PyTorch

ExactRef

F.conv1d, F.conv2d, and F.conv3d on a CPU, ungrouped

er.convolution(x, w, b, stride=s, padding=p, dilation=d)

padding="valid", and padding="same" with an odd kernel

padding=0, and padding=d * (k - 1) // 2 for a kernel of size k and dilation d

F.conv2d in float16, grouped and depthwise convolutions, and convolutions on CUDA

the same with groups= as given and standard="any_order": those kernels follow neither loop nesting

F.conv_transpose1d, F.conv_transpose2d, and F.conv_transpose3d

er.convolution(..., transposed=True, output_padding=) with standard="any_order"

a depthwise 3 by 3 convolution on a macOS CPU, and Winograd or FFT convolutions on CUDA

not covered: they round transformed values, not the products

padding_mode="reflect", "replicate", or "circular", and padding="same" with an even kernel

pad the input first, with F.pad or by hand, then er.convolution with padding=0

their gradients

er.convolution.backward(x, w, b, grad, ...) with standard="any_order"

er.convolution's tolerance allows the products of each output added one at a time, in either nesting of the loops: over the input channels and then the kernel positions, or the other way round. Each product may be rounded or fused into its addition. A kernel that blocks or reorders the sum needs standard="any_order". Here is a ViT patch embedding, which cuts a 224 by 224 image into 196 patches of 16 by 16 pixels:

Code
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# One image, and the patch embedding's weight and bias for width 768
image = torch.rand(1, 3, 224, 224, generator=g)
pw = torch.randn(768, 3, 16, 16, generator=g) / 50
pb = torch.randn(768, generator=g) / 50

c = er.convolution(image, pw, pb, stride=16)
print("shape:", c.rounded.shape)
print("float32 covered:", c.covers(F.conv2d(image, pw, pb, stride=16)).all())

# The same layer in float16, whose CPU kernel adds in an order of its own
ih, wh, bh = image.half(), pw.half(), pb.half()
c16 = er.convolution(ih, wh, bh, stride=16)
print("float16 covered:", c16.covers(F.conv2d(ih, wh, bh, stride=16), standard="any_order").all())
Output
shape: (1, 768, 14, 14)
float32 covered: True
float16 covered: True

Attention#

PyTorch

ExactRef

F.scaled_dot_product_attention(q, k, v, ...)

er.scaled_dot_product_attention(q, k, v, ...)

The arguments and shapes are PyTorch's. ExactRef returns two outputs: output, and the per-row logsumexp that fused kernels return. Dropout is random and has no reference, so dropout_p must be 0. By default the tolerance lets exp and log be 1 step off each. CUDA's are within 2: to check a CUDA kernel with er.scaled_dot_product_attention itself, pass ulps=2. The attention algorithms take their own exp_ulps.

Where PyTorch rounds differently#

The math path computes the probabilities P, normalized and rounded, before the product with V. No tolerance allows for that rounding.

Fused kernels such as FlashAttention round the weights to bfloat16, rescale per block, or normalize by a reciprocal: use an attention algorithm.

The CUDA backends, FlashAttention-2, memory-efficient, and cuDNN, run on tensor cores: Algorithms gives each one's methods on NVIDIA's DGX Spark (GB10).

The CPU flash kernel, which F.scaled_dot_product_attention runs on the CPU, runs its softmax over blocks of 512 keys, normalizes by a rounded reciprocal, and adds its gradients block by block: AttentionAlgorithm(online_softmax=True, block_size=512, reciprocal=True, backward_blocks=...). For bfloat16 and float16 inputs, also set weights to the input format and exp_ulps for its approximate exp. Algorithms gives the block sizes and the exp_ulps for each machine.

To check its backward, you have two choices. Pass the kernel's own out and logsumexp, from torch.ops.aten._scaled_dot_product_flash_attention_for_cpu. Or chain ExactRef's forward results, with the tolerance option ulps, how many units in the last place exp may be off, set to the exp_ulps value. Backward shows a float32 check.

Pre-scaled inputs. The math path scales Q and K by the square root of the scale first. Pass the pre-scaled values with scale=1. For the backward, the reference is then the gradient for the pre-scaled inputs; the math path's final product by the square root of the scale is not covered.

Parameters with no ExactRef argument#

Some attention kernels and lower-level APIs, such as PyTorch's torch.ops.aten._flash_attention_forward, take parameters that er.scaled_dot_product_attention does not have. Each can be expressed with the inputs ExactRef already takes:

In the kernel or API

Express it as

bottom-right causal alignment (causal_lower_right)

a bool mask

sliding windows (window_size_left, window_size_right)

ALiBi biases (alibi_slopes)

a float mask

variable lengths (cum_seq_q, cum_seq_k, seqused_k)

one call per sequence

paged layouts (block_table)

Matrix exponential#

PyTorch

ExactRef

torch.linalg.matrix_exp(A)

er.matrix_exp(A)

its gradient

er.matrix_exp.backward(A, grad), which is er.matrix_exp_frechet(A^H, grad)

Guarantees and limits says where PyTorch's and SciPy's results fall outside the tolerance.

Fourier transforms#

PyTorch

ExactRef

torch.fft.fft(x, n, dim, norm)

er.fft.fft(x, n, axis=dim, norm=norm)

torch.fft.ifft, rfft, irfft, hfft, and ihfft, with the same arguments

er.fft.ifft, rfft, irfft, hfft, and ihfft, with axis=dim

torch.fft.fft2(x, s, dim=(-2, -1), norm)

er.fft.fft(x, n=s, axis=dim, norm=norm)

torch.fft.fftn(x, s, dim, norm)

er.fft.fft(x, n=s, axis=dim, norm=norm); for dim=None, axis is the last len(s) axes, or every axis when s is None too

the 2 and n forms of ifft, rfft, irfft, hfft, and ihfft

the same transform, with axis a tuple

their gradients

er.fft.fft.backward(x, grad, n, axis, norm), and the same for the other five

torch.fft.fftfreq, rfftfreq, fftshift, and ifftshift

none: ExactRef has no counterpart

The rfft, irfft, hfft, and ihfft forms over several dimensions take the half spectrum on the last dimension of dim, as ExactRef's take it on the last axis of axis. Autograd's gradients follow the same convention as the backwards, dL/dRe + i dL/dIm. The spectra of 16 images of 256 by 256 pixels, as an FFT-based convolution layer computes them:

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# 16 images of 256 by 256 pixels
images = torch.rand(16, 256, 256, generator=g)

# torch.fft.rfft2 is rfft over the last two axes
r = er.fft.rfft(images, axis=(-2, -1))
print("shape:", r.rounded.shape)
print("covered:", r.covers(torch.fft.rfft2(images)).all())
Output
shape: (16, 256, 129)
covered: True

PyTorch's CPU FFT runs pocketfft in builds without MKL, such as its ARM builds, and MKL in its x86-64 builds. MKL's plans are not public. FFT algorithms gives pocketfft's plans, for a tighter check.

Flush to zero#

With torch.set_flush_denormal(True), PyTorch's CPU kernels flush subnormal values to zero. Check them with flush_to_zero=True; Flushing subnormals to zero gives ExactRef's rule. PyTorch flushes wherever a value moves into float32 or float64:

In PyTorch, with flushing on

Becomes

a float32 or bfloat16 subnormal value, read into a computation or converted to float32 or float64

zero, sign kept

a float64 value below 2**-126, converted to float32 or bfloat16

zero, sign kept

float32 or bfloat16 data combined with float64 data in add, sub, mul, or div, also as a tensor of shape ()

the narrower operand's subnormal values read as zero

float32 data summed by sum, mean, or cumsum with dtype=torch.float64

its subnormal values read as zero

float16 and 8-bit values, and a Python scalar

not flushed

a complex value

each part flushed as its real format

An x86 CPU and an ARM CPU differ on a value just below the smallest normal number that rounds up to it: ARM gives zero, and x86 keeps the rounded value. PyTorch's macOS build flushes on the calling thread only, so the part of a large tensor that its other threads compute is not flushed. The bounds with flush_to_zero=True allow all of these outputs.