KBench / tools /factory /AGENT_GUIDE.md
ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 2)
ee8e482 verified
|
Raw
History Blame Contribute Delete
8.23 kB
# How to add a kernel-generation task
Read this fully before writing anything. Everything here is a hard requirement learned from building
the existing 153 tasks; the pitfalls at the bottom are all things that actually went wrong.
## What a task is
An agent is given a slow-but-correct `reference.py` and an empty stub, and must write a fast GPU kernel.
reward = 0 if the submission is incorrect
reward = achieved TFLOP/s or GB/s otherwise, UNCAPPED
Correctness is the **gate**. Speed is the **reward**. There is no oracle and no gold solution: the
score is an absolute hardware metric, so it is hardware-portable and nothing needs re-benchmarking.
## Workflow
```bash
cd /home/zhuominc/MLE-Bench/mle_tasks/kernel-generation/kernels
$EDITOR _factory/specs/my_task.py # write the spec (see below)
python3 _factory/build.py _factory/specs/my_task.py # generates the whole task directory
bash _factory/validate.sh <YOUR_GPU> my-task-name # stub must be 0, reference must be > 0
python3 _factory/audit_sizes.py my-task-name # roofline must be >= 250 us
```
**Write the spec file to disk the moment you have it drafted, before validating.** Agents have been
lost mid-run; anything not on disk is gone.
`validate.sh` must print:
my-task-name stub[0.0 <metric> | correct: 0.0] ref[<positive> <metric> | correct: 1.0]
If the stub scores non-zero or the reference scores zero, the task is broken. Do not move on.
## The spec
Every field is in `_factory/spec.py`. The ones that matter most:
| field | notes |
|---|---|
| `reference_src` | correct + simple. NOT a performance target. Must be numerically *tractable*, not fair. |
| `make_inputs_src` | `def _mk(*shape, seed)` returning the arg tuple, on `cuda`, seeded |
| `flops_src` | `def canonical_work(*shape)` — FLOPs or BYTES from **shape alone**, never from the data |
| `flops_formula` | set this explicitly whenever `canonical_work` uses helpers or multiple statements |
| `metric` | `"TFLOP/s"` for compute-bound, `"GB/s"` for bandwidth-bound. Pick honestly. |
| `compare` | `"tensor"` \| `"tuple"` (needs `tuple_names`) \| `"rowwise"` (needs `row_pass`) |
| `tol` | **measure it**, do not guess. See Precision below. |
| `grader_shapes` / `correct_shapes` / `measure_shapes` | see Sizing below |
`canonical_work` depending on the *data* (e.g. counting actual non-zeros) breaks the leaderboard —
two submissions would be credited differently for the same work. Shape only.
## Sizing — the most common failure
The kernel must dominate, not launch overhead. **At the largest graded shape the roofline time must be
>= 250 us**, where roofline is `FLOPs / 700e12` (bf16 H200) or `bytes / 4.8e12`.
`python3 _factory/audit_sizes.py <task>` checks this. If it reports under 250 us, make the tensors
bigger — and then update `regime_md` so the prose matches the new numbers.
Keep `correct_shapes` **small** (they run many times) and `grader_shapes` **large**. They are separate
lists precisely so correctness can be cheap while timing is at scale.
## Precision
Prefer **bf16 / fp8** — that is what LLM and diffusion inference actually use. fp32 references are fine
as the numerical *spec*, but the graded dtype should be realistic.
**Measure the tolerance, do not guess it.** Write the reference, write a second independent-but-correct
implementation (different reduction order, different chunking), compare them, and set `tol` at roughly
**2x** the observed difference. State the reasoning in `precision_md`.
If a task ships pre-quantised inputs (fp8/int4/nvfp4), the reference must dequantise **those exact
bytes**. Making the agent quantise and then charging them the quantisation error is a bug — it cost the
megakernel fp8 task a 10x tolerance error before it was caught.
## Quantisation tasks: constrain the input span
Quantised tasks have a failure mode the rest of the lane does not — the measured error depends on the
input span, so a tolerance measured on a few seeds can be a lottery.
* **Per-TENSOR scales must be exactly representable.** A scalar scale drawn from a continuous
distribution is not representable in bf16, and its rounding error multiplies the WHOLE output
coherently instead of averaging out. `nvfp4-dequant-gemm` measured a **221x spread** in E across 80
seeds from one such scalar, leaving 1.73x headroom at the worst seed. Round per-tensor scales onto
the bf16 grid at generation. Per-row and per-block scales average out over the reduction and should
be left alone — rounding them would misrepresent the real format.
* **Measure E over MANY seeds, not two or three.** The tail grows: that same task measured 2.4e-3 over
20 seeds and 2.9e-3 over 80. And the grader validates the last TIMED rep on seeds 10000+i, which are
different from the correctness seeds 100+i, so an unstable E can pass correctness and fail timing.
* **Watch for underflow outliers.** If a fixture lets a dequantised value reach exactly zero where a
divisor expects it not to, a handful of elements can dominate the relative-Frobenius norm.
`quantized-optimizer-state` had 8 elements carrying 86% of the output energy for that reason.
* **Relative Frobenius error under-weights what quantisation damages.** It is dominated by the largest
elements, which are the ones that SET absmax and are best represented. Keep the block dynamic range
(`absmax/rms`) near what a gaussian gives (~3.2 for a 128-block); if you want real activation
outliers, inject them at a FIXED count and magnitude rather than relying on the tail of `randn`.
* **If your gate ends up tight enough to forbid bf16 metadata, say so in the prose.** Scales and
dequantisation maps are tiny and fully reused, so keeping them fp32 costs no bandwidth — but an
agent will not guess that a 4e-5 gate is enforcing it.
## Contract clarity
Difficulty must come from the kernel, never from ambiguity. `contract_md` must state, for every
argument: shape, dtype, layout, and meaning; and for every output: shape, dtype, and whether it may be
bf16 or must be exact. Say explicitly whether inputs are read-only and whether updates are in-place or
functional. If a dimension is ragged (not a multiple of any tile), say so and include a ragged
`correct_shape`.
`perf_md` must tell the agent where the performance actually comes from, and `instruction.md` must
explicitly push for speed — this is a leaderboard, not a pass/fail.
## Toolchain policy (what agents may use)
Encouraged: **CUDA C++ / CuTe DSL**, then Triton (Gluon ships with it), CUTLASS. `torch` is allowed for
setup and where there is no efficient direct alternative.
Not available, by absence rather than by scanning: no internet at run time, and no flashinfer, vLLM,
flash-attn, TensorRT-LLM, or any pre-fused library kernel installed. **Never add an anti-cheat source
scan** — if agents should not have something, it simply is not installed.
## Novelty
Tasks must be genuinely new, LLM- or video-generation-related, and not duplicate any of the 153
existing directories. `ls -d */ | grep -v '^_'` before you name anything.
## Pitfalls that have actually bitten
* **Integer tensors must compare exactly.** `.float()` is lossy above 2^24, so two distinct page/token
ids can compare equal and let a wrong kernel pass. The generated grader already handles this — do not
reintroduce float comparison in a custom check.
* **Top-k / argmax gates are fragile.** Near-tied values flip on ordinary numerical noise, so two
*correct* implementations disagree. Gate on relative error instead. This killed a MoBA design and a
megakernel design.
* **`tensor / python_float` is a reciprocal-multiply** and flips ~0.05% of fp8 codes. Use a 0-dim
tensor divisor.
* **Check the drop-the-feature error.** Measure what a kernel that *ignores* your task's distinguishing
feature would score. It must be far above `tol`, or the feature is not actually being graded.
* **Do not trust a reference you have not verified.** Validate against a known-correct special case or
an independent implementation before shipping.
* **Disk.** Reap images as you go: `docker rmi -f mle-v-<task>`. `/` has filled mid-run several times.