Find the step that loses accuracy#
The problem#
A computation with several steps loses accuracy somewhere. A transformer's attention block, for example, computes the query, key, and value projections, then attention, then an output projection, then adds the residual. Its output differs from a reference implementation's, or you want to be sure each step does what it should. Comparing the final output says at best that something is wrong, not where.
Why the usual approach falls short#
The error of the final output mixes the roundings of every step, so a check of the output alone cannot say which step is responsible. It may not even see the problem: later steps can average an error out. Checking each step against a float64 version of that step has the usual problems of a hand-picked tolerance, and it ignores that each step works on the previous step's stored, rounded output.
The solution#
Run the same steps in ExactRef as a chain: pass each step's result, in place
of an array, as the next step's input. The next result's bounds then cover
every value the earlier result allows, since the implementation may have
stored any of them (Chains and any_of). Check every
intermediate the implementation stores with covers(), which says per element
whether a correct implementation can produce it. Then check the first step
that fails on its own inputs:
Each step is checked twice: against the chain, whose bounds cover every value the earlier steps allow, and alone, on the input the implementation stored. The step that fails alone is the one that loses accuracy.
The implementation here is a float32 attention block for 128 tokens of hidden size 1024, with 16 heads of 64. It has a flaw in its second step: it runs attention through a fused kernel that supports only bfloat16, so it converts the queries, keys, and values to bfloat16 and the output back:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# 128 tokens of hidden size 1024, and the block's four weights
x = torch.randn(128, 1024, generator=g)
w_q, w_k, w_v, w_o = (torch.randn(1024, 1024, generator=g) / 32 for _ in range(4))
def heads(t):
"""(tokens, 1024) as (batch, heads, tokens, head dimension): 16 heads of 64."""
return t.reshape(1, 128, 16, 64).transpose(1, 2)
def merge(t):
"""The heads side by side again: (tokens, 1024)."""
return t.transpose(1, 2).reshape(128, 1024)
# Step 1: the query, key, and value projections
q, k, v = (heads(x @ w.T) for w in (w_q, w_k, w_v))
# Step 2: causal attention, through a kernel that takes and returns bfloat16
attn = torch.nn.functional.scaled_dot_product_attention(
q.bfloat16(), k.bfloat16(), v.bfloat16(), is_causal=True).float()
# Step 3: the output projection
o = merge(attn) @ w_o.T
# Step 4: the residual connection
y = x + o
The ExactRef chain mirrors the steps. Results have reshape and transpose,
so the heads are split and merged the same way. Attention has two named
outputs, output and logsumexp, and ["output"] gives the result for the
first:
# Step 1: each projection's result, split into heads
step1 = [er.matmul(x, w.T).reshape((1, 128, 16, 64)).transpose(1, 2) for w in (w_q, w_k, w_v)]
# Steps 2 to 4 each take the previous step's result, so their bounds cover
# every value the previous step's bounds allow the implementation to store
step2 = er.scaled_dot_product_attention(*step1, is_causal=True)["output"]
step3 = er.matmul(step2.transpose(1, 2).reshape((128, 1024)), w_o.T)
step4 = er.add(x, step3)
# The end-to-end check
print("step 4 covered:", step4.covers(y).all())
# Each intermediate the implementation stores, in order
print("step 1 covered:", all(r.covers(t).all() for r, t in zip(step1, (q, k, v))))
print("step 2 covered:", step2.covers(attn).all())
print("step 3 covered:", step3.covers(o).all())
step 4 covered: True
step 1 covered: True
step 2 covered: False
step 3 covered: True
The final output passes. After four steps, the chain's bounds, which cover every value the earlier steps allow, are wide enough to hide the attention step's error, and the output projection averages it out. The intermediates show it: step 2 is the first that fails.
To see whether step 2 is at fault, or only passes on an error from earlier, check each step alone, on the input the implementation actually stored:
# Step 2 alone, on the q, k, and v the implementation stored
alone = er.scaled_dot_product_attention(q, k, v, is_causal=True)["output"]
print("step 2 alone:", alone.covers(attn).all())
# Steps 3 and 4 alone, each on its stored input
print("step 3 alone:", er.matmul(merge(attn), w_o.T).covers(o).all())
print("step 4 alone:", er.add(x, o).covers(y).all())
step 2 alone: False
step 3 alone: True
step 4 alone: True
Step 2 fails even on its own inputs, and steps 3 and 4 are correct on theirs, so step 2 loses the accuracy: its conversions to bfloat16.
A step that rounds in an extra place on purpose, such as a deliberate
bfloat16 store, is not a bug. Describe that rounding as a step of its own, so
the chain's bounds allow for it. For example,
er.multiply(..., 1, dtype="bfloat16") multiplies by 1 and rounds the result
to bfloat16. A fused attention kernel's own extra roundings are described
with an attention algorithm.