Replace hand-picked test tolerances#

The problem#

A test compares an implementation with a reference computed in float64, using torch.testing.assert_close or allclose with an rtol and atol someone picked once, or with their defaults. The test is flaky: it fails on a correct implementation when large values cancel, and someone loosens atol until it passes. After that it also passes real bugs whose effect is smaller than the loosened tolerance. On small values, such as gradients, even the default atol can be larger than the values themselves.

Why the usual approach falls short#

A fixed relative and absolute tolerance cannot fit every input. How far a correct float32 result can land from the exact answer depends on the inputs: on cancellation, on the number of terms, and on their size. A float64 reference is not exact either, and it says nothing about which float32 results are correct.

A sum of many large products assert_close ExactRef's tolerance correct output assert_close fails it; ExactRef passes it A tiny gradient element assert_close ExactRef's tolerance buggy output assert_close passes it; ExactRef fails it

assert_close's band (outlined) depends only on the size of the reference. ExactRef's tolerance (filled), how far a correct implementation's output can be from the exact answer rounded once, comes from the inputs, so it can be wider or far narrower.

The solution#

Ask ExactRef, for the inputs you have, which outputs a correct implementation can produce. covers() answers per element: by default for an implementation that adds the normal way, in index order or a few SIMD lanes side by side, and with standard="any_order" for any order of additions at all. The two examples below are the two halves of the problem: a correct kernel that assert_close rejects, and a buggy one it accepts.

A correct kernel that assert_close rejects#

A projection from hidden size 4096 to 1024, for 128 tokens whose hidden states have grown large, as they do deep in a model. The kernel under test gives each output element one thread, which adds its 4096 products one at a time. It is correct: it is the ordinary loop, in float32.

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The hidden states, with standard deviation 4, and the layer's weight
x = torch.randn(128, 4096, generator=g) * 4
w = torch.randn(4096, 1024, generator=g) / 64

# The kernel, emulated with elementwise operations so that it adds in a fixed
# order. Every output element starts at 0.
out = torch.zeros(128, 1024)
for k in range(4096):
    # Add x[i, k] * w[k, j] to element (i, j): the product and the sum each rounded to float32
    out = out + x[:, k:k + 1] * w[k:k + 1, :]

# The usual test: compare with the product computed in float64
try:
    torch.testing.assert_close(out, (x.double() @ w.double()).float())
    print("assert_close: passed")
except AssertionError:
    print("assert_close: failed")

# Could a correct float32 implementation produce every element?
print("covered:", er.matmul(x, w).covers(out).all())
Output
assert_close: failed
covered: True

assert_close fails it on about 0.5% of the elements: those whose running sum grows largest along the way. Each of the 4,096 additions rounds to float32, with an error in proportion to the running sum's size, so these elements collect the most error, more than assert_close allows for their final size. ExactRef's tolerance comes from the products themselves, so it allows for those errors.

A bug that assert_close passes#

A weight gradient, grad.T @ x, for a layer of width 1024 over a batch of 2000 tokens. Gradients are small: here the gradient of the layer's output has a standard deviation of 3e-7, as for a loss averaged over many tokens. The kernel under test works through the tokens in tiles of 64 and has a common bug: it skips the last tile when it is only partly full. With 2000 tokens, that drops the last 16.

Code
# 2000 tokens: the layer's inputs, and the gradient of its outputs
x = torch.randn(2000, 1024, generator=g)
grad = torch.randn(2000, 1024, generator=g) * 3e-7

# The buggy kernel: 31 full tiles of 64 tokens, and the last 16 tokens skipped
grad_w = grad[:1984].T @ x[:1984]

# The usual test, against the full product computed in float64
try:
    torch.testing.assert_close(grad_w, (grad.double().T @ x.double()).float())
    print("assert_close: passed")
except AssertionError:
    print("assert_close: failed")

# The reference for the full weight gradient
r = er.matmul(grad.T, x)
# Could a correct implementation produce every element?
print("covered:", r.covers(grad_w).all())

# Elements no correct implementation produces, whatever its order of additions
impossible = r.covers(grad_w, standard="any_order").scalars().count(False)
print(f"impossible: {100 * impossible / r.rounded.size:.0f}% of the elements")
Output
assert_close: passed
covered: False
impossible: 97% of the elements

The gradient's elements are about 1e-5, the size of assert_close's default atol for float32, so the 16 missing tokens hide inside it. ExactRef's tolerance comes from these inputs and is far smaller than the missing tokens' share, so it finds the bug in almost every element.

In your test suite#

Replace the comparison with one line:

Code
# The reference for x @ w
r = er.matmul(x, w)
# Every element must be one a correct implementation can produce
assert r.covers(out).all()

Get started has a short helper that lists the failing elements when the check fails. Find a bug in a matmul backend follows a backend's test from a failing check to the cause: which outputs no correct implementation produces, and which rounding the kernel really does.