Get started#

This page takes you from installing ExactRef to a test that checks an implementation at a model's real sizes, and says what went wrong when it fails.

Install#

pip install exactref

ExactRef needs CPython 3.10 or newer with the GIL (free-threaded builds are not supported) and nothing else: its arithmetic is its own C extension. pip installs a prebuilt wheel on Linux (x86_64 and aarch64, glibc 2.17 or newer), macOS on Apple silicon (14 or newer), and Windows (x86_64); elsewhere it builds the extension from source, which needs a C compiler. NumPy and PyTorch are optional: ExactRef reads their arrays and tensors when you pass them, and needs neither.

Your first reference#

A linear layer in float32: 128 tokens of hidden size 1024 through a 1024 by 1024 weight. ExactRef's reference for its product, the exact answer rounded once to float32:

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The layer's input, and its weight scaled as in a trained model
x = torch.randn(128, 1024, generator=g)
w = torch.randn(1024, 1024, generator=g) / 32

# The reference for the layer's product, x @ w.T
r = er.matmul(x, w.T)
# rounded is an ExactRef array, with a dtype and a shape
print("dtype:", r.rounded.dtype.name)
print("shape:", r.rounded.shape)

# The first three elements of row 0: the exact product, rounded once to float32
print("rounded:", r.rounded.tolist()[0][:3])
# How far a correct float32 output can land from each of them
print("tolerance:", r.tolerance().tolist()[0][:3])
Output
dtype: float32
shape: (128, 1024)
rounded: [-1.4767972230911255, 0.2517056167125702, 0.9538595676422119]
tolerance: [5.364418029785156e-05, 1.5676021575927734e-05, 4.4286251068115234e-05]

r.rounded is the exact product of the float32 inputs, rounded once to float32: the best answer float32 can hold. r.tolerance() says, per element, how far a correct float32 implementation can land from it. It differs from element to element because it depends on the inputs: on how many terms are added, how large they are, and how much they cancel.

Every operation works the same way. er.sum adds over the dimensions you name, here each token's 1024 activations, as a mean over the hidden size needs:

Code
# The sum over each token's activations
s = er.sum(x, axis=1)
print("shape:", s.rounded.shape)
# Could a correct implementation produce PyTorch's sums?
print("covered:", s.covers(x.sum(dim=1)).all())
Output
shape: (128,)
covered: True

Bring your data#

Operations accept arrays from anywhere, and er.asarray imports them explicitly:

  • Python values and nested lists. Without a dtype, floats become float64, ints int64, complex numbers complex128, and bools bool. With one, each value is rounded once to that format.

  • NumPy arrays and anything else with the buffer protocol, imported exactly in their own dtype.

  • PyTorch tensors (and JAX arrays) on the CPU, imported exactly through DLPack, bfloat16 and float8 included. A tensor that requires grad is detached first.

Code
import numpy as np

# A PyTorch layer's weight: a bfloat16 parameter that requires grad
layer = torch.nn.Linear(4096, 4096, dtype=torch.bfloat16)
weight = er.asarray(layer.weight)
print("weight:", weight.dtype.name, weight.shape)

# An embedding table held in a NumPy float32 array
table = er.asarray(np.random.default_rng(67).standard_normal((32000, 512), dtype=np.float32))
print("table:", table.dtype.name, table.shape)
Output
weight: bfloat16 (4096, 4096)
table: float32 (32000, 512)

A tensor on a GPU has to be copied to the CPU first: er.asarray(t.cpu()). Passing it directly raises ValueError: ... is not CPU memory; copy the tensor to the CPU first.

To convert while importing, give a dtype, and rounding if you want other than round-to-nearest-even. A kernel that converts its float32 activations to bfloat16 itself, by truncating them, is checked on inputs converted the same way:

Code
# The activations converted the way that kernel does: rounded toward zero
x_kernel = er.asarray(x, "bfloat16", rounding=er.Rounding.TOWARD_ZERO)
# The default conversion, to nearest, as x.to(torch.bfloat16) does
x_nearest = er.asarray(x, "bfloat16")

