"""megakernel-batch4-decode — the same 1B model with four sequences in flight. Batch 4 is the smallest batch at which the inner multiplies stop being GEMVs and become skinny GEMMs, and it is where a real serving stack spends most of its time. The weight traffic is unchanged, so the roofline per *token* drops 4x and the whole task becomes about not wasting the reuse you were handed. """ 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, perf_md TOL = 6e-2 # MEASURED: fp32-twin divergence E = 0.0293 at batch 4 / 16 layers -> tol = 2.05x 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, all four rows compared together). The twin computes the whole forward pass in **fp32** -- fp32 residual stream, fp32 GEMV outputs, RMSNorm written out by hand instead of `F.rms_norm`, RoPE by complex multiply from an fp64 table instead of stack/flatten, 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.0283 - 0.0293** (max over 4 seeds x 8 steps) | | `Z` -- reference vs *itself*, independently allocated fixtures | 0.0 - **0.0067** | | `tol` | **6e-2** = **2.05x** `E` | `Z` is the reference disagreeing with *itself* on bitwise identical weights and KV: a freshly allocated KV cache lands at a different address, `scaled_dot_product_attention` picks a different reduction split, and the 1-ULP difference compounds through 16 layers. Batch 4 averages that noise over four rows, so `Z` is smaller here than at batch 1 (where it reaches 0.023) -- but it is still a floor no implementation can get under.""" 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` | |---|---|---| | drop RoPE | 1.00 | 17x | | attend over only the last 128 KV positions | 1.41 | 24x | | attend over only half the KV history | 1.21 | 20x | | drop the SiLU in the MLP | 1.26 | 21x | | **skip one of the 16 layers** | **0.259** | **4.3x** | The first four are the shortcuts this gate exists to stop and they sit 17-24x outside it. The last is the finest-grained skip possible -- one sixteenth of the model -- and is the binding margin at 4.3x. `E` and that `D` are a factor of 9 apart, so the gate separates "different rounding" from "different model" comfortably, but not much finer than a whole layer.""" SPEC = MegaSpec( name="megakernel-batch4-decode", unfused_kernels=628, title="Write a whole-model decode megakernel (1B, bf16, batch 4)", blurb=("The batched form of the whole-model decode megakernel: four independent sequences decode " "in lockstep through one persistent kernel. The weight stream is shared across all four, so " "the per-token roofline is a quarter of the batch-1 task and the inner multiplies become " "4-row GEMMs -- which is exactly where an unfused implementation wastes the reuse."), keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "decode", "batching", "low-latency", "memory-bound"], cfg=dict(LLAMA_1B), batch=4, prefill_len=2048, max_seq=4096, 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) + """ All four rows are compared together in one Frobenius norm over the `(4, vocab)` logit tensor, so a kernel that is correct for row 0 and drops a row cannot hide inside the average -- a single dead row contributes ~0.5 relative error on its own.""" + DROP_MD, perf_md=perf_md( floor_us=572, eager_us=8247, graph_us=3917, toks=4, lead="""At batch 4 the weight stream is **amortised over four tokens**. The bytes moved per step barely change (2.47 GB of weights, plus 4x the KV), but you get four tokens out of them, so the per-token roofline drops from 529 us to ~143 us. Arithmetic intensity is still only ~4, so this remains a bandwidth problem -- it is just one where throwing away reuse now costs 4x.""", extra=""" * **Load each weight tile once for all four rows.** The single most common mistake at small batch is a kernel that is really four independent GEMVs sharing a launch: it reads `Wgate` four times and performs exactly as badly as batch 1. One load, four accumulators. * **The four sequences share `pos` but not their KV.** Attention is the only part that does not batch into a single GEMM -- each row reads its own cache. Keep the four attention streams independent and let them overlap the shared MLP weight load. * **`(4, d)` still fits in registers.** The residual stream for the whole batch is 4x2048 bf16 = 16 KB; there is no excuse for it to touch HBM between layers."""), regime_md=("**Regime**: **batch 4**, 16 layers, `d`=2048, ffn=8192, 32 query / 8 KV heads, head_dim " "64, vocab 128256, tied LM head. Each of the four sequences has its own KV cache holding " "2048 tokens; all four advance to the same `pos` each step. Reward is tokens/s over the " "whole batch, so the four tokens per step all count."), ).validate()