"""Spec for `based-forward` — Based / Taylor linear attention (2nd-order feature map).""" import pathlib import sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from spec import TaskSpec SPEC = TaskSpec( name="based-forward", title="Write a fast Based (Taylor linear attention) forward kernel", blurb=("Based replaces softmax with its 2nd-order Taylor expansion, 1 + s + s^2/2. That polynomial is " "exactly a dot product of the feature map [1, x, x (x) x / sqrt(2)], so the whole layer is a " "linear attention over a feature dimension of 1 + K + K^2 — a state hundreds of times larger " "than the head dimension, plus a running normaliser that has to be carried alongside it."), keywords=["mle", "kernel-generation", "based", "taylor", "linear-attention", "feature-map", "gpu"], module="based.py", func="based_forward", signature="based_forward(q, k, v, scale=None)", returns_doc="""Based / Taylor linear attention forward. Args: q, k: (B, T, H, K) bfloat16 — queries / keys. K is the small Taylor FEATURE dimension (8 or 16). v: (B, T, H, V) bfloat16 — values. V is the (larger) head dimension. 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=''' CHUNK_SIZE = 256 def based_forward(q, k, v, scale=None): """Based forward in fp32: the exact 2nd-order Taylor attention, evaluated with the explicit feature map across chunks and with the direct polynomial inside a chunk. Correct and simple — it is the numerical SPECIFICATION, not a performance target. """ B, T, H, K = q.shape V = v.shape[-1] C = CHUNK_SIZE if scale is None: scale = K ** -0.5 q, k, v = [x.transpose(1, 2).contiguous().to(torch.float32) for x in (q, k, v)] q = q * scale P = 1 + K + K * K dev = q.device rt2 = 2.0 ** -0.5 def phi(x): # [1, x, x (x) x / sqrt(2)] n = x.shape[2] return torch.cat([torch.ones(B, H, n, 1, device=dev, dtype=torch.float32), x, (x[..., :, None] * x[..., None, :]).reshape(B, H, n, K * K) * rt2], -1) S = torch.zeros(B, H, P, V, device=dev, dtype=torch.float32) # sum_j phi(k_j) v_j^T z = torch.zeros(B, H, P, 1, device=dev, dtype=torch.float32) # sum_j phi(k_j) tri = torch.tril(torch.ones(C, C, device=dev, dtype=torch.float32)) o = torch.empty(B, H, T, V, device=dev, dtype=torch.float32) for i in range(0, T, C): q_i, k_i, v_i = q[:, :, i:i + C], k[:, :, i:i + C], v[:, :, i:i + C] n = q_i.shape[2] pq = phi(q_i) s = q_i @ k_i.transpose(-1, -2) A = (1.0 + s + 0.5 * s * s) * tri[:n, :n] # causal 2nd-order Taylor weights num = pq @ S + A @ v_i den = pq @ z + A.sum(-1, keepdim=True) o[:, :, i:i + n] = num / (den + 1e-6) pk = phi(k_i) S = S + pk.transpose(-1, -2) @ v_i z = z + pk.sum(-2)[..., None] return o.transpose(1, 2).contiguous() ''', make_inputs_src=''' def _mk(B, T, H, K, V, seed): gen = torch.Generator(device="cuda").manual_seed(seed) q = torch.randn(B, T, H, K, device="cuda", dtype=torch.bfloat16, generator=gen) k = torch.randn(B, T, H, K, device="cuda", dtype=torch.bfloat16, generator=gen) v = torch.randn(B, T, H, V, device="cuda", dtype=torch.bfloat16, generator=gen) return q, k, v ''', flops_src=''' def canonical_work(B, T, H, K, V, C=64): """FLOPs attributed to one Based forward, from the SHAPE ALONE (chunk length C = 64). The linear form carries a (P, V) state with P = 1 + K + K*K. Per token it costs 2*P*V to fold that token into the state and 2*P*V to read the state back out -> 4*P*V. The intra-chunk part is done in the quadratic form: 2*C*K for the C scores of one query and 2*C*V to apply them -> 2*C*(K + V) per token. Building the feature map itself, the running normaliser and the final divide are O(K*K + V) per token and are not counted. """ P = 1 + K + K * K return B * H * T * (4 * P * V + 2 * C * (K + V)) ''', flops_formula="B*H*T * (4*(1 + K + K*K)*V + 2*C*(K + V)) with C = 64", metric="TFLOP/s", compare="tensor", tol=2e-2, shape_names=("B", "T", "H", "K", "V"), grader_shapes=[(4, 16384, 32, 16, 128), (8, 8192, 32, 16, 128), (8, 16384, 16, 16, 128), (8, 16384, 32, 16, 64), (8, 16384, 32, 8, 128)], measure_shapes=[(4, 12288, 32, 16, 128), (8, 8192, 16, 16, 128), (4, 16384, 32, 16, 64), (2, 16384, 32, 16, 128), (4, 16384, 32, 8, 128)], measure_quick_shapes=[(1, 2048, 16, 16, 128), (2, 2048, 8, 16, 128), (1, 4096, 16, 8, 128)], correct_shapes=[(1, 256, 4, 16, 128), (2, 512, 8, 16, 64), (1, 512, 6, 8, 128), (2, 128, 4, 16, 128)], spec_md="""Based is causal attention with softmax replaced by its 2nd-order Taylor expansion. Per batch `b` and head `h`, with `s[i, j] = scale * (q_i . k_j)` and `scale` defaulting to `K ** -0.5`: ``` A[i, j] = 1 + s[i, j] + s[i, j]^2 / 2 for j <= i, 0 otherwise o_i = ( sum_j A[i, j] * v_j ) / ( sum_j A[i, j] + 1e-6 ) ``` Note both parts: the **weights are the quadratic polynomial** (not `exp`, not a softmax — there is no row maximum and no exponential anywhere), and the output is **normalised by the row sum of those same weights**, with a fixed `+ 1e-6` guard added to the denominator. **Why this is not an O(T^2) op.** The polynomial is an exact inner product of the feature map ``` phi(x) = [ 1 , x , x (x) x / sqrt(2) ] (length P = 1 + K + K*K) ``` because `phi(q) . phi(k) = 1 + (q.k) + (q.k)^2 / 2`. So the whole layer is an ordinary linear attention over a `P`-dimensional feature space: ``` o_i = ( phi(q_i)^T S_i ) / ( phi(q_i)^T z_i + 1e-6 ), S_i = sum_{j<=i} phi(k_j) v_j^T, z_i = sum_{j<=i} phi(k_j) ``` `K` is the small Taylor **feature** dimension (8 or 16), not the head dimension — `V` is the head dimension. That is what keeps `P` (73 or 273) manageable, and it is also what makes this kernel unusual: the state `(P, V)` is one to two orders of magnitude larger than the `(K, V)` state of a normal linear-attention layer, so how you place and update it dominates the design. The 2nd-order term is the entire point of the method and is **not** optional: truncating to `1 + s` (plain linear attention) is off by **0.6 to 2.5** in relative error across the graded shapes, and dropping the normaliser is off by a factor of thousands. `/app/reference.py` computes exactly this in fp32. Its chunk length is an internal detail — the answer does not depend on it, and you may use any chunking or algebraic rearrangement that matches numerically. The reference 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` is the Taylor **feature** dimension | | `k` | `(B, T, H, K)` | `bfloat16` | keys | | `v` | `(B, T, H, V)` | `bfloat16` | values; `V` is the head dimension | | `scale` | scalar | `float` or `None` | query scale; `None` means `K ** -0.5` (note: `K`, not `V`) | **Return** `o` of shape `(B, T, H, V)`, dtype `bfloat16` **or** `float32`. `scale` multiplies **`q` only**, before the dot product, so the polynomial is evaluated at `s = (scale * q_i) . k_j`. The denominator guard is exactly `+ 1e-6`, added after the row sum. Attention is fully causal and includes the diagonal (`j <= i`); position `0` therefore has the single weight `A[0, 0]`, never an empty row. `K != V` in general and `K` is small. There is no initial or final state, no sliding window, and no softmax. All tensors are CUDA and contiguous. `T` is a multiple of 64. 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 4–8, `T` in 8192–16384, `H` in 16–32, `K` in {8, 16}, `V` in {64, 128}. `K` changes `P = 1 + K + K*K` from 73 to 273 — a nearly 4x change in state size and in the work per token — so a kernel that hard-codes one feature dimension will fail or score badly on the other. Write a **general** kernel.""", 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 is already sub-quadratic and already vectorised, so there is no free win from "removing python loops". What it wastes is memory traffic: it materialises `phi(q)` and `phi(k)` — `P/K` times bigger than `q` and `k` themselves — writes them to HBM, and rereads the `(P, V)` state every chunk. The kernel you want never materialises `phi` at all. `phi(x)` is `[1, x, outer(x, x)/sqrt(2)]`, so the `(P, V)` state is really `(1, V)` + `(K, V)` + `(K, K, V)` blocks, and each block has its own natural update: - the constant block is a running sum of `v`, - the linear block is the ordinary linear-attention state `sum k_j v_j^T`, - the quadratic block is `sum (k_j (x) k_j) v_j^T`, which is `K` separate `(K, V)` rank-1 updates — i.e. `K` independent linear-attention states, one per feature of `k`. At `K = 16`, `V = 128` the quadratic block alone is `256 x 128` floats (128 KB in fp32, 64 KB in bf16), which does fit in shared memory but leaves little room — so the interesting design decisions are how to split it across warps/CTAs, whether to hold it in bf16 with fp32 accumulation of the increments, and how to keep the `sum (k (x) k) v^T` update on tensor cores instead of doing it as `K` skinny outer products. The other half of the win is the intra-chunk term. Inside a chunk it is cheaper to evaluate `1 + s + s^2/2` **directly** from a `C x C` score tile than to go through the `P`-dimensional feature map — that is what the reference does, and a good kernel does the same, so the inner loop is two ordinary bf16 matmuls (`q k^T` and `A v`) plus one elementwise polynomial. Fuse the numerator and the running normaliser into the same pass (the normaliser is the same computation with `v` replaced by a column of ones — do not spend a second matmul on it), and keep the running sums in fp32.""", 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. The **state carry must be fp32**. Both `S = sum phi(k_j) v_j^T` and the normaliser `z = sum phi(k_j)` are ungated sums over the entire prefix — there is no decay to forget old terms — so by the end of the sequence they are reductions over up to 16384 contributions and grow like `T` (for `z`) while each increment stays `O(1)`. In bf16 the increments stop moving the accumulator well before the end and the error compounds with `T`. Note also that `z` is a **denominator**: an error there is a relative error on the whole output row, not a damped one, so it deserves the same care as `S`. The polynomial itself is benign — `1 + s + s^2/2 = (1+s)^2/2 + 1/2 >= 1/2 > 0` always, so the denominator is strictly positive and no cancellation can occur — but note that computing `s^2` in bf16 doubles its relative error before it is summed; square in fp32. For calibration, a correct bf16 fused kernel of this family lands around **4e-3** relative error against the fp32 reference — roughly 5x inside the `2e-2` gate — while truncating the feature map to first order misses by **0.6 or more** (2.5 at some graded shapes), i.e. two orders of magnitude outside the gate. Do **not** infer from the reference that fp32 compute is wanted. It runs in fp32 purely to be a stable numerical *specification*.""", ).validate()