| """Spec for `comba-decode-step` — one Comba recurrent step (decoupled read key p) over a decode batch.""" |
| import pathlib |
| import sys |
|
|
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) |
| from spec import TaskSpec |
|
|
| SPEC = TaskSpec( |
| name="comba-decode-step", |
| title="Write a fast Comba decode-step (single-token state update) kernel", |
| blurb=("This is what a Comba layer runs at every generated token: ONE gated delta-rule recurrent step " |
| "with a DECOUPLED read key — the state correction is read with p while the write still uses k — " |
| "applied to every sequence in the decode batch at once. No chunking and no WY transform: it is a " |
| "pure bandwidth problem over the (K, V) recurrent state, which for a large decode batch is a " |
| "gigabyte of HBM traffic per layer per token."), |
| keywords=["mle", "kernel-generation", "comba", "decode", "linear-attention", "delta-rule", |
| "memory-bound", "gpu"], |
| module="comba_step.py", |
| func="comba_decode_step", |
| signature="comba_decode_step(state, q, k, v, p, beta, g, scale=None)", |
| returns_doc="""One Comba decode step, batched over B sequences. |
| |
| Args: |
| state: (B, H, K, V) float32 — the recurrent state carried in from the previous token. |
| q: (B, H, K) bfloat16 — this token's query. |
| k: (B, H, K) bfloat16 — this token's WRITE key (L2-normalised along K). |
| v: (B, H, V) bfloat16 — this token's value. |
| p: (B, H, K) bfloat16 — this token's READ key (L2-normalised along K). |
| beta: (B, H) bfloat16 — delta-rule step size in (0, 1). |
| g: (B, H) float32 — this token's SCALAR log-decay (<= 0); exp(g) is the gate. |
| scale: float or None — query scale; None means K ** -0.5. |
| |
| Returns: |
| (state_new, o) where |
| state_new: (B, H, K, V) float32 — the NEW state (functional; `state` is not modified) |
| o: (B, H, V) bfloat16/float32 — this token's output""", |
|
|
| reference_imports="import torch", |
| reference_src=''' |
| def comba_decode_step(state, q, k, v, p, beta, g, scale=None): |
| """One Comba recurrent step, written out in fp32. |
| |
| Correct and simple — it is the numerical SPECIFICATION, not a performance target. |
| """ |
| K = q.shape[-1] |
| if scale is None: |
| scale = K ** -0.5 |
| q, k, v, p, beta, g = [x.float() for x in (q, k, v, p, beta, g)] |
| |
| S = state.float() * g.exp()[..., None, None] # scalar forget gate on the whole state |
| u = (v - (S * p.unsqueeze(-1)).sum(-2)) * beta.unsqueeze(-1) # correction, read with p (NOT with k) |
| S = S + k.unsqueeze(-1) * u.unsqueeze(-2) # rank-1 write, using k |
| o = (S * (q * scale).unsqueeze(-1)).sum(-2) # readout from the UPDATED state |
| return S, o |
| ''', |
| make_inputs_src=''' |
| _WARMUP = 16 # decode steps run from a zero state, so `state` has realistic decode-time magnitudes |
| |
| |
| def _mk(B, H, K, V, seed): |
| import torch.nn.functional as F |
| gen = torch.Generator(device="cuda").manual_seed(seed) |
| |
| def _token(): |
| q = torch.randn(B, H, K, device="cuda", dtype=torch.bfloat16, generator=gen) |
| k = F.normalize(torch.randn(B, H, K, device="cuda", generator=gen), dim=-1).to(torch.bfloat16) |
| v = torch.randn(B, H, V, device="cuda", dtype=torch.bfloat16, generator=gen) |
| p = F.normalize(torch.randn(B, H, K, device="cuda", generator=gen), dim=-1).to(torch.bfloat16) |
| beta = torch.rand(B, H, device="cuda", generator=gen).sigmoid().to(torch.bfloat16) |
| g = (F.logsigmoid(torch.randn(B, H, device="cuda", generator=gen)) / 4.0).to(torch.float32) |
| return q, k, v, p, beta, g |
| |
| state = torch.zeros(B, H, K, V, device="cuda", dtype=torch.float32) |
| for _ in range(_WARMUP): |
| state = _ref(state, *_token())[0] |
| return (state, *_token()) |
| ''', |
| flops_src=''' |
| def canonical_work(B, H, K, V): |
| """BYTES moved by one Comba decode step, from the SHAPE ALONE. |
| |
| The state dominates and is unavoidable: (B, H, K, V) fp32 read once and written once. Everything else is |
| one token's worth of activations per (b, h): q, k and p (bf16, K each), v (bf16, V), beta (bf16) and the |
| scalar log-gate g (fp32), and the output o (bf16, V). At K = V = 128 the state is 99.1% of this number. |
| Score = this byte count / your runtime, i.e. achieved HBM bandwidth. |
| """ |
| state = 2 * B * H * K * V * 4 |
| token = B * H * (2 * K + 2 * K + 2 * K + 2 * V + 2 + 4 + 2 * V) |
| return state + token |
| ''', |
| flops_formula="""bytes = 2 * B*H*K*V * 4 # fp32 state: read once + written once (>= 99% of the traffic) |
| + B*H * (6*K + 4*V + 6) # one token in: q, k, p, v, beta, g and one token out: o""", |
|
|
| metric="GB/s", |
| compare="tuple", |
| tuple_names=("state_new", "o"), |
| tol=2e-2, |
| shape_names=("B", "H", "K", "V"), |
| grader_shapes=[(1024, 16, 128, 128), (512, 32, 128, 128), (2048, 8, 128, 128), |
| (1536, 16, 64, 128), (768, 24, 128, 128)], |
| measure_shapes=[(896, 16, 128, 128), (448, 32, 128, 128), (1792, 8, 128, 128), |
| (1280, 16, 64, 128), (640, 24, 128, 128)], |
| measure_quick_shapes=[(256, 16, 128, 128), (128, 32, 128, 128), (512, 16, 64, 128)], |
| correct_shapes=[(8, 4, 128, 128), (16, 2, 64, 128), (4, 8, 128, 64), (32, 4, 64, 64)], |
|
|
| spec_md="""One step of the Comba recurrence, for every `(b, h)` independently. `S` is the incoming |
| `state[b, h]` of shape `(K, V)`: |
| |
| ``` |
| S = exp(g) * S # scalar forget gate on the whole state |
| u = beta * ( v - S^T p ) # correction, read with p (NOT with k) |
| S_new = S + k u^T # rank-1 write, using k |
| o = S_new^T (scale * q) # readout, from the UPDATED state |
| ``` |
| |
| `scale` defaults to `K ** -0.5` and multiplies `q` only. Written out elementwise, with `i` indexing `K` and |
| `j` indexing `V`: |
| |
| ``` |
| S[i, j] <- exp(g) * state[i, j] |
| u[j] = beta * ( v[j] - sum_i p[i] * S[i, j] ) |
| S_new[i, j] = S[i, j] + k[i] * u[j] |
| o[j] = sum_i (scale * q[i]) * S_new[i, j] |
| ``` |
| |
| The single thing that distinguishes Comba from a gated delta rule is that the state is **read with `p` and |
| written with `k`** — in DeltaNet those are the same vector. `p` and `k` are separate `(B, H, K)` inputs and |
| both must be streamed; using `k` in place of `p` is a different, wrong computation. |
| |
| The correction `u` is read out of the state **after** the decay and **before** the write, and the readout `o` |
| uses the state **after** the write. `u` is a reduction over the whole `K` axis and the write then needs `u`, |
| so the state is needed on both sides of a reduction — see *Where the performance comes from*. |
| |
| This is the same recurrence as the `comba-forward` task, run for exactly one token. Running this step `T` |
| times in a loop reproduces that task's output to ~1e-7 relative error. |
| |
| `/app/reference.py` writes the step out in fp32. That is the exact specification; it is deliberately simple |
| rather than fast, and its runtime has no bearing on your score.""", |
|
|
| contract_md="""| arg | shape | dtype | meaning | |
| |-----|-------|-------|---------| |
| | `state` | `(B, H, K, V)` | `float32` | recurrent state carried in from the previous token | |
| | `q` | `(B, H, K)` | `bfloat16` | this token's query | |
| | `k` | `(B, H, K)` | `bfloat16` | **write** key (L2-normalised along `K`) | |
| | `v` | `(B, H, V)` | `bfloat16` | this token's value | |
| | `p` | `(B, H, K)` | `bfloat16` | **read** key (L2-normalised along `K`) | |
| | `beta` | `(B, H)` | `bfloat16` | delta-rule step size, in `(0, 1)` | |
| | `g` | `(B, H)` | `float32` | **scalar** log-decay per `(b, h)`, `<= 0` (`exp(g)` is the gate) | |
| | `scale` | scalar | `float` or `None` | query scale; `None` means `K ** -0.5` | |
| |
| Note the argument order is `(state, q, k, v, p, beta, g)` — `p` comes after `v`, and `g` is last. This matches |
| the `comba-forward` task's `(q, k, v, p, beta, g)` with `state` prepended. |
| |
| **Return a 2-tuple `(state_new, o)` in that order:** |
| |
| | out | shape | dtype | |
| |-----|-------|-------| |
| | `state_new` | `(B, H, K, V)` | `float32` | |
| | `o` | `(B, H, V)` | `bfloat16` or `float32` | |
| |
| **The update is functional, not in-place.** `state` is an input and must be treated as **read-only**; |
| `state_new` must be a **new** tensor. The grader calls your function and the reference on the *same* input |
| tensors, so scribbling on `state` makes the reference disagree with you and you fail the correctness gate. |
| |
| **`state_new` must be `float32`** — a genuine fp32 tensor, not bf16/fp8 values in a wider container and not a |
| narrower dtype. Half the graded byte count is the fp32 state write; returning a narrower state is a contract |
| violation, not an optimisation. |
| |
| `B` is the decode batch (one recurrent state per in-flight sequence), `H` the number of heads. All tensors are |
| CUDA and contiguous. `K` and `V` are multiples of 32. No variable-length packing, no GQA, no cache |
| indirection — the batch is dense.""", |
|
|
| regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` |
| (concurrent sequences) in 512–2048, `H` in 8–32, `K` in {64, 128}, `V` = 128. `B * H` is in the tens of |
| thousands, so the state alone is 0.5–1.2 GB and a roofline kernel takes 300–500 us — large enough that |
| bandwidth, not launch overhead, decides the score. Write a **general** kernel; one tuned to a single shape |
| will not score well.""", |
|
|
| correctness_md="""**Both** returned tensors must match the reference (evaluated in fp32 as a stable |
| ground truth) within **relative Frobenius error `2e-2`** at every graded shape, including the timed ones — |
| the new state as well as the output. The worse of the two is what is checked.""", |
|
|
| perf_md="""This kernel is **memory-bound and nothing else**. Per state element you read 4 bytes, write 4 |
| bytes and do about four flops; arithmetic intensity is well under 1 flop/byte. Your score is achieved HBM |
| bandwidth and the target is that device's roofline — measure it with a large stream-copy rather than |
| taking a datasheet number on faith. |
| |
| The reference is a chain of separate elementwise/reduction ops over the `(B, H, K, V)` state, so it drags the |
| state through HBM five or six times. A good kernel moves it **exactly twice**: read once, write once. |
| |
| Getting to exactly twice is the whole problem, because a delta-rule step is not a single streaming pass: |
| |
| ``` |
| u = beta * (v - S^T p) # a reduction over the ENTIRE K axis of the decayed state |
| S += k u^T # a write that cannot start until that reduction has finished |
| ``` |
| |
| The state is needed on both sides of a reduction. Reading it twice costs you a third of your bandwidth |
| budget. The fix is to keep it **resident**: the reduction runs down the `K` axis independently for each column |
| of `V`, so `V` splits cleanly across CTAs. Give each CTA a slab of `V` columns and the full `K` axis — a |
| `K x V_slab` fp32 tile (128 x 32 = 16 KB, or the whole 128 x 128 = 64 KB state of one head) fits in shared |
| memory (check `p.shared_memory_per_block_optin`) or even registers. Load the slab once, apply the scalar |
| decay, reduce down `K` against `p` |
| for `u`, apply the rank-1 write with `k` and accumulate the readout `o = S_new^T (scale q)` in the same |
| registers, then store the slab once. |
| |
| Beyond that it is straight bandwidth engineering: |
| |
| - `V` is the contiguous axis of `state`, so tile so that every load and store is a fully coalesced 128-bit |
| (`float4`) access. Vectorised fp32 traffic is the single biggest lever. |
| - `B * H` is in the tens of thousands, so occupancy is free — but the *tail* is not. Choose the CTA tile so |
| the grid is close to a whole number of waves, and consider a persistent grid. |
| - `q`, `k`, `p`, `v`, `beta`, `g` are one token's worth per `(b, h)` — a few KB total. Load them once into |
| registers/shared and reuse them across every tile of the slab. Comba streams one more `(B, H, K)` vector |
| than Gated DeltaNet does (`p` as well as `k`), but at `K = 128` that is still under 1% of the traffic. |
| - Fuse everything into **one** kernel. Decay, reduce, write and readout as four launches is exactly what the |
| reference does and it is why it is slow. |
| - `torch.compile` on the reference will fuse some of this and is a fair sanity baseline, but it will not find |
| the resident-slab schedule and it will not hit the roofline.""", |
|
|
| precision_md="""The activations are **bfloat16** — this is an LLM decode kernel and that is the precision |
| it runs at in production. The **state is `float32`, in and out**, and all state arithmetic must be done in |
| **fp32**: the state is the quantity that is accumulated across thousands of decode steps, so rounding it is |
| not a local error, it compounds token after token. That is also why the graded byte count charges you 4 bytes |
| each way for it. |
| |
| Concretely: upcast `q`, `k`, `v`, `p`, `beta` to fp32 as you load them, keep `exp(g)` in fp32, do the |
| `K`-reduction for `u` in an fp32 accumulator, and write `state_new` back as fp32. There is no tensor-core |
| matmul anywhere in this kernel — there is nothing to gain from bf16 or fp8 arithmetic, and **narrowing the |
| state is not a legal trade**: it would halve the write traffic that the score is defined against. |
| |
| For calibration, a correct fp32-state kernel reproduces the reference to about **1e-7** relative error — this |
| is not a low-precision kernel, and there is no algebraic rearrangement here that needs a tolerance. The `2e-2` |
| gate is generous on purpose so that reasonable reduction orders and fused-multiply-add differences never bite; |
| if your error is anywhere near it, you have a bug or you have dropped part of the spec. For reference, a |
| kernel that rounds the state to bf16 lands at ~1.5e-3 (inside the gate, but it is still a contract violation), |
| one that drops the forget gate lands at ~2.0e-1, one that reads the correction with `k` instead of `p` lands |
| at ~6.4e-2, and one that drops the `- S^T p` correction entirely lands at ~4.5e-2. Every one of those is |
| outside the gate, and every one of them gets *worse* the longer the model decodes, because the error feeds |
| straight back into the next step's state.""", |
| ).validate() |
|
|