# How many of the 131,072 activations the two conversions round differently
differ = sum(a != b for a, b in zip(x_kernel.scalars(), x_nearest.scalars()))
print("rounded differently:", differ)
Output
rounded differently: 65581

About half of them: passing x_kernel to er.matmul checks the kernel on the inputs it really multiplies.

Check an implementation#

Run the operation on the same inputs your implementation got, then ask the result whether each output element is one a correct implementation can produce. Here the implementation is a split-K matrix product, as GPU kernels compute a long inner dimension: the inner dimension cut into four pieces, each piece's product computed on its own, then the four added.

Code
def split_k(a, b, pieces=4):
    """a @ b with the inner dimension cut into pieces, whose products are added."""
    size = a.shape[1] // pieces
    return sum(a[:, i * size:(i + 1) * size] @ b[i * size:(i + 1) * size] for i in range(pieces))


# The implementation's output for the layer above
out = split_k(x, w.T)
# Can a correct implementation produce every element?
print("covered:", r.covers(out).all())

# The lowest and highest finite output a correct implementation can produce at (0, 0)
low, high = r.finite_range()
print("range at (0, 0):", low.scalar((0, 0)), high.scalar((0, 0)))
Output
covered: True
range at (0, 0): -1.4768508672714233 -1.4767435789108276

The split-K product adds in another order than a plain loop, so it does not match rounded everywhere, but every element lies in its range. covers() checks each finite element against finite_range(): the lowest and highest finite outputs a correct implementation can produce. Both ends are at most tolerance() away from rounded. An infinity or NaN passes only where a correct implementation can produce one, for example near the top of the format's range, and r.may_be("+inf"), r.may_be("-inf"), and r.may_be("nan") tell you where. Reading complicated tolerances shows these cases.

The output you pass must have the result's dtype and shape. A PyTorch tensor from the implementation already does. A kernel outside PyTorch may hand back raw bytes; read them as an array of the result's dtype and shape:

Code
# The output as raw bytes, as a C or CUDA kernel writes it
raw = out.numpy().tobytes()
# The bytes read as a float32 array of the result's shape
print("covered:", r.covers(er.Array("float32", (128, 1024), raw)).all())
Output
covered: True

An output of another dtype raises TypeError: output must have the result's dtype float32, got float64.

Check exactly when you know the order#

covers() has to accept every implementation that adds in an ordinary order: index order, or a few SIMD lanes side by side, with each product rounded or fused into the sum. Its tolerance is the worst case over all of them, which allows for all of a sum's roundings going the same way. That is hundreds of ulps (units in the last place: the spacing of float32 values at that size) for most elements of this layer, while PyTorch's own product is off by less than a tenth of that. So covers() never rejects such an implementation, and it catches errors far beyond rounding, such as a wrong index or a missing term, but an error of a few dozen ulps can pass it.

When you know the order your implementation adds in, check it exactly instead. r.normal() emulates the simplest order exactly: each product rounded to float32, then added to a running sum in index order, each sum rounded to float32 too. A kernel that adds that way must match it bit for bit:

Code
def loop_kernel(a, b):
    """a @ b, adding each element's products in index order in float32."""
    result = torch.zeros(a.shape[0], b.shape[1])
    for k in range(a.shape[1]):
        # Add a[i, k] * b[k, j] to element (i, j): the product and the sum each rounded to float32
        result = result + a[:, k:k + 1] * b[k:k + 1, :]
    return result


# The kernel's output for the layer above
loop_out = loop_kernel(x, w.T)
# normal() emulates its roundings exactly, so the two match bit for bit
print("matches normal():", r.normal().identical(er.asarray(loop_out)))

# The same output with element (3, 5) moved up by 42 ulps, as a small bug could leave it
bad = loop_out.clone()
for _ in range(42):
    bad[3, 5] = torch.nextafter(bad[3, 5], torch.tensor(float("inf")))
print("bad covered:", r.covers(bad).all())
print("bad matches normal():", r.normal().identical(er.asarray(bad)))

