"""megakernel-nvfp4-decode — NVFP4 (e2m1 + per-16 e4m3 block scale) whole-model decode.""" 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 SPEC_MD, CORRECTNESS_MD, perf_md import nvfp4 TOL = 1.1e-1 # MEASURED: 0.0553 for the most precise legitimate implementation (e2m1 # codes dequantised to fp32 in registers rather than rounded to bf16 as # the reference does), over 36 layers and 2 seeds. Was 8e-2, i.e. only # 1.45x that. Cheapest feature-drop D = 1.42, so D/tol = 12.9. CFG = dict(layers=36, d=2560, ffn=9728, n_q=32, n_kv=8, hd=128, vocab=151936, eps=1e-6, theta=1000000.0, wdtype="nvfp4", block=16) SPEC = MegaSpec( name="megakernel-nvfp4-decode", unfused_kernels=1480, title="Write a whole-model decode megakernel with NVFP4 weights", blurb=("Fuse a 36-layer 4B decoder whose weights arrive in NVFP4 -- e2m1 nibbles with an e4m3 " "scale every 16 elements and one fp32 scale per tensor -- into a single persistent GPU " "kernel. The e2m1 ladder is not uniform, so dequantisation is a table lookup rather than a " "multiply, and the block scales are themselves an 8-bit float you have to decode."), keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "decode", "nvfp4", "fp4", "blackwell", "microscaling", "quantization", "low-latency"], cfg=CFG, model_src=nvfp4.MODEL_SRC, batch=1, prefill_len=2048, max_seq=4096, decode_steps=32, tol=TOL, bytes_per_step=2_569_236_480, arg_doc=("weights : dict from the reference's make_weights; 2-D weights are (packed, bscale, gscale)" "\n kv_cache : list of (k, v) per layer, each (B, n_kv, max_seq_len, hd) bf16, prefilled"), spec_md=SPEC_MD + """ ### The weight format NVFP4 is a two-level microscaling format. Every 2-D weight is a triple `(packed, bscale, gscale)`: ``` packed : (out, in // 2) uint8 two e2m1 codes per byte, LOW nibble is the EVEN input index bscale : (out, in // 16) float8_e4m3fn one scale per 16 contiguous input elements gscale : () float32 one scale for the whole tensor value : E2M1[code] * bscale.float() * gscale ``` `e2m1` is 1 sign bit, 2 exponent bits, 1 mantissa bit. Its magnitude ladder is exactly ``` index : 0 1 2 3 4 5 6 7 value : 0.0 0.5 1.0 1.5 2.0 3.0 4.0 6.0 ``` and the nibble is `sign << 3 | magnitude_index`. The ladder is **not uniform** -- the gap is 0.5 below 2.0 and 1.0/2.0 above it -- so decoding a code is a lookup, not an affine map. A 16-entry signed LUT (the 8 magnitudes and their negations) fits in a handful of registers or a 64-byte constant bank and is indexed directly by the nibble. `/app/reference.py` contains `_deq`, which unpacks and dequantises exactly these bytes. The weights are quantised **once, when the fixture is built**, and the reference dequantises those same bytes -- you are graded on your kernel, not on your rounding policy.""", 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 36 dicts) | | `weights["embed"]` | `(vocab, d)` logical | NVFP4 triple | token embedding table; also the **tied** LM head, used as `embed.T`. Quantised like every other matrix | | `weights["final_norm"]` | `(d,)` | `bfloat16` | RMSNorm gain before the LM head; **not** quantised | | `weights["layers"][i]` | 9 entries | 2 norms `bfloat16`, 7 NVFP4 triples | `in_norm (d,)`, `post_norm (d,)`; `q (32*128, d)`, `k (8*128, d)`, `v (8*128, d)`, `o (d, 32*128)`, `gate (ffn, d)`, `up (ffn, d)`, `down (d, ffn)` -- logical shapes, row-major, applied as `h @ W.T` | | every 2-D weight | a **3-tuple** `(packed, bscale, gscale)` | `uint8 (out, in//2)`, `float8_e4m3fn (out, in//16)`, `float32 ()` (0-dim) | `value[o, i] = E2M1[code[o, i]] * bscale[o, i//16].float() * gscale` | | `kv_cache` | `list` of 36 `(k, v)` pairs | `bfloat16` | each tensor `(B, n_kv, max_seq_len, hd)`; 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, block` (`block` = 16) | | `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 | 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. Nibble order matters: `packed[o, i]` holds input index `2i` in its **low** nibble and `2i+1` in its high nibble. Getting this backwards fails loudly (relerr ~1), not subtly. `bscale` is a real `float8_e4m3fn` tensor, not an integer exponent -- you must decode it as an 8-bit float (torch will convert it for you; in CUDA, `__nv_fp8_e4m3` or a 256-entry LUT both work). `build_model` is untimed. Repack, pre-swizzle, interleave the scales with the codes, hoist `bscale * gscale` into a single bf16 per block -- all fine. Dequantising the whole model to bf16 in `build_model` is also legal, and will simply lose: it triples the bytes you move per token and the reward is throughput.""", correctness_md=CORRECTNESS_MD.format(tol=TOL) + """ The weights carry ~9.5% relative quantisation error, but that error is **identical** for you and for the reference because you are both given the same packed bytes. The model is just a model with slightly different weights. **Drop-the-feature margin.** The 1.1e-1 bound sits **13x** below the cheapest way to get the dequantisation wrong: reading the nibbles in the wrong order measures **1.42**, a uniform 3-bit ladder instead of the e2m1 one **1.61**, dropping the per-16 block scale **1.85**, and dropping the per-tensor global scale **2.1e4**. See the Precision section for where 1.1e-1 comes from.""", precision_md="""Weights are **NVFP4**; the KV cache and all activations are **bfloat16** with **fp32 accumulation**. Dequantise as `E2M1[code] * bscale.float() * gscale`. The product `bscale * gscale` is a per-block constant -- compute it once per block, not once per element. Accumulate in fp32: RMSNorm reductions, the attention softmax, the residual adds, and the GEMV dot products. A 2560-term dot product accumulated in bf16 loses more than the tolerance allows. Do not quantise the activations. This is weight-only NVFP4 (W4A16): activations stay bf16, which is what the reference does and what the tolerance is calibrated against. (Real Blackwell NVFP4 GEMMs quantise both sides and use the fp4 tensor cores; that is a different task with a different tolerance, and it is not this one.) **The residual stream may be kept in bf16 or fp32 -- both pass.** **The dequantised weight may be kept in fp32 or rounded to bf16 -- both pass, and this is the largest single term in the tolerance.** The reference materialises `E2M1[code] * bscale * gscale` as a **bf16** tensor in `build_model`; a kernel that expands from the LUT in registers immediately before the FMA -- which is what the performance section tells you to do -- never rounds it. Measured over 36 layers, that difference alone moves the twin from 0.050 to 0.055. **Where the tolerance comes from (measured, not guessed).** `tol` is `1.1e-1`. Measured on the graded fixtures (batch 1, prefill 2048, 8 consecutive steps, 2 weight/token seeds): | implementation | worst relative error | |---|---| | fp32 residual + fp32 GEMV, weights dequantised then **rounded to bf16** as the reference does | 5.0e-2 | | **fp32 LUT dequantisation in registers, bf16 GEMV, fp32 residual** | **5.4e-2** | | **fp32 LUT dequantisation in registers, everything else fp32 too** | **5.5e-2** | | *(the gate)* | *1.1e-1* | | read the packed nibbles high-first instead of low-first | 1.42 | | a uniform 3-bit magnitude ladder instead of `[0, .5, 1, 1.5, 2, 3, 4, 6]` | 1.61 | | ignore the per-16 `bscale` and use the global scale alone | 1.85 | | ignore the per-tensor `gscale` | 2.1e4 | So **E = 5.5e-2**, **tol = 1.1e-1 = 2.0x E**, and the cheapest way to get the dequantisation wrong is **13x** the tolerance. The gate previously sat at 8e-2, only **1.45x** above a correct register-resident kernel -- it would have rejected the *more precise* implementation. This is an arithmetic gate, not an exactness check.""", perf_md=perf_md( floor_us=535, eager_us=19846, graph_us=8333, lead="""At batch 1 this is **pure weight bandwidth**: 2.01 GB of packed e2m1 codes, 251 MB of e4m3 block scales, 307 MB of KV -- 2.57 GB per token, against 8.04 GB for the same model in bf16. Arithmetic intensity is ~1 and the floor is 535 us.""", extra=""" * **The block scales are 12.5% of your traffic.** One e4m3 byte per 8 packed bytes is not a rounding error at this ratio -- they belong in the same coalesced load stream as the codes, not in a separate pass. Interleaving codes and scales in `build_model` so that one 128-bit load brings both is a real and legal win. * **Decode with a LUT, not with arithmetic.** The e2m1 ladder is irregular. A 16-entry signed table in registers, indexed by the nibble, beats any sequence of shifts and selects. * **Two weights per byte means two FMAs per byte loaded.** Use 128-bit vector loads, unpack 32 codes at a time, and keep `bscale * gscale` for the block in a register across all 16 of its elements. * **The tied LM head is 195 MB packed**, ~8% of your bytes, and still one GEMV you cannot launch separately."""), regime_md=("**Regime**: batch 1, 36 layers, `d`=2560, ffn=9728, 32 query / 8 KV heads, head_dim " "128, vocab 151936, tied LM head, **NVFP4 weights (e2m1 + e4m3 scale every 16 + one " "fp32 tensor scale)**. The KV cache arrives holding 2048 tokens and you decode 32 more. " "2.57 GB moved per token puts the floor near 535 us."), ).validate()