| """megakernel-int4-weight-decode — W4A16 group-quantised 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 int4 |
|
|
| TOL = 1e-1 |
| |
| |
| |
| CFG = dict(layers=28, d=3072, ffn=8192, n_q=24, n_kv=8, hd=128, |
| vocab=128256, eps=1e-5, theta=500000.0, wdtype="int4", group=128) |
|
|
| SPEC = MegaSpec( |
| name="megakernel-int4-weight-decode", |
| unfused_kernels=1236, |
| title="Write a whole-model decode megakernel with int4 group-quantised weights (W4A16)", |
| blurb=("Fuse a 28-layer 3B decoder whose weights arrive as packed 4-bit codes with per-group scales " |
| "and zero points -- the AWQ/GPTQ layout -- into a single persistent GPU kernel. Four bits " |
| "per weight puts the roofline at 400 us, but only if the unpack and the dequantise happen " |
| "in registers between the load and the FMA. Materialise a bf16 copy and you have given the " |
| "whole advantage back."), |
| keywords=["mle", "kernel-generation", "megakernel", "persistent-kernel", "decode", "int4", "awq", |
| "gptq", "quantization", "weight-only", "low-latency"], |
| cfg=CFG, model_src=int4.MODEL_SRC, |
| batch=1, prefill_len=2048, max_seq=4096, decode_steps=32, |
| tol=TOL, |
| bytes_per_step=1_920_133_120, |
| arg_doc=("weights : dict from the reference's make_weights; 2-D weights are (packed, scale, zero)" |
| "\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 |
| |
| Every 2-D weight is a triple `(packed, scale, zero)`: |
| |
| ``` |
| packed : (out, in // 2) uint8 two 4-bit codes per byte, LOW nibble is the EVEN input index |
| scale : (out, in // group) bf16 |
| zero : (out, in // group) uint8 values 0..15 |
| value : (code - zero) * scale with group = cfg["group"] = 128 contiguous input elements |
| ``` |
| |
| This is the standard asymmetric AWQ/GPTQ layout. `/app/reference.py` contains `_deq`, which unpacks and |
| dequantises exactly these bytes -- read it, because your kernel has to reproduce it bit for bit in |
| meaning if not in order. |
| |
| 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: were the fixture fp32 and the |
| quantisation yours, a correct int4 kernel would disagree with the reference by the quantisation error |
| (~0.10 relative on the weights) instead of by its own error.""", |
| 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 28 dicts) | |
| | `weights["embed"]` | `(vocab, d)` logical | int4 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 int4 triples | `in_norm (d,)`, `post_norm (d,)`; `q (24*128, d)`, `k (8*128, d)`, `v (8*128, d)`, `o (d, 24*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, scale, zero)` | `uint8 (out, in//2)`, `bfloat16 (out, in//128)`, `uint8 (out, in//128)` | `value[o, i] = (code[o, i] - zero[o, i//128]) * scale[o, i//128]`, `code` in `0..15` | |
| | `kv_cache` | `list` of 28 `(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, group` (`group` = 128) | |
| | `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 is the single most common way to fail this task, and it fails |
| loudly (relerr ~1), not subtly. |
| |
| `build_model` is untimed. You may repack the weights into any layout you like there -- interleaved |
| nibbles, pre-swizzled for your MMA fragment, scales hoisted into a separate stream. That is exactly |
| what a real W4A16 serving kernel does and it is not cheating. What you may **not** do is dequantise to |
| bf16 once in `build_model` and then stream bf16 in `decode_step`: that is legal, and it will simply |
| lose, because it doubles the bytes you move per token and the reward is throughput.""", |
| correctness_md=CORRECTNESS_MD.format(tol=TOL) + """ |
| |
| The weights carry ~10% 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 simply a model with slightly |
| different weights, and the logits are as well-conditioned as in the bf16 case. |
| |
| **Drop-the-feature margin.** The 1e-1 bound sits **14x** below the cheapest way to get the |
| dequantisation wrong: reusing one group's `(scale, zero)` for a whole output row measures **1.51**, |
| reading the nibbles in the wrong order measures **1.43**, and ignoring the zero point measures |
| **10.2**. See the Precision section for the full table and for where the 1e-1 comes from.""", |
| precision_md="""Weights are **int4 with per-group (scale, zero)**; the KV cache and all activations |
| are **bfloat16** with **fp32 accumulation**. |
| |
| Dequantise as `(code - zero) * scale`, where `code` is the 4-bit unsigned value and `scale`/`zero` are |
| shared by 128 contiguous **input** elements. Note the subtraction happens before the multiply; folding |
| it as `code * scale - zero * scale` is algebraically identical but the second term is a per-group |
| constant you can hoist out of the inner loop. |
| |
| Accumulate in fp32: RMSNorm reductions, the attention softmax, the residual adds, and the GEMV dot |
| products. A dot product of 3072 int4-derived terms accumulated in bf16 loses more than the tolerance |
| allows on its own. |
| |
| Do not quantise the activations. This is weight-only int4 (W4A16): activations stay bf16, which is what |
| the reference does and what the tolerance is calibrated against. |
| |
| **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 single |
| biggest term in the tolerance.** The reference materialises `(code - zero) * scale` as a **bf16** |
| tensor in `build_model`; a kernel that unpacks in registers immediately before the FMA (which is what |
| the performance section tells you to do) never rounds it, and `(code - zero) * scale` needs up to 12 |
| mantissa bits, so the two differ. Measured over 28 layers, that difference alone moves the twin from |
| 0.039 to 0.049. |
| |
| **Where the tolerance comes from (measured, not guessed).** `tol` is `1e-1`. 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 (allocator / cuBLAS algorithm choice) | 1.6e-2 | |
| | fp32 residual + fp32 GEMV, weights dequantised then **rounded to bf16** as the reference does | 4.4e-2 | |
| | **fp32 dequantisation kept in registers, bf16 GEMV, fp32 residual** | **4.6e-2** | |
| | **fp32 dequantisation kept in registers, everything else fp32 too** | **4.9e-2** | |
| | *(the gate)* | *1e-1* | |
| | read the packed nibbles high-first instead of low-first | 1.43 | |
| | one `(scale, zero)` per output row instead of one per group of 128 | 1.51 | |
| | ignore the zero point (treat the quantisation as symmetric) | 10.2 | |
| |
| So **E = 4.9e-2**, **tol = 1e-1 = 2.0x E**, and the cheapest way to get the dequantisation wrong is |
| **14x** the tolerance. The gate previously sat at 7e-2, which is only **1.43x** above a correct |
| register-resident kernel -- it would have rejected the *more precise* implementation, which is the |
| defect this benchmark has hit before. It is an arithmetic gate, not an exactness check.""", |
| perf_md=perf_md( |
| floor_us=400, eager_us=14233, graph_us=5858, |
| lead="""At batch 1 this is **pure weight bandwidth**, and four bits per weight is the whole |
| point: 1.61 GB of packed codes, 75 MB of scales and zeros, 239 MB of KV -- 1.92 GB per token against |
| 6.43 GB if the same model were bf16. The roofline is 400 us and arithmetic intensity is ~1.""", |
| extra=""" |
| * **Unpack in registers, never in memory.** The entire benefit of int4 is that only 4 bits per weight |
| cross HBM. A kernel that expands to bf16 in shared memory has already moved the bytes it was trying |
| to save; expand in the register file, immediately before the FMA. |
| * **Two weights per byte means two FMAs per byte loaded.** Use 128-bit loads (`uint4` / `int4` vector |
| types), unpack 32 codes at a time with shifts and masks, and keep the scale/zero for the group in |
| registers across all 128 of its input elements. |
| * **Scales are 1/128th of the data but on the same critical path.** Load them into shared memory once |
| per output tile; they are reused by every input group of that tile. |
| * **The LM head is 197 MB packed and still 10% of your bytes.** It is quantised like everything else."""), |
| regime_md=("**Regime**: batch 1, 28 layers, `d`=3072, ffn=8192, 24 query / 8 KV heads, head_dim " |
| "128, vocab 128256, tied LM head, **int4 group-128 weights with zero points**. The KV " |
| "cache arrives holding 2048 tokens and you decode 32 more. 1.92 GB moved per token puts " |
| "the floor near 400 us -- a quarter of what the same model costs in bf16."), |
| ).validate() |
|
|