Find a bug in a matmul backend#
The problem#
You are bringing up a backend: a new device, a compiler, or a kernel library.
Its matrix products need tests, and the usual test runs the same product on
PyTorch's CPU and compares with torch.testing.assert_close. For bfloat16,
that check accepts any output within about 1.6% of PyTorch's, which is several
bfloat16 steps. A bug smaller than that passes, on every shape you try.
Why the usual approach falls short#
assert_close uses one tolerance per dtype, a guess that has to cover every
input. It cannot know that for your inputs, a correct kernel has only one
possible output for most elements. When a check like this fails, it says
only that the outputs differ, not what the kernel does wrong.
The solution#
This page builds a small backend whose matmul has a real bug, the kind that
ships, and tests it the way a backend team would. assert_close passes it.
ExactRef finds it, shows that no correct implementation produces the output,
and tells you what the kernel does instead. A second bug, which assert_close
does catch, shows what ExactRef adds even then.
A backend with its own matmul#
PyTorch lets a backend register a device of its own. Real backends do it in
C++. PyTorch also has an experimental pure-Python way, used here so the
example runs anywhere: a device named demo that keeps its data in ordinary
CPU tensors.
import torch
from torch.utils.backend_registration import _setup_privateuseone_for_python_backend
# Register PyTorch's spare device slot (PrivateUse1) under the name "demo"
_setup_privateuseone_for_python_backend("demo")
class DemoTensor(torch.Tensor):
"""A tensor on the demo device, whose data lives in a CPU tensor."""
@staticmethod
def __new__(cls, cpu_data):
# An empty tensor that PyTorch places on the demo device
tensor = torch._C._acc.create_empty_tensor(cpu_data.shape, cpu_data.dtype)
tensor.__class__ = cls
return tensor
def __init__(self, cpu_data):
self.cpu_data = cpu_data
# The device's implementations of PyTorch's operators
demo = torch.library.Library("aten", "IMPL")
# New tensors on the device: a new CPU tensor inside
def empty(size, dtype=None, layout=None, device=None, pin_memory=None, memory_format=None):
return DemoTensor(torch.empty(size, dtype=dtype))
def empty_strided(size, stride, dtype=None, layout=None, device=None, pin_memory=None):
return DemoTensor(torch.empty_strided(size, stride, dtype=dtype))
# Copies between the CPU and the device
def copy_from(src, dst, non_blocking=False):
source = src.cpu_data if isinstance(src, DemoTensor) else src
target = dst.cpu_data if isinstance(dst, DemoTensor) else dst
target.copy_(source)
return dst
demo.impl("empty.memory_format", empty, "PrivateUse1")
demo.impl("empty_strided", empty_strided, "PrivateUse1")
demo.impl("_copy_from", copy_from, "PrivateUse1")
The device's matmul works like a typical kernel for bfloat16 inputs. It adds the products in blocks of 64, keeps a running sum in an accumulator, then converts the result to bfloat16. Two settings choose the accumulator's format and the conversion, so one kernel can be correct or carry either of two bugs:
# The correct settings: a float32 accumulator, and a conversion that rounds to nearest
settings = {"accumulator": torch.float32, "conversion": "round"}
def truncate_to_bfloat16(x):
"""float32 to bfloat16 by keeping the top 16 bits of each value."""
# Clear the low 16 bits of each float32; what is left is a bfloat16 value
return (x.view(torch.int32) & -65536).view(torch.float32).to(torch.bfloat16)
def mm(a, b):
"""The demo device's matrix product."""
a32, b32 = a.cpu_data.float(), b.cpu_data.float()
# Add the products in blocks of 64, each block's sum added to the accumulator
acc = torch.zeros(a32.shape[0], b32.shape[1], dtype=settings["accumulator"])
for k in range(0, a32.shape[1], 64):
acc += (a32[:, k:k + 64] @ b32[k:k + 64]).to(settings["accumulator"])
# Convert the result to bfloat16
if settings["conversion"] == "round":
return DemoTensor(acc.to(torch.bfloat16))
return DemoTensor(truncate_to_bfloat16(acc.float()))
demo.impl("mm", mm, "PrivateUse1")
def on_demo(a, b):
"""a @ b computed on the demo device, copied back to the CPU."""
return (a.to("demo") @ b.to("demo")).cpu()
The bug: truncating to bfloat16#
A bfloat16 is the top half of a float32. Converting a float32 correctly rounds it to the nearest bfloat16. The bug keeps the top half and throws the rest away, which rounds every value toward zero:
A bfloat16 keeps a float32's sign, its 8 exponent bits, and its top 7 fraction bits.
The product to test is one attention head's scores, q @ k.T, for 2048
positions with head dimension 128. The test runs it on the device with the
truncating conversion and compares with PyTorch's CPU result:
import math
import random
# Seeded, so every run uses the same values
rng = random.Random(67)
def randn(*shape, scale=1.0):
"""A bfloat16 tensor of normal values with standard deviation scale."""
values = [rng.gauss(0, scale) for _ in range(math.prod(shape))]
return torch.tensor(values, dtype=torch.bfloat16).reshape(shape)
# Queries and keys for one attention head: 2048 positions, head dimension 128
q, k = randn(2048, 128), randn(2048, 128)
# The scores on the demo device, with the buggy conversion
settings["conversion"] = "truncate"
scores = on_demo(q, k.T)
print("device:", q.to("demo").device)
# The usual test: compare with PyTorch's CPU result
try:
torch.testing.assert_close(scores, q @ k.T)
print("assert_close: passed")
except AssertionError:
print("assert_close: failed")
device: demo:0
assert_close: passed
Truncation is never off by more than one bfloat16 step, so it stays inside
assert_close's tolerance everywhere.
What ExactRef sees#
ExactRef works out, element by element, which outputs a correct
implementation can produce. covers() checks an output against them: 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:
import exactref as er
# The reference for q @ k.T: the exact product, rounded once to bfloat16
r = er.matmul(q, k.T)
# Could a correct implementation produce these scores?
print("covered:", r.covers(scores).all())
# Elements no correct implementation produces, whatever its order of additions
impossible = r.covers(scores, standard="any_order").scalars().count(False)
print(f"impossible: {100 * impossible / r.rounded.size:.0f}% of the elements")
covered: False
impossible: 46% of the elements
Adding 128 products in float32 moves an element by far less than one bfloat16 step, so for most elements only one output is correct: the exact value rounded to nearest. The tolerance, how far a correct output can be from that value, is a narrow band around it. Where the exact value lies in the half of its bfloat16 step farther from zero, truncation lands one step closer to zero, outside the band:
One element: the exact value, the correct output it rounds to, and where truncation sends it instead.
Name the bug#
The same reference with another rounding tells you what the kernel does. Rounded toward zero, the exact answer covers every element of the output:
# The exact product, rounded toward zero instead of to nearest
toward_zero = er.matmul(q, k.T, rounding=er.Rounding.TOWARD_ZERO)
print("covered rounding toward zero:", toward_zero.covers(scores).all())
# The fix: round to nearest, and run the test again
settings["conversion"] = "round"
print("covered after the fix:", r.covers(on_demo(q, k.T)).all())
covered rounding toward zero: True
covered after the fix: True
So the kernel truncates, and with the conversion fixed it passes.
The same check on PyTorch and NumPy#
The check needs nothing from the backend but its output, so it works on any implementation. PyTorch's CPU matmul and NumPy's float32 matmul pass:
# PyTorch's own CPU result for the same product
print("PyTorch covered:", r.covers(q @ k.T).all())
# NumPy has no bfloat16: the same values as float32, multiplied in float32
qn, kn = q.float().numpy(), k.float().numpy()
print("NumPy covered:", er.matmul(qn, kn.T).covers(qn @ kn.T).all())
PyTorch covered: True
NumPy covered: True
A second bug: a bfloat16 accumulator#
A kernel that keeps its running sum in the input's format loses precision at every addition. Here it computes a model's projection: 128 tokens of hidden size 4096, times a 4096 by 512 slice of a weight matrix.
# A batch of 128 tokens, and a weight slice scaled like a trained layer's
x, w = randn(128, 4096), randn(4096, 512, scale=1 / 64)
# The projection on the device, with the accumulator in bfloat16
settings["accumulator"] = torch.bfloat16
out = on_demo(x, w)
try:
torch.testing.assert_close(out, x @ w)
print("assert_close: passed")
except AssertionError:
print("assert_close: failed")
# Elements no implementation that accumulates in float32, ExactRef's default for
# bfloat16 inputs, produces in any order
r = er.matmul(x, w)
impossible = r.covers(out, standard="any_order").scalars().count(False)
print(f"impossible with a float32 accumulator: {100 * impossible / r.rounded.size:.0f}%")
# Back to the correct settings
settings["accumulator"] = torch.float32
assert_close: failed
impossible with a float32 accumulator: 15%
This time assert_close catches the bug too, but it says only that the
outputs differ, by more than some tolerance. ExactRef says more: 15% of the
elements are values that no kernel accumulating in float32 produces, whatever
order it adds in. Neither the order of additions nor the conversion explains
them, so look at the accumulator.
In your test suite#
Test each product at your model's shapes and dtypes with covers(), as
above, instead of assert_close. When a check fails, count the impossible
elements, then try the reference with another rounding: one that covers
the output names the conversion the kernel does.
Get started has a short helper that
lists the failing elements.