"""Spec for `comba-forward` — Comba (2025), a delta-rule variant with a decoupled read key.""" import pathlib import sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from spec import TaskSpec SPEC = TaskSpec( name="comba-forward", title="Write a fast Comba forward kernel", blurb=("Comba is a 2025 linear-attention layer: the gated delta rule with a DECOUPLED read key — the " "state correction is read with a separate vector p while the write still uses k, so the " "within-chunk transform is no longer the symmetric one DeltaNet's WY trick relies on."), keywords=["mle", "kernel-generation", "comba", "linear-attention", "delta-rule", "gpu"], module="comba.py", func="comba_forward", signature="comba_forward(q, k, v, p, beta, g, scale=None)", returns_doc="""Comba forward. Args: q, k, p: (B, T, H, K) bfloat16 — queries, write-keys, read-keys. v: (B, T, H, V) bfloat16 — values. beta: (B, T, H) bfloat16 — delta-rule step size in (0, 1). g: (B, T, H) float32 — per-step log-decay (<= 0); exp(g) is the gate. scale: float or None — query scale; None means K ** -0.5. Returns: o: (B, T, H, V), bfloat16 or float32 — must match /app/reference.py numerically.""", reference_imports="import torch", reference_src=''' def comba_forward(q, k, v, p, beta, g, scale=None): """Comba forward, written as the plain step-by-step recurrence in fp32. Correct and simple — it is the numerical SPECIFICATION, not a performance target. """ q, k, v, p, beta, g = [x.transpose(1, 2).contiguous().to(torch.float32) for x in (q, k, v, p, beta, g)] B, H, T, K = k.shape V = v.shape[-1] if scale is None: scale = K ** -0.5 q = q * scale o = torch.zeros(B, H, T, V, device=q.device, dtype=torch.float32) h = torch.zeros(B, H, K, V, device=q.device, dtype=torch.float32) for i in range(T): h = h * g[:, :, i].exp()[..., None, None] # scalar forget gate v_i = v[:, :, i] - (h * p[:, :, i][..., None]).sum(-2) # read the state with p v_i = v_i * beta[:, :, i][..., None] # delta-rule step size h = h + k[:, :, i].unsqueeze(-1) * v_i.unsqueeze(-2) # write the state with k o[:, :, i] = torch.einsum('bhd,bhdm->bhm', q[:, :, i], h) # readout return o.transpose(1, 2).contiguous() ''', make_inputs_src=''' def _mk(B, T, H, K, V, seed): import torch.nn.functional as F gen = torch.Generator(device="cuda").manual_seed(seed) q = torch.randn(B, T, H, K, device="cuda", dtype=torch.bfloat16, generator=gen) k = F.normalize(torch.randn(B, T, H, K, device="cuda", generator=gen), dim=-1).to(torch.bfloat16) v = torch.randn(B, T, H, V, device="cuda", dtype=torch.bfloat16, generator=gen) p = F.normalize(torch.randn(B, T, H, K, device="cuda", generator=gen), dim=-1).to(torch.bfloat16) beta = torch.rand(B, T, H, device="cuda", generator=gen).sigmoid().to(torch.bfloat16) g = (F.logsigmoid(torch.randn(B, T, H, device="cuda", generator=gen)) / 4.0).to(torch.float32) return q, k, v, p, beta, g ''', flops_src=''' def canonical_work(B, T, H, K, V, C=64): """FLOPs attributed to one Comba forward, from the SHAPE ALONE (chunked form, chunk length C).""" return B * H * T * (2 * C * (2 * K + V) + 6 * K * V) ''', metric="TFLOP/s", compare="tensor", tol=2e-2, shape_names=("B", "T", "H", "K", "V"), grader_shapes=[(2, 8192, 32, 128, 128), (4, 4096, 32, 128, 128), (2, 16384, 32, 128, 128), (4, 8192, 16, 128, 128), (2, 8192, 32, 64, 128)], measure_shapes=[(3, 6144, 32, 128, 128), (2, 12288, 24, 128, 128), (4, 8192, 32, 128, 128), (2, 8192, 16, 128, 128), (4, 4096, 16, 64, 128)], measure_quick_shapes=[(1, 2048, 16, 128, 128), (2, 2048, 8, 128, 128), (1, 4096, 16, 64, 128)], correct_shapes=[(1, 256, 4, 128, 128), (2, 512, 8, 64, 128), (1, 512, 6, 128, 128), (2, 128, 4, 64, 64)], spec_md="""Per batch `b` and head `h`, with a recurrent state `S` of shape `(K, V)` initialised to zero, for `t = 0 … T-1`: ``` S = exp(g_t) * S # scalar forget gate on the whole state u_t = beta_t * ( v_t - S^T p_t ) # correction, read with p (NOT with k) S = S + k_t u_t^T # rank-1 write, using k o_t = S^T (scale * q_t) # readout ``` `scale` defaults to `K ** -0.5`. 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, which is what makes its within-chunk transform `(I - tril(beta k kᵀ))⁻¹` symmetric-ish and lets the WY/UT trick apply directly. Here the corresponding chunk matrix is built from `p` against `k` and is **not** symmetric, so the standard transform has to be re-derived rather than reused. `/app/reference.py` writes the recurrence out step by step 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 | |-----|-------|-------|---------| | `q` | `(B, T, H, K)` | `bfloat16` | queries | | `k` | `(B, T, H, K)` | `bfloat16` | **write** keys (L2-normalised along `K`) | | `v` | `(B, T, H, V)` | `bfloat16` | values | | `p` | `(B, T, H, K)` | `bfloat16` | **read** keys (L2-normalised along `K`) | | `beta` | `(B, T, H)` | `bfloat16` | delta-rule step size, in `(0, 1)` | | `g` | `(B, T, H)` | `float32` | per-step log-decay, `<= 0` (`exp(g)` is the gate) | | `scale` | scalar | `float` or `None` | query scale; `None` means `K ** -0.5` | **Return** `o` of shape `(B, T, H, V)`, dtype `bfloat16` or `float32`. Note the argument order is `(q, k, v, p, beta, g)` — `p` comes after `v`, and `g` is last. All tensors are CUDA and contiguous. `T` is a multiple of 64. No initial/final state, no variable-length packing, no GQA. Treat all inputs as read-only.""", regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in 2–4, `T` in 4096–16384, `H` in 16–32, `K` in {64, 128}, `V` = 128. These are large enough that kernel time, not launch overhead, dominates. Write a **general** kernel — one tuned to a single shape will not score well.""", correctness_md="""Your output 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.""", perf_md="""The reference walks the sequence one position at a time, so essentially all of its time is launch overhead on tiny operations — but note that beating it is trivial and **not** the point: your score is absolute throughput, so the question is how close to the machine's roofline you get. The real work is the chunked reformulation. Within a chunk of length `C`, the `C` rank-1 writes can be linearised into a single transform so the chunk becomes dense matmuls, and only a small state has to be carried sequentially between chunks. Because the read key `p` differs from the write key `k`, the chunk matrix here is `tril(beta ⊙ (p kᵀ))` rather than the symmetric DeltaNet form — derive the inverse (a forward substitution) and fuse it into the same kernel rather than materialising it. Keep the `(K, V)` state in registers/shared memory across chunks, use bf16 tensor cores for the chunk matmuls with fp32 accumulation, and fold the scalar decay into the matmul operands instead of materialising `exp(g)` tensors.""", precision_md="""All inputs and outputs are **bfloat16** — this is an LLM kernel and that is the precision it runs at in production. Your kernel is expected to do its matmuls on **bf16 tensor cores with fp32 accumulation**. **fp8** is acceptable anywhere you can still hold the tolerance. For calibration, a correct bf16 fused delta-rule-family kernel lands around **4e-3** relative error against the fp32 recurrence — roughly 5x inside the `2e-2` gate — while a wrong algorithm misses by 0.2 or more. The state carry is the sensitive part: accumulate it in fp32, since errors there compound along the sequence and will grow with `T`. Do **not** infer from the reference that fp32 compute is wanted. It runs in fp32 purely to be a stable numerical *specification*.""", ).validate()