# The tolerance at (3, 5) in ulps: the spacing of float32 values there
ulp = (torch.nextafter(loop_out[3, 5], torch.tensor(float("inf"))) - loop_out[3, 5]).item()
print("tolerance at (3, 5):", round(r.tolerance().scalar((3, 5)) / ulp), "ulps")
Output
matches normal(): True
bad covered: True
bad matches normal(): False
tolerance at (3, 5): 943 ulps
what covers() accepts: about 943 ulps each way at this element rounded 42 ulps higher: covers() passes, the exact check fails the loop's output: equal to normal(), bit for bit

Element (3, 5), drawn to scale: an error of 42 ulps sits deep inside the band covers() accepts, and only the exact check catches it.

For other fixed orders, the matmul algorithms give the exact output with run(): left to right, as a balanced tree, or in blocks of a given size, in an accumulator format you choose, with or without fused multiply-add (Algorithms). When you do not know the order, as with BLAS libraries, multithreaded kernels, and GPUs, use tolerance() and covers(), with standard="any_order" when the order may be other than normal accumulation.

Say how the implementation computes#

By default, tolerance() and covers() assume the most common kind of implementation, one that:

  • keeps its products and partial sums in the usual compute format,

  • adds them by normal accumulation, the order ordinary kernels add in,

  • and keeps subnormals, the tiny values below a format's smallest normal number, which some hardware modes flush to zero.

Each assumption can be changed:

Assumption

Default

Change it with

the compute format

float32 for inputs narrower than float32 (bfloat16, float16, float8), else the input format

compute="bfloat16", or any other floating-point format

the order of additions

index order, or 2 or 4 interleaved running sums as SIMD code keeps them (more for softmax)

standard="any_order": any order, any summation tree, with or without fused multiply-add

subnormals

kept

flush_to_zero=True, as torch.set_flush_denormal(True) does

The compute format matters most. Here is a bfloat16 layer, 128 tokens of hidden size 4096 times a 4096 by 1024 weight, computed two ways: by PyTorch's own @, and by an implementation that keeps its running sums in bfloat16.

Code
# 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()

# The reference for A @ B
r = er.matmul(A, B)
# PyTorch's own @, judged under the default float32 compute format
print("A @ B covered:", r.covers(A @ B).all())

# An implementation that keeps its running sums in bfloat16
acc = torch.zeros(128, 1024, dtype=torch.bfloat16)
for k in range(4096):
    # Add A[i, k] * B[k, j] to every element (i, j), rounding to bfloat16
    acc = acc + A[:, k:k + 1] * B[k:k + 1, :]

print("bfloat16 sums covered:", r.covers(acc).all())

# How many outputs have a tolerance of 0 when the sums are kept in float32
tolerances = r.tolerance().scalars()
print("zero tolerances:", sum(t == 0 for t in tolerances), "of", len(tolerances))
# The largest tolerance if the sums are kept in bfloat16 instead
print("largest bfloat16 tolerance:", max(r.tolerance("bfloat16").scalars()))
Output
A @ B covered: True
bfloat16 sums covered: False
zero tolerances: 112885 of 131072
largest bfloat16 tolerance: 375390211.234375

With float32 sums, 112,885 of the 131,072 outputs have a tolerance of 0: every implementation that adds in float32 the normal way lands exactly on the reference. The bfloat16 sums miss it. Judged with compute="bfloat16" they would pass, but only because the worst case of 4,096 additions in bfloat16 is enormous: the largest tolerance is about 3.8e8, for outputs no larger than about 4. That is why kernels accumulate low-precision products in float32, and why the default assumes they do.

On the operation itself, dtype= sets the output format. rounding= sets the rounding mode of the reference and of the implementation's last step, the conversion to the output format. For the roundings inside the computation, the tolerance assumes round-to-nearest.

tolerance(), finite_range(), may_be(), and covers() all take the same options, so you can look at the numbers behind a verdict.

Put it in a test#

In a test, assert r.covers(out).all() is enough to pass or fail. To see what failed, copy a helper like this one into your tests. It lists the elements no correct implementation produces:

Code
import exactref as er


