"""persistent-kv-append-inline -- append into a paged cache and attend over it in the SAME kernel.""" import pathlib, sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "models")) from spec import MegaSpec import paged_append_attend CFG = dict(n_q=32, n_kv=8, hd=128, page=256, wdtype="bf16") B, PF, DS = 32, 16384, 32 MS = 16640 BYTES = B * (PF + DS // 2) * CFG["n_kv"] * CFG["hd"] * 2 * 2 SPEC = MegaSpec( name="persistent-kv-append-inline", family="e2", title="Append to a paged KV cache and attend over it -- including the entry you just wrote -- in ONE kernel", blurb=("Every serving stack does append-then-attend as two kernels, because a kernel boundary is a " "free device-wide fence. Fuse them and you have to rebuild that guarantee yourself: a " "release fence after a scattered page write, a grid-wide barrier, an acquire on the other " "side -- for a store whose address came out of a shuffled page table and whose reader is a " "different block. This task allows ONE launch, so the boundary genuinely has to go."), keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "paged-attention", "kv-cache", "grid-sync", "memory-model", "gqa", "decode"], cfg=CFG, model_src=paged_append_attend.MODEL_SRC, batch=B, prefill_len=PF, max_seq=MS, decode_steps=DS, correct_steps=8, prof_steps=4, tol=1e-2, max_kernels_per_step=1.0, min_dominant_share=0.98, bytes_per_step=BYTES, reward_metric="GB/s", reward_work=BYTES / 1e9, entry_build="build_attn", entry_step="append_attend", step_sig="handle, q, k_new, v_new, pos", step_ret="(out, k_rd, v_rd)", step_doc=("Write this position's K/V into the paged cache, then attend over 0..pos inclusive." "\n\n q : (B, n_q, hd) bf16 already rotated queries" "\n k_new : (B, n_kv, hd) bf16 already rotated keys for this position" "\n v_new : (B, n_kv, hd) bf16" "\n pos : (B,) int32 absolute position to append, one per request" "\n returns : (out, k_rd, v_rd) -- out (B, n_q*hd); k_rd, v_rd (B, n_kv*hd) read" " back from the cache\n "), arg_doc=("weights : {} -- no projection weights; K and V arrive already computed and rotated" "\n kv_cache : dict with `k`, `v` (n_pages, n_kv, page, hd) bf16 and" " `table` (B, pages_per_req) int32"), unfused_kernels=24, intro_md="""Append-then-attend is the most-executed pattern in LLM serving, and essentially every implementation of it is two kernels. Not because two kernels are faster -- they are not -- but because a kernel boundary is a **free device-wide fence**: whatever the append kernel stored is guaranteed visible to every thread of the attention kernel, and nobody has to think about the memory model. Fuse them into one kernel and that guarantee disappears. Block 7 writes 2 KB into a page whose index came out of a page table; block 91, which has never touched that page, must read it back a few microseconds later. Getting that right needs a release fence, a real grid-wide barrier, and an acquire on the other side -- and getting it *wrong* usually still passes a casual test and then corrupts one token in ten thousand. This task allows exactly **one launch**, so the boundary genuinely has to go.""", spec_md="""## The computation ``` # 1. append, into a PAGED cache pg = table[b, pos[b] // page] # which physical page sl = pos[b] % page # which slot inside it k_pool[pg, :, sl] = k_new[b] v_pool[pg, :, sl] = v_new[b] # 2. attend, over positions 0 .. pos INCLUSIVE (so, including what you just wrote) K = gather over t in [0, pos] of k_pool[table[b, t//page], :, t%page] # (n_kv, L, hd) out = softmax(q[b] @ K.T / sqrt(hd)) @ V # 32 q heads / 8 KV (rep 4) return out, k_pool[pg, :, sl], v_pool[pg, :, sl] ``` `B` = 32 requests, 32 query / 8 KV heads, head_dim 128, page size 256. The cache arrives holding 16384 tokens per request and you append one per call, so the attention covers ~16.4k keys and reads 2.15 GB per call. `/app/reference.py` implements exactly this in eager torch: 24 kernel launches per call, and it materialises the entire gathered cache to do it. ### The page table is shuffled `table` is a random permutation of the page pool, so logically consecutive positions are physically scattered. There is no stride to exploit; each page is 256 x 8 x 128 x 2 = 512 KB of contiguous bf16 and the next one is somewhere else entirely. ### The token you just wrote carries real weight `q` and `k_new` are correlated on purpose -- in a real model both are projected from the same hidden state, so a token attends strongly to the position it is itself writing. Here that self term is about 15% of the softmax mass. An implementation that attends over `0..pos-1` and forgets the entry it just appended is wrong by **0.9**, not by `1/16384`. Measured. ### K and V are returned from the cache The second and third return values are read back **out of the pool** at the slot just written, not the values passed in. A wrong page index, a wrong slot, or a write that never happened shows up directly.""", contract_md="""```python def build_attn(weights, kv_cache, cfg, max_seq_len) -> handle # UNTIMED def append_attend(handle, q, k_new, v_new, pos) -> (out, k_rd, v_rd) # TIMED def teardown(handle) # OPTIONAL ``` `build_attn` is handed all four arguments below. `append_attend` is handed the handle you returned, plus `q`, `k_new`, `v_new` and `pos`. `B` = 32 requests. | arg | shape | dtype | meaning | |-----|-------|-------|---------| | `weights` | `{}` | -- | an **empty dict**: there are no projection weights, K/V and Q arrive already computed and already rotated | | `kv_cache` | `dict` | see rows below | three keys: `k`, `v`, `table` | | `kv_cache["k"]` | `(n_pages, n_kv, page, hd)` = `(2080, 8, 256, 128)` | `bfloat16` | the key page pool. `n_pages` = `B * ceil(max_seq_len / page)` | | `kv_cache["v"]` | same shape as `["k"]` | `bfloat16` | the value pool | | `kv_cache["table"]` | `(B, pages_per_req)` = `(32, 65)` | `int32`, on the GPU | `table[b, j]` is the physical page holding logical positions `[j*page, (j+1)*page)` of request `b`. A shuffled permutation of the pool, fixed for the life of the handle | | `cfg` | `dict` | python `int` / `str` | `n_q` = 32, `n_kv` = 8, `hd` = 128, `page` = 256, `wdtype` = `"bf16"` | | `max_seq_len` | scalar | python `int` | `16640` -- the logical context capacity per request, i.e. `pages_per_req * page`. `pos < max_seq_len` always holds | | `q` | `(B, n_q, hd)` = `(32, 32, 128)` | `bfloat16`, on the GPU | already-rotated queries | | `k_new` | `(B, n_kv, hd)` = `(32, 8, 128)` | `bfloat16`, on the GPU | already-rotated keys for this position | | `v_new` | `(B, n_kv, hd)` = `(32, 8, 128)` | `bfloat16`, on the GPU | values for this position | | `pos` | `(B,)` = `(32,)` | `int32`, **on the GPU** | the absolute position each request is appending (all equal in the graded runs) | **Return** -- `append_attend` returns a **3-tuple** `(out, k_rd, v_rd)` **in that order**: | out | shape | dtype | meaning | |-----|-------|-------|---------| | `out` | `(B, n_q*hd)` = `(32, 4096)` | bf16 or fp32 | attention output, **head-major** (head `h`'s `hd` values are contiguous), over positions `0 .. pos` **inclusive** | | `k_rd` | `(B, n_kv*hd)` = `(32, 1024)` | bf16 or fp32 | the key read **back out of the pool** at the slot just written, head-major | | `v_rd` | `(B, n_kv*hd)` = `(32, 1024)` | bf16 or fp32 | the value read back out of the pool at the slot just written, head-major | All three are compared in fp32, so bf16 or fp32 storage both pass. `build_attn` returns an opaque handle of any type; the grader never inspects it and only passes it back to `append_attend`. `weights`, `cfg`, `q`, `k_new`, `v_new`, `pos` and `kv_cache["table"]` are **read-only**. The `k` and `v` pools are the one thing you must update **in place**, and `k_rd` / `v_rd` must be read back out of them rather than echoed from the inputs -- that read-back is what proves the write landed. The softmax scale is `1/sqrt(hd)`; there is no mask beyond the `t <= pos` bound and no ALiBi/sink term. `pos` is handed to you as a **GPU tensor** specifically so that a compliant implementation never needs a host-to-device copy inside the timed call -- see the gate note below. `build_attn` is untimed: re-layout the pool, pin or reformat the page table, allocate scratch, launch a persistent kernel.""", gates_md="""**Why these gates, for this task.** This is the one task in the group with a limit of **one** launch, and it is not gratuitous. The word "inline" in the name is the entire specification: the property being graded is that there is no kernel boundary between the store and the load. A limit of 2 would permit exactly the two-kernel append-then-attend that every existing serving stack already ships, and the task would measure nothing. So: `<= 1 kernel/call`, and `>= 0.98` dominant share so that the single launch is also the one doing the work. Two practical notes, because a limit of 1 is unforgiving and the difficulty must come from the kernel rather than from a trap: * **`pos` is already a GPU tensor.** You never need `torch.tensor(...)` or `.item()` inside the timed call, and you should not use them -- a host-to-device copy shows up in the profile as device time and will fail the gate. Everything you need is on the device when the call starts. * **A persistent kernel launched in `build_attn` and signalled by a flag shows 0 launches/call.** That is the ideal design and it passes trivially. If you go that route, define `teardown(handle)` so the daemon exits cleanly. Allocating the output tensor with `torch.empty` is *not* a kernel launch (the caching allocator does not touch the device), so that is safe. **Why `tol` is 1e-2.** Measured, on the graded fixtures over 8 steps and 2 seeds: an independent implementation of the same attention (fp32, chunked online softmax, a different reduction order) differs from the reference by **E = 1.7e-3**, and *every* structural mistake measures **D >= 0.999**. The tolerance is 6x above the floor and 100x below the nearest wrong implementation -- the widest margin in this group, because the appended token carries ~15% of the softmax mass by construction.""", regime_md="""**Regime**: 32 concurrent decode requests, 16384 tokens of context each, 32 query / 8 KV heads, head_dim 128, paged cache with 256-token pages and a shuffled page table. 2.15 GB of KV read per call; the roofline is that divided by the HBM bandwidth you measure. Measured eager torch: 7531 us -- **16.8x** that roofline, because the reference gathers the entire paged cache into a contiguous tensor before it can call an attention kernel at all.""", correctness_md="""All three returned tensors must match the reference within **relative error 1e-2** at every compared step (the comparison takes the worst of the three). What this actually catches, measured on this exact fixture over 8 steps and 2 seeds: | implementation | relative error | |---|---| | **independent fp32 attention, chunked online softmax, different reduction order** | **0.0017** (passes, 6x inside) | | *(the gate)* | *0.01* | | attends over `0..pos-1`, forgetting the appended token | **0.999** | | never appends at all | **1.000** | | attends over only the most recent half of the context | **1.000** | | ignores the page table and reads the pool contiguously | **1.004** | The first line is why the tolerance is 1e-2 and not tighter; the rest are why 1e-2 is not loose -- `tol/E` is 6.0 and `D/tol` is 100. Note that the page table is genuinely load-bearing here in a way it is not in a batch-1 paged task: the pool is shared by all 32 requests, so reading it contiguously reads *another request's* KV rather than a permutation of your own. Use an online (streaming) softmax with a running maximum and rescale, in fp32, and accumulate `p @ V` in fp32. Over 16.4k keys a bf16 accumulator drifts past the bound on its own. The cache is **stateful across calls**: an entry you fail to write at step `i` is still missing at step `i+1`, and the last timed rep is validated, so it will surface.""", precision_md="""`q`, `k_new`, `v_new` and the entire pool are **bfloat16**. K and V arrive already rotated -- there is no RoPE in this task -- and must be stored **as bf16, unmodified**, because the grader reads those bytes back. Scores are `q . k / sqrt(hd)` accumulated in **fp32**; the softmax uses a running max and rescale in fp32; `p @ V` accumulates in fp32. The queries here are deliberately scaled so the softmax over 16k keys is genuinely peaked rather than a flat average -- a flat average would wash out any error in the bulk of the cache and make the correctness gate meaningless. Expect score spreads of a few units, well inside fp32 `exp` range but far outside bf16's.""", perf_md="""`BW` is the HBM bandwidth you measure on the device with a large stream-copy -- never a datasheet figure. The measured rows come from one machine, so read the **x floor** column, not the absolute microseconds. | | us/call | GB/s | x floor | |---|---|---|---| | roofline | 2.15 GB -> divide by `BW` | `BW` | 1.0 | | eager torch (24 launches, gathers the whole cache) | 7531 | 285 | 16.8 | The reference is bad on purpose and in an instructive way: because torch's attention wants contiguous K and V, an unfused paged implementation has to *gather 2.15 GB into a fresh tensor* before it can start. That gather is the entire cost. A real kernel reads the pages where they lie. What actually wins here: * **Split by (request, KV-chunk), not by request.** 32 requests is fewer blocks than the device has SMs (`p.multi_processor_count`), so most of the machine would sit idle. Assign each block a `(request, page-range)` pair, have each produce a partial `(max, sumexp, acc)`, and combine -- inside the same kernel, after a barrier. * **The append is 16 KB and the attention is 2.15 GB.** Do the append first, in a handful of blocks, fence, barrier, then let everyone read. Do not build an elaborate pipeline around 16 KB. * **Get the fence right.** Release semantics (`__threadfence()` / `st.release.gpu`) *after* the page store and *before* arriving at the barrier; acquire on the far side. A plain store plus a barrier built from relaxed atomics is a real race, and on this hardware it will usually appear to work. * **GQA: one KV head serves 4 query heads.** Load a page's `K[h]` once into shared memory and let all 4 query heads consume it. * **Pages are 512 KB and contiguous.** That is a good transfer size -- issue whole-page async copies rather than chasing the page table per token. The table itself is 32 x 65 int32; read it once into shared memory. * **The last page is partial.** `pos` moves by one per call and only occasionally crosses a page boundary; the tail page has between 1 and 256 valid slots and the rest is stale. Bound the loop by `pos`, not by the page size.""", faithfulness_md="""Your kernel must actually append and actually attend. Specifically: * Do **not** return `k_new` / `v_new` as `k_rd` / `v_rd` without writing them into the pool. The next call attends over that slot, the cache is stateful, and the last timed rep is validated -- an unwritten position surfaces as a wrong `out` later even if it slips past `k_rd`. * Do **not** keep a side copy of recently appended tokens and attend over that instead of the pool. The pool is the cache. * Do **not** skip context, subsample keys, or approximate the softmax normalisation. * Do **not** cache outputs across calls: `q`, `k_new` and `v_new` are fresh every call. You may re-layout the pool, reformat or invert the page table, and allocate scratch inside `build_attn`; that is untimed setup. A persistent kernel launched there and signalled by a flag shows 0 launches/call and is the recommended design under a limit of one launch.""", ).validate()