"""megakernel-llama1b-longctx-decode — 32k context, so KV reads dominate instead of weights.""" import pathlib, sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from spec import MegaSpec from _common import LLAMA_1B, SPEC_MD, CONTRACT_MD, BF16_WEIGHTS_NOTE, CORRECTNESS_MD, PRECISION_MD TOL = 6e-2 # MEASURED: fp32-twin divergence E = 0.0294 at 32k context -> tol = 2.04x E. MEASURED_MD = """ **How this tolerance was measured.** A second, independent implementation of this model was written and compared against the reference on the grader's own fixtures (`make_weights` / `make_kv`, seeds 11/20/21/22, 8 steps each, at the full 32768-token prefill). The twin computes the whole forward pass in **fp32** -- fp32 residual stream, fp32 GEMV outputs, hand-written RMSNorm, RoPE by complex multiply from an fp64 table, and attention by `einsum` with an explicit max-subtract softmax in fp64 instead of `scaled_dot_product_attention` over a `repeat_interleave`d KV -- while still writing **bf16** K/V back into the cache, as the contract requires. | quantity | measured | |---|---| | `E` -- reference vs the independent fp32 twin | **0.0271 - 0.0294** (max over 4 seeds x 8 steps) | | `Z` -- reference vs *itself*, independently allocated fixtures | **0.0** at all four seeds | | `tol` | **6e-2** = **2.04x** `E` | Note that `Z` is exactly 0 here while the 2k-context task shows up to 0.023. At 32k the attention reduction is large enough that `scaled_dot_product_attention` selects the same split regardless of where the cache was allocated, so the reference is reproducible. Do not read that as "the softmax is exact" -- it means the *reference* is stable, not that your attention has to match it bit for bit. Summing 32768 terms is precisely where a different (and better) online-softmax split is expected, and `E` above is measured with exactly such a split.""" DROP_MD = """ **Drop-the-feature margins**, measured on the same fixtures; each variant is identical to the reference except for one deleted behaviour: | variant | relative error | x `tol` | |---|---|---| | attend over only the last 128 KV positions | 1.43 | 24x | | drop the SiLU in the MLP | 1.29 | 21x | | attend over only half the 32k history | 0.626 | 10x | | drop RoPE | 0.400 | 6.7x | | **skip one of the 16 layers** | **0.253** | **4.2x** | Two of these are notably *smaller* than in the short-context task, and for an instructive reason: with 32768 cached tokens the attention output is an average over so many values that truncating half the history or removing the positional rotation both move it less than they do at 2k. Truncating the KV is the shortcut this task most needs to catch, and at 10-24x outside the gate it is caught. The one-layer skip is again the binding margin at 4.2x; `E` and that `D` are a factor of 8.6 apart.""" SPEC = MegaSpec( unfused_kernels=628, name="megakernel-llama1b-longctx-decode", title="Write a whole-model decode megakernel (1B, 32k context, batch 1)", blurb=("The long-context form of the whole-model decode megakernel. At 32k of KV the bottleneck " "flips: reading the cache costs more per token than reading the weights, so the fusion has " "to keep the attention streaming while the MLP weights load. A different balance from the " "short-context case, and a different kernel."), keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "decode", "long-context", "kv-cache", "memory-bound"], cfg=dict(LLAMA_1B), batch=1, prefill_len=32768, max_seq=33024, decode_steps=32, tol=TOL, spec_md=SPEC_MD, contract_md=CONTRACT_MD.format(wnote=BF16_WEIGHTS_NOTE), precision_md=PRECISION_MD + MEASURED_MD, correctness_md=CORRECTNESS_MD.format(tol=TOL) + DROP_MD, perf_md="""At 32k of context the arithmetic is still trivial but the **balance has flipped**. Per decode step you read ~2.47 GB of weights *and* the KV cache: 16 layers x 8 KV heads x 32768 positions x 64 dims x 2 tensors (K and V) x 2 bytes is ~1.07 GB. Attention is now ~30% of your traffic rather than a rounding error, and the roofline moves from 529 us to ~739 us. That changes what the megakernel has to do. The short-context version can treat attention as a small interlude between big weight loads; here the two are comparable, and the win comes from **overlapping them** -- streaming the KV for layer `i` while the MLP weights for layer `i` are still arriving, so neither pipeline sits idle. Specific levers: * **Split the KV read across the persistent grid** and combine partial attention outputs with an online-softmax merge (running max + rescaled running sum), so no block needs the whole cache. * **Never materialise the repeated KV.** GQA gives 32 query heads over 8 KV heads; expanding to 32 is 4x the traffic for zero information. Have four query heads share one KV load in registers. * **Keep the weight pipeline running through the attention.** The layer's `Wo`, `Wgate`, `Wup`, `Wdown` do not depend on the attention result until the very end -- start those loads early. * The LM head is still ~525 MB and still ~11% of the traffic here.""", regime_md=("**Regime**: batch 1, 16 layers, `d`=2048, 32 query / 8 KV heads, head_dim 64, vocab " "128256. The KV cache arrives holding **32768** tokens and you decode 32 more. KV " "traffic (~1.07 GB/step) is now ~30% of the ~2.47 GB of weight traffic -- budget for " "both; the floor is ~739 us."), ).validate()