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 loop of |
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:
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:
# 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 |
|
one call per group |
BLAS's |
the operand already transposed or conjugate-transposed; an earlier result has |
BLAS's |
a full product, comparing only the triangle the implementation computes |
Elementwise arithmetic and conversions#
PyTorch |
ExactRef |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
not covered: another operation |
|
|
|
|
its gradient there |
|
|
|
|
|
|
|
|
|
their gradients |
|
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 |
|
bfloat16 on ARM (macOS, Linux ARM) |
|
bfloat16 on x86 |
|
complex32 |
|
float16 |
|
For example, a residual branch scaled by 0.3 and added in float16, over 128 tokens of hidden size 1024:
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())
alpha: 0.300048828125
covered: True
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 |
|---|---|
|
|
the same on MPS |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
as |
|
|
complex |
|
complex |
|
complex |
not covered: MPS uses a formula that subtracts |
complex |
not covered: CUDA computes it as a complex power |
their gradients, float32, float64, and complex |
|
their gradients, float16 and bfloat16 |
the same with |
|
a chain on the forward's output |
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:
# 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())
covered: True
Elementary functions#
PyTorch |
ExactRef |
|---|---|
|
|
the same on CUDA |
the same with |
the same on MPS, but |
the same with |
|
|
their gradients, float32 and float64 |
|
their gradients, float16 and bfloat16 |
the same with |
complex |
|
complex |
|
complex |
|
complex |
|
complex |
|
complex |
|
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:
# 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()))
covered: True
largest tolerance: 5.960464477539063e-08
with ulps=2: 1.1920928955078125e-07
Sums and means#
PyTorch |
ExactRef |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
an embedding's backward |
|
|
|
any of these scatters on CUDA |
the same with |
their gradients |
|
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:
# 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])
covered: True
float32 running sum: 0.0025721192359924316
float64 running sum: 0.0
Variance and standard deviation#
PyTorch |
ExactRef |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
their gradients |
|
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:
# 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())
per token covered: True
overall covered: True
Softmax, log_softmax, and logsumexp#
PyTorch |
ExactRef |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
the same with |
complex |
|
complex |
|
their gradients on a CPU |
|
|
|
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:
# 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())
softmax covered: True
log_softmax covered: True
Normalizations#
PyTorch |
ExactRef |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
their gradients on a CPU |
|
|
|
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:
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())
float32 covered: True
bfloat16 covered: True
Convolution#
PyTorch |
ExactRef |
|---|---|
|
|
|
|
|
the same with |
|
|
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 |
|
pad the input first, with |
their gradients |
|
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:
# 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())
shape: (1, 768, 14, 14)
float32 covered: True
float16 covered: True
Attention#
PyTorch |
ExactRef |
|---|---|
|
|
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 ( |
a bool mask |
sliding windows ( |
|
ALiBi biases ( |
a float mask |
variable lengths ( |
one call per sequence |
paged layouts ( |
Matrix exponential#
PyTorch |
ExactRef |
|---|---|
|
|
its gradient |
|
Guarantees and limits says where PyTorch's and SciPy's results fall outside the tolerance.
Fourier transforms#
PyTorch |
ExactRef |
|---|---|
|
|
|
|
|
|
|
|
the |
the same transform, with |
their gradients |
|
|
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:
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())
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 |
the narrower operand's subnormal values read as zero |
float32 data summed by |
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.