"""Prose + architecture shared by the Llama-1B-shaped megakernel pilots. The three pilots differ only in precision (bf16 / fp8) and context length (weight-bound vs KV-bound), so everything else lives here and each spec overrides what it changes. """ LLAMA_1B = dict(layers=16, d=2048, ffn=8192, n_q=32, n_kv=8, hd=64, vocab=128256, eps=1e-5, theta=500000.0, wdtype="bf16") SPEC_MD = """## The computation A standard decoder layer, repeated `layers` times, then a tied LM head. For one decode position `pos`: ``` x = embed[token_ids] for each layer: h = rmsnorm(x, in_norm) q,k,v = h @ Wq.T, h @ Wk.T, h @ Wv.T # q: n_q heads, k/v: n_kv heads (GQA) q,k = rope(q, pos), rope(k, pos) kv_cache[layer].k[:, :, pos] = k # append THIS position kv_cache[layer].v[:, :, pos] = v a = softmax(q @ K[:pos+1].T / sqrt(hd)) @ V[:pos+1] # K/V repeated n_q//n_kv times x = x + a_flat @ Wo.T h = rmsnorm(x, post_norm) x = x + (silu(h @ Wgate.T) * (h @ Wup.T)) @ Wdown.T logits = rmsnorm(x, final_norm) @ embed.T # tied lm_head ``` `/app/reference.py` implements exactly this, unfused, in eager torch. It is the numerical spec, not a performance target — it launches ~628 kernels per step and you are being asked to do it in <= 8. The KV cache arrives **already holding `prefill_len` tokens**; you start decoding at `pos = prefill_len` and append one position per call. There is no prefill to implement.""" CONTRACT_MD = """```python def build_model(weights, kv_cache, cfg, max_seq_len) -> handle # UNTIMED def decode_step(handle, token_ids, pos) -> logits # TIMED def teardown(handle) # OPTIONAL ``` `build_model` is handed all four arguments below. `decode_step` is handed the handle you returned, plus `token_ids` and `pos`. | arg | shape | dtype | meaning | |-----|-------|-------|---------| | `weights` | `dict` | mixed, see rows below | keys: `embed`, `final_norm`, `layers` (a `list` of `cfg["layers"]` dicts) | | `weights["embed"]` | `(vocab, d)` | per `cfg["wdtype"]` | the token embedding table; also the **tied** LM head, used as `embed.T` | | `weights["final_norm"]` | `(d,)` | `bfloat16` | RMSNorm gain before the LM head | | `weights["layers"][i]` | 9 tensors | norms `bfloat16`; the 7 matrices per `cfg["wdtype"]` | `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)` — all row-major, all applied as `h @ W.T` | | `kv_cache` | `list` of `cfg["layers"]` `(k, v)` pairs | `bfloat16` | each tensor `(B, n_kv, max_seq_len, hd)`; slots `[0, prefill_len)` 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` | | `max_seq_len` | scalar | python `int` | 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 | this step's input token, one per sequence | | `pos` | scalar | python `int` | the absolute position this call writes; it advances by 1 per call | **Return** — `decode_step` returns a **single tensor** `logits` of shape `(B, vocab)`, **bf16 or fp32, both accepted** (the grader compares in fp32). `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**: `decode_step` has to append this position's K and V into the very tensors it was given, because the next call attends over them. {wnote} `build_model` is untimed: repack weights, pre-transpose, allocate scratch, launch a persistent kernel, build an instruction schedule — whatever you need.""" BF16_WEIGHTS_NOTE = ("**Weight format.** `cfg[\"wdtype\"]` is `bf16`, so every matrix above is a plain " "`bfloat16` tensor — nothing is quantised and nothing needs unpacking.") CORRECTNESS_MD = """Logits must match the reference within **relative error `{tol}`** (Frobenius norm over the whole `(B, vocab)` tensor) at every compared step. This is a **whole-logit** bound, deliberately not a top-k or argmax check. With seeded random weights the logits are near-uniform, so top-1 and top-2 are frequently near-tied and flip on ordinary numerical noise — measured top-1 agreement between two *correct* implementations is only 0.79-0.92, which would fail honest kernels. Relative error is stable across depth (0.016 at 16 layers, 0.021 at 48) and is what you are held to. Accumulate in fp32 inside each reduction (RMSNorm sums, the attention softmax, GEMV dot products). **The residual stream may be kept in bf16 or fp32 — both pass.** The reference keeps it in bf16, which is what production serving stacks do; a megakernel holding `x` in registers naturally keeps it in fp32. Those two choices differ by a measured 0.016 to 0.031 in final-logit relative error, and the tolerance is set to span both rather than force you to reproduce the reference's exact rounding points.""" PERF_MD = """At batch 1 this is **pure weight bandwidth**. Every decode step streams the entire model through the SMs to do a handful of GEMV-shaped multiplies; arithmetic intensity is ~1, so the floor is `weight_bytes / HBM_bandwidth` and nothing you do to the math matters next to how you move bytes. Measured for the bf16 1B config on one machine. The absolute microseconds are that machine's; the **ratio** is what carries over, and the floor itself is `weight_bytes / (the HBM bandwidth you measure with a large stream-copy)` -- work it out for the device you actually land on. | | us/step | tokens/s | |---|---|---| | weight-bandwidth floor | 515 | 1942 | | eager torch, GPU busy | 2063 | 485 | | eager torch + CUDA Graphs | 2119 | 472 | So there is **~4x** between a graphed torch implementation and the roofline. That gap is what you are competing for, and it exists because a per-op implementation drains and refills the memory pipeline at every one of ~628 kernel boundaries. The whole point of a megakernel is that the pipeline never drains. What actually wins here: * **Persist the grid.** Launch once, size the grid to the SM count, and loop over work inside the kernel. Cross-layer dependencies become grid-wide barriers or atomic counters, not kernel boundaries. * **Overlap weight loads with compute.** The next layer's weights should be in flight (async copy / TMA, double-buffered into shared memory) while the current layer's math runs. This is the single biggest lever — it is what closes the 4x. * **Specialise warps.** Dedicate producer warps to loading and consumer warps to the MMA/FMA work so neither stalls on the other. * **Keep the residual stream resident.** `x` is only `(B, d)`; it should never round-trip to HBM between layers. * **Do not ignore the LM head.** At vocab 128256 it is ~21% of the weight bytes — a fifth of your roofline sits in one GEMV.""" PRECISION_MD = """Weights and the KV cache are **bfloat16**; the reference computes in bf16 with fp32 accumulation, and that is what you must reproduce. Do the accumulation in **fp32**: RMSNorm reductions, the attention softmax, and the residual adds. A bf16 running sum across 16 residual adds drifts past the correctness bound on its own. RoPE is applied in **fp32** on `q` and `k` before the cache write (the reference builds its cos/sin table in fp32), then cast back to bf16 for storage. Storing rotated K in anything wider than bf16 breaks the cache contract.""" # -------------------------------------------------------------------------------------------------- # Shared architecture dicts for the deeper configs. LLAMA_8B = dict(layers=32, d=4096, ffn=14336, n_q=32, n_kv=8, hd=128, vocab=128256, eps=1e-5, theta=500000.0, wdtype="bf16") QWEN3_8B = dict(layers=36, d=4096, ffn=12288, n_q=32, n_kv=8, hd=128, vocab=151936, eps=1e-6, theta=1000000.0, wdtype="bf16") def perf_md(floor_us, eager_us, graph_us, lead="", extra="", toks=1, unit="tokens/s", graph_label="eager torch + CUDA Graphs", bar="CUDA-graphed"): """The standard 'where the performance comes from' section, with MEASURED numbers. floor_us : weight+KV bandwidth roofline eager_us : measured eager-torch wall time per step (python-dispatch bound) graph_us : measured CUDA-graphed torch wall time per step -- the honest bar """ return f"""{lead or '''At batch 1 this is **pure weight bandwidth**. Every decode step streams the entire model through the SMs to do a handful of GEMV-shaped multiplies; arithmetic intensity is ~1, so the floor is `bytes_moved / HBM_bandwidth` and nothing you do to the math matters next to how you move bytes.'''} Measured for this exact config on one machine. The absolute microseconds are that machine's; the **ratio** is what carries over, and you should recompute the floor for the device you actually land on from the byte (or FLOP) count above -- measure HBM bandwidth with a large stream-copy rather than trusting a datasheet figure. | | us/step | {unit} | |---|---|---| | bandwidth floor | {floor_us:.0f} | {toks * 1e6 / floor_us:.0f} | | eager torch (wall) | {eager_us:.0f} | {toks * 1e6 / eager_us:.0f} | | {graph_label} | {graph_us:.0f} | {toks * 1e6 / graph_us:.0f} | Eager wall-clock is python-dispatch bound and is **not** a meaningful baseline. The honest bar is the {bar} number: **{graph_us / floor_us:.1f}x** the roofline. That gap is what you are competing for, and it exists because a per-op implementation drains and refills the memory pipeline at every kernel boundary. The whole point of a megakernel is that the pipeline never drains. What actually wins here: * **Persist the grid.** Launch once, size the grid to the SM count, and loop over work inside the kernel. Cross-layer dependencies become grid-wide barriers or atomic counters, not kernel boundaries. * **Overlap weight loads with compute.** The next layer's weights should be in flight (async copy / TMA, double-buffered into shared memory) while the current layer's math runs. This is the single biggest lever. * **Specialise warps.** Dedicate producer warps to loading and consumer warps to the MMA/FMA work so neither stalls on the other. * **Keep the residual stream resident.** `x` is only `(B, d)`; it should never round-trip to HBM between layers.{extra}"""