KBench / tools /factory /specs /deepseek_v32_sparse_mla_decode.py
ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 21)
4161512 verified
Raw
History Blame Contribute Delete
13.5 kB
"""Spec for `deepseek-v32-sparse-mla-decode` — absorbed MLA decode restricted to an index list, the second
half of DeepSeek-V3.2 sparse attention."""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from spec import TaskSpec
SPEC = TaskSpec(
name="deepseek-v32-sparse-mla-decode",
title="Write a fast sparse MLA decode kernel (attention over an index list)",
blurb=("Once DeepSeek-V3.2's indexer has picked the few thousand positions worth attending to, this is "
"the kernel that actually attends to them: absorbed Multi-head Latent Attention over an "
"arbitrary LIST of cache rows rather than a contiguous history. One latent per selected "
"position serves as both key and value for all 128 heads, and the rows are scattered anywhere "
"in a multi-gigabyte pool — so unlike dense decode there is no contiguity to exploit at all, "
"and the whole problem is turning a random gather into something that still streams."),
keywords=["mle", "kernel-generation", "mla", "dsa", "deepseek", "sparse-attention", "latent-attention",
"decode", "gather", "kv-cache", "memory-bound"],
module="sparse_mla.py",
func="sparse_mla_decode",
signature="sparse_mla_decode(q, kv_cache, indices, dv, scale=None)",
returns_doc="""Absorbed MLA decode over an explicit list of selected cache rows.
Args:
q: (B, H, DT) bfloat16 — this token's query per head, already absorbed into the latent
space; DT = dv + rope width.
kv_cache: (NROWS, DT) bfloat16 — the flat latent pool; one vector per cached position, SHARED by
all heads: [ latent(dv) | k_rope(DT - dv) ].
indices: (B, K) int32 — the K cache rows selected for request b, in ARBITRARY order.
dv: int — width of the latent (value) part; the trailing DT - dv dims are
the decoupled-RoPE key, which scores but is not read out.
scale: float or None — logit scale; None means DT ** -0.5.
Returns:
o: (B, H, dv), bfloat16 or float32 — must match /app/reference.py numerically.""",
reference_imports="import torch",
reference_src='''
CH = 32 # the reference tiles over requests purely so it FITS; it makes no attempt to be fast
def sparse_mla_decode(q, kv_cache, indices, dv, scale=None):
"""Gather the selected rows and run a dense fp32 softmax over them.
Correct and simple — it is the numerical SPECIFICATION, not a performance target. It materialises the
gathered (K, DT) block in fp32 for every request and then makes several passes over it; a real kernel
reads each selected row ONCE, in bfloat16, straight into registers.
The latent is shared by every head (this is MQA with one very wide head), and the SAME vector is both
the key (all DT dims score) and the value (its leading dv dims are read out).
"""
B, H, DT = q.shape
if scale is None:
scale = DT ** -0.5
o = torch.empty(B, H, dv, device=q.device, dtype=torch.float32)
for b0 in range(0, B, CH):
b1 = min(b0 + CH, B)
kv = kv_cache[indices[b0:b1].long()].float() # (b, K, DT) the selected rows
s = torch.einsum("bhd,bkd->bhk", q[b0:b1].float() * scale, kv) # FULL DT-wide dot product
p = torch.softmax(s, dim=-1) # no mask: every slot is selected
o[b0:b1] = torch.einsum("bhk,bkd->bhd", p, kv[:, :, :dv]) # value = the LATENT part only
return o.to(torch.bfloat16)
''',
make_inputs_src='''
def _mk(B, K, H, DV, DR, NROWS, seed):
"""A latent pool plus K DISTINCT selected rows per request, scattered over the whole pool.
The selection is stratified (one row from each of K equal buckets) so the indices are distinct without
a sort, and then randomly permuted, so the kernel sees them in arbitrary order — which is what the
indexer's top-k actually produces.
"""
gen = torch.Generator(device="cuda").manual_seed(seed)
DT = DV + DR
q = torch.randn(B, H, DT, device="cuda", dtype=torch.bfloat16, generator=gen)
kv_cache = (torch.randn(NROWS, DT, device="cuda", generator=gen) * DT ** -0.25).to(torch.bfloat16)
stride = NROWS // K
base = (torch.arange(K, device="cuda") * stride).view(1, K)
off = (torch.rand(B, K, device="cuda", generator=gen) * stride).long()
idx = base + off # distinct by construction
order = torch.rand(B, K, device="cuda", generator=gen).argsort(dim=-1)
indices = idx.gather(1, order).to(torch.int32) # arbitrary order
return q, kv_cache, indices, DV, None
''',
flops_src='''
def canonical_work(B, K, H, DV, DR, NROWS):
"""BYTES attributed to one sparse MLA decode step, from the SHAPE ALONE.
Sparse decode is memory bound, so work is counted as the unavoidable HBM traffic: the B*K SELECTED
latent rows read EXACTLY ONCE, in native bfloat16, DT = DV + DR elements each. Note there is only ONE
such read: in MLA the key and the value are the same latent, so unlike ordinary attention there is no
second pass for V, and all H heads share the row. The query and the output are included; the index
list is 4 bytes per selected row.
"""
DT = DV + DR
return 2 * DT * B * K + 4 * B * K + 2 * B * H * DT + 2 * B * H * DV
''',
flops_formula=("DT = DV + DR\n"
"bytes = 2*DT*B*K + 4*B*K + 2*B*H*DT + 2*B*H*DV\n"
"# selected rows indices query output"),
metric="GB/s",
compare="tensor",
tol=7e-3, # MEASURED: 2.05x the 3.41e-3 worst gap to an independent online-softmax implementation
shape_names=("B", "K", "H", "DV", "DR", "NROWS"),
grader_shapes=[(768, 2048, 128, 512, 64, 1048576), (512, 4096, 128, 512, 64, 1048576),
(1024, 2048, 128, 512, 64, 1048576), (768, 3072, 128, 512, 64, 1048576),
(640, 2048, 64, 512, 64, 786432)],
measure_shapes=[(704, 2048, 128, 512, 64, 1048576), (448, 4096, 128, 512, 64, 1048576),
(896, 2048, 128, 512, 64, 1048576), (704, 3072, 128, 512, 64, 1048576),
(576, 2048, 64, 512, 64, 786432)],
measure_quick_shapes=[(64, 1024, 64, 512, 64, 131072), (128, 512, 32, 512, 64, 65536),
(32, 2048, 128, 512, 64, 131072)],
correct_shapes=[(5, 256, 8, 128, 32, 4096), (3, 129, 16, 256, 64, 2048),
(7, 512, 4, 512, 64, 8192), (2, 64, 32, 128, 32, 1024)],
spec_md="""This is the second half of DeepSeek-V3.2's sparse attention: the indexer has already chosen
`K` cache rows per request, and this kernel attends over exactly those.
```
kv[b, j, :] = kv_cache[ indices[b, j], : ] # (B, K, DT), an arbitrary gather
s[b, h, j] = ( q[b, h, :] . kv[b, j, :] ) * scale # scale = DT**-0.5 when scale is None
p = softmax(s, over j) # every selected slot is valid: no mask
o[b, h, :] = sum_j p[b, h, j] * kv[b, j, :dv] # read out the LATENT part only
```
Three things follow from Multi-head Latent Attention that make this different from a sparse-gather
attention on ordinary K/V:
* **The key and the value are the same tensor.** One row of the cache is scored in full (`DT` dims,
latent *and* decoupled-RoPE key) and then read out in part (its first `dv` dims). There is no second
tensor to fetch, so the byte count credits exactly one read per selected row.
* **Every head shares the row.** This is MQA with one very wide head: `q` has `H` heads but the cache has
none, so a row that is loaded once serves all `H` dot products and all `H` accumulations.
* **The rows are anywhere.** `indices[b]` is what a top-k produced: `K` distinct rows in arbitrary order,
scattered across a pool of `NROWS`. There is no page structure and no contiguity to lean on.
`indices` contains no padding and no `-1` — every slot is a real selected row — so there is nothing to
mask.
`/app/reference.py` gathers each request's `(K, DT)` block into fp32 and runs a dense softmax over it. That
is the exact specification; it is deliberately simple rather than fast.""",
contract_md="""| arg | shape | dtype | meaning |
|-----|-------|-------|---------|
| `q` | `(B, H, DT)` | `bfloat16` | absorbed query per head; `DT = dv + DR` |
| `kv_cache` | `(NROWS, DT)` | `bfloat16` | flat latent pool, `[ latent(dv) \\| k_rope(DR) ]` per row |
| `indices` | `(B, K)` | `int32` | the `K` selected rows of request `b`, **arbitrary order**, distinct |
| `dv` | int | | width of the latent part read out |
| `scale` | float or `None` | | logit scale; `None` means `DT ** -0.5` |
**Return** a single tensor `o` of shape `(B, H, dv)`, bfloat16 or float32 (the grader compares in fp32).
All inputs are **read-only**. `K` is **not** guaranteed to be a multiple of any tile size — the correctness
shapes include `K = 129` — and `B` is small and ragged (3, 5, 7 appear).""",
regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B`
(concurrent requests) in 512–1024, `K` (selected rows per request) in 2048–4096, `H` in 64–128,
`dv` = 512, `DR` = 64 (so `DT` = 576), and a pool `NROWS` of 786432 to 1048576 rows (0.9–1.2 GB).
Between 1 and 2.5 GiB
of latent is gathered per call — that gather is the entire kernel, and the arithmetic on top of it
(`2*H*DT` FLOPs per row at `H = 128`) still leaves it firmly bandwidth-bound.""",
correctness_md="""The returned tensor must match the reference (evaluated in fp32) within **relative
Frobenius error `7e-3`** at every graded shape, including the timed ones.
That gate is **measured**, and the shortcuts this shape invites miss it by orders of magnitude: scoring
only the latent part and ignoring the trailing decoupled-RoPE dimensions of the key scores **0.063**
(9x the tolerance — the RoPE part is only 64 of 576 dims, so this is the tightest ablation here and the
first place to look if you are off by a few percent), and ignoring `indices` to read the first `K` rows of
the pool scores **1.2**, 174x the tolerance.""",
perf_md="""A random gather of 1–2.5 GiB with a softmax on top. Everything is decided by how well the
gather streams.
**One row, all heads, once.** Each selected row is 1152 bytes at the graded shapes — nine 128-byte
sectors, perfectly coalesced *within* a row and completely unrelated to the next one. Load it once into
registers or shared memory and use it for all `H` dot products *and* for the `p @ v` accumulation. A
kernel that makes a scoring pass and then a second value pass reads the pool twice and halves its score;
the fix is an online (flash-decoding) softmax that keeps a running max, a running sum, and an accumulator
so one visit per row suffices.
**`H = 128` heads share one 576-wide row.** That is 128 dot products of length 576 per loaded row, i.e.
plenty of arithmetic to hide the latency of an irregular load — but only if you have enough rows in flight.
Deep unrolling and multi-stage prefetch (async copy / TMA-style) on the index list is what turns a
dependent gather into a stream.
**Sorting is allowed and can pay.** The indices arrive in arbitrary order; nothing in the contract depends
on the order in which you visit them, only on the mathematical result. Rows that happen to be near each
other in the pool share DRAM pages, so a per-request sort (or a partial bucketing) can measurably improve
locality — weigh it against its own cost.
**Split-K for occupancy.** `B*H` is large but `B` alone is only in the hundreds, so a one-block-per-request
grid under-fills the machine. Partition the index list across blocks and merge partial `(o, m, l)` triples
with the standard log-sum-exp combine.
The output is `(B, H, dv)` — up to a hundred megabytes — so make its write vectorised, and note that `q` at
`(B, H, DT)` is read once and is small enough to stay resident per request.""",
precision_md="""The cache and the query are **bfloat16**; the output may be bf16 or fp32.
Accumulate the logits, the online softmax and the `p @ v` product in **fp32**, and merge split-K partials
in fp32. `K` reaches 4096, so a bf16 accumulator over the value axis would lose the tail of the sum and
produce an error that *grows* with `K` — which the faithfulness clause below rejects.
**fp8 is not appropriate here**: the latent arrives in bf16 and re-quantising it on the fly is an
approximation of the specified computation rather than an implementation of it.
**Where the tolerance comes from.** `6e-3` is measured. A second, independent implementation — the rows
gathered per request instead of per batch chunk, the scoring done as a bf16 tensor-core matmul with fp32
accumulate, an online softmax processing the index list in 256-row blocks (a completely different
reduction order from the reference's dense one), and the output kept in bf16 — differs from this fp32
reference by a worst relative Frobenius error of **3.41e-3** across the correctness shapes and a full-size
graded shape, over several seeds. The tolerance is **2.05x** that, and the error does not grow with `K`
(3.17e-3 at `K = 2048`, 3.41e-3 at `K = 129`) — it is the bf16 rounding of the operands and of the
returned tensor.""",
).validate()