Checking a kernel: hk.check¶
One call answers the three questions a kernel's author -- a person or a coding
agent -- asks after every edit: what does it cost (registers, occupancy, LDS,
spills), is it right (against a torch reference), and is it fast (against
torch eager and torch.compile, interleaved in one process).
python -m hk.check my_kernel.py:gelu_mul --ref "F.gelu(a, approximate='tanh') * b" \
--inputs "bf16[4096,14336], bf16[4096,14336], bf16[4096,14336]" --json out.json
import hk
report = hk.check(gelu_mul, reference, inputs) # the same, from Python
print(report) # the summary below
report.json() # the JSON below, as a dict
- The loop
- What it checks
- Telling it what to check
- Reading the report
- Without a GPU, and the other GPU
- Rules it keeps, and its limits
- Why it is slow:
--profile - Which XCD runs which workgroup:
--placement
The loop¶
Write the kernel in a file with its reference and its inputs:
# gelu_mul.py
import torch
import torch.nn.functional as F
import hk
@hk.kernel(grid=lambda p: (hk.cdiv(p.o.cols, 64), hk.cdiv(p.o.rows, 16), 1))
def gelu_mul(a: hk.Tensor[hk.bf16], b: hk.Tensor[hk.bf16], o: hk.Tensor[hk.bf16]):
idx = hk.tile_coord(0, 0, hk.arch.block_idx.y, hk.arch.block_idx.x)
x = a[idx].load(hk.RT(hk.fp32, 16, 64))
x.gelu(into=x) # hk.math.gelu is the tanh form
x *= b[idx].load(hk.RT(hk.fp32, 16, 64))
o[idx] = x.to(hk.bf16)
def reference(a, b): # takes what the kernel reads, returns what it writes
return F.gelu(a, approximate="tanh") * b
SHAPES = [(16, 14336), (4096, 14336)] # decode- and prefill-sized
def inputs(device, shape=(4096, 14336)):
a = torch.randn(*shape, device=device, dtype=torch.bfloat16)
return a, torch.randn_like(a), torch.empty_like(a)
A kernel written for every dtype (hk.Tensor[hk.T]) is checked as it is:
T comes from the tensors inputs() returns, the way a call reads it, and
each case reads its own (fp16 inputs check the fp16 specialization).
Then run it after every change:
python -m hk.check gelu_mul.py:gelu_mul # reference, inputs and SHAPES from the file
and act on what it says: a FAIL names the first wrong element; an
occupancy below the card's maximum names what binds it; a loss against
torch.compile at a small fraction of the DRAM peak says the kernel is not
moving bytes fast enough (a streaming kernel wants register strips or a
template, not 16x64 tiles); the hint: lines say which page covers it.
Exit status 0 is pass, 1 a wrong answer, 2 an error, so a script or an agent
can branch on it; --json - puts the report on stdout.
Sample output, not a benchmark claim: an R9700 (gfx1201), hk 0.9.7, ROCm 7.2.3, torch 2.10, on 2026-11-05, at 4096 x 14336:
hk.check gelu_mul gfx1201 (AMD Radeon Graphics) [gpu] hk 0.9.7 torch 2.10.0+rocm7.2.3.git1a270074
build gelu_mul: warps=1 lds=0 B 7.2 s
vgpr=70 (charged 72, headroom 26) occupancy=16/16 (regs 16, lds 16) scratch=0 spill=0
case 0: bf16[4096,14336], bf16[4096,14336], bf16[4096,14336]
correct ok out0 bfloat16: max |err| 0.0625 (0.0038 of max|ref|), mean 0.000447; allowed 0.0163 + 0.016*|ref|
eager's own max |err| 0.0625
compile's own max |err| 0.0625
time hk 601.6 us ±0.2% eager 985.0 us ±0.2% compile 605.9 us ±0.8%
speed hk is 1.64x eager (win, band 2%) 1.01x compile (tie, band 2%)
rate hk 586 GB/s = 92% of DRAM peak (inputs + outputs once; cold: 2 copies of the inputs, rotated past the cache)
first hk 7.26 s eager 0.00 s compile 1.77 s (first call: trace, build or cache load, launch)
PASS
On the R9700 this tile kernel is correct, fully occupied and at 92% of the
DRAM peak, level with torch.compile: GDDR6 is slow enough that its 8-byte
accesses keep up. On a faster memory system the same kernel falls behind,
and the report says why. Sample output from an MI355X (gfx950, hk 0.4.0,
ROCm 7.2.3, 2026-10-21), abridged:
time hk 114.4 us ±0.9% eager 102.2 us ±0.6% compile 62.0 us ±1.2%
speed hk is 0.90x eager (loss, band 2%) 0.54x compile (loss, band 2%)
rate hk 3081 GB/s = 39% of DRAM peak (inputs + outputs once; cold: 2 copies of the inputs, rotated past the cache)
hint: case 0: 1.84x slower than torch.compile (...); at 39% of the DRAM peak a streaming
kernel is not moving bytes fast enough: start from hk.templates (docs/templates/), or
put rows on register strips (hk.RS, docs/language.md#register-strips) with 16-byte runs
Rewritten on register strips as the hint says -- the ten-line kernel in
llms.txt -- it tied torch.compile there (61.7 us), and
hk.ops.silu_mul, the tuned op for the same pass, took 56.8 us.
What it checks¶
- Build (no GPU). Every kernel instantiation the call launches is
traced and compiled by hipcc, and its resources reported: VGPRs (and
AGPRs on CDNA), the count occupancy is charged on and the headroom to the
next step down, occupancy by registers and by LDS and the smaller of the
two, LDS bytes, scratch and spills, and the passes' warnings. A spilling
build is an error, as it is everywhere in hk (the resource
gates). A trace error (
hk.VerifyError, aTypeErrorfrom the language) and a hipcc error are reported with their message and the line they point at, and stop there. - Correct (a GPU). The outputs against the reference at a tolerance
for the output's dtype (below): max
and mean absolute error, the error relative to the reference's largest
magnitude, the count of mismatches and the first one's index, got and
want. torch eager's and
torch.compile's own error against the same reference is printed beside it, so a tolerance can be judged. - Time (a GPU). The kernel, torch eager (the reference itself) and
torch.compile(reference), plus any--baseline, in one process: warmup, then rounds that rotate the contenders, each round a burst of back-to-back calls filling about a millisecond. Each contender's median over the rounds and its noise (median absolute deviation over the median), the ratio to each baseline (the median of the per-round ratios; above 1 hk is faster) with a verdict inside a noise band, the bandwidth (inputs and outputs counted once), and the first call of each timed on its own (trace and hipcc, ortorch.compile's compile).
Timing is cold by default. Each contender runs on copies of its inputs in turn, enough that together they exceed twice the GPU's last-level cache (96 MiB on a W7900D, 64 MiB on an R9700, 256 MiB on an MI355X). The outputs of the last calls are kept too, so a function that returns a new tensor writes a different buffer each call instead of the one torch's allocator would hand back. Each call then reads and writes DRAM, as a model's layers do, and the bandwidth reported is DRAM traffic. A small input reused over and over would otherwise sit in the cache and report more than the card's DRAM can deliver.
The run is timed hot instead, with a note saying why, when: - the inputs are too small to leave the cache in rotation (they stay there in use too), or - the copies would take over a quarter of the free device memory.
--hot (cache="hot") always times the same inputs every call. A rate past
the DRAM peak is reported as what it is: the inputs were cache-resident,
and it is not DRAM bandwidth.
Telling it what to check¶
What is checked (TARGET) is one of:
| form | example |
|---|---|
a raw @hk.kernel |
my.py:gelu_mul -- the outputs are the tensors it stores into |
| a function that calls hk kernels | my.py:gelu_mul_fn -- returns the output(s) |
| a shipped op or a template's product | hk.ops.silu_mul, hk.ops:rmsnorm |
| a file | my.py -- its CHECK dict, else its kernel or fn |
For a raw kernel the reference takes the tensors the kernel only reads and
returns the ones it writes, in order (TracedKernel.written_tensors).
Constexprs are --const NAME=VALUE. A function's reference takes the same
arguments the function does. A function that writes into an argument
instead of returning names it: --outputs 2 (outputs are NaN-filled before
the call and not given to the reference). An argument updated in place --
read, then written, as fused_add_rms_norm's x and residual -- is
--inplace NAME (or an index): the reference gets it as it was and returns
its new value, in argument order with the outputs.
The reference (--ref): FILE.py:name, module:name, a lambda, or an
expression over the reference's argument names -- the target's own parameter
names -- with torch, F (torch.nn.functional), math and hk in scope:
--ref "F.silu(a) * b". Default: the file's reference.
The inputs (--inputs, one per case, repeat it for several shapes): a
generator FILE.py:name called as gen(device) or gen(device=, shape=),
or a spec:
bf16[4096,14336] torch.randn of that shape, as bf16
fp32[64]@rand uniform [0, 1)
i32[64]@randint(0,128) integers in [0, 128); ints default to randint(0,100)
bf16[16,64]@zeros @ones @full(2.5) @arange @empty
bf16[4096,4096]@randn*0.1 scaled
1e-6 a scalar argument
Default: the file's inputs, once per entry of its SHAPES if it has them.
More contenders: --baseline NAME=REF (--baseline ops=hk.ops:silu_mul);
in Python, extra={"name": callable}. They take the reference's arguments,
and are checked against the reference too, so a baseline that computes
something else shows it. --no-eager, --no-compile, --compile-mode
max-autotune-no-cudagraphs.
In Python every option is a keyword of hk.check(fn, reference, inputs, ...)
(the API); cases=[...] takes several input generators,
and report.raise_for_status() makes it a test.
Tuning a constexpr: --sweep CW=512,1024,2048 (repeatable; every
combination) builds, checks and times a raw kernel at each value beside the
default, as hk[CW=1024], and names the fastest (best). A value that does
not build -- a strip width that is not whole chunks on this arch, a tile
that spills -- is a note, not an error; a wrong one is reported and not
timed. On an MI355X (hk 0.4.0, 2026-10-21), llms.txt's strip kernel at 4096x14336: CW=512 61.3
us, 1024 64.6, 2048 72.0 (CW=256 is not a whole 64-lane chunk there).
Reading the report¶
--json writes (abridged; the R9700 run above, sample output):
{
"schema": 1, "name": "gelu_mul", "status": "pass", "arch": "gfx1201", "mode": "gpu",
"device": "AMD Radeon Graphics",
"versions": {"python": "3.12.3", "hk": "0.9.7", "hk_src": "baec00a67790",
"torch": "2.10.0+rocm7.2.3.git1a270074", "hip": "7.2.53211",
"triton": "3.6.0+rocm7.2.3.git4ed88892"},
"builds": [{"kernel": "gelu_mul", "consts": {}, "arch": "gfx1201", "warps": 1, "threads": 32,
"lds_bytes": 0, "warnings": [], "trace_s": 0.0, "build_s": 7.233, "cached": false,
"source": ".../hk-cache/379e5e51.../kernel.cpp",
"instantiations": [{"name": "gelu_mul_kernel(globals)", "vgpr": 70, "agpr": 0,
"sgpr": 15, "vgpr_charged": 72, "vgpr_headroom": 26, "lds": 0,
"scratch": 0, "spill": 0, "occupancy_by_regs": 16,
"occupancy_by_lds": 16, "occupancy": 16,
"max_waves_per_simd": 16}]}],
"cases": [{"case": 0, "inputs": "bf16[4096,14336], bf16[4096,14336], bf16[4096,14336]",
"first_call_s": {"hk": 7.256, "eager": 0.0019, "compile": 1.7658},
"correct": {"ok": true,
"outputs": [{"dtype": "bfloat16", "shape": [4096, 14336],
"numel": 58720256, "ok": true, "rtol": 0.016,
"atol": 0.01631, "scale": 16.31, "max_abs": 0.06248,
"mean_abs": 0.000447, "max_rel": 0.00383,
"mismatches": 0, "nan": 0}],
"baselines": {"eager": {"max_abs": 0.06248, "ok": true},
"compile": {"max_abs": 0.06248, "ok": true}}},
"time": {"rounds": 15, "calls_per_round": {"hk": 2, "eager": 2, "compile": 2},
"bytes": 352321536, "flops": null, "cache": "cold", "copies": 2,
"ms": {"hk": {"median": 0.60162, "min": 0.59938, "noise": 0.0023,
"gb_s": 585.6},
"eager": {"median": 0.98505, "min": 0.97817, "noise": 0.0021,
"gb_s": 357.7},
"compile": {"median": 0.60587, "min": 0.59814, "noise": 0.0075,
"gb_s": 581.5}},
"vs": {"eager": {"x": 1.635, "band": 0.02, "verdict": "win"},
"compile": {"x": 1.0058, "band": 0.02, "verdict": "tie"}},
"of_dram_peak": 0.915}}],
"errors": [], "notes": [], "hints": []
}
| key | meaning |
|---|---|
status |
pass (correct at every case), fail (a wrong answer), error (did not trace, build or run: see errors), built (no GPU: the build is all there is) |
mode |
gpu, build-only (no GPU, or a GPU of another arch) or trace-only (no hipcc) |
builds[] |
one per kernel and constexpr set the call launched; cached is true when hipcc did not run (the disk cache had it); build_s is null when the first call built it (then it is in first_call_s); source is the generated C++ |
instantiations[] |
the compiler's numbers: occupancy is waves per SIMD, the smaller of occupancy_by_regs and occupancy_by_lds, out of max_waves_per_simd; vgpr_charged is what occupancy is charged on (rounded to the granule, AGPRs included on CDNA); vgpr_headroom is how many more VGPRs fit before it drops a step |
correct.outputs[] |
per output: ok when every element has abs(got - want) <= atol + rtol * abs(want); scale is max abs(want), max_rel is max_abs / scale; first_mismatch is {index, got, want}; nan counts NaNs the reference does not have |
correct.baselines |
torch eager's and torch.compile's own error against the same reference |
time.ms |
per contender: median and min ms a call over the rounds, noise the rounds' spread, gb_s bytes / median |
time.vs |
per baseline: x = baseline time / hk time (above 1 hk is faster), band, verdict |
errors[] |
{stage, type, message, where}; stage is trace, build, inputs, reference, run or time |
hints[] |
what to try next, read off the numbers (heuristics; the timing is the verdict) |
profile |
with --profile: hk.profile's report of the first case (its JSON, docs/profile.md) and its summary |
Without a GPU, and the other GPU¶
With no GPU, hk.check traces and builds and stops: the resources need
hipcc, not a device (mode: build-only, status: built). A raw kernel needs
only its constexprs; a function is run once on CPU tensors with launching
switched off, to see which kernels and constexprs it would launch. Without
hipcc either, it traces (mode: trace-only): the warps, the LDS bytes and
the passes' warnings.
--arch gfx1100,gfx950 reports each arch, one process each with HK_ARCH
set: the arch of the GPU in the machine is checked and timed, the other is
built. --arch naming only another arch builds for it. So on a gfx950 box:
python -m hk.check gelu_mul.py:gelu_mul --arch gfx1100,gfx950 --json both.json
gives the gfx1100 build's register count and occupancy (92 VGPRs, occupancy 16/16 on the W7900D's wave32 SIMDs) beside the gfx950 run. Per-arch facts that change a kernel's plan are in hk.target.
Rules it keeps, and its limits¶
- The reference runs in fp32 on fp32 copies of the 16-bit inputs
(
--ref-precision nativeto run it as given), and the tolerance is the output dtype's, about two units in the last place: bf16rtol 1.6e-2,atol 1e-3 x max|ref|; fp162e-3,1e-4 x; fp321e-4,1e-5 x; integers exact (hk.check.TOLERANCES).--rtol/--atoloverride (--atolis then absolute),--exactasks for bit equality. A tolerance is where a wrong kernel hides: when the kernel's error is larger than torch eager's own, find out why before loosening it, and keep one case with an exact answer in the kernel's tests (for agents). - A raw kernel's outputs are filled with NaN before it runs, so an element it never writes is a mismatch, not a stale value that happens to match.
- Timing is in one process, interleaved, the only comparison this
project trusts: across processes a kernel A/B manufactured 13-16% out of
nothing. A verdict is
tieinside a band of max(2%, the noise), andnoisewhen the band passes 15%. Back-to-back calls find a footprint smaller than the cache (96 MB on a W7900D, 256 MB on an MI355X) resident, for every contender alike; therateline flags a rate past the card's ceiling. - The bandwidth counts every input and output once. It is what a
streaming kernel's roofline is drawn from, not what a GEMM or attention
moves; pass
--bytes/--flopsfor those. - First calls include the build: hipcc (seconds) or the disk cache's
load (milliseconds), and
torch.compile's compile. A kernel built in this process beforehk.checkran reports its load, not its build. - What it can see: kernels launched through
Kernel.__call__,Kernel._launcheror built throughKernel.buildduring the call -- every@hk.kernel, everyhk.opsop written in the DSL, and the templates (checked againsthk.templates.rowwiseandhk.templates.gemm(epilogue=...)on their branches: a rowwise RMSNorm's two plans, a GEMM's split-K kernel, its reduction carrying the epilogue and its pingpong). A launcher a template cached beforehk.checkran is not seen again: check in a fresh process. The HipKittens C++ kernels wrapped byhk.ops.hipkittensare launched otherwise and have no build row. A function's no-GPU discovery runs it on CPU tensors, so a function that needs a GPU tensor to decide what to launch is reported as not discoverable; check its kernel directly. hk.__version__of a checkout is its last release's; the report'sversionscarrieshk_commitwhere git can see the checkout, andhk_src(a hash of the package's Python sources) everywhere, so two reports from the same code say so.
Why it is slow: --profile¶
hk.check says how fast; hk.profile says why. --profile
(profile=True in Python) runs it on the first case after the check: per
kernel the call launches, the roofline, how busy the matrix core was, the
grid's rounds and tail, where the waves wait (the counters, and a thread
trace of one CU), the main loop's instruction mix, and a verdict line. The
report gains a profile key (hk.profile's JSON); the summary ends with its
lines. On its own: python -m hk.profile FILE.py:NAME --inputs ....
Which XCD runs which workgroup: --placement¶
A kernel with an hk.Placement (or placement="auto", or an op whose kernels
have one) runs its workgroups in another order than the hardware deals them
(hk.dsl.placement, design). That order must still
run every grid point exactly once. --placement checks it at the given inputs
and exits: it evaluates the decode the kernel's own emitted ops compute, for
every workgroup id of the launch, and reports the order it installs.
python -m hk.check my_kernel.py:kernel --placement --inputs "i32[2,1,1,45]"
# case 0: kernel: a bijection over 270 workgroups, grid (45, 3, 2), order (z, y, x), 8 XCDs
A raw @hk.kernel needs no GPU (its inputs are made on the CPU; only their
shapes matter). A function is run on the GPU, and every hk kernel it launches
is checked (hk.dsl.placement.recording). For placement="auto" both the
kernel and its cluster placement are checked.