KBench / tools /factory /specs /based_backward.py
ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 10)
0f775e2 verified
Raw
History Blame Contribute Delete
14.1 kB
"""Spec for `based-backward` — the training-side counterpart of based-forward."""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from spec import TaskSpec
# the chunked Based forward, reused as the differentiable spec (it matches the based-forward reference to
# ~3e-7 in fp32; the chunk length is an internal detail of both)
_FWD = '''
CHUNK_SIZE = 128
def _based_forward(q, k, v, scale=None):
"""Based / Taylor linear attention forward in fp32 — differentiable; autograd through this defines the
gradients. The exact 2nd-order Taylor attention: explicit feature map across chunks, direct polynomial
inside a chunk."""
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).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 = q.new_zeros(B, H, P, V) # sum_j phi(k_j) v_j^T
z = q.new_zeros(B, H, P, 1) # sum_j phi(k_j)
tri = torch.tril(torch.ones(C, C, device=dev, dtype=torch.float32))
outs = []
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)
outs.append(num / (den + 1e-6))
pk = phi(k_i)
S = S + pk.transpose(-1, -2) @ v_i
z = z + pk.sum(-2)[..., None]
return torch.cat(outs, 2).transpose(1, 2).contiguous()
def based_backward(q, k, v, do, scale=None):
"""Based backward — the baseline runs the chunked fp32 forward under autograd."""
ins = [x.detach().clone().requires_grad_(True) for x in (q, k, v)]
o = _based_forward(*ins, scale=scale)
return torch.autograd.grad(o, ins, do.float())
'''
SPEC = TaskSpec(
name="based-backward",
title="Write a fast Based (Taylor linear attention) BACKWARD kernel",
blurb=("The training-side counterpart of Based: softmax replaced by its 2nd-order Taylor expansion, "
"1 + s + s^2/2, which is exactly a dot product of the feature map [1, x, x (x) x / sqrt(2)] — a "
"linear attention over 1 + K + K^2 features plus a running normaliser. The backward has to "
"differentiate through BOTH the huge (P, V) state and the quotient by that normaliser, and the "
"reference does it by replaying the whole chunked graph under autograd."),
keywords=["mle", "kernel-generation", "based", "taylor", "backward", "linear-attention", "feature-map"],
module="based_bwd.py",
func="based_backward",
signature="based_backward(q, k, v, do, scale=None)",
returns_doc="""Based / Taylor linear attention backward.
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.
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) with shapes (B,T,H,K), (B,T,H,K), (B,T,H,V).""",
reference_imports="import torch",
reference_src=_FWD,
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)
do = torch.randn(B, T, H, V, device="cuda", dtype=torch.bfloat16, generator=gen)
return q, k, v, do
''',
flops_src='''
def canonical_work(B, T, H, K, V, C=64):
"""FLOPs attributed to one Based BACKWARD, from the SHAPE ALONE (chunk length C = 64).
The forward's linear form carries a (P, V) state with P = 1 + K + K*K: per token 2*P*V to fold the token
into the state and 2*P*V to read it 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. The backward
is credited the standard 2x the forward. Building the feature map, the running normaliser and the
divide are O(K*K + V) per token and are not counted.
"""
P = 1 + K + K * K
return 2 * (B * H * T * (4 * P * V + 2 * C * (K + V)))
''',
flops_formula="2 * ( B*H*T * (4*(1 + K + K*K)*V + 2*C*(K + V)) ) with C = 64 # 2x the forward",
metric="TFLOP/s",
compare="tuple",
tuple_names=("dq", "dk", "dv"),
tol=2e-2,
shape_names=("B", "T", "H", "K", "V"),
grader_shapes=[(4, 8192, 32, 16, 128), (8, 4096, 32, 16, 128), (8, 8192, 16, 16, 128),
(6, 8192, 24, 16, 128), (8, 8192, 32, 8, 128)],
measure_shapes=[(4, 8192, 24, 16, 128), (8, 4096, 16, 16, 128), (4, 8192, 32, 16, 64),
(6, 4096, 32, 16, 128), (4, 8192, 32, 8, 128)],
measure_quick_shapes=[(1, 2048, 16, 16, 128), (2, 2048, 8, 16, 128), (1, 4096, 16, 8, 128)],
correct_shapes=[(1, 512, 4, 16, 128), (2, 1024, 8, 8, 64), (1, 1024, 6, 16, 64), (2, 256, 4, 16, 128)],
spec_md="""The forward 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 )
```
You must return the gradients of that forward with respect to `q, k, v`, given the incoming gradient `do` of
the loss with respect to `o`.
**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 layer is an ordinary linear attention over a
`P`-dimensional feature space with state `S = sum_j phi(k_j) v_j^T` and normaliser `z = sum_j phi(k_j)`. `K`
is the small Taylor **feature** dimension (8 or 16), not the head dimension — `V` is the head dimension —
which is what keeps `P` (73 or 273) manageable.
Two things make the backward its own problem rather than a transposed forward. First, the output is a
**quotient**: `do` has to be pushed through `num/(den + 1e-6)`, which produces a second, `V`-contracted
signal `-o * do / den` that feeds the *normaliser* path `z`, so every one of `dq`, `dk`, `dv` has a
numerator term and a denominator term. Second, `dq` needs the derivative of `phi(q)` — the outer product
`q (x) q` differentiates to something that touches every feature twice — and `dk` needs the same for
`phi(k)` while `k` also appears inside the reverse state.
`/app/reference.py` gives you `_based_forward` — the forward in its chunked form (chunk length 128: the
explicit feature map across chunks, the direct polynomial inside a chunk) — and obtains the gradients by
running it under **autograd**. That is the specification, and it is what torch gives you for free, but it
materialises `phi(q)` and `phi(k)` (`P/K` times bigger than `q` and `k`), every `C x C` weight tile and the
`(P, V)` state at every chunk boundary 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` is the Taylor **feature** dimension |
| `k` | `(B, T, H, K)` | `bfloat16` | keys |
| `v` | `(B, T, H, V)` | `bfloat16` | values; `V` is the head dimension |
| `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: `K`, not `V`) |
**Return** a 3-tuple `(dq, dk, dv)` **in that order**, with shapes `(B,T,H,K)`, `(B,T,H,K)`, `(B,T,H,V)` —
the same shapes as `q`, `k`, `v`. Each may be `bfloat16` or `float32`.
**All three are graded.** Getting two of three right scores **0**.
`scale` multiplies **`q` only**, before the dot product, so the polynomial is evaluated at
`s = (scale * q_i) . k_j` and `dq` carries that factor. The denominator guard is exactly `+ 1e-6`, added
after the row sum, and it is inside the derivative: `d/d(den) [num/(den + 1e-6)] = -num/(den + 1e-6)^2`.
Attention is fully causal and includes the diagonal (`j <= i`), so position `0` has the single weight
`A[0, 0]` and never an empty row. `K != V` in general and `K` is small. There is no initial or final state,
no state gradient, no sliding window and no softmax.
All tensors are CUDA and contiguous. `T` is a multiple of 128. 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 4096–8192, `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. `B*H` is 96–256. Write a **general** kernel.""",
correctness_md="""**All three** gradients must match the reference (evaluated in fp32) within **relative
Frobenius error `2e-2`** at every graded shape, including the timed ones. Getting two of three right scores
**0**.""",
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, and autograd multiplies it: `phi(q)`, `phi(k)`,
every `C x C` tile of `s` and `A`, and the `(P, V)` state at every chunk boundary are all kept alive for the
reverse pass.
The kernel you want never materialises `phi` at all. `phi(x) = [1, x, outer(x, x)/sqrt(2)]`, so the `(P, V)`
state is really a `(1, V)` block, a `(K, V)` block and a `(K, K, V)` block, and the same decomposition
applies to the **reverse** state `dS = sum_{i >= j} phi(q_i) (do_i)^T` that `dk` and `dv` are read out of.
Each block has its own natural update, and the quadratic block — `K` independent `(K, V)` linear-attention
states, one per feature of `k` — is where essentially all the FLOPs are.
Three structural points specific to the backward:
- **The normaliser is a second, cheaper linear attention.** `den` is the same computation with `v` replaced
by a column of ones, and its adjoint is the same reverse scan with `do` replaced by `-o . do / den`
(a per-position scalar). Fuse it into the same pass — do not spend a second set of matmuls on it.
- **Inside a chunk, stay in the quadratic form.** Evaluating `1 + s + s^2/2` directly from a `C x C` score
tile is much cheaper than going through the `P`-dimensional feature map, and its adjoint is just
`dA -> (1 + s) * dA` folded back into `dq` and `dk` — two ordinary bf16 matmuls plus one elementwise
polynomial, exactly as in the forward.
- **Recompute, don't store.** `A`, `phi(q)`, `phi(k)` and the running state are all cheap to rebuild from
`q, k, v` during the reverse scan; at `K = 16, V = 128` the quadratic state block alone is `256 x 128`
floats, so how you split it across warps/CTAs and whether you keep it in bf16 with fp32 accumulation of
the increments is the main design decision.""",
precision_md="""All inputs and outputs are **bfloat16** — 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.
Both state carries **must be fp32**: the forward `S = sum phi(k_j) v_j^T` / `z = sum phi(k_j)`, and the
reverse `dS = sum phi(q_i) do_i^T`. These are **ungated** sums over the whole prefix (resp. suffix) — there
is no decay to forget old terms — so by the end of the sequence they are reductions over thousands of
contributions while each increment stays `O(1)`. In bf16 the increments stop moving the accumulator well
before the end and the error compounds with `T`. `z` is a **denominator**, so an error there is a relative
error on the whole output row and on its entire gradient, not a damped one.
**Gradient reductions drift first**, and here `dq` and `dk` are the exposed ones: each is a contraction over
the full `P`-dimensional feature axis *and* over `V`, so they want fp32 accumulators throughout. Note also
that `s^2` computed in bf16 doubles its relative error before it is summed — square in fp32.
For calibration, a measured bf16 pipeline for this op (bf16 matmul operands, fp32 accumulation, fp32 state
and normaliser) lands at **3.5e-3 / 3.5e-3 / 2.7e-3** relative error on `dq / dk / dv` at
`(B, T, H, K, V) = (2, 2048, 8, 16, 128)` — roughly 6x inside the `2e-2` gate, and flat in `T`.
For a sense of scale on the other side: truncating the feature map to first order (`A = 1 + s`, i.e. plain
linear attention) misses by **2.9 / 2.6 / 0.75** on `dq / dk / dv` at that shape. The 2nd-order term is the
entire point of the method and is not optional.
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()