| """megakernel-mtp-decode — main model + a DeepSeek-V3-style multi-token-prediction head, fused.""" |
| 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 mtp |
|
|
| TOL = 8e-2 |
| |
| CFG = dict(LLAMA_1B) |
|
|
| SPEC = MegaSpec( |
| name="megakernel-mtp-decode", |
| unfused_kernels=684, |
| title="Write a whole-model decode megakernel with a multi-token-prediction head", |
| blurb=("Fuse a 16-layer decoder AND a DeepSeek-V3-style MTP module into one persistent kernel. The " |
| "main model emits logits for the next token; the MTP head takes the same final hidden state " |
| "plus the following token's embedding, projects 2d->d, runs one more decoder block against " |
| "its own KV cache, and emits logits two tokens ahead. Both are graded, both share the tied " |
| "head, and the step stops being a straight line."), |
| keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "decode", "mtp", |
| "multi-token-prediction", "speculative-decoding", "low-latency"], |
| cfg=CFG, model_src=mtp.MODEL_SRC, |
| batch=1, prefill_len=2048, max_seq=4096, decode_steps=32, |
| tol=TOL, |
| bytes_per_step=2_682_346_144, |
| step_sig="handle, token_ids, next_token_ids, pos", |
| step_ret="(logits0, logits1)", |
| step_doc=("One decode step plus one MTP step; append `pos` into all layers+1 caches." |
| "\n\n token_ids : (B,) int64 the current token" |
| "\n next_token_ids : (B,) int64 the token that follows it" |
| "\n pos : int absolute position being written" |
| "\n returns : (logits0, logits1), each (B, vocab)\n "), |
| arg_doc=("weights : dict from the reference's make_weights, including a `mtp` sub-module" |
| "\n kv_cache : list of layers+1 (k, v) pairs -- the extra one is the MTP block's"), |
| spec_md="""## The computation |
| |
| The main model is the standard 16-layer decoder. The MTP module is appended to it: |
| |
| ``` |
| x = embed[token_ids] |
| for each of the 16 layers: |
| x = decoder_block(x, kv_cache[layer], pos) # rmsnorm/QKV/rope/append/attend/o + rmsnorm/SwiGLU |
| logits0 = rmsnorm(x, final_norm) @ embed.T # prediction for the NEXT token |
| |
| # --- MTP module ----------------------------------------------------------------------------------- |
| he = rmsnorm(embed[next_token_ids], mtp.enorm) # the following token, embedded and normed |
| hh = rmsnorm(x, mtp.hnorm) # the main model's hidden state, BEFORE final_norm |
| xm = concat([hh, he]) @ mtp.proj.T # (B, 2d) -> (B, d) |
| xm = decoder_block(xm, kv_cache[16], pos) # one more full block, its OWN KV cache |
| logits1 = rmsnorm(xm, final_norm) @ embed.T # prediction TWO tokens ahead, SAME tied head |
| return logits0, logits1 |
| ``` |
| |
| `/app/reference.py` implements exactly this, unfused, in eager torch. |
| |
| Note `hh` normalises `x` *before* `final_norm` is applied -- `logits0` and the MTP module read the same |
| hidden state through two different norms. Getting that wrong is a silent factor-of-scale error, so read |
| the reference. |
| |
| ### Why `next_token_ids` is an input |
| |
| In real generation the MTP module is fed the token sampled from `logits0`. Sampling from a random-weight |
| model's near-uniform logits is an argmax coin flip -- two correct implementations pick different tokens |
| and then disagree about everything downstream. This family gates on relative error precisely to avoid |
| that class of failure, so the second token is supplied as data and the step is deterministic. |
| |
| ### What makes this a different fusion problem |
| |
| The step is no longer a chain. `x` feeds three consumers: `final_norm` (for `logits0`), `mtp.hnorm` |
| (for the projection), and nothing else -- and the tied embedding matrix is read by *two* GEMVs, the |
| `logits0` head and the `logits1` head, separated by an entire decoder block. |
| |
| A per-op implementation writes `x` to HBM and reads it twice, and streams the 525 MB embedding matrix |
| twice. A fused one keeps `x` in registers and, if it is clever, keeps the head resident across the MTP |
| block so the 525 MB crosses HBM once. That single decision is ~20% of the roofline.""", |
| contract_md="""```python |
| def build_model(weights, kv_cache, cfg, max_seq_len) -> handle # UNTIMED |
| def decode_step(handle, token_ids, next_token_ids, pos) -> (logits0, logits1) # TIMED |
| def teardown(handle) # OPTIONAL |
| ``` |
| |
| `build_model` is handed all four arguments below. `decode_step` is handed the handle you returned, plus |
| `token_ids`, `next_token_ids` and `pos`. |
| |
| | arg | shape | dtype | meaning | |
| |-----|-------|-------|---------| |
| | `weights` | `dict` | `bfloat16` throughout | keys: `embed`, `final_norm`, `layers` (16 dicts), `mtp` | |
| | `weights["embed"]` | `(vocab, d)` = `(128256, 2048)` | `bfloat16` | **tied**: gathered at the top, used as `embed.T` by **both** heads at the bottom | |
| | `weights["final_norm"]` | `(d,)` | `bfloat16` | applied before **both** heads | |
| | `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`. 16 of them | |
| | `weights["mtp"]` | `dict` | `bfloat16` | `enorm (d,)`, `hnorm (d,)`, `proj (d, 2*d)`, and `block`, one more full layer dict of the same 9 tensors. `proj` consumes `concat([hnorm(x), enorm(embed[next])], dim=-1)` in **that order** | |
| | `kv_cache` | `list` of **17** `(k, v)` pairs | `bfloat16` | each tensor `(B, n_kv, max_seq_len, hd)`; indices 0..15 are the main layers, index **16** is the MTP block. Slots `[0, 2048)` hold the prefix, the rest are zero | |
| | `cfg` | `dict` | python `int` / `float` / `str` | `layers, d, ffn, n_q, n_kv, hd, vocab, eps, theta, wdtype` (`layers` = 16, i.e. it does **not** count the MTP block) | |
| | `max_seq_len` | scalar | python `int` | `4096` -- the allocated time capacity of every cache, exactly `kv_cache[i][0].shape[2]`. `pos < max_seq_len` always holds, so a RoPE table of this length covers the whole run | |
| | `token_ids` | `(B,)` | `int64`, on the GPU | the current token | |
| | `next_token_ids` | `(B,)` | `int64`, on the GPU | the token after it -- the MTP module's second input. It is **given**, not sampled from `logits0` | |
| | `pos` | scalar | python `int` | the absolute position this call writes into **all 17** caches; it advances by 1 per call | |
| |
| **Return** -- `decode_step` returns a **2-tuple** `(logits0, logits1)` **in that order**: `logits0` is |
| the main model's next-token prediction and `logits1` is the MTP module's two-ahead prediction, each |
| `(B, vocab)`, **bf16 or fp32, both accepted** (the grader compares in fp32). **Both** are compared and |
| the worse of the two relative errors is the one that gates. `build_model` returns an opaque handle of |
| any type; the grader never inspects it and only passes it back to `decode_step`. |
| |
| `weights` and `cfg` are **read-only**. `kv_cache` is the one thing you must update **in place**, in all |
| 17 entries, because the next call attends over them. |
| |
| `build_model` is untimed: repack weights, pre-transpose, allocate scratch, launch a persistent kernel, |
| build an instruction schedule -- whatever you need. `decode_step` must append K/V for `pos` into all 17 |
| caches, because the next call attends over them.""", |
| correctness_md=CORRECTNESS_MD.format(tol=TOL).replace( |
| "over the whole `(B, vocab)` tensor", |
| "over each of the two `(B, vocab)` tensors, worst of the two") + """ |
| |
| The 8e-2 bound is measured for this config, and it is looser than the 5e-2 of the plain 1B decode task |
| for a specific reason: `logits1` sits behind 17 blocks *and* a 2d->d projection of two separately-normed |
| inputs, so it inherits and amplifies the main model's divergence. |
| |
| Both heads are checked, so you cannot pass by computing `logits0` correctly and returning garbage for |
| `logits1`; the gate takes the worse of the two. Measured, returning `logits0` twice scores **1.43** |
| and normalising after the concatenation instead of before scores **0.84** -- see the Precision |
| section for the full table and for where 8e-2 comes from.""", |
| precision_md=PRECISION_MD + """ |
| |
| The MTP projection consumes `concat([rmsnorm(x, hnorm), rmsnorm(embed[next], enorm)])`. Both halves are |
| normalised **separately** and then concatenated -- not normalised after concatenation. Accumulate the |
| `2d`-wide dot product in fp32. |
| |
| **Where the tolerance comes from (measured, not guessed).** `tol` is `8e-2`, applied to the *worse* of |
| the two logit tensors. Measured on the graded fixtures (batch 1, prefill 2048, 8 consecutive steps, |
| 2 weight/token seeds): |
| |
| | implementation | worst relative error | |
| |---|---| |
| | the reference against an independently *built* copy of itself | **0.0** (bit-identical -- bf16 weights need no dequantisation, so there is no allocator noise) | |
| | all-fp32 twin: residual, GEMVs and attention softmax in fp32 | 3.0e-2 | |
| | **bf16 GEMVs + fp32 residual, hand-rolled attention** | **3.2e-2** | |
| | *(the gate)* | *8e-2* | |
| | normalise after the concatenation instead of before | 8.4e-1 | |
| | skip attention in all 17 blocks | 1.25 | |
| | return `logits0` for both heads (no MTP block at all) | 1.43 | |
| |
| So **E = 3.2e-2**, **tol = 8e-2 = 2.5x E**, and the cheapest feature-drop is **10.5x** the tolerance. |
| This is an arithmetic gate; bf16 and fp32 residual streams both pass. |
| |
| **One thing this gate cannot see**, quantified so you do not have to guess: at batch 1 over a |
| 2048-token cache of random KV, one block's attention output is ~1% of its residual stream, so skipping |
| the attention *of the MTP block alone* moves `logits1` from 2.5e-2 to 2.8e-2 -- inside the noise. It |
| takes dropping the attention of all 17 blocks (1.25) for the gate to see it. Attention is graded in |
| aggregate, not per block, and the faithfulness rules below are not optional just because a single |
| block's contribution is small.""", |
| perf_md=perf_md( |
| floor_us=559, eager_us=8963, graph_us=3050, |
| lead="""At batch 1 this is **pure weight bandwidth**, with one twist: the tied embedding matrix |
| is used by two heads. Per step you move 1.95 GB of main-layer weights, 122 MB for the MTP block, 17 MB |
| for the projection, 525 MB of tied head, and 72 MB of KV -- 2.68 GB if the head crosses HBM **once**, |
| 3.21 GB if it crosses twice. That 20% is decided entirely by whether the two heads share a load.""", |
| extra=""" |
| * **Read the head once.** `logits0` and `logits1` multiply the same 525 MB matrix by two different |
| vectors, separated by one decoder block. A persistent kernel can hold `x_final0` in registers, run |
| the MTP block, and then stream the head once computing both dot products per tile. This is the single |
| biggest lever in the task and it is invisible to any per-op implementation. |
| * **`x` has two consumers; keep it in registers.** It is `(B, 2048)`. There is no reason for it to |
| touch HBM. |
| * **The MTP block is a 17th layer with a different input.** Everything you built for the main loop |
| applies, so do not write a second code path for it -- write one block routine and call it 17 times. |
| * **The 17th KV cache is the same shape as the others.** Its append is on the critical path of |
| `logits1` and nothing else."""), |
| regime_md=("**Regime**: batch 1, 16 main layers + 1 MTP block, `d`=2048, ffn=8192, 32 query / 8 KV " |
| "heads, head_dim 64, vocab 128256, tied LM head used **twice**. 17 KV caches, each " |
| "arriving with 2048 tokens; you decode 32 more. ~2.68 GB per token puts the floor near " |
| "559 us -- if you read the head once."), |
| ).validate() |
|
|