KBench / tools /mega_factory /specs /megakernel_gqa_paged_decode.py
ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 10)
0f775e2 verified
Raw
History Blame Contribute Delete
11.6 kB
"""megakernel-gqa-paged-decode — whole-model decode over a PAGED KV cache at 16k context."""
import pathlib, sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "models"))
from spec import MegaSpec
from _common import LLAMA_1B, CORRECTNESS_MD, PRECISION_MD, perf_md
import paged
TOL = 6e-2
CFG = dict(LLAMA_1B); CFG["page_size"] = 128
SPEC = MegaSpec(
name="megakernel-gqa-paged-decode",
unfused_kernels=772,
title="Write a whole-model decode megakernel over a paged KV cache (16k context)",
blurb=("The whole-model decode megakernel with production KV storage: the cache is a pool of "
"128-token pages and a per-sequence page table maps logical position to physical page, with "
"the pages deliberately shuffled through the pool. The weight stream is still a schedule "
"you can prefetch; the 538 MB of KV only has addresses after a table lookup."),
keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "decode", "paged-attention",
"kv-cache", "gqa", "long-context"],
cfg=CFG, model_src=paged.MODEL_SRC,
batch=1, prefill_len=16384, max_seq=16512, decode_steps=32,
tol=TOL,
arg_doc=("weights : dict from the reference's make_weights (see /app/reference.py)"
"\n kv_cache : dict with paged pools, a page table and the page size (see below)"),
spec_md="""## The computation
A standard decoder layer, repeated 16 times, then a tied LM head -- but the KV cache is **paged**:
```
x = embed[token_ids]
for layer li:
h = rmsnorm(x, in_norm)
q,k,v = h @ Wq.T, h @ Wk.T, h @ Wv.T # q: 32 heads, k/v: 8 heads (GQA, rep = 4)
q,k = rope(q, pos), rope(k, pos)
page = page_table[b, pos // page_size] # PHYSICAL page for this logical position
slot = pos % page_size
k_pool[li][page, :, slot] = k # append THIS position into its page
v_pool[li][page, :, slot] = v
K = concat over j of k_pool[li][page_table[b, j]] # logical KV, gathered through the table
V = concat over j of v_pool[li][page_table[b, j]]
a = softmax(q @ K[:pos+1].T / sqrt(hd)) @ V[:pos+1]
x = x + a_flat @ Wo.T
h = rmsnorm(x, post_norm)
x = x + (silu(h @ Wgate.T) * (h @ Wup.T)) @ Wdown.T
logits = rmsnorm(x, final_norm) @ embed.T # tied lm_head
```
`/app/reference.py` implements exactly this, unfused, in eager torch (it materialises the gathered KV,
which is correct and extremely slow -- do not copy that strategy).
### Why paging changes the kernel
The pool is **oversubscribed**: it holds 258 pages per layer and this sequence owns 129 of them, chosen
at random and scattered through it. The other 129 hold other sequences' KV, which is live data you must
not read. Logically adjacent positions 127 and 128 live in physically unrelated pages, so:
* there is no contiguous 538 MB KV read to issue -- there are 129 independent 128-token page reads per
layer, and their addresses only exist after an int32 load;
* the address computation is on the critical path of the attention, but *not* of the weight stream, so
the two halves of the layer have completely different latency structures;
* a page is `n_kv x page_size x hd` = 8 x 128 x 64 bf16 = 128 KB, which is a natural unit of work for
one block of a persistent grid.
The KV cache arrives **already holding 16384 tokens** spread over 128 pages per layer; you start
decoding at `pos = 16384` and append one position per call.""",
contract_md="""```python
def build_model(weights, kv_cache, cfg, max_seq_len) -> handle # UNTIMED
def decode_step(handle, token_ids, pos) -> logits # TIMED
def teardown(handle) # OPTIONAL
```
`build_model` is handed all four arguments below. `decode_step` is handed the handle you returned, plus
`token_ids` and `pos`.
| arg | shape | dtype | meaning |
|-----|-------|-------|---------|
| `weights` | `dict` | `bfloat16` throughout | keys: `embed`, `final_norm`, `layers` (a `list` of 16 dicts) |
| `weights["embed"]` | `(vocab, d)` = `(128256, 2048)` | `bfloat16` | token embedding table; also the **tied** LM head, used as `embed.T` |
| `weights["final_norm"]` | `(d,)` | `bfloat16` | RMSNorm gain before the LM head |
| `weights["layers"][i]` | 9 tensors | `bfloat16` | `in_norm (d,)`, `post_norm (d,)`, `q (n_q*hd, d)`, `k (n_kv*hd, d)`, `v (n_kv*hd, d)`, `o (d, n_q*hd)`, `gate (ffn, d)`, `up (ffn, d)`, `down (d, ffn)` -- row-major, applied as `h @ W.T` |
| `kv_cache` | `dict` | see rows below | this task's cache is a **dict**, not a list of pairs. Keys: `k`, `v`, `page_table`, `page_size` |
| `kv_cache["k"]` | `list` of 16 tensors, each `(n_pages, n_kv, page_size, hd)` | `bfloat16` | per-layer key page pool. `n_pages` = `2 * B * ceil(max_seq_len / page_size)` = 258 -- **twice** what this batch needs; the surplus pages hold other sequences' KV |
| `kv_cache["v"]` | same shape as `["k"]` | `bfloat16` | the value pool |
| `kv_cache["page_table"]` | `(B, pages_per_seq)` | `int32`, on the GPU | `page_table[b, j]` is the physical page holding logical positions `[j*page_size, (j+1)*page_size)` of sequence `b`. A random selection of half the pool, in random order |
| `kv_cache["page_size"]` | scalar | python `int` | `128` -- also available as `cfg["page_size"]` |
| `cfg` | `dict` | python `int` / `float` / `str` | `layers, d, ffn, n_q, n_kv, hd, vocab, eps, theta, wdtype, page_size` |
| `max_seq_len` | scalar | python `int` | `16512` -- the logical context capacity, i.e. `pages_per_seq * page_size`. `pos < max_seq_len` always holds, so a RoPE table of this length covers the whole run |
| `token_ids` | `(B,)` | `int64`, on the GPU | this step's input token, one per sequence |
| `pos` | scalar | python `int` | the absolute **logical** position this call writes; it advances by 1 per call |
**Return** -- `decode_step` returns a **single tensor** `logits` of shape `(B, vocab)` = `(1, 128256)`,
**bf16 or fp32, both accepted** (the grader compares in fp32). `build_model` returns an opaque handle
of any type; the grader never inspects it and only passes it back to `decode_step`.
`weights`, `cfg` and `kv_cache["page_table"]` are **read-only**. The `k` and `v` pools are the one
thing you must update **in place**, because the next call gathers over them.
The page table is **read-only and fixed for the life of the handle** -- you may hoist it, gather it,
convert it to int64, or precompute base pointers in `build_model`. What you may not do is assume it is
the identity, or that this sequence owns the whole pool: it owns half of it, scattered, and the grader
builds the table from a seed you do not control. Reading the pool contiguously instead of through the
table measures a relative error of **0.76** and fails the correctness gate by 13x.
You must write this position's K and V into `k_pool[li][page_table[b, pos // page_size], :, pos %
page_size]`, because the next call gathers over it.
`build_model` is untimed: repack weights, pre-transpose, allocate scratch, launch a persistent kernel,
build an instruction schedule -- whatever you need.""",
precision_md=PRECISION_MD + """
**Where the tolerance comes from (measured, not guessed).** `tol` is `6e-2`. Two independent
implementations were run against the reference on the graded fixtures (batch 1, prefill 16384, 8
consecutive steps, 2 weight/token seeds):
| implementation | worst relative error |
|---|---|
| bf16 GEMVs + fp32 residual stream, hand-rolled paged attention | 2.77e-2 |
| **all-fp32 twin: residual, GEMVs and softmax all in fp32** | **2.77e-2** |
| *(the gate)* | *6e-2* |
| never append this position's K/V into its page | 1.07e-1 |
| **ignore the page table -- read the pool contiguously** | **7.6e-1** |
So **E = 2.8e-2**, **tol = 6e-2 = 2.2x E**, and ignoring the indirection -- the thing this task exists
to test -- is **13x** the tolerance.
The 2.8e-2 floor is higher than the 1.6e-2 that the same model shows at 2k context, and the reason is
context length: 16385 keys of accumulated softmax difference feed 16 layers of residual. It is an
*arithmetic* gate, nowhere near bf16 epsilon, and both a bf16 and an fp32 residual stream pass.
The paged reference was validated against the contiguous one: given identical weights and identical KV
*contents*, the two agree to a relative error of **0.000000**. Paging is a pure storage change, so if
your gather is right you inherit exactly the tolerance of the contiguous task.""",
correctness_md=CORRECTNESS_MD.format(tol=TOL) + """
**Drop-the-feature margin.** The pool is deliberately twice the size this batch needs, and that is what
makes the gate able to see the gather at all. A kernel that ignores `page_table` and reads pages
`0..128` of the pool measures **0.76**, versus a numerical floor of **0.028** -- see the Precision
section. (When the pool was exactly one sequence's worth, ignoring the table gathered a *permuted copy
of the same keys*; attention is permutation-invariant over the key axis, so that shortcut measured
0.087 and the gate could barely see it. The fixture was changed for this reason.)""",
perf_md=perf_md(
floor_us=627, eager_us=10764, graph_us=6296,
graph_label="eager torch, GPU busy only", bar="GPU-busy",
lead="""At 16k of context the traffic is **2.47 GB of weights and 538 MB of KV** per step, so
attention is ~18% of your bytes rather than a rounding error -- and unlike the weights, those bytes are
scattered across 129 pages per layer whose addresses come from a table.""",
extra="""
* **The reference cannot even be CUDA-graphed.** Resolving a physical page id forces a device-to-host
sync, so graph capture fails outright; the 6.3 ms row above is the *GPU-busy* time with all launch
and sync overhead removed, a strictly more generous baseline than a graph. It is still 10x the floor.
* **Gather, never materialise.** The reference builds a contiguous `(n_kv, pos+1, hd)` copy of the
cache for every layer. That is 33 MB of pure copy per layer, 538 MB per step of traffic that buys
nothing. Read pages straight into your attention accumulator.
* **One page per block, online softmax.** 128 tokens x 8 KV heads is a natural block-sized unit. Have
each block compute a partial `(max, sumexp, acc)` over its page and merge with a running rescale, so
the KV read parallelises across the persistent grid without a second pass.
* **Never expand GQA.** 32 query heads over 8 KV heads: expanding to 32 is 4x the KV traffic for zero
information. Four query heads share one KV page load in registers.
* **Prefetch page pointers a layer ahead.** The table is identical for every layer, so the 129 int32
loads can be done once per step -- or once per handle -- rather than once per layer.
* **The weight pipeline does not depend on the gather.** `Wo`, `Wgate`, `Wup`, `Wdown` for layer `li`
are needed after the attention but their loads are not; keep them streaming while the pages land."""),
regime_md=("**Regime**: batch 1, 16 layers, `d`=2048, ffn=8192, 32 query / 8 KV heads, head_dim 64, "
"vocab 128256, tied LM head. KV is **paged**: 128-token pages, a 258-page pool per layer "
"of which this sequence owns 129, scattered. The cache arrives holding **16384** tokens "
"and you decode 32 more. 2.47 GB of weights + 538 MB of KV puts the floor near 627 us."),
).validate()