Skip to content

Add SnapKV Importance Scores challenge (medium #164) - #393

Open
claude[bot] wants to merge 2 commits into
mainfrom
add-challenge-164-snapkv-importance-scores
Open

claude[bot] wants to merge 2 commits into
mainfrom
add-challenge-164-snapkv-importance-scores

Conversation

@claude

@claude claude Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

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 window prompt queries attend causally over all seq_len keys. Each key's score is the total softmax probability it receives, summed over the window queries and over the G = num_q_heads / num_kv_heads query heads that share its KV head (GQA). The output is scores[num_kv_heads, seq_len].

What a solver learns

  • Reducing attention probabilities along the query axis. Attention kernels usually reduce along keys, via P·V. Here each probability p[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).
  • Choosing a work decomposition without atomics. In pass 2, if each block owns a key tile and loops over all G × window queries of its KV head, the result is deterministic and needs no atomics. Parallelizing over queries instead needs a cross-block reduction.
  • GQA-aware data reuse. Each K tile is loaded once and reused against all G × window queries that share the KV head, instead of being re-read for each query head.

Novelty versus the closest existing challenges

Naive vs. optimized

  • Naive (correct): materialize logits[Hkv, G·W, S], then mask, softmax and sum(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.
  • Optimized (same result): run two tiled passes over K and never store the probability matrix.
    1. Row statistics: tiled Q·Kᵀ with a per-thread online max and sum, merged with warp shuffles. Split along keys for parallelism, then combine the splits.
    2. Scores: each block owns a 64-key tile and loops over all G × window rows of its KV head. It recomputes the logits, adds exp(s − m_i) / l_i into per-column registers, and writes each score once. No atomics, deterministic.
      Only the masked diagonal band (the last window keys) 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 a window = 64 observation window over a 32,768-token prompt (Q 1 MB, K 134 MB, standard-normal data).

  • G × window = 256 queries 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,768 is long enough that the materialized [8, 256, 32768] probability tensor dominates the naive version's traffic.
  • With only 8 KV heads and 256 query rows, row-tile parallelism alone gives too few blocks for pass 1 on a T4. The solver has to split the key axis and merge the partial (max, sum) pairs.

Tests

11 functional cases. scores is pre-filled with 123.0, so unwritten elements fail.

  • Case 0 is the example. Its values come from closed-form e-based expressions, [1.5495, 1.4516, 0.9989], and the reference matches them to 3e-8.
  • Case 2 uses zero queries. The exact answer is a harmonic-style sum, e.g. 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:

Mistake Cases that catch it
no causal mask 0, 2, 3, 5–10
mask off by one (t < p) all
mask off by one (t ≤ p + 1) 0, 2, 3, 5, 7–10
queries placed at positions 0..window-1 instead of the end of the prompt 0, 2, 4–10
missing 1/√head_dim 0, 3–10
query head → KV head mapped as h % Hkv instead of h / G 5, 7, 10
only one head of each group summed 0, 2, 3, 5–7, 9, 10
no max subtraction (overflow; logits up to ~117) 6
single pass that normalizes with a stale running max 6–10
TF32 / FP16 / BF16 inputs 3–10

Shapes covered:

  • the minimal 1×1×1 case
  • window == seq_len, where query 0 sees only key 0
  • window = 1
  • non-power-of-two seq_len = 255, window = 30, head_dim = 40 (tile tails on every axis)
  • powers of two with head_dim = 128 (MHA)
  • MQA with 16 query heads
  • a realistic 4,096-token case

Tolerance

atol = 1e-5, rtol = 1e-4, applied elementwise. Every score is a sum of at most 8,192 probabilities, each in [0, 1].

  • Float32 reference vs. float64 recomputation: at most 0.4% of the budget on every case except the large-logit case (12%), and 0.2% on the perf case.
  • Independent two-pass, key-tiled float32 implementation vs. reference: at most 0.2%.
  • Mutants: each one in the table misses by one to several orders of magnitude more than the budget on at least one functional case.

Validation

  • run_challenge.py on T4 with a two-pass tiled CUDA solution (not committed): --action run passes, and --action submit passes all tests, including perf.
  • pre-commit run --all-files and scripts/validate_challenges.py pass. The Mojo starter builds as a shared library.
  • The reference uses only bmm, masked_fill, softmax and sum, so it should lower on XLA. No CUDA-only APIs, and every allocation uses device=self.device.
  • The CLAUDE.md checklist was checked item by item: the HTML section structure, Example 1 matching 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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
github-actions[bot]
github-actions Bot previously approved these changes Nov 27, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 shxjames left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 equal G * window. Every test dict includes the scores buffer (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.py comment typo 1.4515 vs HTML 1.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>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 shxjames left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant