| """Spec for `adaptive-sparsity-threshold` — per-row adaptive block threshold + 3D dilation + bit-packing.""" |
| import pathlib |
| import sys |
|
|
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) |
| from spec import TaskSpec |
|
|
| SPEC = TaskSpec( |
| name="adaptive-sparsity-threshold", |
| title="Write a fast adaptive block-sparsity threshold + 3D mask dilation kernel", |
| blurb=("Every run-time sparse video attention scheme has to turn a tile-level score estimate into the " |
| "actual bitmap the attention kernel consumes, and a fixed top-k is the wrong tool: heads differ " |
| "wildly in how concentrated they are, so the budget has to ADAPT. The rule that survives is " |
| "per-row and relative — keep every tile within `delta` logits of the row's best — followed by a " |
| "3D DILATION, because a pooled estimate is coarse and the real mass straddles tile boundaries. " |
| "One pass over a multi-gigabyte score map, out comes a packed bitmap, per-row counts and the " |
| "per-head density the scheduler needs."), |
| keywords=["mle", "kernel-generation", "sparse-attention", "video-diffusion", "block-mask", "bitmap", |
| "dilation", "hunyuanvideo", "wan", "mask-build"], |
| module="adaptive_mask.py", |
| func="adaptive_sparsity_mask", |
| signature="adaptive_sparsity_mask(scores, delta, grid)", |
| returns_doc="""Adaptive per-row threshold + 3D dilation of a tile-level attention score map. |
| |
| Args: |
| scores: (B, NH, NT, NT) float32 — tile-level score estimate; scores[b,h,i,j] is query tile i against key |
| tile j. Both axes index the SAME 3D tile grid, raster ordered (f, then h, then w). |
| delta: (NH,) float32 — per-head threshold margin, in logits, below the row maximum. |
| grid: (GF, GH, GW) tuple of int — the 3D tile grid; GF*GH*GW == NT, and NT is a multiple of 8. |
| |
| Returns: |
| (bits, counts, density): |
| bits: (B, NH, NT, NT//8) uint8 — packed keep-mask, LSB-first (bit b of byte w is tile 8*w+b). |
| counts: (B, NH, NT) int32 — number of kept key tiles per row. |
| density: (B, NH) float32 — kept fraction per head = sum(counts) / (NT*NT). |
| `bits` and `counts` are compared EXACTLY; they are the bitmap a sparse attention kernel then runs on.""", |
|
|
| reference_imports="import torch", |
| reference_src=''' |
| def adaptive_sparsity_mask(scores, delta, grid): |
| """Adaptive threshold + 3D dilation + bit packing, written as dense boolean tensor algebra in fp32. |
| |
| Correct and simple — it is the numerical SPECIFICATION, not a performance target. It materialises the |
| whole boolean keep-map one (batch, head) at a time and shifts it six ways to dilate. |
| """ |
| B, NH, NT, _ = scores.shape |
| GF, GH, GW = grid |
| dev = scores.device |
| bits = torch.empty(B, NH, NT, NT // 8, device=dev, dtype=torch.uint8) |
| counts = torch.empty(B, NH, NT, device=dev, dtype=torch.int32) |
| pw = (1 << torch.arange(8, device=dev, dtype=torch.int32)) |
| step = max(1, int(6e7) // NT) |
| for b in range(B): |
| for h in range(NH): |
| d = delta[h] |
| for q0 in range(0, NT, step): |
| q1 = min(NT, q0 + step) |
| sc = scores[b, h, q0:q1].float() |
| keep = sc >= (sc.amax(-1, keepdim=True) - d) # adaptive per-ROW threshold |
| rows = torch.arange(q1 - q0, device=dev) |
| keep[rows, torch.arange(q0, q1, device=dev)] = True # a tile always keeps itself |
| k3 = keep.view(-1, GF, GH, GW) |
| dil = k3.clone() # 6-neighbour dilation on the tile grid |
| dil[:, 1:] |= k3[:, :-1] |
| dil[:, :-1] |= k3[:, 1:] |
| dil[:, :, 1:] |= k3[:, :, :-1] |
| dil[:, :, :-1] |= k3[:, :, 1:] |
| dil[:, :, :, 1:] |= k3[:, :, :, :-1] |
| dil[:, :, :, :-1] |= k3[:, :, :, 1:] |
| kk = dil.reshape(-1, NT) |
| counts[b, h, q0:q1] = kk.sum(-1, dtype=torch.int32) |
| bits[b, h, q0:q1] = ((kk.view(-1, NT // 8, 8).to(torch.int32) * pw) |
| .sum(-1).to(torch.uint8)) |
| density = counts.sum(-1, dtype=torch.int64).float() / float(NT * NT) |
| return bits, counts, density |
| ''', |
| make_inputs_src=''' |
| def _mk(B, NH, GF, GH, GW, seed): |
| gen = torch.Generator(device="cuda").manual_seed(seed) |
| NT = GF * GH * GW |
| ff = torch.arange(NT, device="cuda") // (GH * GW) |
| hh = (torch.arange(NT, device="cuda") // GW) % GH |
| ww = torch.arange(NT, device="cuda") % GW |
| # a realistic estimate: energy decays with 3D tile distance, plus per-pair noise |
| dist = ((ff[:, None] - ff[None, :]).abs().float() * 1.6 |
| + (hh[:, None] - hh[None, :]).abs().float() * 0.5 |
| + (ww[:, None] - ww[None, :]).abs().float() * 0.5) |
| scores = torch.randn(B, NH, NT, NT, device="cuda", dtype=torch.float32, generator=gen) |
| scores -= 0.35 * dist |
| delta = _deltas(NH).to("cuda") |
| return scores, delta, (GF, GH, GW) |
| ''', |
| flops_src=''' |
| def _deltas(NH): |
| """Per-head threshold margin, from the SHAPE ALONE: heads differ in how concentrated they are.""" |
| return torch.tensor([1.0 + 1.6 * (h % 7) / 6.0 for h in range(NH)], dtype=torch.float32) |
| |
| |
| def canonical_work(B, NH, GF, GH, GW): |
| """BYTES moved by one call, from the SHAPE ALONE. |
| |
| The score map is read once (4 bytes per entry), the packed bitmap is written once (1 bit per entry), |
| plus the per-row counts and the per-head density. A kernel that reads the map twice -- once for the row |
| max, once for the compare -- moves twice this and scores half. |
| """ |
| NT = GF * GH * GW |
| return B * NH * NT * (4 * NT + NT // 8 + 4) + B * NH * 4 |
| ''', |
| flops_formula=("NT = GF*GH*GW\n" |
| "BYTES = B*NH*NT*(4*NT + NT/8 + 4) + B*NH*4 # read the fp32 map once, write the " |
| "packed bitmap + counts"), |
|
|
| metric="GB/s", |
| compare="tuple", |
| tuple_names=("bits", "counts", "density"), |
| tol=1e-4, |
| shape_names=("B", "NH", "GF", "GH", "GW"), |
| grader_shapes=[(2, 24, 11, 15, 16), |
| (3, 40, 7, 15, 16), |
| (3, 24, 13, 12, 16), |
| (2, 32, 9, 16, 18), |
| (4, 24, 8, 15, 16)], |
| measure_shapes=[(2, 24, 11, 15, 14), |
| (3, 40, 7, 12, 16), |
| (2, 24, 13, 12, 16), |
| (2, 32, 9, 14, 16), |
| (4, 16, 8, 15, 16)], |
| measure_quick_shapes=[(1, 8, 5, 8, 16), |
| (2, 6, 4, 10, 12), |
| (1, 12, 6, 6, 16)], |
| correct_shapes=[(1, 4, 3, 4, 8), |
| (2, 3, 5, 4, 6), |
| (1, 6, 4, 5, 8), |
| (1, 2, 7, 3, 8), |
| (2, 4, 3, 5, 16), |
| (1, 5, 2, 4, 10)], |
|
|
| spec_md="""`scores[b,h,i,j]` is an upstream estimate of how much attention mass query tile `i` puts on key |
| tile `j`, in logits. Both axes index the same 3D tile grid of `NT = GF*GH*GW` tiles in raster order, so tile |
| id `t` is the grid position `(f, h, w) = (t // (GH*GW), (t // GW) % GH, t % GW)`. |
| |
| For every `(b, h, i)` row, in this order: |
| |
| **1. Adaptive threshold.** Keep key tile `j` iff it is within `delta[h]` of the row's best tile: |
| |
| ``` |
| m = max_j scores[b,h,i,j] |
| keep[j] = ( scores[b,h,i,j] >= m - delta[h] ) |
| ``` |
| |
| This is per **row**, not per head and not per tensor: a row whose mass is spread out keeps many tiles, a |
| peaked row keeps a handful. That is the whole point — the budget adapts. |
| |
| **2. Self.** `keep[i] = True` — a tile always attends to itself, whatever the score says. |
| |
| **3. 3D dilation.** The estimate came from pooled tiles, so it is blurry; every kept tile pulls in its six |
| face-neighbours on the tile grid: |
| |
| ``` |
| out[f,h,w] = keep[f,h,w] | keep[f±1,h,w] | keep[f,h±1,w] | keep[f,h,w±1] |
| ``` |
| |
| Neighbours outside the grid do not exist (**no wrap-around**: `w = GW-1` is *not* adjacent to `w = 0` of the |
| next row of tiles, even though they are adjacent in the raster). The dilation reads the mask from step 2 — it |
| is a single dilation, **not** iterated to a fixed point. |
| |
| **4. Pack.** `bits[b,h,i,w]` holds tiles `8w .. 8w+7`, **LSB first**: bit `(1 << t)` of byte `w` is tile |
| `8w + t`. `counts[b,h,i]` is the popcount of the row *after* dilation. `density[b,h]` is |
| `sum_i counts[b,h,i] / (NT*NT)`. |
| |
| `/app/reference.py` materialises the whole boolean map per `(b, h)` and shifts it six ways. That is the exact |
| specification; it is deliberately simple rather than fast.""", |
|
|
| contract_md="""| arg | shape | dtype | meaning | |
| |-----|-------|-------|---------| |
| | `scores` | `(B, NH, NT, NT)` | `float32` | tile-level score estimate, query-tile major | |
| | `delta` | `(NH,)` | `float32` | per-head margin below the row max; a **device** tensor | |
| | `grid` | `(GF, GH, GW)` | tuple of int | tile grid, `GF*GH*GW == NT` | |
| |
| **Return** a 3-tuple `(bits, counts, density)` **in that order**: |
| |
| | out | shape | dtype | notes | |
| |-----|-------|-------|-------| |
| | `bits` | `(B, NH, NT, NT//8)` | `uint8` | packed keep-mask, LSB-first; compared **exactly** | |
| | `counts` | `(B, NH, NT)` | `int32` | kept tiles per row, after dilation; compared **exactly** | |
| | `density` | `(B, NH)` | `float32` | `sum_i counts[b,h,i] / (NT*NT)` | |
| |
| `NT` is always a multiple of 8 but **not** of 32, and `GW` is not always a power of two. `scores` is |
| read-only and contiguous; all tensors are CUDA. The score map is the big object here — it is up to 1.3 GB and |
| it is `float32` on purpose (see Precision). |
| |
| `bits` and `counts` must be **exactly** right: they are consumed by a block-sparse attention kernel, where one |
| flipped bit is a missing or a phantom tile.""", |
|
|
| regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): tile grids |
| of `NT` 1700-2900 tiles (`GF` 7-13 temporal by `GH` 12-16 by `GW` 14-18 — a 33x45x80 HunyuanVideo latent cut |
| into ~45-token tiles, or a 21x45x80 Wan latent), `NH` 20-40 heads, `B` 2-4. That is a **1.0-1.4 GiB score map |
| per call**, and the output is 1/32 of it. |
| |
| This is a pure bandwidth kernel with nothing to hide behind: the floor is that ~1.3 GB divided by your |
| device's achieved HBM bandwidth. Everything that matters is whether you read the map exactly **once**.""", |
|
|
| correctness_md="""`bits` and `counts` are compared **element-exactly** — one wrong bit anywhere fails. |
| `density` must be within relative Frobenius error `1e-4`. All of this is checked at every graded shape, |
| including the timed ones.""", |
|
|
| perf_md="""**One row fits in shared memory.** A row is `NT` floats — 7-12 KB. Load it once, reduce for the |
| max, threshold, dilate and pack entirely on chip. The two-pass shape (one kernel for the row max, another to |
| compare) reads 1.3 GB twice and can never beat half the achievable score. |
| |
| **Vectorise the load.** `float4` (128-bit) loads of a contiguous row are the difference between roughly half |
| of achievable HBM bandwidth and most of it. `NT` is a multiple of 8 but not of 32, so handle the tail |
| explicitly rather than padding the whole row. |
| |
| **The dilation is three shifts, not six.** `out = keep | shift_w(±1) | shift_h(±GW) | shift_f(±GH*GW)` — in a |
| warp-per-row layout the `w` neighbours are `__shfl_up`/`__shfl_down` of the same lane's bits, and the `h` and |
| `f` neighbours are a fixed lane offset away. If you keep the row as one bit per bit-position in registers, the |
| whole dilation is a handful of shifts and ORs on 32-bit words plus the boundary fixups (**no wrap** at |
| `w = GW-1`, `h = GH-1`, `f = GF-1`). |
| |
| **Popcount is free** once the row is packed: `__popc` on the packed words, warp-reduce, one `int32` store. |
| |
| **`density` is a second, tiny reduction** over `NT` counts per head. Do not launch a whole extra pass over |
| `scores` for it — reduce the counts you already produced, with an atomic add per row or a small second |
| kernel over the `(B, NH, NT)` count array. |
| |
| **Occupancy:** `B*NH*NT` rows is 100k-300k independent rows, so one CTA (or one warp) per row is plenty of |
| parallelism. The interesting question is how few bytes per row you can touch.""", |
|
|
| precision_md="""`scores` is **float32** and the threshold comparison must be done **in float32**: |
| `keep = (score >= rowmax - delta[h])` with `rowmax` the exact fp32 maximum of the row. |
| |
| This is not decoration. `rowmax - delta` is a single fp32 operation on values you were given exactly, so every |
| faithful implementation gets bit-identical decisions. Rounding the row max or the difference to bf16/fp16 |
| moves the threshold by up to ~0.03 logits, which flips the tiles that sit near it — and with hundreds of |
| millions of entries, some always do. The output is compared exactly, so a flipped tile is a failure, not a |
| rounding error. |
| |
| `counts` is the popcount **after** dilation, and `density` divides by `NT*NT` exactly. Accumulate the counts |
| as integers; an fp32 running sum of hundreds of thousands of small integers is still exact here, but there is |
| no reason to risk it. |
| |
| There is no low-precision arithmetic anywhere in this kernel: the tolerance exists only for `density`.""", |
| ).validate() |
|
|
| |
| ALT_SRC = ''' |
| def _alt(scores, delta, grid): |
| """Independent impl: row-blocked, dilation via index gathers instead of shifted slices, packing via |
| matmul. Used only to check that two correct implementations agree bit-exactly.""" |
| B, NH, NT, _ = scores.shape |
| GF, GH, GW = grid |
| dev = scores.device |
| t = torch.arange(NT, device=dev) |
| f, h, w = t // (GH * GW), (t // GW) % GH, t % GW |
| nb = [t] |
| for dd, lim, stride in ((f, GF, GH * GW), (h, GH, GW), (w, GW, 1)): |
| for s in (-1, 1): |
| ok = ((dd + s) >= 0) & ((dd + s) < lim) |
| nb.append(torch.where(ok, t + s * stride, t)) |
| bits = torch.empty(B, NH, NT, NT // 8, device=dev, dtype=torch.uint8) |
| counts = torch.empty(B, NH, NT, device=dev, dtype=torch.int32) |
| for b in range(B): |
| for h_ in range(NH): |
| keep = scores[b, h_] >= (scores[b, h_].max(-1, keepdim=True).values - delta[h_]) |
| keep[t, t] = True |
| dil = torch.zeros_like(keep) |
| for src in nb: # out[j] |= keep[neighbour of j] (symmetric relation) |
| dil |= keep[:, src] |
| counts[b, h_] = dil.sum(-1, dtype=torch.int32) |
| pk = torch.zeros(NT, NT // 8, device=dev, dtype=torch.int32) |
| for i in range(8): |
| pk |= dil.view(NT, NT // 8, 8)[:, :, i].int() << i |
| bits[b, h_] = pk.to(torch.uint8) |
| density = counts.sum(-1, dtype=torch.int64).float() / float(NT * NT) |
| return bits, counts, density |
| ''' |
|
|
| DROP_SRC = ''' |
| def _drop(scores, delta, grid): |
| """Drop-the-feature: skip the 3D dilation.""" |
| B, NH, NT, _ = scores.shape |
| dev = scores.device |
| t = torch.arange(NT, device=dev) |
| bits = torch.empty(B, NH, NT, NT // 8, device=dev, dtype=torch.uint8) |
| counts = torch.empty(B, NH, NT, device=dev, dtype=torch.int32) |
| pw = (1 << torch.arange(8, device=dev, dtype=torch.int32)) |
| for b in range(B): |
| for h_ in range(NH): |
| keep = scores[b, h_] >= (scores[b, h_].amax(-1, keepdim=True) - delta[h_]) |
| keep[t, t] = True |
| counts[b, h_] = keep.sum(-1, dtype=torch.int32) |
| bits[b, h_] = (keep.view(NT, NT // 8, 8).to(torch.int32) * pw).sum(-1).to(torch.uint8) |
| density = counts.sum(-1, dtype=torch.int64).float() / float(NT * NT) |
| return bits, counts, density |
| ''' |
|
|
| DROP2_SRC = ''' |
| def _drop2(scores, delta, grid): |
| """Second drop check: one GLOBAL threshold per head instead of the per-row adaptive one.""" |
| B, NH, NT, _ = scores.shape |
| GF, GH, GW = grid |
| dev = scores.device |
| t = torch.arange(NT, device=dev) |
| bits = torch.empty(B, NH, NT, NT // 8, device=dev, dtype=torch.uint8) |
| counts = torch.empty(B, NH, NT, device=dev, dtype=torch.int32) |
| pw = (1 << torch.arange(8, device=dev, dtype=torch.int32)) |
| for b in range(B): |
| for h_ in range(NH): |
| keep = scores[b, h_] >= (scores[b, h_].max() - delta[h_]) |
| keep[t, t] = True |
| k3 = keep.view(NT, GF, GH, GW) |
| dil = k3.clone() |
| dil[:, 1:] |= k3[:, :-1] |
| dil[:, :-1] |= k3[:, 1:] |
| dil[:, :, 1:] |= k3[:, :, :-1] |
| dil[:, :, :-1] |= k3[:, :, 1:] |
| dil[:, :, :, 1:] |= k3[:, :, :, :-1] |
| dil[:, :, :, :-1] |= k3[:, :, :, 1:] |
| kk = dil.reshape(NT, NT) |
| counts[b, h_] = kk.sum(-1, dtype=torch.int32) |
| bits[b, h_] = (kk.view(NT, NT // 8, 8).to(torch.int32) * pw).sum(-1).to(torch.uint8) |
| density = counts.sum(-1, dtype=torch.int64).float() / float(NT * NT) |
| return bits, counts, density |
| ''' |
|
|