KBench / tools /factory /specs /causal_video_kv_cache_decode.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
16.9 kB
"""Spec for `causal-video-kv-cache-decode` — CausVid / self-forcing chunked autoregressive video decode."""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from spec import TaskSpec
SPEC = TaskSpec(
name="causal-video-kv-cache-decode",
title="Write a fast block-causal video KV-cache decode attention kernel",
blurb=("Autoregressive video generation (CausVid, self-forcing) does not decode a token at a time — it "
"decodes a CHUNK OF FRAMES at a time. The new chunk's ~5k tokens attend bidirectionally to each "
"other and causally to every frame already generated, and the cache is paged at FRAME "
"granularity, so the keys arrive through a per-request frame table with a different number of "
"cached frames per request. A prefill-shaped query block against a paged, ragged, frame-indexed "
"KV cache."),
keywords=["mle", "kernel-generation", "attention", "video-diffusion", "causvid", "self-forcing",
"kv-cache", "paged-attention", "autoregressive-video", "block-causal"],
module="causal_video_decode.py",
func="causal_video_cache_attention",
signature=("causal_video_cache_attention(q, k_new, v_new, k_cache, v_cache, frame_table, cache_frames, "
"frame_tokens, scale=None)"),
returns_doc="""Block-causal attention of a new frame chunk against a frame-paged video KV cache.
Args:
q, k_new, v_new: (B, CQ*S, NH, D) bfloat16 — the new chunk: CQ frames of S = frame_tokens tokens.
k_cache, v_cache: (B, NSLOT, S, NH, D) bfloat16 — the frame-paged cache; one slot holds one frame.
frame_table: (B, P) int32 — frame_table[b, j] is the SLOT holding request b's j-th cached frame,
in temporal order. Only the first cache_frames[b] entries are valid.
cache_frames: (B,) int32 — number of valid cached frames per request, 0 <= cache_frames[b] <= P.
frame_tokens: int — S, the number of latent tokens in one frame.
scale: float or None — logit scale; None means D ** -0.5.
Returns:
o: (B, CQ*S, NH, D), bfloat16 or float32 — must match /app/reference.py numerically.""",
reference_imports="import torch",
reference_src='''
def causal_video_cache_attention(q, k_new, v_new, k_cache, v_cache, frame_table, cache_frames,
frame_tokens, scale=None):
"""Block-causal chunk-vs-cache attention, written as an explicit gather + dense softmax in fp32.
Correct and simple — it is the numerical SPECIFICATION, not a performance target. It gathers every
request's whole cache through the frame table and softmaxes the full score matrix.
"""
B, QT, NH, D = q.shape
S = frame_tokens
P = frame_table.shape[1]
if scale is None:
scale = D ** -0.5
dev = q.device
o = torch.empty(B, QT, NH, D, device=dev, dtype=torch.float32)
for b in range(B):
n = int(cache_frames[b].item())
slots = frame_table[b, :n].long()
kc = k_cache[b, slots].reshape(n * S, NH, D).float() if n else \\
torch.zeros(0, NH, D, device=dev)
vc = v_cache[b, slots].reshape(n * S, NH, D).float() if n else \\
torch.zeros(0, NH, D, device=dev)
kk = torch.cat([kc, k_new[b].float()], dim=0) # cache first, then the new chunk
vv = torch.cat([vc, v_new[b].float()], dim=0)
qf = q[b].float() * scale
step = max(1, int(2e8) // max(1, kk.shape[0] * NH * 4))
for s0 in range(0, QT, step):
e0 = min(QT, s0 + step)
s = torch.einsum("qhd,khd->hqk", qf[s0:e0], kk)
o[b, s0:e0] = torch.einsum("hqk,khd->qhd", torch.softmax(s, dim=-1), vv)
return o
''',
make_inputs_src='''
def _mk(B, CQ, S, NH, D, P, seed):
gen = torch.Generator(device="cuda").manual_seed(seed)
NSLOT = P + 8 # the pool is bigger than any request needs
QT = CQ * S
def r(*sh):
return torch.randn(*sh, device="cuda", dtype=torch.bfloat16, generator=gen)
q, kn, vn = r(B, QT, NH, D), r(B, QT, NH, D), r(B, QT, NH, D)
kc, vc = r(B, NSLOT, S, NH, D), r(B, NSLOT, S, NH, D)
cf = torch.tensor(_cache_frames(B, P), device="cuda", dtype=torch.int32)
# a scrambled frame table: temporal order is NOT slot order, and unused entries hold stale slot ids
tab = torch.rand(B, NSLOT, device="cuda", generator=gen).argsort(dim=-1)[:, :P].int().contiguous()
return q, kn, vn, kc, vc, tab, cf, S
''',
flops_src='''
def _cache_frames(B, P):
"""Valid cached frames per request, from the SHAPE ALONE — a deterministic ragged mix."""
return [max(1, P - ((b * 5 + 3) % (P // 2 + 1))) for b in range(B)]
def canonical_work(B, CQ, S, NH, D, P):
"""FLOPs attributed to one forward, from the SHAPE ALONE.
Request b's CQ*S new queries each attend to cache_frames[b]*S cached keys plus the whole CQ*S new chunk
(bidirectional inside the chunk). Each pair costs 4*D FLOPs. The padding beyond cache_frames[b] is never
credited.
"""
QT = CQ * S
pairs = sum(QT * (n * S + QT) for n in _cache_frames(B, P))
return 4 * D * NH * pairs
''',
flops_formula="""QT = CQ * S
FLOPs = 4 * D * NH * sum over b of ( QT * ( cache_frames[b]*S + QT ) ) # 2*D for q.k + 2*D for p*v""",
metric="TFLOP/s",
compare="tensor",
tol=5e-3,
shape_names=("B", "CQ", "S", "NH", "D", "P"),
grader_shapes=[(1, 3, 1536, 16, 128, 24),
(2, 2, 1536, 12, 128, 20),
(1, 4, 2048, 12, 128, 16),
(1, 3, 1536, 24, 64, 24),
(2, 3, 1024, 16, 128, 28)],
measure_shapes=[(1, 3, 1536, 12, 128, 20),
(2, 2, 1536, 10, 128, 16),
(1, 4, 1536, 12, 128, 16),
(1, 3, 1536, 20, 64, 20),
(2, 3, 1024, 12, 128, 24)],
measure_quick_shapes=[(1, 2, 512, 8, 128, 8),
(2, 2, 384, 8, 64, 6),
(1, 3, 512, 8, 128, 6)],
correct_shapes=[(1, 2, 256, 4, 64, 6),
(3, 2, 192, 4, 64, 5),
(1, 3, 320, 8, 128, 8),
(2, 1, 256, 4, 64, 4),
(1, 4, 128, 6, 128, 7),
(2, 2, 200, 4, 64, 9)],
spec_md="""A chunked autoregressive video decoder. Each step generates `CQ` **whole frames** of `S`
latent tokens, so the query block is `QT = CQ*S` tokens — thousands of them, a prefill-shaped block, not one
token.
**The cache is paged at frame granularity.** `k_cache` / `v_cache` are a pool of `NSLOT` slots, each holding
one whole frame of `S` tokens. Request `b`'s history is `cache_frames[b]` frames, and the slot holding its
`j`-th oldest frame is `frame_table[b, j]`. Slots are **not** assigned in order, the table is shared between
requests only in the sense that they draw from the same pool, and entries at `j >= cache_frames[b]` are
**stale**: valid slot ids that point at other requests' data, so dereferencing them will not fault, it will
silently give the wrong answer.
**The mask.** For request `b`, write `Kb` for the concatenation
```
Kb = [ cache frame 0 | cache frame 1 | ... | cache frame cache_frames[b]-1 | the new chunk ]
(that is, cache_frames[b]*S cached keys followed by the QT keys of k_new)
```
Every one of the `QT` new queries attends to **all** of `Kb`:
```
logit(i, r) = scale * (q_i . Kb_r)
o_i = softmax_r( logit(i, r) ) @ Vb
```
with `scale` defaulting to `D ** -0.5`. Two things follow:
* **The history is fully visible** — that is the "causal" part, at chunk granularity: everything already
generated is in the past.
* **Inside the new chunk the attention is bidirectional** — there is *no* token-level causal mask. The chunk
is denoised jointly, so its tokens see each other in both directions. This is the single most common thing
to get wrong here: it is not a triangular mask.
The concatenation order (cache then new chunk) is not observable in the result — softmax is permutation
invariant over keys — but the *set* is, and so is which cache slots belong to the set.
`cache_frames[b]` is at least 1 and varies between requests, so the reduction length differs per request.
`/app/reference.py` gathers each request's whole cache through the frame table and softmaxes the full score
matrix. That is the exact specification; it is deliberately simple rather than fast.""",
contract_md="""| arg | shape | dtype | meaning |
|-----|-------|-------|---------|
| `q` | `(B, CQ*S, NH, D)` | `bfloat16` | the new chunk's queries |
| `k_new`, `v_new` | `(B, CQ*S, NH, D)` | `bfloat16` | the new chunk's own keys / values |
| `k_cache`, `v_cache` | `(B, NSLOT, S, NH, D)` | `bfloat16` | frame-paged cache pool; slot = one whole frame |
| `frame_table` | `(B, P)` | `int32` | slot of the `j`-th cached frame, temporal order; only `[0, cache_frames[b])` is valid |
| `cache_frames` | `(B,)` | `int32` | valid cached frames per request, `1 <= cache_frames[b] <= P` |
| `frame_tokens` | scalar | `int` | `S`, tokens per frame |
| `scale` | scalar | `float` or `None` | logit scale; `None` means `D ** -0.5` |
**Return** `o` of shape `(B, CQ*S, NH, D)`, dtype `bfloat16` or `float32`.
`NSLOT >= P` and slot ids are in `[0, NSLOT)`. `frame_table` and `cache_frames` are **device** tensors —
reading them back to the host inside the call is a synchronisation on the critical path and is measured.
Nothing is written back: the cache append for this chunk happens elsewhere.
All tensors are CUDA, contiguous, **read-only**. No GQA, no RoPE, no dropout, no bias, and **no token-level
causal mask**.""",
regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `CQ` 2-4
frames per step, `S` 1024-2048 tokens per frame (so `QT` = 2k-8k queries), `NH` 12-24, `D` in {64, 128},
`P` 16-28 cached frames, `B` 1-2. `cache_frames[b]` is ragged and roughly `P/2` to `P`.
That is 20k-45k cached keys against a few thousand queries: a fat, cache-dominated attention where the KV
stream is the bottleneck and the frame table is the only indirection.""",
correctness_md="""Your output must match the reference (evaluated in fp32 as a stable ground truth)
within **relative Frobenius error `5e-3`** at every graded shape, including the timed ones. Reading one
stale table entry (index `>= cache_frames[b]`) corrupts an entire frame of keys and fails immediately.
The gate is calibrated against the ways this kernel actually goes wrong. Measured on the real graded
inputs, relative error of a kernel that:
* **ignores `cache_frames`** and reads all `P` table entries (stale slots included): **0.34-0.64**
* **ignores the frame table** and reads cache slots `0..n-1` in slot order: **0.72-1.14**
* **drops the oldest half** of each request's cached frames: **0.49-0.87**
* **applies a token-level causal mask inside the new chunk**: **0.25-0.63**
The weakest of those is still **~50x the tolerance**, so every one of the four is rejected outright.""",
perf_md="""**This is a flash-attention prefill whose key stream comes through a page table.** The query
block is `QT` = thousands of rows, the key stream is tens of thousands, and each cache "page" is a whole
frame — `S x NH x D` bf16, i.e. hundreds of kilobytes — so the indirection cost per byte loaded is
negligible *if* you hoist it: read `frame_table[b, j]` once per page, then stream that page contiguously.
**Split over the key axis.** With `QT` in the thousands and the cache in the tens of thousands, a single
threadblock per `(query tile, head)` gives you `QT/BLOCK_M * NH` blocks — usually enough, but the reduction
per block is long. If occupancy is short (small `B`, small `NH`), split the key axis, produce partial
`(o, lse)` per split and merge; the merge is cheap next to a 45k-key reduction.
**Ragged reductions.** `cache_frames[b]` differs per request, so with `B = 2` one request can do twice the
work of the other. Build the work list from `cache_frames` on the device and schedule flat over
`(b, query tile, key split)` rather than a rectangular grid.
**The new chunk is contiguous and dense.** Handle it as the final (or first) segment of the same online
softmax; there is no mask on it at all, so it is a plain dense tile — do not build a triangular mask you then
have to ignore.
**Do not synchronise on `cache_frames`.** Its values decide the loop bound. Either read it inside the kernel
and loop dynamically, or precompute a device-side work list in a tiny setup kernel. A `.item()` per request
serialises the launch.
**Frame-major cache layout.** `k_cache[b, slot]` is `S*NH*D` contiguous elements; a whole frame is a single
long, perfectly coalesced read. Vectorise along `D` and stream it — this kernel should be close to KV
bandwidth bound at the graded shapes.""",
precision_md="""All inputs and outputs are **bfloat16** except the two index tensors (`int32`). Matmuls
on bf16 tensor cores with **fp32 accumulation**; online-softmax state in **fp32**. Reductions are 20k-45k
keys long and *ragged*, so a bf16 running sum degrades differently for different requests — easy to misread
as a paging bug.
**How the tolerance was set (measured, not guessed).** Two independent implementations were compared
against the reference on the real graded inputs: an fp32 whole-batch dense masked softmax over a padded
key stream — no per-request loop, no query chunking — which reproduces the reference bit for bit
(relative error 0.0 at the correctness shapes, 2e-7 at the largest graded one), and a fused **bf16**
flash kernel with fp32 accumulation, the shape of implementation this task wants. The bf16 one differs
from the fp32 reference by **E = 2.3e-3**, essentially constant from 1.5k to 45k keys. `tol` is set at
**5e-3, about 2.2x E**. This is an arithmetic gate, not a bit-exactness one: 5e-3 sits below bf16 epsilon
(~8e-3) but an honest bf16 kernel clears it with more than 2x of margin, because the Frobenius error of a
long fp32-accumulated reduction is well under one bf16 ULP.
**fp8** is acceptable for the cache-side matmuls if you can hold the tolerance; this is the regime where a
quantised KV cache is actually used.
`frame_table` and `cache_frames` are **exact integer data**. Compare and index with integers — `.float()` is
lossy above `2**24` and buys nothing here. Slots at `j >= cache_frames[b]` are *valid but wrong*: they will
not fault, so a bounds bug shows up only as a numerical error.
Do not shorten the reduction: every cached frame in `[0, cache_frames[b])` is in the denominator, and
skipping the oldest frames (they "matter less") is a systematic error that grows with `P`.
Do **not** infer from the reference that fp32 compute is wanted; it runs in fp32 purely to be a stable
numerical *specification*.""",
).validate()
# ---------------------------------------------------------------------------------------------------
DROP_SRC = '''
def _drop(q, k_new, v_new, k_cache, v_cache, frame_table, cache_frames, frame_tokens, scale=None):
"""Drop-the-feature: ignore cache_frames and use the WHOLE frame table (stale entries included)."""
B, QT, NH, D = q.shape
S = frame_tokens
P = frame_table.shape[1]
if scale is None:
scale = D ** -0.5
dev = q.device
o = torch.empty(B, QT, NH, D, device=dev, dtype=torch.float32)
for b in range(B):
slots = frame_table[b].long()
kk = torch.cat([k_cache[b, slots].reshape(P * S, NH, D).float(), k_new[b].float()], 0)
vv = torch.cat([v_cache[b, slots].reshape(P * S, NH, D).float(), v_new[b].float()], 0)
s = torch.einsum("qhd,khd->hqk", q[b].float() * scale, kk)
o[b] = torch.einsum("hqk,khd->qhd", torch.softmax(s, -1), vv)
return o
'''
DROP2_SRC = '''
def _drop2(q, k_new, v_new, k_cache, v_cache, frame_table, cache_frames, frame_tokens, scale=None):
"""Second drop check: apply a token-level CAUSAL mask inside the new chunk."""
B, QT, NH, D = q.shape
S = frame_tokens
if scale is None:
scale = D ** -0.5
dev = q.device
o = torch.empty(B, QT, NH, D, device=dev, dtype=torch.float32)
ar = torch.arange(QT, device=dev)
for b in range(B):
n = int(cache_frames[b].item())
slots = frame_table[b, :n].long()
kk = torch.cat([k_cache[b, slots].reshape(n * S, NH, D).float(), k_new[b].float()], 0)
vv = torch.cat([v_cache[b, slots].reshape(n * S, NH, D).float(), v_new[b].float()], 0)
s = torch.einsum("qhd,khd->hqk", q[b].float() * scale, kk)
m = torch.ones(QT, n * S + QT, dtype=torch.bool, device=dev)
m[:, n * S:] = ar[None, :] <= ar[:, None]
s = s.masked_fill(~m, float("-inf"))
o[b] = torch.einsum("hqk,khd->qhd", torch.softmax(s, -1), vv)
return o
'''