Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Reference implementation | A simple, trusted version of the computation (often PyTorch in FP32 or FP64) that a fast kernel’s output is compared with. |
| Tolerance (atol / rtol) | How far a result may be from the reference and still pass: |out − ref| ≤ atol + rtol × |ref|. |
| ULP | Unit in the last place: the gap between a number and the next representable one in its format. BF16 has 8 bits of precision, so 1 ULP is about 0.4–0.8 % of the value. |
| Sanitizer | A tool that instruments a program to catch out-of-bounds accesses, races, uninitialised reads or bad synchronisation as they happen. |
| Autotuning | Running a kernel with many configurations (tile sizes, stages, warps) on the target GPU and keeping the fastest, per shape. |
| Config space | The set of configurations an autotuner may try. |
| Shape bucket | A range of problem sizes (for example M in 1–16, 17–64, …) that share one tuned configuration. |
| L2 flush | Overwriting the L2 cache between benchmark runs so a kernel cannot benefit from data the previous run left behind. |
1. What is it?#
The engineering discipline that turns a fast kernel into one you can ship:
- Verifying correctness: comparing with a reference at tolerances that are tight enough to catch bugs and loose enough to allow legitimate rounding differences; sweeping shapes, layouts, dtypes and edge cases; running sanitizers.
- Measuring performance honestly: warm-up, cache state, clocks, statistics, and measuring in the context the kernel will run in.
- Autotuning: choosing configurations per GPU and per shape, offline or at start-up, and caching the result.
- Guarding production: regression tests in CI, golden-output checks, and timeouts that turn a hang into a failed test rather than a stuck fleet.
Numerics of whole models (accuracy evaluation, logprob comparison, batch invariance) are Module 28’s subject (28.b–28.e). This lesson is about the kernel in isolation.
Facts checked on 13 November 2026 (Triton 3.9.0, Helion 1.5.2, CUDA compute-sanitizer).
2. Why does it matter?#
The kernels of 25.a–25.k fail in ways ordinary code does not:
- Silent wrong answers. A wrong parity, a missing proxy fence or a mismatched swizzle (25.a) can produce numbers that are almost right, only for some shapes, only sometimes.
- Hangs. A barrier that is never completed stops the GPU until a watchdog kills the process.
- Shape-dependent bugs. Edge tiles, K not divisible by the block size, M = 0 (an expert with no tokens), very large M that overflows 32-bit indices.
- Performance cliffs. A config that is fastest for one shape is 3× slower for another; a library upgrade changes heuristics.
And inference is unforgiving: a kernel bug corrupts outputs for every user on every replica, often subtly enough to show up as “quality dropped a bit” weeks later (28.f).
3. Simple analogy#
Testing a new bridge. You compare its deflection with the engineering model, allowing for the fact that real steel is not perfect (tolerance). You drive trucks of every size over it, including the empty lane and the overweight truck (edge cases). You put sensors on every joint while doing so (sanitizers). You time traffic in rush hour, not at 3 a.m. (benchmark in context). And you re-inspect after every change of supplier (CI on library upgrades).
4. Tiny example: how big is a legitimate difference?#
Two correct GEMM kernels with different tile shapes add the same products in different orders. With BF16 inputs, FP32 accumulation and BF16 output, how far apart can they be, and from an exact reference?
// tolerance.go — how big are "correct" differences between two GEMM kernels?
// BF16 inputs, FP32 accumulation in two different orders, BF16 output, against a float64 reference.
package main
import (
"fmt"
"math"
"math/rand"
)
// bf16 rounds a float32 to bfloat16 precision (round to nearest even) and back.
func bf16(x float32) float32 {
b := math.Float32bits(x)
b += 0x7fff + (b>>16)&1
return math.Float32frombits(b &^ 0xffff)
}
func main() {
rng := rand.New(rand.NewSource(3))
fmt.Println(" K |out|~ fp32 order A vs ref order A vs order B bf16 output vs ref rtol needed")
for _, k := range []int{64, 1024, 16384} {
const trials = 200
var outMag, errA, errAB, errOut float64
for t := 0; t < trials; t++ {
a := make([]float32, k)
b := make([]float32, k)
ref := 0.0
for i := range a {
a[i] = bf16(float32(rng.NormFloat64()))
b[i] = bf16(float32(rng.NormFloat64()))
ref += float64(a[i]) * float64(b[i])
}
// Order A: one running FP32 sum (one CTA walks K).
var sA float32
for i := range a {
sA += a[i] * b[i]
}
// Order B: 64-wide partial sums, then a tree of partials (split-K / another tile shape).
var parts []float32
for i := 0; i < k; i += 64 {
var p float32
for j := i; j < i+64; j++ {
p += a[j] * b[j]
}
parts = append(parts, p)
}
for len(parts) > 1 {
var next []float32
for i := 0; i+1 < len(parts); i += 2 {
next = append(next, parts[i]+parts[i+1])
}
if len(parts)%2 == 1 {
next = append(next, parts[len(parts)-1])
}
parts = next
}
sB := parts[0]
outMag = max(outMag, math.Abs(ref))
errA = max(errA, math.Abs(float64(sA)-ref))
errAB = max(errAB, math.Abs(float64(sA-sB)))
errOut = max(errOut, math.Abs(float64(bf16(sA))-ref))
}
fmt.Printf("%5d %7.1f %19.2e %18.2e %18.2e %11.1e\n",
k, outMag, errA, errAB, errOut, errOut/outMag)
}
} K |out|~ fp32 order A vs ref order A vs order B bf16 output vs ref rtol needed
64 23.7 1.61e-06 0.00e+00 4.34e-02 1.8e-03
1024 114.4 2.93e-05 3.43e-05 2.22e-01 1.9e-03
16384 362.8 9.51e-04 9.46e-04 9.84e-01 2.7e-03What it teaches:
- FP32 accumulation order matters little (10⁻⁶ to 10⁻³ absolute) but is never zero for large K: two correct kernels are not bit-identical (28.c).
- Rounding the output to BF16 dominates by two to three orders of magnitude. Its error is relative (about 2⁻⁹ of the value, half a ULP), so the absolute error grows with the output’s magnitude, which grows like √K for random data.
- A fixed absolute tolerance is wrong.
atol = 1e-2passes everything at K = 64 and fails correct kernels at K = 16,384. Use a relative tolerance at the output dtype’s precision (BF16:torch.testing.assert_closedefaults to rtol 1.6 × 10⁻², atol 10⁻⁵), plus a small atol for values near zero — and compare against a reference computed in higher precision, not against another BF16 kernel’s output.
5. Technical explanation#
A correctness test suite for one kernel#
import itertools, pytest, torch
SHAPES = [(1, 4096, 4096), (7, 4096, 4096), (16, 7168, 2048), (128, 4096, 14336),
(4096, 4096, 4096), (8193, 1024, 1000), (0, 4096, 4096)] # odd, ragged, empty
DTYPES = [torch.bfloat16, torch.float16]
@pytest.mark.parametrize("m,n,k", SHAPES)
@pytest.mark.parametrize("dtype", DTYPES)
def test_gemm(m, n, k, dtype):
torch.manual_seed(m * 31 + n * 7 + k)
a = torch.randn(m, k, device="cuda", dtype=dtype)
b = torch.randn(k, n, device="cuda", dtype=dtype)
ref = (a.double() @ b.double()) # higher-precision reference
out = my_gemm(a, b)
torch.testing.assert_close(out.double(), ref, rtol=1.6e-2, atol=1e-2 * k ** 0.5 / 64)What a serious suite adds:
- Shapes: every captured CUDA-graph batch size (13.k), sizes one below and one above each block multiple, M = 0, the model’s real dimensions, and a very large M to catch 32-bit index overflow (M × K > 2³¹ elements).
- Layouts and strides: non-contiguous inputs, transposed views, misaligned pointers (offset by one element), if the API accepts them — or a test that it rejects them.
- Value distributions: Gaussian, all-zero, large-magnitude outliers (activation outliers are real, 13.d), values that overflow FP8/FP16 when accumulated, NaN and Inf propagation where defined.
- Quantised kernels: compare with dequantise-then-reference, and check scale handling on blocks that are all zero (scale = 0 must not produce NaN).
- Determinism: run twice and compare bitwise when the kernel promises determinism; record whether it does not (atomics, split-K, dynamic schedulers; 28.c).
- Composition: test the kernel inside the layer it serves (attention with paging, MoE with routing), not just alone.
Sanitizers and checkers#
| Tool | Catches | How |
|---|---|---|
compute-sanitizer --tool memcheck | out-of-bounds and misaligned global/shared accesses | compute-sanitizer python test.py |
--tool racecheck | shared-memory data races | slow; run on small shapes |
--tool initcheck | reads of uninitialised global memory | catches “works only on fresh allocations” bugs |
--tool synccheck | invalid __syncthreads / barrier use | divergent barriers |
Triton ConSan (TRITON_INSTRUMENTATION_MODE=consan) | races and synchronisation bugs in Triton/Gluon kernels, including async copies and mbarriers | compiler instrumentation (Triton 3.9 made it faster) |
Triton FpSan (TRITON_INSTRUMENTATION_MODE=fpsan) | wrong operands, wrong data flow, missing synchronisation, by replacing float ops with an exact integer “payload algebra” so equivalent kernels must agree bit for bit | compiler instrumentation |
| Triton GSan (experimental) | races on global memory, including peer accesses over NVLink | shadow memory |
DeepGEMM DG_JIT_CHECK_NO_SPILLS, DG_JIT_CHECK_NO_LOCAL_MEMORY | register spills and local memory in compiled kernels | assert at JIT time |
Run sanitizers on small shapes in CI; they slow kernels by 10–100×. Treat any finding as a bug even if outputs look right.
Hangs#
Warp-specialised and multi-GPU kernels deadlock when a barrier is never completed. Guard every test
with a timeout (pytest-timeout, or run each test in a subprocess with a deadline), and in production
rely on NCCL/RAS watchdogs and engine-level step timeouts (23.e). Some libraries add a debug mode that
zeroes or poisons buffers between calls (DeepGEMM’s DG_COMM_KERNEL_DEBUG for Mega MoE) so stale data
shows up as obviously wrong results.
Measuring performance honestly#
- Warm up (JIT compilation, autotuning, clock ramp, lazy allocation) before timing.
- Flush L2 between repetitions unless the kernel will really see warm data. Triton’s
triton.testing.do_benchclears a cache buffer before each run;ncudoes it by default (--cache-control all) and also locks clocks to base frequency (--clock-control base), which makes numbers comparable but lower than production boost clocks. - Time with CUDA events or CUPTI, not host timers around asynchronous launches. For
microsecond kernels, time a CUDA graph of many launches (
triton.testing.do_bench_cudagraph) to remove launch overhead from the measurement, then remember that production pays it unless graphs are used. - Report a distribution (median and p10/p90 over many runs), the GPU model, clocks, driver and library versions.
- Convert to roofline units: TFLOP/s for compute-bound kernels, GB/s for memory-bound ones (6.a). “1.2× faster” means little without “and now at 85 % of peak”.
- Measure in context. A kernel that is fastest alone can be slower in the model: it may use more SMs (starving a concurrent communication kernel, 25.i), more L2, or a different output layout that costs the next kernel.
Autotuning#
@triton.autotune(
configs=[triton.Config({"BLOCK_M": bm, "BLOCK_N": bn, "BLOCK_K": bk},
num_warps=w, num_stages=s)
for bm in (64, 128) for bn in (64, 128, 256) for bk in (32, 64)
for w in (4, 8) for s in (3, 4)],
key=["M_BUCKET", "N", "K"], # re-tune when these change; bucket M yourself
prune_configs_by={"early_config_prune": drop_configs_that_exceed_smem},
)
@triton.jit
def kernel(...): ...Principles:
- Key on what changes the best config, and bucket dynamic dimensions. Keying on exact M re-tunes for every new batch size at serving time (a latency spike per new shape).
- Prune impossible configs before running them (shared-memory or register limits) to cut tuning time.
- Tune offline, ship the results. vLLM ships JSON configs per (model shape, GPU) for its Triton
fused-MoE kernel and a script to generate them; Helion prints a
helion.Config(...)to hard-code after its search; TileLang and FlashInfer cache tuned results.TRITON_PRINT_AUTOTUNING=1shows what was chosen. - Budget the search. Helion’s README shows a 586-second session over 1,520 configurations for one matmul. Exhaustive tuning of every kernel at start-up is unaffordable; tune offline per GPU SKU and load at start-up.
- Tune per GPU model, driver and library version. A config tuned on H100 is not right for H200 (different memory bandwidth), B200, or MI355X (25.k).
- Check correctness for every config. Autotuners pick the fastest config; if one config has a bug for some shape, the tuner will happily pick it. Run the correctness suite over the config space, not just the default.
AI-written kernels need the same harness#
Since KernelBench (Stanford, 2025) benchmarked language models on writing GPU kernels, LLM-generated and agent-optimised kernels have become common. They fail in characteristic ways: passing the tests by exploiting them (caching outputs, skipping work for the tested shapes, relying on uninitialised memory that happens to hold the right answer), or tolerances loosened until wrong answers pass. Everything in this lesson — randomised inputs per run, higher-precision references, initcheck, shape sweeps, measuring in context — is the defence.
6. Under the hood: what a kernel CI job runs#
on every change to kernels/ or to a pinned dependency (Triton, CUTLASS, FlashInfer, DeepGEMM, driver):
1. build / JIT-compile for every target arch (sm_90a, sm_100a, sm_103a, sm_120; gfx942, gfx950)
2. correctness suite (shapes x dtypes x layouts x value distributions), per arch, with timeouts
3. sanitizers on a reduced suite (memcheck, initcheck, racecheck; Triton consan for Triton/Gluon)
4. determinism check for kernels that promise it
5. microbenchmarks at the model's real shapes vs the last release's numbers; fail on > 3–5 % regressions
6. layer- and model-level golden tests: logits / logprobs vs a stored reference (28.e)
7. publish tuned configs and benchmark results as build artifactsSteps 5–6 need dedicated, quiet GPUs (no other tenants, fixed clocks or at least recorded clocks); shared CI machines produce noisy numbers that hide real regressions.
7. Performance implications#
- Autotuning is often the biggest cheap win. For Triton kernels on a new GPU or a new model shape, a tuned config commonly beats the default by tens of percent; for MoE kernels without a config file, more.
- Benchmark artefacts mislead in both directions. Warm L2 flatters small kernels; locked base clocks understate production; timing without graphs overstates launch-bound kernels’ cost.
- Shape buckets trade tuning cost against fit. Finer buckets find better configs but cost tuning time and binary size (each config is a compiled kernel).
8. Production implications#
- Treat dependency upgrades as kernel changes. Triton, CUTLASS, FlashInfer, DeepGEMM, AITER, cuBLAS and the driver all change kernels or heuristics. Run the full suite and benchmarks before rolling out, and canary (20.j).
- Ship tuned configs with the image, versioned with the GPU SKU and library versions; never tune in the request path.
- Keep a slow reference path that can be switched on in production (an “eager”, “reference” or alternative backend) to triage suspected kernel bugs (28.f).
- Watch for hangs as a symptom. A replica that stops making progress with GPUs at 100 % “busy”
is often a spinning kernel; capture
cuda-gdborcompute-sanitizerstate, or at least the kernel name fromnvidia-smi/DCGM, before restarting. - Record kernel selection in logs (which attention backend, which MoE kernel, which config) so a quality or performance incident can be tied to a kernel.
9. Common mistakes#
- Comparing a fast kernel with another fast kernel instead of a higher-precision reference.
- Fixed absolute tolerances that are too loose for small K and too tight for large K.
- Testing only “nice” shapes (multiples of 128) and only fresh allocations.
- No timeout on tests of warp-specialised or multi-GPU kernels.
- Benchmarking with warm caches and no warm-up, or with host timers.
- Autotuning on exact dynamic shapes at serving time.
- Trusting the autotuner’s choice without testing that config’s correctness.
- Reusing tuned configs across GPU models, drivers or library versions.
10. Hands-on exercise#
- Extend the Go program to FP16 inputs with FP16 accumulation (round after every add). How does the error grow with K, and why do all serious kernels accumulate in FP32 (4.f)?
- Write the pytest suite above for a Triton matmul from 6.e, add an
initcheckrun withcompute-sanitizer --tool initcheck, and fix anything it finds. - Add
@triton.autotunewith an M-bucket key to the same kernel; measure tuning time and the speedup over a fixed config for M ∈ {1, 16, 128, 4096}. - Benchmark one kernel with
triton.testing.do_bench, withdo_bench_cudagraph, and withncu. Explain every difference between the three numbers. - Run a Gluon tutorial kernel under
TRITON_INSTRUMENTATION_MODE=consanafter deliberately breaking its mbarrier parity (25.a exercise). Does ConSan catch it?
11. Interview questions#
- How do you choose tolerances for testing a BF16 GEMM? Why is a fixed atol wrong?
- What should a kernel’s correctness suite cover beyond random inputs at one shape?
- Which sanitizers would you run on a new warp-specialised kernel, and what does each catch?
- List five ways a kernel benchmark can mislead, and how to avoid each.
- How do you design an autotuning key and config space for a kernel used in decode?
- A library upgrade made one model’s outputs subtly different. How do you decide whether it is a bug?
- How would you test an LLM-generated kernel before trusting it?
12. Further reading#
Checked on 13 November 2026.
- [REFERENCE] NVIDIA Compute Sanitizer documentation
- [REFERENCE] Triton debugging guide and FpSan
- [REFERENCE] Triton
do_benchand autotuning - [REFERENCE] Helion autotuning
- [REFERENCE] PyTorch
torch.testing.assert_close - [ESTABLISHED] Ouyang et al., “KernelBench: Can LLMs Write Efficient GPU Kernels?” (2025)
- [REFERENCE] Nsight Compute: cache and clock control
- Related lessons: profiling (6.d), Triton (6.e), CUDA graphs in serving (13.k), Module 28 on correctness and determinism (28.b–28.f)