Test a custom kernel#

The problem#

You wrote a kernel: a Triton or CUDA matmul, a Metal shader, a C++ reduction. You need to know that it is correct at every shape your model runs it at, not only that it looks close to PyTorch on one random matrix. Comparing with the framework's own result can hide a shared mistake, and comparing with a tolerance picked by eye fails or passes for the wrong reasons.

Why the usual approach falls short#

The framework's output is one correct answer among many, so a different correct answer looks like a difference. A kernel that splits the sum into pieces, as split-K kernels do, adds in another order than PyTorch and can legitimately differ from it. What you need is the set of answers a correct implementation can give.

The solution#

Run your kernel, copy the output to the CPU, and check it against ExactRef for the same inputs. Here a stand-in written with PyTorch plays the kernel: a split-K matrix product for bfloat16 inputs. It cuts the inner dimension into 4 pieces, computes each piece's product in float32, adds the pieces' partial products in float32, and rounds the sum once to bfloat16:

the inner dimension, cut into pieces piece 1 piece 2 piece 3 piece 4 partial 1 partial 2 partial 3 partial 4 each in float32 add the partial products round once to the output format

A split-K product: the inner dimension cut into pieces, one partial product per piece, then one final reduction and one rounding to the output format.

Test it at the shapes your model runs. Here they are Llama 2 7B's projections when decoding one token (hidden size 4096, MLP width 11008), its attention projections for a prefill of 128 tokens, and a ragged shape whose inner dimension the 4 pieces do not divide evenly:

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)


def split_k_matmul(a, b, pieces=4):
    """The kernel under test: a @ b with the inner dimension cut into pieces."""
    # The length of each piece; the last one may be shorter
    size = -(-a.shape[1] // pieces)
    # Each piece's partial product in float32, added into a float32 sum
    total = torch.zeros(a.shape[0], b.shape[1])
    for start in range(0, a.shape[1], size):
        total += a[:, start:start + size].float() @ b[start:start + size].float()
    # One rounding, to the output format
    return total.to(a.dtype)


# Shapes (tokens, inner dimension, outputs)
shapes = [(1, 4096, 4096), (1, 4096, 11008), (1, 11008, 4096), (128, 4096, 4096), (77, 4099, 1000)]
for m, k, n in shapes:
    # bfloat16 inputs, the weight scaled as in a trained model
    a = torch.randn(m, k, generator=g).bfloat16()
    b = (torch.randn(k, n, generator=g) / k ** 0.5).bfloat16()
    # A kernel that runs on a GPU copies its output back to the CPU
    out = split_k_matmul(a, b).cpu()
    # Could a correct implementation that adds in any order produce out?
    covered = er.matmul(a, b).covers(out, standard="any_order").all()
    print((m, k, n), "covered:", covered)
Output
(1, 4096, 4096) covered: True
(1, 4096, 11008) covered: True
(1, 11008, 4096) covered: True
(128, 4096, 4096) covered: True
(77, 4099, 1000) covered: True

Use standard="any_order" for a kernel that adds in its own order: it accepts every order of additions that does not overflow. When your kernel always adds in the same, known order, such as sequential sums inside blocks of a known size, the matching algorithm, ExactRef's model of that one way of computing with its own bounds, gives a tighter check and can reproduce the kernel's output exactly.

Kernels on tensor cores#

Most GPU matrix kernels multiply float16, bfloat16, and TF32 inputs on tensor cores. A tensor core adds each block of products in one adder that truncates, so a correct tensor-core kernel can fail even the standard="any_order" check. Check such a kernel with the tensor-core algorithms, which take the parameters of one tensor-core step on your GPU (er.MMAStep). On NVIDIA's DGX Spark (GB10), for bfloat16 inputs:

Code
# Your kernel's output on the GPU, for one shape's inputs, copied back to the CPU
out = my_kernel(a.cuda(), b.cuda()).cpu()

# The GB10's tensor-core step for bfloat16 inputs: 16 products per step, 25 bits
# kept below the largest exponent, and nothing assumed about how the sum is split
step = er.MMAStep(16, 25, -133, 1)
# Could a kernel that adds in such steps have produced out?
print("covered:", er.linalg.products.matmul_mma(step).covers(out, a, b).all())

Beyond random inputs#

Test more than random inputs: cancellation, a large inner dimension, values near the top of the format's range, subnormals, and infinities and NaN in the inputs. For inputs narrower than float32, ExactRef assumes by default that the kernel adds in float32, its compute format. If your kernel accumulates in a narrower format, say so with compute= (Check low-precision kernels).