"""Spec for `cache-hit-skip-gate` — block-granular cache hit/miss gating inside a diffusion transformer.""" import pathlib import sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from spec import TaskSpec SPEC = TaskSpec( name="cache-hit-skip-gate", title="Write a fast block-granular cache hit/skip gate kernel", blurb=("Token-block caching in video diffusion decides hit-or-miss per TOKEN BLOCK, not per request: the " "static background of a clip can reuse its cached residual for many steps while the moving region " "is recomputed every step. The gate kernel walks the hidden states with that per-block boolean, " "reconstructing hit blocks from the cache and refreshing missed ones — and the whole point is that " "a hit block never has to touch the freshly computed tensor and a missed block never has to touch " "the cache, so the traffic is one stream lower than the naive select."), keywords=["mle", "kernel-generation", "diffusion", "caching", "block-cache", "video-generation", "memory-bound"], module="cache_gate.py", func="cache_hit_skip_gate", signature="cache_hit_skip_gate(hidden, fresh, cache, hit, block)", returns_doc="""Block-granular cache gate: reconstruct hit blocks, refresh missed ones. Args: hidden: (B, L, D) bfloat16 — block input x. fresh: (B, L, D) bfloat16 — freshly computed block output y (only meaningful in missed blocks). cache: (B, L, D) bfloat16 — cached residual (only meaningful in hit blocks). hit: (B, NB) bool — per (request, token-block) cache hit, NB = ceil(L / block). block: int — token-block size. Returns: (out, cache_out), both (B, L, D) bfloat16.""", reference_imports="import torch", reference_src=''' def cache_hit_skip_gate(hidden, fresh, cache, hit, block): """Block-granular gate, written as an explicit full-size select in fp32. Correct and simple — it is the numerical SPECIFICATION, not a performance target. """ B, L, D = hidden.shape tok = torch.arange(L, device=hidden.device) m = hit[:, tok // block].unsqueeze(-1) # (B, L, 1) broadcast of the per-block flag x = hidden.float() y = fresh.float() c = cache.float() out = torch.where(m, x + c, y) cache_out = torch.where(m, c, y - x) return out.to(hidden.dtype), cache_out.to(hidden.dtype) ''', make_inputs_src=''' def _mk(B, L, D, G, seed): gen = torch.Generator(device="cuda").manual_seed(seed) hidden = torch.randn(B, L, D, device="cuda", dtype=torch.bfloat16, generator=gen) fresh = torch.randn(B, L, D, device="cuda", dtype=torch.bfloat16, generator=gen) cache = (0.3 * torch.randn(B, L, D, device="cuda", generator=gen)).to(torch.bfloat16) NB = (L + G - 1) // G hit = torch.rand(B, NB, device="cuda", generator=gen) < 0.6 # ~60% of blocks hit the cache return hidden, fresh, cache, hit, G ''', flops_src=''' def canonical_work(B, L, D, G): """BYTES moved by the gate, from the SHAPE ALONE. FOUR bf16 streams of B*L*D elements, not five. `hidden` is read by both branches and both outputs are always written; the fourth stream is `cache` in hit blocks and `fresh` in missed blocks -- exactly one of them per block, whatever the hit pattern. That is the unavoidable traffic for any implementation that respects the gate, so the byte count does not depend on the data. The (B, NB) flag array is negligible. """ return 4 * (B * L * D) * 2 ''', metric="GB/s", compare="tuple", tuple_names=("out", "cache_out"), tol=2e-3, shape_names=("B", "L", "D", "G"), grader_shapes=[(2, 29040, 3072, 512), (1, 124440, 3072, 1024), (4, 18480, 3072, 256), (2, 29040, 5120, 512), (8, 12870, 3072, 768)], measure_shapes=[(2, 24000, 3072, 512), (1, 99552, 3072, 1024), (3, 18480, 3072, 256), (1, 29040, 5120, 512), (6, 12870, 3072, 768)], measure_quick_shapes=[(2, 8190, 1536, 512), (4, 4096, 3072, 256), (1, 18480, 3072, 1024)], correct_shapes=[(5, 129, 256, 64), (2, 8190, 1536, 512), (3, 1025, 64, 256), (1, 4097, 3072, 1024)], spec_md="""Token `l` of request `b` belongs to block `n = l // block`, and its flag is `hit[b, n]`. The last block is short whenever `block` does not divide `L`. Elementwise over `D`: ``` if hit[b, l // block]: # cache HIT: the block was not recomputed out[b, l] = hidden[b, l] + cache[b, l] # reconstruct from input + cached residual cache_out[b, l] = cache[b, l] # cache unchanged else: # cache MISS: the block was recomputed this step out[b, l] = fresh[b, l] cache_out[b, l] = fresh[b, l] - hidden[b, l] # refresh the cached residual ``` The cache stores the block **residual** `y - x`, which is what stays stable across denoising steps. Hit blocks never read `fresh` and missed blocks never read `cache`; that asymmetry is the whole point of the scheme and it is why `canonical_work` counts four streams rather than five. About 60% of blocks hit in the graded inputs, but the hit pattern is random and unstructured — neighbouring blocks disagree — so the branch is real and cannot be hoisted out of the grid. `/app/reference.py` builds an `(B, L, 1)` boolean mask by indexing and evaluates BOTH branches everywhere before selecting. That is the numerical specification; it is also exactly what a fast kernel must not do.""", contract_md="""| arg | shape | dtype | meaning | |-----|-------|-------|---------| | `hidden` | `(B, L, D)` | `bfloat16` | block input `x`, contiguous | | `fresh` | `(B, L, D)` | `bfloat16` | freshly computed block output `y` | | `cache` | `(B, L, D)` | `bfloat16` | cached residual | | `hit` | `(B, ceil(L/block))` | `bool` | per (request, token-block) cache hit | | `block` | — | `int` | token-block size, a plain Python int | **Return** a 2-tuple `(out, cache_out)` **in that order**, both `(B, L, D)` **bfloat16**. All tensor inputs are **read-only** and the update is **functional** — do not write into `cache`. `block` varies between 256 and 1024 in the graded shapes and **never** divides `L` exactly in the correctness shapes (`L = 4097`, `block = 1024`), so the ragged last block must be handled. Values in `fresh` inside hit blocks and in `cache` inside missed blocks are arbitrary and must not influence the result.""", regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` 1–8 requests, `L` **12000–125000** video tokens (a 720p clip after patchify is ~10^5 of them), `D` 3072–5120, `block` in {256, 512, 768, 1024}. Every graded shape moves **1.1–2.9 GiB** of the four counted streams. `B` is small: parallelise over `L*D`. Write a **general** kernel — `L` is ragged and `block` never divides it.""", correctness_md="""**Both** returned tensors must match the reference (evaluated in fp32) within **relative Frobenius error `2e-3`** at every graded shape, including the timed ones. Getting the block boundary off by one token is not a rounding error — it produces a completely different value in `D` elements and lands far outside the gate (measured below).""", precision_md="""Hidden states, fresh output and cache are **bfloat16**; do the two arithmetic branches (`x + c` and `y - x`) in **fp32** and round once when storing. **The tolerance is measured, and this operator is genuinely bit-exact.** An independent implementation — one that slices per `(request, token-block)`, branches once per block, loads only the stream its branch needs, and does the add/subtract in **native bf16** instead of the reference's fp32 — was compared against the reference across all four correctness shapes and all five graded shapes. The measured relative error `E` is **exactly 0.0** at every one of them. Each output element is a *single* add or subtract of two bf16 values rounded once, so no reassociation, no accumulation order and no intermediate width can change the result. `tol = 2e-3` is therefore not a numerical budget — there is nothing for it to absorb. It is a quarter of bf16 epsilon (~8e-3), set low precisely because `E = 0`: the only thing it must leave room for is an incidental 1-ULP double-rounding difference (worst case ~4e-4 in Frobenius terms), while staying tight enough to catch real bugs at the *largest* graded shape, where an error in a handful of tokens is heavily diluted. **Drop-the-feature margin.** The feature this task exists to test is that the hit flag is per *token block*, not per request. An implementation that keeps everything else identical but applies one flag per request scores relative error **0.58–1.00** (min 0.58 across all nine shapes) — **290x** the gate. Ignoring the gate entirely (recompute everywhere) scores 0.83–1.55. Boundary bugs are caught too: shifting the block index by one token gives **0.032–0.15** (16x the gate), and flipping the branch for a *single* token gives 0.0042–0.056 — still above `2e-3` at every shape, whereas at the previous `8e-3` setting that single-token bug would have passed at the two largest graded shapes. That is why the tolerance was tightened. **fp8 is not useful here** and is not expected.""", perf_md="""Four counted streams, one add or subtract per element: the roofline is `canonical_work`, and beating a naive `torch.where` is mostly about *not moving the fifth stream*. The reference is roughly 3x off the roofline for two reasons. First it evaluates both branches everywhere, so it reads all three inputs in full and materialises fp32 temporaries for `x + c` and `y - x`. Second, `hit[:, tok // block]` builds a full `(B, L)` int64 index tensor and gathers through it, which is more traffic than the flags themselves by a factor of `block`. The structure to exploit: the flag is constant over `block * D` contiguous elements — hundreds of thousands of them — so a block-per-tile kernel reads one boolean, branches **once**, and then runs a straight-line loop with no divergence at all. Give each CUDA block a tile that lies entirely inside one token block and the branch is free. After that it is ordinary streaming: 128-bit vectorised loads and stores, enough blocks to fill the GPU when `B = 1`, and a tail path for the short final token block.""", ).validate()