"""persistent-layer-fused-decode -- one whole transformer layer, one launch.""" 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 fused_layers CFG = dict(layers=1, d=8192, ffn=28672, n_q=64, n_kv=8, hd=128, eps=1e-5, theta=500000.0, wdtype="bf16") PF, DS = 4096, 32 WB = (CFG["n_q"] * CFG["hd"] * CFG["d"] + 2 * CFG["n_kv"] * CFG["hd"] * CFG["d"] + CFG["d"] * CFG["n_q"] * CFG["hd"] + 3 * CFG["ffn"] * CFG["d"]) * 2 KVB = 2 * 1 * CFG["n_kv"] * (PF + DS) * CFG["hd"] * 2 SPEC = MegaSpec( name="persistent-layer-fused-decode", family="e2", title="Fuse one entire transformer decoder layer into a single kernel launch", blurb=("RMSNorm, GQA QKV projection, RoPE, KV append, attention over 4k tokens, output projection, " "residual, second RMSNorm, 28672-wide SwiGLU MLP, residual -- about 40 operations and " "1.71 GB of weights, in one launch. This is the unit cell of a whole-model megakernel: get " "it right and a 16-layer megakernel is this plus a schedule. Graded on tokens/s."), keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "decode", "gqa", "swiglu", "rmsnorm", "rope", "memory-bound"], cfg=CFG, model_src=fused_layers.src("build_layer", "layer_step"), batch=1, prefill_len=PF, max_seq=4224, decode_steps=DS, correct_steps=8, prof_steps=4, tol=1.5e-2, max_kernels_per_step=2.0, min_dominant_share=0.95, bytes_per_step=WB + KVB, reward_metric="tokens/s", reward_work=1.0, entry_build="build_layer", entry_step="layer_step", step_sig="handle, x, pos", step_ret="x_out", step_doc=("Run the layer on one hidden state; append this position's K/V into the cache." "\n\n x : (B, d) bf16 the incoming residual stream" "\n pos : int the absolute position being written" "\n returns : (B, d) the residual stream after the layer\n "), arg_doc=("weights : dict with `layers[0]` holding `in_norm, post_norm, q, k, v, o, gate, up, down`" "\n kv_cache : list of one (k, v), each (B, n_kv, max_seq_len, hd) bf16, prefilled"), unfused_kernels=43, intro_md="""This is the unit cell. A whole-model megakernel is one of these repeated 16 to 80 times with a schedule wrapped around it, and almost everything that is hard about the whole-model version is already hard here: a norm whose reduction gates every downstream output, a GQA attention that has to share a KV head across 8 query heads, a cache write that the very next operation reads, and a 705 MB MLP that has to stream while the attention's registers are still live. One layer, one launch. Roughly 40 fusable operations and 1.71 GB of weights.""", spec_md="""## The computation One standard decoder layer, for a single decode position `pos`: ``` h = rmsnorm(x, in_norm) # reduction over d = 8192 q = h @ Wq.T -> (B, 64, hd) # 64 query heads k = h @ Wk.T -> (B, 8, hd) # 8 KV heads (GQA, rep = 8) v = h @ Wv.T -> (B, 8, hd) q, k = rope(q, pos), rope(k, pos) kv_cache.k[:, :, pos] = k # append THIS position kv_cache.v[:, :, pos] = v a = softmax(q @ K[:pos+1].T / sqrt(hd)) @ V[:pos+1] # K/V shared by 8 query heads each x = x + a_flat @ Wo.T h = rmsnorm(x, post_norm) x = x + (silu(h @ Wgate.T) * (h @ Wup.T)) @ Wdown.T # ffn = 28672 return x ``` `d` = 8192, `ffn` = 28672, 64 query / 8 KV heads, head_dim 128 -- one layer of a 70B-class model. The KV cache arrives holding 4096 tokens and you append one per call, so by the end of a timed run the attention covers 4128 keys. `/app/reference.py` implements exactly this, unfused, in eager torch: 43 kernel launches per call. Note there is no embedding and no LM head. The input is a hidden state and the output is a hidden state; the layer is the whole task.""", contract_md="""```python def build_layer(weights, kv_cache, cfg, max_seq_len) -> handle # UNTIMED def layer_step(handle, x, pos) -> x_out # TIMED def teardown(handle) # OPTIONAL ``` `build_layer` is handed all four arguments below. `layer_step` is handed the handle you returned, plus `x` and `pos`. | arg | shape | dtype | meaning | |-----|-------|-------|---------| | `weights` | `dict` | `bfloat16` | exactly one key, `layers`, holding a list of **one** dict. There is **no** embedding and **no** LM head in this task | | `weights["layers"][0]` | 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`. With `d`=8192, `ffn`=28672, `n_q`=64, `n_kv`=8, `hd`=128 | | `kv_cache` | `list` of **1** `(k, v)` pair | `bfloat16` | each tensor `(B, n_kv, max_seq_len, hd)`; slots `[0, 4096)` hold the prefix, the rest are zero | | `cfg` | `dict` | python `int` / `float` / `str` | `layers` = 1, `d, ffn, n_q, n_kv, hd, eps, theta, wdtype` | | `max_seq_len` | scalar | python `int` | `4224` -- the allocated time capacity of the cache, exactly `kv_cache[0][0].shape[2]`. `pos < max_seq_len` always holds, so a RoPE table of this length covers the whole run | | `x` | `(B, d)` = `(1, 8192)` | `bfloat16`, on the GPU | the incoming residual stream, fresh every call | | `pos` | scalar | python `int` | the absolute position to write; it advances by 1 per call | **Return** -- `layer_step` returns a **single tensor** `x_out` of shape `(B, d)` = `(1, 8192)`, the residual stream after the layer, **bf16 or fp32, both accepted** (the grader compares in fp32). `build_layer` returns an opaque handle of any type; the grader never inspects it and only passes it back to `layer_step`. `weights`, `cfg` and `x` are **read-only**. `kv_cache` is the one thing you must update **in place**: you **must** write K and V for `pos` into the cache you were given, because the next call attends over it and the timed run is validated at the end, so an unwritten position surfaces as a wrong answer later. `build_layer` is untimed: repack weights, fuse Q/K/V into one matrix, build the RoPE tables, allocate scratch, launch a persistent kernel.""", gates_md="""**Why these gates, for this task.** Here the tight kernel-count gate is exactly right, with none of the caveats that apply to the smaller primitives in this group. A decoder layer is ~40 distinct operations with a data dependency between almost every consecutive pair; the reference launches 43 kernels, and there is no natural implementation that lands between "fused" and "one kernel per op". Setting the limit at 2 means the norm, both projections, RoPE, the cache write, the attention, the output projection, both residuals and the whole MLP happen without the activation ever going back to HBM -- which is the definition of the thing being asked for. CUDA Graphs do not help: a graph replays 40 nodes. Dominant share >= 0.95 closes the obvious loophole in the count. The two natural "two big kernels" splits are attention-then-MLP and QKV-then-rest. The MLP is 705 M of the 856 M parameters, so an attention/MLP split gives a dominant share of about 0.82 by weight bytes and fails; a QKV/rest split fails harder. 0.95 leaves room only for a genuinely trivial second launch, such as zeroing a barrier flag. **Why the reward is tokens/s.** One call is one decoded token for one sequence, so tokens/s is the literal, directly comparable serving metric, and it makes this task's number commensurable with the whole-model megakernel tasks (which are the same metric on the same hardware). **Why `tol` is 1.5e-2.** Measured: the reference keeps the residual stream in bf16, which is what production serving stacks do; a megakernel holding `x` in registers naturally keeps it in fp32. Those differ by 0.0038 here. The tolerance is ~4x that, tighter than the whole-model tasks' 5e-2 because there is only one layer of accumulation.""", regime_md="""**Regime**: batch 1, one layer, `d` = 8192, `ffn` = 28672, 64 query / 8 KV heads, head_dim 128 -- a 70B-class layer. 856 M parameters = 1.71 GB, plus 17 MB of KV read at the deepest position, so the roofline is that 1.73 GB divided by the HBM bandwidth you measure, and the whole thing is weight bandwidth. Measured eager torch: 770 us, i.e. 2.25 TB/s and **2.14x** that roofline.""", correctness_md="""The returned `(B, d)` residual stream must match the reference within **relative error 1.5e-2** at every compared step, and the KV cache must contain what the reference's cache contains -- not because it is compared directly, but because the next call attends over it and the final timed step is validated. Accumulate in fp32 inside every reduction: the RMSNorm sums, the attention softmax (running max + rescale), and all six GEMV dot products. **The residual stream may be kept in bf16 or fp32 -- both pass.** Measured difference between those two choices: 0.0038.""", precision_md="""Weights and the KV cache are **bfloat16**; compute in bf16 with **fp32 accumulation**. RoPE is applied in **fp32** on `q` and `k` before the cache write -- the reference builds its cos/sin table in fp32 -- and `k` is cast back to bf16 for storage. Storing rotated K in anything wider than bf16 breaks the cache contract, because the reference will read those bytes back as bf16 next call. The attention softmax must use a running maximum and rescale in fp32. At 4128 keys a naive `exp` of raw scores is fine numerically, but the accumulation of `p @ V` in bf16 is not. `eps` = 1e-5 goes inside the square root of the RMSNorm: `x * rsqrt(mean(x^2) + eps)`.""", perf_md="""At batch 1 this is pure weight bandwidth: 1.71 GB streamed to produce 8192 numbers. `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 | tokens/s | x floor | |---|---|---|---| | roofline | 1.73 GB -> divide by `BW` | -- | 1.0 | | eager torch (43 launches) | 770 | 1299 | 2.14 | 2.1x is a smaller gap than the whole-model tasks show, and that is honest: with only 43 launches the per-op overhead is a smaller fraction than it is at 628. What is left is real -- pipeline drain at every boundary, the intermediate `(1, 28672)` SwiGLU activation round-tripping through HBM, and the `q/k/v` triple being read as three separate passes over the same `h`. What actually wins here: * **Fuse Q, K and V into one pass.** They share the same input `h` and their weight matrices can be concatenated in `build_layer` into a single `(n_q*hd + 2*n_kv*hd, d)` matrix. One pass, one set of accumulators. * **Never materialise the SwiGLU intermediate.** `silu(gate@h) * (up@h)` is `(1, 28672)`; produce a block of it, immediately consume it into the `down` accumulation, discard. This alone removes two full HBM trips. * **The attention is tiny; treat it as such.** 4128 keys x 8 KV heads x 128 = 8.5 MB of KV against 1.71 GB of weights. Give it a small slice of the grid and overlap it with the MLP weight loads rather than letting the whole grid stall on a 0.5% workload. * **GQA means the KV head is read once for 8 query heads.** Load `K[h]` into shared memory and let 8 query heads consume it; loading per query head is an 8x mistake on the KV side. * **Keep `x` resident.** The residual stream is 8192 numbers -- 16 KB. It should live in registers or shared memory from the first residual add to the last. * **The MLP is 82% of your bytes.** Whatever you do about the attention, the score is decided by how well `gate`, `up` and `down` stream.""", ).validate()