Repository navigation
Add SnapKV Importance Scores challenge (medium #164) - #393
claude[bot] wants to merge 2 commits into
Conversation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
✅ Review bot: low risk, safe to merge. Lint and structure checks passed; no sensitive paths or grader edits; 187 lines changed.
- The diff is complete: challenge.html, challenge.py and all six starters. The PR body is cut off mid-sentence, but that is only metadata.
- ID 164 is not used by any existing challenge, and the challenge is not a duplicate. Existing attention challenges (GQA, causal, flash decoding, block-sparse selection) reduce along keys, while this one sums softmax probabilities down the query axis.
- The challenge is non-trivial: it needs a row-statistics pass plus a column-accumulation pass, with GQA reuse of K tiles.
- challenge.py imports only ctypes, math, typing, torch and the challenge base. It has no I/O, network, subprocess or import-time code. It defines the 5 required methods plus a private _build helper, and no init. name, atol, rtol, num_gpus and access_tier are all set.
- reference_impl asserts shapes and dtypes with no device checks, and uses only standard PyTorch ops (bmm, masked_fill, softmax).
- All tensor allocations in generate_* use self.device. The performance case uses RandnTensor and OutTensor, with about 135 MB of inputs plus a small output, far under the memory limit.
- Functional tests cover many edge cases: 1x1, zero queries with a closed-form answer, window == seq_len, window == 1, GQA/MHA/MQA, large logits, non-power-of-2 sizes, and a garbage-prefilled output. Tolerances (1e-5 / 1e-4) are tight and documented as justified.
- The hand-computed example in challenge.html matches my recomputation: [1.5495, 1.4516, 0.9989].
- The starters are empty stubs with only the parameter comment, and the Mojo starter uses max.gpu and MutAnyOrigin. The JAX starter omits the output tensor, consistent with the repo's convention of returning it.
shxjames
left a comment
There was a problem hiding this comment.
Spec matches the code: observation-window queries sit at p_i = seq_len - window + i, attend with t <= p_i, softmax over keys, and each score sums those probabilities over the window and over the G query heads that share KV head floor(h / G). No pooling or clustering kernel; the HTML is clear this is the raw importance scores. GQA uses the standard consecutive-group map.
Example 1 matches a closed-form calculation: [1.549507115, 1.451565285, 0.998927600]. The HTML rounding [1.5495, 1.4516, 0.9989] is correct (max rounding error 3.5e-5). The reference matches the closed form to 3e-8, and the zero-query case matches the exact harmonic sums exactly. Nit: the comment in generate_functional_test writes 1.4515; the HTML's 1.4516 is the right rounding.
Correctness (independent fp64 two-pass online softmax + column accumulate in /workspace/kr, no torch.softmax):
- Example + all 11 functional cases: worst share of the prod grader budget (
atol + rtol * max|ref|per output tensor, atol=1e-5, rtol=1e-4) is 0.0196 on the large-logit case (f6, max abs 5.84e-6, ~51x headroom). Other cases <= 0.003. Row sums equalG * window. Every test dict includes thescoresbuffer (pre-filled 123). - Perf 32 / 8 / 64 / 32768 / 128 (seed 0): max abs 2.05e-8, max|y| 0.0204, share 0.00170 (~588x headroom).
Bugs / low-prec (prod grader). Every intended mutant is caught on at least one functional case: no mask 9, drop-diagonal 11, mask off-by-one 8, queries placed at the start 9 (not the window == seq_len case, correctly), missing 1/sqrt(d) 9, h % Hkv 3 (exactly f5, f7, f10, the G>1 cases that can tell it apart), only one head of the group 8, no max subtraction 1 (f6 only), stale running max 10 (all but the 1x1).
TF32 / BF16 are rejected on f3-f10; FP16 is rejected on f4-f10 but slips past f3 under the prod grader (share 0.67; it would fail an elementwise allclose). On perf, all three are rejected (shares 3.08 / 1.22 / 9.49). No need to tighten the tolerance.
Perf / T4. Q 1.0 MB, K 134 MB, scores 1.0 MB, naive logits 268 MB. Total with the materialized tensor ~0.38 GiB, comfortably inside 16 GB. Two-pass work ~34.4 GFLOP; T4 fp32 floor ~4.2 ms. Medium is the right difficulty.
Starters. All 6 match the signature; JAX returns the output. Coverage includes 1x1, window == seq_len, window = 1, non-power-of-two tails, MHA, MQA, GQA, and a 4k prompt.
Nits, not blockers:
challenge.pycomment typo1.4515vs HTML1.4516.- The comment says the tolerance is applied elementwise; the prod grader uses
atol + rtol * max|ref|per output tensor. The 12% figure in the comment is the elementwise share on f6; under the prod rule it is 2.0%. Conclusions unchanged. - The runner zero-fills output buffers, so the 123 pre-fill is not enforced live. The HTML already requires every element to be written.
- This is the SnapKV scoring sum, not the paper's pooling/clustering step. The spec already says that.
CI on 4d3a92c1b2868cd88a950ad2c3d2b80ac60bf99e is green (review, checks, Lint Python Files, Check Mojo Files, Lint C++/CUDA Files, check-index). Merge is blocked only on a code-owner approval. LGTM, no blockers.
The SVG staircase used 30px cells, drawing 16 key columns for seq_len = 12. Use 40px columns so row i visibly covers keys 0..8+i. Also correct the rounded example score in the test comment (1.451565 -> 1.4516). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
✅ Review bot: low risk, safe to merge. Lint and structure checks passed; no sensitive paths or grader edits; 187 lines changed.
- ID 164 is unused among the existing challenges, and the problem (column-sum of causal GQA attention probabilities over an observation window) is distinct from the existing attention, selection and backward challenges
- challenge.py imports only ctypes, math, typing, torch and the challenge base. It has no I/O, network or import-time side effects, and no init override
- It defines the 5 required methods plus a private _build helper, and sets name, atol, rtol, num_gpus and access_tier
- reference_impl asserts shapes and dtypes and uses only standard PyTorch ops with no device checks
- All generate_* allocations use device=self.device, and the performance case (about 135 MB of inputs and outputs) is well under the memory limit
- Functional tests cover minimal, zero-Q, window == seq_len, window = 1, GQA/MHA/MQA, large logits and non-power-of-2 sizes. The tolerances (atol 1e-5, rtol 1e-4) are justified in comments and are tight enough to reject TF32 and mask errors
- I hand-checked the example in challenge.html (scores 1.5495, 1.4516, 0.9989) against the reference semantics and it matches
- The starters are empty stubs that carry only the parameter comment, and the Mojo starter uses the max.gpu and MutAnyOrigin style
- I did not confirm that RandnTensor and OutTensor exist in core.challenge_base; they are presumably used by other challenges
shxjames
left a comment
There was a problem hiding this comment.
Re-checked 3fc93c1663e5b8007a1615ee2a2eea0e8685e6d3: the follow-up only fixes the example-score comment typo (1.4515 -> 1.4516) and the SVG staircase (40px columns, 12 keys, so row i covers keys 0..8+i). No change to the reference, tests, tolerances, or starters. CI is green. Prior verdict holds: LGTM, no blockers.
New medium challenge #164 SnapKV Importance Scores: the scoring step that SnapKV-style KV-cache compression (SnapKV, and H2O / PyramidKV variants) runs after prefill to pick which prompt tokens to keep. The last
windowprompt queries attend causally over allseq_lenkeys. Each key's score is the total softmax probability it receives, summed over the window queries and over theG = num_q_heads / num_kv_headsquery heads that share its KV head (GQA). The output isscores[num_kv_heads, seq_len].What a solver learns
P·V. Here each probabilityp[i, t]is summed down its column. A column sum needs every row's final softmax max and denominator, so one streaming pass with an online softmax can't produce it. The solver has to split the work into a row-statistics pass and a column-accumulation pass (or keep the logits around).G × windowqueries of its KV head, the result is deterministic and needs no atomics. Parallelizing over queries instead needs a cross-block reduction.G × windowqueries that share the KV head, instead of being re-read for each query head.Novelty versus the closest existing challenges
softmax(QKᵀ)·V, where the reduction runs along keys and fits in one online-softmax pass. Here there is no V. The reduction runs along queries, so the online-softmax trick alone does not work.dK,dV), but it is handed the forward output. It is a full backward pass, not a score-and-reduce kernel. There's no overlap with the open attention-backward PR Add GQA Causal Attention Backward challenge (hard #163) #390 (GQA backward) either.Naive vs. optimized
logits[Hkv, G·W, S], then mask, softmax andsum(dim=1), as the reference does. Or use one thread per (head, query, key) that reads K straight from global memory. On the perf case the materialized tensor is 268 MB, written and re-read several times. The per-thread version re-reads every K row once per query, 256× per KV head.Q·Kᵀwith a per-thread online max and sum, merged with warp shuffles. Split along keys for parallelism, then combine the splits.G × windowrows of its KV head. It recomputes the logits, addsexp(s − m_i) / l_iinto per-column registers, and writes each score once. No atomics, deterministic.Only the masked diagonal band (the last
windowkeys) needs mask checks. Recomputing the logits (about 17 GFLOP) costs less than writing and re-reading 268 MB of probabilities several times on a T4.How the benchmark exposes it
Perf case: Llama-3-8B-style GQA,
num_q_heads = 32,num_kv_heads = 8,head_dim = 128, with awindow = 64observation window over a 32,768-token prompt (Q1 MB,K134 MB, standard-normal data).G × window = 256queries share each KV head. A kernel that reuses each K tile across all 256 is compute-bound at about 34 GFLOP for both passes. Any kernel that re-reads K per query head or per query is bound by memory and L2 bandwidth instead.seq_len = 32,768is long enough that the materialized[8, 256, 32768]probability tensor dominates the naive version's traffic.Tests
11 functional cases.
scoresis pre-filled with 123.0, so unwritten elements fail.e-based expressions,[1.5495, 1.4516, 0.9989], and the reference matches them to 3e-8.2·(1/3 + 1/4 + 1/5), and the reference matches it exactly.I ran each plausible mistake locally as a mutant against
allclose(atol, rtol). Every one fails at least one case:t < p)t ≤ p + 1)0..window-1instead of the end of the prompt1/√head_dimh % Hkvinstead ofh / GShapes covered:
window == seq_len, where query 0 sees only key 0window = 1seq_len = 255,window = 30,head_dim = 40(tile tails on every axis)head_dim = 128(MHA)Tolerance
atol = 1e-5,rtol = 1e-4, applied elementwise. Every score is a sum of at most 8,192 probabilities, each in [0, 1].Validation
run_challenge.pyon T4 with a two-pass tiled CUDA solution (not committed):--action runpasses, and--action submitpasses all tests, including perf.pre-commit run --all-filesandscripts/validate_challenges.pypass. The Mojo starter builds as a shared library.bmm,masked_fill,softmaxandsum, so it should lower on XLA. No CUDA-only APIs, and every allocation usesdevice=self.device.generate_example_test, the perf bullet, the dark-theme SVG, the five class attributes, shape/dtype-only assertions, and exactly one parameter comment per starter.🤖 Generated with Claude Code