| """Spec for `causal-conv1d-decode-step` — the single-token decode form of the SSM/linear-attn short conv.""" |
| import pathlib |
| import sys |
|
|
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) |
| from spec import TaskSpec |
|
|
| SPEC = TaskSpec( |
| name="causal-conv1d-decode-step", |
| title="Write a fast causal conv1d decode-step kernel", |
| blurb=("At every generated token, a Mamba-2 / Qwen3-Next block advances a short depthwise causal " |
| "convolution by ONE position: read the rolling window state, produce one output, shift the state. " |
| "Batched over hundreds of concurrent sequences this is pure bandwidth on the conv state, and it " |
| "runs once per layer per token — a different kernel shape entirely from the prefill convolution."), |
| keywords=["mle", "kernel-generation", "conv1d", "mamba", "qwen3-next", "decode", "memory-bound"], |
| module="conv1d_step.py", |
| func="causal_conv1d_decode_step", |
| signature="causal_conv1d_decode_step(x, state, weight, bias)", |
| returns_doc="""Causal depthwise conv1d, one decode step. |
| |
| Args: |
| x: (B, D) bfloat16 — this token's input, one vector per sequence. |
| state: (B, D, W-1) bfloat16 — the previous W-1 inputs, oldest at index 0. |
| weight: (D, W) bfloat16 — per-channel causal filter taps. |
| bias: (D,) bfloat16 — per-channel bias, added before the activation. |
| |
| Returns: |
| (y, state_out) where |
| y: (B, D) — silu(conv(window) + bias) for this position |
| state_out: (B, D, W-1) — the window shifted by one, ready for the next token""", |
|
|
| reference_imports="import torch\nimport torch.nn.functional as F", |
| reference_src=''' |
| def causal_conv1d_decode_step(x, state, weight, bias): |
| """One decode step of the causal depthwise conv, in fp32. |
| |
| Correct and simple — it is the numerical SPECIFICATION, not a performance target. |
| """ |
| # window = [ state (oldest .. newest) | x ] -> (B, D, W) |
| win = torch.cat([state.float(), x.float().unsqueeze(-1)], dim=-1) |
| y = (win * weight.float().unsqueeze(0)).sum(-1) + bias.float().unsqueeze(0) |
| return F.silu(y), win[:, :, 1:].to(state.dtype) |
| ''', |
| make_inputs_src=''' |
| def _mk(B, D, W, seed): |
| gen = torch.Generator(device="cuda").manual_seed(seed) |
| x = torch.randn(B, D, device="cuda", dtype=torch.bfloat16, generator=gen) |
| state = torch.randn(B, D, W - 1, device="cuda", dtype=torch.bfloat16, generator=gen) |
| weight = (torch.randn(D, W, device="cuda", dtype=torch.bfloat16, generator=gen) * 0.5) |
| bias = (torch.randn(D, device="cuda", dtype=torch.bfloat16, generator=gen) * 0.1) |
| return x, state, weight, bias |
| ''', |
| flops_src=''' |
| def canonical_work(B, D, W): |
| """BYTES attributed to one decode step, from the SHAPE ALONE. |
| |
| Read x and the (W-1)-deep state, write y and the shifted state, all bf16; the (D, W) taps and (D,) bias |
| are negligible and stay resident. This is a bandwidth kernel, so the score is achieved bandwidth against |
| this fixed byte count. |
| """ |
| return 2 * (B * D * 2) + 2 * (B * D * (W - 1) * 2) |
| ''', |
|
|
| metric="GB/s", |
| compare="tuple", |
| tuple_names=("y", "state_out"), |
| tol=4e-3, |
| shape_names=("B", "D", "W"), |
| grader_shapes=[(16384, 8192, 4), (32768, 4096, 4), (8192, 16384, 4), |
| (24576, 8192, 4), (65536, 2048, 4)], |
| measure_shapes=[(12288, 8192, 4), (24576, 4096, 4), (8192, 12288, 4), |
| (16384, 6144, 4), (49152, 2048, 4)], |
| measure_quick_shapes=[(2048, 4096, 4), (4096, 2048, 4), (1024, 8192, 4)], |
| correct_shapes=[(64, 256, 4), (129, 512, 4), (257, 128, 4), (32, 1024, 4)], |
|
|
| spec_md="""One step of the depthwise causal convolution, for every sequence in the batch at once. |
| |
| The rolling window for channel `d` of sequence `b` is the previous `W-1` inputs followed by this token's: |
| |
| ``` |
| win[b, d, :] = [ state[b, d, 0], ..., state[b, d, W-2], x[b, d] ] # oldest first, current last |
| y[b, d] = silu( bias[d] + sum over i in [0, W) of win[b, d, i] * weight[d, i] ) |
| state_out[b, d, :] = win[b, d, 1:] # drop the oldest, keep W-1 |
| ``` |
| |
| `silu(z) = z * sigmoid(z)`. Channels never mix — this is depthwise. `weight[d, W-1]` multiplies the |
| **current** input and `weight[d, 0]` the oldest, matching the prefill convolution's tap order. |
| |
| `state` is the carry between tokens: what this call returns is what the next token's call receives. The |
| contract is **functional** — return a new `state_out`; do not mutate `state` in place. The grader calls your |
| function and the reference on the same buffers, so an in-place update corrupts the comparison and fails. |
| |
| Note this is the DECODE counterpart of the prefill conv: there is no time axis to parallelise over, only the |
| batch and the channels, and the state traffic dominates everything. |
| |
| `/app/reference.py` builds the window with a concatenate and reduces it in fp32. That is the exact |
| specification; it is deliberately simple rather than fast.""", |
|
|
| contract_md="""| arg | shape | dtype | meaning | |
| |-----|-------|-------|---------| |
| | `x` | `(B, D)` | `bfloat16` | this token's input, one vector per sequence | |
| | `state` | `(B, D, W-1)` | `bfloat16` | previous `W-1` inputs, **oldest at index 0** | |
| | `weight` | `(D, W)` | `bfloat16` | per-channel taps; `weight[d, W-1]` hits the current input | |
| | `bias` | `(D,)` | `bfloat16` | per-channel bias, applied **before** the SiLU | |
| |
| **Return** a 2-tuple `(y, state_out)` **in that order**: |
| |
| | out | shape | notes | |
| |-----|-------|-------| |
| | `y` | `(B, D)` | this position's output; bf16 or fp32 | |
| | `state_out` | `(B, D, W-1)` | window shifted by one; **must be bf16** | |
| |
| `W` is always 4. `B` is **not** guaranteed to be a multiple of any tile size — the correctness shapes include |
| `B = 129` and `B = 257`, so handle the tail. Treat all inputs as read-only; the update is functional.""", |
|
|
| regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` |
| (concurrent sequences) in 8192–65536, `D` (channels) in 2048–16384, `W` = 4. Large batches are the point — |
| this kernel only matters when hundreds of sequences decode together, and that is what makes it a bandwidth |
| problem rather than a latency one. Write a **general** kernel that handles a ragged `B`.""", |
|
|
| correctness_md="""**Both** returned tensors must match the reference (evaluated in fp32) within |
| **relative error `4e-3`** at every graded shape, including the timed ones — the shifted state as well as the |
| output. A wrong `state_out` corrupts every subsequent token, so it is graded just as hard as `y`; the grader |
| scores the **worse** of the two. |
| |
| `state_out` carries no arithmetic at all — it is a bf16 copy of values that were already bf16 — so a correct |
| kernel reproduces it **bit for bit** and the gate on it is effectively exact. The whole `4e-3` budget exists |
| for `y`. |
| |
| That gate is **measured**, and kernels that skip this task's actual work miss it by orders of magnitude: no |
| SiLU scores **1.04**, taps applied in the reversed causal order **1.28**, an unshifted `state_out` **1.42**, |
| and even the subtlest variant tried — bias added *after* the SiLU instead of before — scores **0.104**, still |
| **26x** the tolerance.""", |
|
|
| perf_md="""There are four multiply-adds and a SiLU per element, so this is entirely a memory problem: |
| the floor is one read of `x` and `state` and one write of `y` and `state_out`, which is what |
| `canonical_work` counts. |
| |
| The obvious implementation reads `state`, concatenates, writes a new `state`, and moves `(W-1)` values per |
| channel in each direction. Most of that traffic is the *same data being shifted by one slot* — the window |
| overlaps itself between consecutive steps by `W-2` elements. A good kernel loads the window once into |
| registers, computes `y`, and writes back only the shifted view, with vectorised 128-bit accesses; `(B, D)` |
| is fully coalesced along `D`, so one warp per group of channels streams cleanly. |
| |
| The taps and bias are tiny and reused by every sequence — hold them in registers or shared memory rather |
| than re-reading them per element. And watch the tail: `B` is ragged, and a branchy epilogue on a kernel this |
| short costs a visible fraction of the runtime.""", |
|
|
| precision_md="""Inputs and outputs are **bfloat16**; do the accumulation and the SiLU in **fp32**. With |
| only four taps the convolution is numerically benign, but evaluate the `sigmoid` in fp32 — a bf16 sigmoid |
| loses enough precision near zero to show up in the norm. |
| |
| `state_out` **must be bfloat16**: it is the carry the next token consumes, and returning it wider would both |
| break the contract and hide the quantisation the real decode loop lives with. |
| |
| **fp8 is not useful here** and is not expected — this is a bandwidth kernel on bf16 data with a fixed output |
| dtype. |
| |
| Do **not** infer from the reference that fp32 storage is wanted; it computes in fp32 purely to be a stable |
| numerical *specification*. |
| |
| **Where the tolerance comes from.** `4e-3` is measured, not inherited. A second, independent implementation — |
| no concatenate, the four taps applied as explicit FMAs in the *reverse* order, the shifted state built by an |
| overwrite rather than a slice of a concatenated window — differs from this fp32 reference by relative |
| Frobenius error **1.73e-3** at worst across the correctness shapes, and 1.67e-3 at a full graded shape. |
| The tolerance is **2.3x** that. That 1.7e-3 is almost entirely the bf16 rounding of `y` itself: with only |
| four taps the fp32 accumulation contributes essentially nothing, so this number is the floor for *any* |
| bf16-returning kernel and there is no reduction-order freedom left to spend.""", |
| ).validate() |
|
|