Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Kernel | One function that runs on the GPU, such as a matrix multiply or an attention step (5.b). |
| Accumulator | The variable that holds a running sum inside a kernel. Its precision matters more than the inputs'. |
| Split-K | Splitting a long sum across several workers, then adding their partial sums at the end (11.c). |
| Absolute / relative error | ` |
| Tolerance | How much error a test allows before it fails. |
| Cancellation | Adding large positive and negative numbers that nearly cancel. The result is small but its error is as large as the terms’ rounding. |
| Golden reference | A slow, simple, high-precision implementation (often float64 on the CPU) used only for testing. |
| Method error vs implementation error | What an approximation loses by design (for example quantization) versus what a bug adds. |
1. What is it?#
Every fast kernel is a different way of computing the same mathematical function. Accuracy testing answers one question: is this kernel’s error the error its design allows, or more?
That is harder than “compare with PyTorch and check it is close”, for three reasons:
- The reference is not exact either. A BF16 framework operation has error of its own.
- “Close” has no single definition. A tolerance that is right for a big output is wrong for a small one.
- Some approximations (quantization, approximate top-k, fast exponentials) lose accuracy on purpose. The test must separate the loss you chose from the loss a bug adds.
This lesson covers the numerical side: error models, references, pass rules, test inputs, and how to find which layer of a model went wrong. The engineering of kernel test suites and autotuning belongs to 25.l; the rules for stable reductions (FP32 accumulation, max-subtracted softmax) are in 11.e and 11.k and are not repeated here.
Facts checked on 13 November 2026.
2. Why does it matter?#
Kernel bugs are the numerics bugs that do reach users. The Anthropic postmortem of September 2025 (28.a) includes one: an approximate top-k operation, after a compiler change, sometimes dropped the most likely token. The fix was to switch to exact top-k with FP32 precision. Model ports have similar histories: in March 2024 Unsloth reported several numerical bugs in public implementations of Google’s Gemma, including RoPE positions computed in BF16 (so neighbouring positions near 8,192 became the same number) and layer norms that needed FP32.
None of these crash. They produce slightly worse text, on some inputs, some of the time. The only defence is a test that knows how big the error is allowed to be.
3. Simple analogy#
Checking a new bathroom scale. You do not compare it with your old scale and demand the same number: the old scale is off too. You weigh a certified 10 kg weight on both. If the old one reads 10.1 and the new one 10.15, the new one is about as good. If the new one reads 11, it is broken, even though “11 is close to 10” by a generous enough rule.
And you test it with a light weight and a heavy one, because a scale that is fine at 70 kg can be badly off at 2 kg.
4. Tiny example: two pass rules, four kernels#
The program computes 512 dot products at three lengths with a float64 golden reference and four implementations that all read BF16 inputs and write BF16 outputs:
- baseline: the plain framework operation, FP32 running sum.
- split-K: a fast kernel with eight FP32 partial sums. Correct.
- BF16-part: a subtle bug: the eight partial sums are written to a BF16 workspace before being added.
- BF16-acc: an obvious bug: the running sum itself is kept in BF16.
It applies two common pass rules: PyTorch’s torch.testing.assert_close defaults for BF16
(pass when |actual − expected| ≤ 1e-5 + 1.6e-2 · |expected| for every element), and the rule
FlashAttention’s tests use: the kernel’s largest error against an FP32 reference must be at most
twice the largest error of the plain framework implementation in the same dtype.
// kerneltest.go — test a "kernel" the way kernel libraries do: against a float64
// reference, with two different pass rules, at three reduction lengths.
package main
import (
"fmt"
"math"
"math/rand"
)
// bf16 rounds a float32 to the nearest BF16 value (round to nearest even).
func bf16(x float32) float32 {
b := math.Float32bits(x)
b += 0x7FFF + (b>>16)&1
return math.Float32frombits(b &^ 0xFFFF)
}
// Three implementations of one output element, all reading BF16 inputs.
func baseline(x, w []float32) float32 { // the plain framework op: FP32 accumulate, BF16 store
var s float32
for i := range x {
s += x[i] * w[i]
}
return bf16(s)
}
func splitK(x, w []float32) float32 { // the fast kernel: 8 partial sums, FP32, BF16 store
var p [8]float32
for i := range x {
p[i%8] += x[i] * w[i]
}
var s float32
for _, v := range p {
s += v
}
return bf16(s)
}
func bf16Partials(x, w []float32) float32 { // subtle bug: split-K partials written in BF16
var p [8]float32
for i := range x {
p[i%8] += x[i] * w[i]
}
var s float32
for _, v := range p {
s += bf16(v)
}
return bf16(s)
}
func bf16Acc(x, w []float32) float32 { // the buggy kernel: running sum kept in BF16
var s float32
for i := range x {
s = bf16(s + x[i]*w[i])
}
return s
}
func main() {
rng := rand.New(rand.NewSource(1))
const rows = 512
fmt.Println(" K kernel max|err| allclose(bf16 defaults) within 2x baseline")
for _, k := range []int{256, 4096, 32768} {
x := make([]float32, k)
for i := range x {
x[i] = bf16(float32(rng.NormFloat64()))
}
var ref [rows]float64
var out [4][rows]float32
for r := 0; r < rows; r++ {
w := make([]float32, k)
for i := range w {
w[i] = bf16(float32(rng.NormFloat64()))
}
for i := range x {
ref[r] += float64(x[i]) * float64(w[i])
}
out[0][r], out[1][r], out[2][r], out[3][r] = baseline(x, w), splitK(x, w), bf16Partials(x, w), bf16Acc(x, w)
}
var maxErr [4]float64
var closeOK [4]bool
for j := range out {
closeOK[j] = true
for r := 0; r < rows; r++ {
e := math.Abs(float64(out[j][r]) - ref[r])
maxErr[j] = max(maxErr[j], e)
if e > 1e-5+1.6e-2*math.Abs(ref[r]) { // torch.testing.assert_close, bfloat16
closeOK[j] = false
}
}
}
for j, name := range []string{"baseline", "split-K", "BF16-part", "BF16-acc"} {
fmt.Printf("%5d %-9s %9.4f %-23v %v\n", k, name, maxErr[j], closeOK[j], maxErr[j] <= 2*maxErr[0])
}
}
}Output:
K kernel max|err| allclose(bf16 defaults) within 2x baseline
256 baseline 0.1227 true true
256 split-K 0.1227 true true
256 BF16-part 0.1827 false true
256 BF16-acc 1.5381 false false
4096 baseline 0.4863 true true
4096 split-K 0.4863 true true
4096 BF16-part 0.5340 false true
4096 BF16-acc 33.9517 false false
32768 baseline 1.6903 true true
32768 split-K 1.6903 true true
32768 BF16-part 2.3097 false true
32768 BF16-acc 156.7078 false falseWhat it shows:
- The correct kernels have large absolute errors (up to 1.7 at K = 32,768). That is not a bug: the outputs are big sums, and the final BF16 store rounds them to about 3 significant digits. Any fixed absolute tolerance is either too tight for long K or too loose for short K.
- The obvious bug fails both rules at every length. Errors grow with K because a BF16 running sum stops absorbing small terms once it is large.
- The subtle bug passes the “2× baseline max error” rule and fails
allclose. The largest error is dominated by big outputs, where the extra rounding hides inside the final BF16 rounding. The bug shows on outputs that are small because of cancellation, where an error of 0.1 on an output of 0.4 is 25%. One rule alone would have shipped it.
5. Technical explanation#
An error model, so tolerances are not guesses#
For a sum of K products computed in a format with unit roundoff u (half the gap between 1
and the next representable number: about 6e-8 for FP32, 3.9e-3 for BF16), the standard bound is:
|computed − exact| ≲ c · u · Σ |x_i · w_i| worst case c ≈ K
typical c ≈ √K (random rounding errors)
pairwise / split sums: c ≈ log2(K)
plus one rounding of the output: u_out · |result|Three things follow:
- Error scales with the sum of absolute terms, not with the result. When terms cancel, the
result is small and the relative error large. Tolerances based only on
|expected|(likertol) will flag correct kernels on such outputs, or must be so loose they miss bugs. - The accumulator’s
umultiplies K. FP32 accumulation over K = 32,768 is fine; BF16 accumulation is not (theBF16-accrow). - The output format often dominates. With BF16 output, the final rounding (
u ≈ 3.9e-3relative) dwarfs FP32 accumulation error, which is whybaselineandsplit-Kshow the same maximum error.
A practical test therefore scales its tolerance by the magnitude of the terms:
pass if |actual − ref| ≤ atol + rtol_out · |ref| + k_acc · u_acc · Σ|x_i·w_i| · √Kwith ref computed in float64, rtol_out set by the output format and k_acc a small constant.
Three references, three questions#
COMPARE THE KERNEL WITH ANSWERS USE WHEN
float64 golden reference "how far from the true function?" always; it is the ruler
same-dtype plain implementation "is it as good as the obvious way?" pass rule: error ≤ α × baseline error
(e.g. eager PyTorch in BF16) (FlashAttention uses α = 2 on max error)
the previous fast kernel "did this change anything?" upgrades; expect bitwise or explain why notComparing a new BF16 kernel directly with an old BF16 kernel and requiring closeness mixes the two kernels’ errors together. Measure both against the golden reference.
Method error versus implementation error#
Approximations lose accuracy on purpose. A 4-bit GEMM differs from the BF16 GEMM by the quantization error, which can be large. Test the kernel against the same approximation computed slowly and exactly: dequantize the weights to float64 with the stored scales, then multiply. Then:
quantized kernel vs dequantize-then-matmul in float64 → implementation error (should be tiny)
dequantize-then-matmul vs original BF16 weights → method error (judged by 28.d/28.e)The same split applies to approximate top-k, fast exponential or reciprocal instructions, FP8 attention and KV-cache quantization: write down the approximation, compute it exactly, and test the kernel against that.
Pass rules, and what each misses#
RULE CATCHES MISSES
max |err| ≤ atol gross bugs anything that scales with K or magnitude
allclose (atol + rtol·|ref|) errors on small outputs flags correct kernels on cancelled outputs
unless rtol is loose
max err ≤ α × baseline max err kernels worse than the obvious bugs that only affect small outputs (section 4)
mean |err| ≤ α × baseline mean err systematic bias in many outputs rare large errors
error relative to Σ|terms| (above) both, if the bound is right needs the terms, so a custom check
bitwise equal to previous version any change at all legitimately different summation ordersUse at least two: one on the maximum, one on the mean or on term-scaled error. Also check the sign of the mean error: a correct kernel’s errors average close to zero; a biased one (always rounding down, a missing term) does not.
Inputs that find bugs#
Standard-normal random inputs are the easiest case a kernel will ever see. Add:
SHAPES M = 1 (decode), M not a multiple of the tile, K not a multiple of the tile,
K = 1, very long K, the largest batch and context you serve, odd head counts
VALUES zeros; a few huge outliers (real activations have "massive activation" channels,
hundreds of times the rest, 11.k); values near the format's limits; denormals;
rows that cancel (sum ≈ 0); all-equal rows (softmax ties)
SPECIALS -inf in masks, NaN propagation where expected, empty sequences, length-1 sequences
LAYOUT non-contiguous inputs, strided views, misaligned pointers, the paged KV layout (12.l)
QUANTIZATION extreme scales, all-zero blocks, the largest and smallest codes, mixed group sizes
REPETITION run twice: bitwise equal? (if not, there are atomics or races; see 28.c)Tail tiles (the last, partial tile when a dimension is not a multiple of the tile size) are the most common place for a kernel to read garbage or skip work. Random shapes catch them; powers of two do not.
Numerical tests do not find memory bugs. A race between thread blocks can produce the right answer
on most runs. Run NVIDIA’s Compute Sanitizer (compute-sanitizer --tool memcheck, racecheck,
initcheck) on kernel tests in CI (25.l).
Model-level testing: find the first bad layer#
When a whole model is wrong, compare layer by layer:
1. Run the reference and the candidate on the same input tokens (teacher forcing, 28.a).
2. Record the output of every block (forward hooks in PyTorch; engines have debug dumps).
3. For each layer, compute the relative error ‖cand − ref‖ / ‖ref‖ and the cosine similarity.
4. Plot error against layer index.Normal drift grows slowly and smoothly through the layers. A bug shows as a step: error jumps by an order of magnitude at one layer and stays high. Look inside that layer: attention or MLP, which kernel, which input shape. The jump at layer 0 usually means embeddings, RoPE or the input (template, tokenizer); a jump at the last layer means the final norm, the LM head or the logits processing.
6. Under the hood: why cancellation is the hard case#
Take a sum whose terms are about 1 in size and whose exact result is 0.4. Each term was rounded when it was produced, and each addition rounded the running sum, whose size along the way was around √K. The rounding errors are proportional to those intermediate sizes, not to the final 0.4. When the terms cancel, the final value is small, but the errors made getting there were not.
That is why BF16-part is caught only on small outputs: rounding each partial sum to BF16 adds
an error of about 0.4% of that partial sum’s size, which may be far larger than the output.
On a large output, the same error is smaller than the output’s own BF16 rounding and disappears.
It is also why real models are more sensitive than random tests suggest: residual streams, norms and attention scores all involve sums with cancellation, and the outputs that matter (the logits of near-tied tokens, 28.a) are exactly the ones where small absolute errors decide the result.
7. Performance implications#
- Accuracy tests cost nothing in production and little in CI. Kernel test suites with thousands of shapes take minutes; run them on every kernel change and every library upgrade.
- The golden reference is slow on purpose. Float64 on the CPU for small shapes, float64 or FP32 on the GPU for large ones. Never optimize the reference.
- Precision fixes are usually cheap. FP32 accumulators, FP32 norms and FP32 sampling arithmetic cost little next to the GEMMs (11.k). Exact top-k in FP32, the fix in the Anthropic postmortem, costs more than an approximate one, which is why the approximate one existed: measure the cost before choosing the approximation, and test the approximation’s error.
8. Production implications#
- Gate kernel and library upgrades on accuracy tests, not only on speed. A new cuBLAS, FlashInfer, Triton or compiler version changes kernels you did not write.
- Test on every GPU type you serve. Kernel selection depends on the architecture; a bug can live only on one of them (the Anthropic bugs differed by hardware platform).
- Keep the per-layer comparison tool ready. It turns “quality got worse” into “layer 31’s MLP on H200 with M < 16” in an afternoon.
- Add cheap runtime checks: NaN or infinity in logits, the share of probability mass on tokens outside the expected script or vocabulary range, and output-character checks (Anthropic added a test for unexpected characters to its deployment process after its incident).
- Record which kernels actually ran. Engines fall back silently between backends; a fallback path is a different numerical implementation (18.c).
9. Common mistakes#
- One absolute tolerance for all shapes. Too tight for long K, too loose for short K.
- Comparing two low-precision implementations with each other instead of each with a high-precision reference.
- Testing quantized kernels against the BF16 model, so the quantization’s own error hides any kernel bug.
- Only standard-normal inputs and power-of-two shapes. Outliers, cancellation and tail tiles are where kernels break.
- Only checking the maximum error. A biased kernel can have a fine maximum and a wrong mean.
- Only checking numerics. Races and out-of-bounds reads need Compute Sanitizer.
- Comparing final text instead of per-layer activations when localizing a model bug.
10. Hands-on exercise#
- Run
kerneltest.go. Add a mean-error column and a term-scaled rule (section 5). Which rules catchBF16-partat every K? - Add a fifth kernel that skips the last
K mod 64elements (a tail-tile bug). Which inputs and which K reveal it? Would a test with K = 4,096 only find it? - Replace the inputs with normal values plus one element per row that is 500 times larger. How do the errors and pass rules change?
- In PyTorch, write a test for an FP8 GEMM that separates method error from implementation error as in section 5.
- Take a small model, add forward hooks, and compare BF16 against FP32 layer by layer. Then compute RoPE positions in BF16 deliberately and find the step in the error curve.
11. Interview questions#
- How do you choose tolerances for testing a BF16 GEMM kernel? Why does a single
atolfail? - Why compare a new kernel against a float64 reference rather than against the old kernel?
- How would you test a 4-bit GEMM kernel so that quantization error does not hide a bug?
- Explain why cancellation makes relative-error checks hard, and how you would handle it.
- A model produces subtly worse output after a port. How do you find the layer at fault?
- What test inputs would you add beyond random normal values, and why?
- What do numerical tests not catch, and what do you use for it?
12. Further reading#
Checked on 13 November 2026.
- PyTorch 2.15,
torch.testing.assert_close(default tolerances per dtype) - FlashAttention test suite (
tests/test_flash_attn.py: the 2× baseline-error rule) - Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM (summation error bounds)
- Anthropic, “A postmortem of three recent issues” (approximate top-k bug)
- Unsloth, “Fixing All Gemma Bugs” (March 2024)
- NVIDIA Compute Sanitizer documentation
- Stable reductions: 11.e, 11.k. Kernel test suites and autotuning: 25.l.