| """Spec for `comba-backward` — the training-side counterpart of comba-forward.""" |
| import pathlib |
| import sys |
|
|
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) |
| from spec import TaskSpec |
|
|
| |
| _FWD = ''' |
| CHUNK_SIZE = 64 |
| |
| |
| def _comba_forward(q, k, v, p, beta, g, scale=None): |
| """Chunked Comba forward in fp32 — differentiable; autograd through this defines the gradients.""" |
| B, T, H, K = q.shape |
| BT = CHUNK_SIZE |
| if scale is None: |
| scale = K ** -0.5 |
| q, k, v, p = [rearrange(x.to(torch.float32), 'b (n c) h d -> b h n c d', c=BT) for x in (q, k, v, p)] |
| beta, g = [rearrange(x.to(torch.float32), 'b (n c) h -> b h n c', c=BT) for x in (beta, g)] |
| gc = g.cumsum(-1) # cumulative log-decay INSIDE each chunk |
| L = (gc[..., :, None] - gc[..., None, :]).exp() # L[i, j] = exp(gc_i - gc_j) <= 1 |
| pb = p * beta[..., None] |
| |
| # linearise the chunk's rank-1 writes: u = (I + X)^-1 (beta*v - beta*exp(gc)*p @ S) |
| tri0 = torch.triu(torch.ones(BT, BT, dtype=torch.bool, device=q.device), diagonal=0) |
| M = (-((pb @ k.transpose(-1, -2)) * L)).masked_fill(tri0, 0) |
| eye = torch.eye(BT, dtype=torch.float32, device=q.device) |
| A = torch.linalg.solve_triangular(eye - M, eye.expand(*M.shape[:-2], BT, BT), upper=False) |
| u = A @ (v * beta[..., None]) |
| w = A @ (pb * gc[..., None].exp()) |
| |
| tri1 = torch.triu(torch.ones(BT, BT, dtype=torch.bool, device=q.device), diagonal=1) |
| S = q.new_zeros(B, H, K, v.shape[-1]) # the (K, V) state carried across chunks |
| outs = [] |
| for i in range(T // BT): |
| q_i, k_i, gc_i = q[:, :, i] * scale, k[:, :, i], gc[:, :, i] |
| attn = ((q_i @ k_i.transpose(-1, -2)) * L[:, :, i]).masked_fill(tri1, 0) |
| u_i = u[:, :, i] - w[:, :, i] @ S |
| outs.append((q_i * gc_i[..., None].exp()) @ S + attn @ u_i) |
| last = gc_i[..., -1] |
| S = S * last[..., None, None].exp() + \\ |
| (k_i * (last[..., None] - gc_i)[..., None].exp()).transpose(-1, -2) @ u_i |
| return rearrange(torch.stack(outs, dim=2), 'b h n c d -> b (n c) h d') |
| |
| |
| def comba_backward(q, k, v, p, beta, g, do, scale=None): |
| """Comba backward — the baseline runs the chunked forward under autograd.""" |
| ins = [x.detach().clone().requires_grad_(True) for x in (q, k, v, p, beta, g)] |
| o = _comba_forward(*ins, scale=scale) |
| return torch.autograd.grad(o, ins, do.float()) |
| ''' |
|
|
| SPEC = TaskSpec( |
| name="comba-backward", |
| title="Write a fast Comba BACKWARD kernel", |
| blurb=("The training-side counterpart of Comba (2025): the gated delta rule with a DECOUPLED read key — " |
| "the state correction is read with `p` while the write still uses `k`, so the within-chunk " |
| "transform is not the symmetric one DeltaNet's WY trick relies on, and neither is its transpose in " |
| "the backward. The reference obtains the six gradients by running the chunked fp32 forward under " |
| "autograd, including the triangular solve; a fused backward recomputes the chunk transform instead " |
| "and carries the reverse state scan in registers."), |
| keywords=["mle", "kernel-generation", "comba", "linear-attention", "delta-rule", "backward", "gpu"], |
| module="comba_bwd.py", |
| func="comba_backward", |
| signature="comba_backward(q, k, v, p, beta, g, do, scale=None)", |
| returns_doc="""Comba backward. |
| |
| 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. |
| do: (B, T, H, V) bfloat16 — incoming gradient w.r.t. the forward output. |
| scale: float or None — query scale; None means K ** -0.5. |
| |
| Returns: |
| (dq, dk, dv, dp, dbeta, dg) with shapes |
| (B,T,H,K), (B,T,H,K), (B,T,H,V), (B,T,H,K), (B,T,H), (B,T,H).""", |
|
|
| reference_imports="import torch\nfrom einops import rearrange", |
| reference_src=_FWD, |
| 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) |
| do = torch.randn(B, T, H, V, device="cuda", dtype=torch.bfloat16, generator=gen) |
| return q, k, v, p, beta, g, do |
| ''', |
| flops_src=''' |
| def canonical_work(B, T, H, K, V, C=64): |
| """FLOPs attributed to one Comba BACKWARD, from the SHAPE ALONE (chunked form, chunk length C=64). |
| |
| Per (b, h) and per token the forward costs the chunk transform's two K-contractions and the intra-chunk |
| score matrix (2*C*2*K), the application to the corrected values (2*C*V), and three (K, V)-state products |
| — the correction read, the readout, and the state update (6*K*V). The backward is credited the standard |
| 2x the forward. The triangular solve and the elementwise gate work are not counted. |
| """ |
| return 2 * (B * H * T * (2 * C * (2 * K + V) + 6 * K * V)) |
| ''', |
| flops_formula="2 * ( B*H*T * (2*C*(2*K + V) + 6*K*V) ) with C = 64 # 2x the forward", |
|
|
| metric="TFLOP/s", |
| compare="tuple", |
| tuple_names=("dq", "dk", "dv", "dp", "dbeta", "dg"), |
| tol=2e-2, |
| shape_names=("B", "T", "H", "K", "V"), |
| grader_shapes=[(8, 4096, 32, 128, 128), (16, 2048, 32, 128, 128), (12, 4096, 32, 64, 128), |
| (16, 4096, 16, 128, 128), (12, 4096, 16, 128, 128)], |
| measure_shapes=[(8, 2048, 32, 128, 128), (12, 2048, 32, 128, 128), (8, 4096, 16, 128, 128), |
| (16, 2048, 32, 64, 128), (10, 4096, 32, 128, 128)], |
| measure_quick_shapes=[(2, 1024, 16, 128, 128), (4, 1024, 8, 128, 128), (2, 2048, 8, 64, 128)], |
| correct_shapes=[(1, 512, 4, 128, 128), (2, 1024, 4, 64, 64), (1, 1024, 8, 128, 64), |
| (2, 256, 4, 64, 128)], |
|
|
| spec_md="""The forward, 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), AFTER the decay |
| S = S + k_t u_t^T # rank-1 write, using k |
| o_t = S^T (scale * q_t) # readout |
| ``` |
| |
| You must return the gradients of that forward with respect to `q, k, v, p, beta, g`, given the incoming |
| gradient `do` of the loss with respect to `o`. `scale` defaults to `K ** -0.5`. |
| |
| The one 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 makes the within-chunk transform |
| `(I - tril(beta k kᵀ))⁻¹` symmetric-ish and lets the WY/UT trick apply directly; here the corresponding |
| matrix is built from `p` against `k`, is **not** symmetric, and its transpose — which is what the backward |
| needs — is a *different* triangular system. |
| |
| `/app/reference.py` gives you `_comba_forward` — the same forward in its equivalent chunked form (chunk |
| length 64: the chunk transform obtained by a triangular solve, then a sequential state scan) — and obtains |
| the gradients by running it under **autograd**. That is the specification, and it is what torch gives you |
| for free, but it replays the entire chunked graph, differentiates through the triangular solve, and |
| materialises every chunk intermediate in HBM. |
| |
| You may reach the same gradients any way you like: derive and fuse the analytic backward, recompute |
| intermediates instead of storing them, use a different chunk length, or restructure the reverse scan. Only |
| the returned numbers are specified.""", |
|
|
| 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) | |
| | `do` | `(B, T, H, V)` | `bfloat16` | incoming gradient w.r.t. the forward output `o` | |
| | `scale` | scalar | `float` or `None` | query scale; `None` means `K ** -0.5` | |
| |
| Note the argument order is `(q, k, v, p, beta, g, do)` — `p` comes after `v`, and `do` is last. |
| |
| **Return** a 6-tuple `(dq, dk, dv, dp, dbeta, dg)` **in that order**, with shapes |
| `(B,T,H,K)`, `(B,T,H,K)`, `(B,T,H,V)`, `(B,T,H,K)`, `(B,T,H)`, `(B,T,H)`. |
| Each may be `bfloat16` or `float32`. |
| |
| **All six are graded.** Getting five of six right scores **0**. `dbeta` and `dg` are per-`(b, t, h)` |
| scalars — they are reductions over the whole `(K, V)` state, not per-channel vectors. |
| |
| All tensors are CUDA and contiguous. `T` is a multiple of 64. No initial state, no state gradient, 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 8–16, |
| `T` in 2048–4096, `H` in 16–32, `K` in {64, 128}, `V` = 128, with `B*H >= 128`. The batch/head product is |
| large and `T` moderate on purpose: the sequential dimension is short enough that the scan does not starve the |
| GPU, and wide enough that every SM has a `(b, h)` pair to work on. Write a **general** kernel.""", |
|
|
| correctness_md="""**All six** gradients must match the reference (evaluated in fp32) within **relative |
| Frobenius error `2e-2`** at every graded shape, including the timed ones.""", |
|
|
| perf_md="""The backward of a chunked delta-rule scan is memory-bound when written through autograd: the |
| chunk transform `A`, the linearised values `u`, the correction operand `w`, the per-chunk `u_i` and the state |
| all stay alive for the reverse pass, and torch also differentiates the triangular solve as a *second* |
| triangular solve against the same matrix. |
| |
| A fused backward instead **recomputes** the chunk-local quantities from `q, k, v, p, beta, g` during the |
| reverse scan, keeps the reverse state `dS` in registers/shared memory across chunks, and uses bf16 tensor |
| cores for the chunk matmuls with fp32 accumulation. The triangular solve should be replaced by the forward |
| substitution it stands for and fused into the same kernel; its adjoint is a *backward* substitution against |
| the transposed system, which is the same primitive run in the other direction — a matrix inverse never has |
| to be materialised. |
| |
| Because the read key `p` and the write key `k` are different, the two sides of that system are different, so |
| `dp` and `dk` come out of separate contractions and cannot be merged. `dbeta` and `dg` are full reductions |
| over the `(K, V)` state; fold the scalar decay into the matmul operands (`exp(gc_i - gc_j)` factorises into |
| per-row and per-column scalings) rather than materialising `exp(g)` tensors.""", |
|
|
| precision_md="""All inputs and outputs are **bfloat16** (the gate `g` is `float32` because it is a log) — |
| this is an LLM-training 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 faithful bf16 implementation of this backward lands around **4e-3 – 5e-3** relative error |
| on every one of the six gradients — roughly 4x inside the `2e-2` gate — and that number is **flat in `T`**. A |
| wrong algorithm misses by 0.2 or more. |
| |
| The **gradient reductions drift first**. `dbeta` and `dg` are contracted over the entire `(K, V)` state at |
| every step, and the reverse state `dS` is accumulated along the whole sequence — all of them need **fp32 |
| accumulators**. If `dbeta`/`dg` sit at 1e-2 while `dq`/`dk`/`dv`/`dp` are at 4e-3, that is a bf16 |
| accumulator, not noise. The chunk-local triangular solve is also worth keeping in fp32: it is a sequential |
| substitution, so rounding there compounds across the chunk. |
| |
| Do **not** infer from the reference that fp32 compute is wanted. It runs in fp32 purely to be a stable |
| numerical *specification*, and its speed has no bearing on your score.""", |
| ).validate() |
|
|