Accept nondeterministic reductions#

The problem#

A GPU kernel that adds with atomic operations gives a slightly different answer each run: a split-K matrix product that adds its partial products into the output with atomics, for example, or index_add_ and scatter_add_ on CUDA. The order of additions changes with thread scheduling, and with it the rounding. A test that compares against a fixed expected value fails at random, and the usual fix is to loosen it until it never fails.

Why the usual approach falls short#

Every one of those answers may be correct, or some may come from a real race or a lost update. A loosened tolerance cannot tell them apart, and a fixed expected value is just one of the correct answers.

The solution#

Check each run on its own with covers(), which says per element whether a correct implementation can produce an output, and pass standard="any_order": the any-order tolerance, how far a correct output can be from the exact answer rounded once, covers every order of additions that does not overflow.

The kernel here is a projection in float32 from hidden size 4096 to 1024, for 128 tokens. It cuts the inner dimension into 16 pieces of 256. Each piece's thread block computes its partial product and adds it into the output with atomic additions, so the partial products arrive in the order their blocks finish:

partial products, in the order they arrive run 1 P2 P4 P1 P3 output run 2 P3 P1 P4 P2 output each addition rounds, so another order gives another output

Two runs of the same kernel. The partial products reach the output in a different order each run, so the sums round differently.

On the CPU, a random order per run stands in for the scheduling:

Code
import random
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, 4096, generator=g)
w = torch.randn(4096, 1024, generator=g) / 64

# Each piece's partial product: 16 pieces of 256 along the inner dimension
partials = [x[:, k:k + 256] @ w[k:k + 256] for k in range(0, 4096, 256)]
# The reference for x @ w
r = er.matmul(x, w)

# Five runs, each adding the partial products in its own order, drawn from one
# seeded generator
orders = random.Random(67)
outputs = []
for run in range(5):
    # This run's order: the 16 pieces, shuffled
    order = orders.sample(range(16), 16)
    # The atomic additions: each partial product added into the output in turn
    out = torch.zeros(128, 1024)
    for i in order:
        out += partials[i]
    outputs.append(out)
    # Could a correct implementation that adds in any order produce this output?
    print(f"run {run} covered:", r.covers(out, standard="any_order").all())

# How many different outputs the five runs gave, compared bit for bit
print("different outputs:", len({out.numpy().tobytes() for out in outputs}))
Output
run 0 covered: True
run 1 covered: True
run 2 covered: True
run 3 covered: True
run 4 covered: True
different outputs: 5

All five outputs are correct, and no two are the same. The any-order tolerance allows for every order: here its largest value is about 0.011. The normal tolerance, which describes the orders ordinary sequential and SIMD code uses, is at most about 0.00069:

Code
# The largest tolerance of any element: for the default, standard="normal",
# and for standard="any_order"
normal = max(r.tolerance().scalars())
any_order = max(r.tolerance(standard="any_order").scalars())
# Both to 2 significant digits
print(f"largest normal tolerance: {normal:.2g}")
print(f"largest any-order tolerance: {any_order:.2g}")
Output
largest normal tolerance: 0.00069
largest any-order tolerance: 0.011

These five runs happen to stay within the normal tolerance too, but an arbitrary order can be worse than the normal orders and still correct, so judge a nondeterministic kernel by the any-order tolerance. A lost update, an addition that two blocks race on so that one partial product never reaches the output, is far outside it:

Code
# The last run again, with a race: its final addition is overwritten, so the
# last piece's partial product never arrives
lost = torch.zeros(128, 1024)
for i in order[:-1]:
    lost += partials[i]

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

The check needs no expected output: one run is enough, and a missing piece moves almost every element out of its range.

On a GPU, run your kernel several times and check every run the same way:

Code
# The kernel under test on a GPU, run five times on the same inputs
for run in range(5):
    out = my_kernel(x.cuda(), w.cuda()).cpu()
    print(f"run {run} covered:", r.covers(out, standard="any_order").all())

This holds for a kernel whose products and additions happen in float32. A kernel that multiplies on tensor cores, as Triton's tl.dot does for float32 inputs by default (in TF32), needs the tensor-core algorithms, which model each tensor-core step, instead: Test a custom kernel shows how.