def check(result, output, **options):
    """Fail, listing the elements of output no correct implementation produces.

    For a result with one real output; options are covers()'s, such as
    compute="bfloat16" or standard="any_order".
    """
    # Per element, whether a correct implementation can produce output
    ok = result.covers(output, **options)
    if ok.all():
        return

    # The shape, then the output, reference, and tolerance as flat row-by-row lists
    shape = result.rounded.shape
    out = er.asarray(output).scalars()
    ref = result.rounded.scalars()
    tol = result.tolerance(**options).scalars()
    # The lowest and highest finite outputs a correct implementation can produce
    low, high = (end.scalars() for end in result.finite_range(**options))
    # The flat positions of the elements that failed
    bad = [i for i, good in enumerate(ok.scalars()) if not good]

    # The report: how many elements failed, then the first five of them
    lines = [f"{len(bad)} of {len(ref)} elements no correct implementation"
             " produces:"]
    for i in bad[:5]:
        # Its index, the output, and the reference with its tolerance and range
        lines.append(f"  {unravel(i, shape)}: got {out[i]}, reference {ref[i]} "
                     f"+/- {tol[i]:.3g}, range [{low[i]}, {high[i]}]")

    raise AssertionError("\n".join(lines))


def unravel(i, shape):
    """The index of flat position i in an array of this shape."""
    index = []
    for n in reversed(shape):
        # k is the index on this axis; i carries on to the axes before it
        i, k = divmod(i, n)
        index.append(k)

    # The indices were found last axis first
    return tuple(reversed(index))

A test then reads like this:

Code
def test_linear_bfloat16():
    # Check PyTorch's bfloat16 product against ExactRef's reference for it
    check(er.matmul(A, B), A @ B)

On the implementation that keeps its sums in bfloat16, the helper reports:

Code
# check() raises AssertionError with its report as the message
try:
    check(r, acc)
except AssertionError as error:
    print(error)
Output
127377 of 131072 elements no correct implementation produces:
  (0, 0): got -1.0546875, reference -0.95703125 +/- 0, range [-0.95703125, -0.95703125]
  (0, 1): got -0.3125, reference -0.25390625 +/- 0, range [-0.25390625, -0.25390625]
  (0, 2): got -1.171875, reference -1.125 +/- 0, range [-1.125, -1.125]
  (0, 3): got -0.1083984375, reference -0.166015625 +/- 0, range [-0.166015625, -0.166015625]
  (0, 4): got -0.8046875, reference -0.8359375 +/- 0.00391, range [-0.8359375, -0.83203125]

pytest and pytest-xdist both work, and so do threads: several threads can call ExactRef at once.

When a check fails#

  1. Look at the failing elements. The helper above lists them with the reference, the tolerance, and the range a correct implementation can reach.

  2. Check with standard="any_order", covers(out, standard="any_order"). If that passes, the implementation is correct but adds in an order that is worse than ordinary kernels can be.

  3. Check what you told ExactRef. Does the implementation compute in bfloat16 or float16 rather than float32? Does it flush subnormals? Does your GPU use TF32 for float32 matrix products? (Round the inputs with er.round_to_tf32 first and pass those; Check low-precision kernels shows how. For products on tensor cores, use the tensor-core algorithms.)

  4. Look for roundings the operation does not require. An implementation that stores an intermediate result, or a fused kernel that rounds its weights to bfloat16, rounds at more steps than the operation's own tolerance allows for. Pass the earlier result in as an input (Chains and any_of), or use the matching algorithm, a named way of computing the operation with its own bounds, so the tolerance allows for those extra roundings too. PyTorch equivalents lists where PyTorch does this.

  5. Try another rounding. If the reference with rounding=er.Rounding.TOWARD_ZERO covers the output, the kernel truncates instead of rounding to nearest, as in Find a bug in a matmul backend.

  6. Compare with r.normal(), what an ordinary implementation that adds in index order computes, emulated exactly.

If you are sure the implementation is right and the reference is wrong, open an issue with the inputs and your exactref version.

If an operation raises ReferenceUnavailableError, ExactRef could not be sure of the exact answer for those inputs, and it says so rather than guess.

Where to go next#