diff --git a/challenges/medium/164_snapkv_importance_scores/challenge.html b/challenges/medium/164_snapkv_importance_scores/challenge.html
new file mode 100644
index 00000000..1160b832
--- /dev/null
+++ b/challenges/medium/164_snapkv_importance_scores/challenge.html
@@ -0,0 +1,110 @@
+
+ Compute the per-key importance scores that SnapKV-style KV-cache compression uses to decide which
+ prompt tokens to keep after prefill. The last window queries of the prompt (the
+ observation window) attend causally over all seq_len keys, and each key's
+ score is the total attention probability it receives, summed over the window queries and over
+ every query head that shares its KV head (grouped-query attention). Given Q of shape
+ num_q_heads × window × head_dim and K of shape
+ num_kv_heads × seq_len × head_dim, write scores of shape
+ num_kv_heads × seq_len. All tensors are 32-bit floats.
+
+
+
+ With G = num_q_heads / num_kv_heads, query head h uses KV head
+ g = ⌊h / G⌋. Window query i sits at absolute position
+ \(p_i = \text{seq_len} - \text{window} + i\) and may only see keys \(t \le p_i\):
+ \[
+ a_{h,i,t} = \begin{cases}
+ \dfrac{\exp\!\left(Q_{h,i} \cdot K_{g,t} / \sqrt{\text{head_dim}}\right)}
+ {\sum_{u=0}^{p_i} \exp\!\left(Q_{h,i} \cdot K_{g,u} / \sqrt{\text{head_dim}}\right)}
+ & t \le p_i \\[4pt]
+ 0 & t > p_i
+ \end{cases}
+ \qquad
+ \text{scores}_{g,t} = \sum_{h = gG}^{gG + G - 1} \; \sum_{i=0}^{\text{window}-1} a_{h,i,t}
+ \]
+ The softmax normalizes over keys (each window query's row of probabilities sums to 1); the score
+ then sums those probabilities down the query axis, so every KV head's scores add up to
+ G × window.
+
+
+
+
+
Implementation Requirements
+
+
Implement the solve function; do not change its signature.
+
External libraries are not permitted.
+
Write the result into scores (row-major, num_kv_heads × seq_len).
+ scores is not zero-initialized; every element must be written.
+
All tensors are row-major and contiguous: Q[h, i, d] and K[g, t, d]
+ with d fastest.
+
Compute the dot products from the float32 inputs; rounding Q or K
+ to TF32, FP16 or BF16 is outside the tolerance.
+ The scaled logits of the four window rows are \([1, 0, -]\), \([0, 1, 0]\), \([0, 0, -]\) and
+ \([0, 0, 2]\) (\(-\) marks the masked key 2 for queries at position 1). Their softmax rows are
+ \([0.7311, 0.2689, 0]\), \([0.2119, 0.5761, 0.2119]\), \([0.5, 0.5, 0]\) and
+ \([0.1065, 0.1065, 0.7870]\); summing them column-wise gives the scores, which add up to
+ G × window = 4.
+
+
+
Constraints
+
+
1 ≤ num_kv_heads ≤ num_q_heads ≤ 64, and
+ num_q_heads is a multiple of num_kv_heads
+
1 ≤ window ≤ min(seq_len, 128)
+
1 ≤ seq_len ≤ 65,536
+
1 ≤ head_dim ≤ 128
+
Q and K hold finite 32-bit floats; scaled logits can exceed 100 in
+ magnitude, so the softmax must be computed in a numerically stable way
+
Performance is measured with num_q_heads = 32, num_kv_heads = 8,
+ window = 64, seq_len = 32,768, head_dim = 128
+
diff --git a/challenges/medium/164_snapkv_importance_scores/challenge.py b/challenges/medium/164_snapkv_importance_scores/challenge.py
new file mode 100644
index 00000000..e704d0d4
--- /dev/null
+++ b/challenges/medium/164_snapkv_importance_scores/challenge.py
@@ -0,0 +1,187 @@
+import ctypes
+import math
+from typing import Any, Dict, List
+
+import torch
+from core.challenge_base import ChallengeBase, OutTensor, RandnTensor
+
+
+class Challenge(ChallengeBase):
+ name = "SnapKV Importance Scores"
+ # Every score is a sum of at most num_groups * window <= 8,192 softmax probabilities, each
+ # in [0, 1]. Against a float64 recomputation the float32 reference uses <= 0.4% of the
+ # elementwise atol + rtol * |ref| budget on every case except the large-logit one (|scaled
+ # logit| up to ~117), where it uses 12%; on the performance case it uses 0.2%. An independent
+ # two-pass, key-tiled float32 implementation stays within 0.2% of the reference. Rounding Q
+ # and K to TF32 / FP16 / BF16, dropping the 1/sqrt(d) scale, moving the causal boundary by
+ # one, or normalizing with a stale running max all exceed the budget on functional cases.
+ atol = 1e-05
+ rtol = 1e-04
+ num_gpus = 1
+ access_tier = "free"
+
+ def reference_impl(
+ self,
+ Q: torch.Tensor,
+ K: torch.Tensor,
+ scores: torch.Tensor,
+ num_q_heads: int,
+ num_kv_heads: int,
+ window: int,
+ seq_len: int,
+ head_dim: int,
+ ):
+ assert Q.shape == (num_q_heads, window, head_dim)
+ assert K.shape == (num_kv_heads, seq_len, head_dim)
+ assert scores.shape == (num_kv_heads, seq_len)
+ assert Q.dtype == K.dtype == scores.dtype == torch.float32
+ assert num_q_heads % num_kv_heads == 0
+ assert 1 <= window <= seq_len
+
+ num_groups = num_q_heads // num_kv_heads
+ scale = 1.0 / math.sqrt(head_dim)
+
+ # Query heads h = g * num_groups + j share KV head g: (num_kv_heads, groups * window, d)
+ Qg = Q.reshape(num_kv_heads, num_groups * window, head_dim)
+ logits = torch.bmm(Qg, K.transpose(1, 2)) * scale
+
+ # Window query i sits at absolute position seq_len - window + i and sees keys t <= pos.
+ q_pos = torch.arange(window, device=Q.device) + (seq_len - window)
+ q_pos = q_pos.repeat(num_groups)
+ k_pos = torch.arange(seq_len, device=Q.device)
+ mask = k_pos.unsqueeze(0) > q_pos.unsqueeze(1)
+ logits = logits.masked_fill(mask.unsqueeze(0), float("-inf"))
+
+ probs = torch.softmax(logits, dim=-1)
+ scores.copy_(probs.sum(dim=1))
+
+ def get_solve_signature(self) -> Dict[str, tuple]:
+ return {
+ "Q": (ctypes.POINTER(ctypes.c_float), "in"),
+ "K": (ctypes.POINTER(ctypes.c_float), "in"),
+ "scores": (ctypes.POINTER(ctypes.c_float), "out"),
+ "num_q_heads": (ctypes.c_int, "in"),
+ "num_kv_heads": (ctypes.c_int, "in"),
+ "window": (ctypes.c_int, "in"),
+ "seq_len": (ctypes.c_int, "in"),
+ "head_dim": (ctypes.c_int, "in"),
+ }
+
+ def _build(
+ self,
+ num_q_heads: int,
+ num_kv_heads: int,
+ window: int,
+ seq_len: int,
+ head_dim: int,
+ seed: int,
+ std: float = 1.0,
+ zero_q: bool = False,
+ ) -> Dict[str, Any]:
+ torch.manual_seed(seed)
+ dev, f32 = self.device, torch.float32
+ Q = torch.randn(num_q_heads, window, head_dim, device=dev, dtype=f32) * std
+ K = torch.randn(num_kv_heads, seq_len, head_dim, device=dev, dtype=f32) * std
+ if zero_q:
+ Q.zero_()
+ return {
+ "Q": Q,
+ "K": K,
+ # Pre-filled with garbage: scores is not zero-initialized, so every key (including
+ # tile tails) must be written and accumulating solutions must initialize it first.
+ "scores": torch.full((num_kv_heads, seq_len), 123.0, device=dev, dtype=f32),
+ "num_q_heads": num_q_heads,
+ "num_kv_heads": num_kv_heads,
+ "window": window,
+ "seq_len": seq_len,
+ "head_dim": head_dim,
+ }
+
+ def generate_example_test(self) -> Dict[str, Any]:
+ dev, f32 = self.device, torch.float32
+ Q = torch.tensor(
+ [
+ [[2.0, 0.0, 0.0, 0.0], [0.0, 2.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 2.0, 2.0]],
+ ],
+ device=dev,
+ dtype=f32,
+ )
+ K = torch.tensor(
+ [[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 1.0]]],
+ device=dev,
+ dtype=f32,
+ )
+ return {
+ "Q": Q,
+ "K": K,
+ "scores": torch.full((1, 3), 123.0, device=dev, dtype=f32),
+ "num_q_heads": 2,
+ "num_kv_heads": 1,
+ "window": 2,
+ "seq_len": 3,
+ "head_dim": 4,
+ }
+
+ def generate_functional_test(self) -> List[Dict[str, Any]]:
+ tests = []
+
+ # Hand-computed example: scores = [1.5495, 1.4516, 0.9989] (see challenge.html). Window
+ # query 0 sits at position 1 and must not see key 2.
+ tests.append(self.generate_example_test())
+
+ # Minimal: one head, one key, one query. The only probability is 1, so scores = [1].
+ tests.append(self._build(1, 1, 1, 1, 1, seed=1))
+
+ # Zero queries: every visible logit is 0, so query i spreads 1 / (pos_i + 1) uniformly
+ # over keys 0..pos_i. With seq_len = 5 and window = 3 the exact answer per KV head is
+ # 2 * [1/3 + 1/4 + 1/5, 1/3 + 1/4 + 1/5, 1/3 + 1/4 + 1/5, 1/4 + 1/5, 1/5]. Catches a
+ # missing causal mask (would give 2 * 3/5 everywhere), a mask that is off by one, and
+ # queries placed at positions 0..window-1 instead of the end of the prompt.
+ tests.append(self._build(4, 2, 3, 5, 8, seed=2, zero_q=True))
+
+ # window == seq_len: the whole prompt is the observation window, so query 0 sees only
+ # key 0. Catches end-alignment bugs at the boundary where the first query is at 0.
+ tests.append(self._build(2, 1, 4, 4, 16, seed=3))
+
+ # window = 1 (decode-like): no key is masked; catches masks that drop the diagonal.
+ tests.append(self._build(4, 4, 1, 37, 32, seed=4))
+
+ # Distinct KV heads with groups of 4: catches mapping query head h to KV head h % H_kv
+ # instead of h // groups, and summing over only one head of the group.
+ tests.append(self._build(8, 2, 8, 64, 32, seed=5))
+
+ # Large logits (|scaled logit| up to ~117): exp overflows in float32 without max
+ # subtraction; also catches a single-pass column accumulation that normalizes with a
+ # stale running max instead of the row's final max and sum.
+ tests.append(self._build(4, 1, 16, 300, 64, seed=6, std=5.0))
+
+ # Non-power-of-2 everything: tile tails along keys, window and head_dim (d = 40).
+ tests.append(self._build(6, 3, 30, 255, 40, seed=7))
+
+ # Power-of-2 shapes with MHA (groups = 1) and head_dim 128.
+ tests.append(self._build(4, 4, 32, 512, 128, seed=8))
+
+ # Multi-query attention (one KV head, 16 query heads): long reduction over 16 * 24
+ # queries per key.
+ tests.append(self._build(16, 1, 24, 1000, 64, seed=9))
+
+ # Realistic: 8 query heads, 2 KV heads, 32-token window over a 4,096-token prompt.
+ tests.append(self._build(8, 2, 32, 4096, 64, seed=10))
+
+ return tests
+
+ def generate_performance_test(self) -> Dict[str, Any]:
+ # Llama-3-8B-style GQA layer (32 query heads, 8 KV heads, head_dim 128) compressing a
+ # 32K-token prompt with a 64-token observation window.
+ num_q_heads, num_kv_heads, window, seq_len, head_dim = 32, 8, 64, 32768, 128
+ return {
+ "Q": RandnTensor((num_q_heads, window, head_dim)),
+ "K": RandnTensor((num_kv_heads, seq_len, head_dim)),
+ "scores": OutTensor((num_kv_heads, seq_len)),
+ "num_q_heads": num_q_heads,
+ "num_kv_heads": num_kv_heads,
+ "window": window,
+ "seq_len": seq_len,
+ "head_dim": head_dim,
+ }
diff --git a/challenges/medium/164_snapkv_importance_scores/starter/starter.cu b/challenges/medium/164_snapkv_importance_scores/starter/starter.cu
new file mode 100644
index 00000000..d7fda759
--- /dev/null
+++ b/challenges/medium/164_snapkv_importance_scores/starter/starter.cu
@@ -0,0 +1,5 @@
+#include
+
+// Q, K, scores are device pointers
+extern "C" void solve(const float* Q, const float* K, float* scores, int num_q_heads,
+ int num_kv_heads, int window, int seq_len, int head_dim) {}
diff --git a/challenges/medium/164_snapkv_importance_scores/starter/starter.cute.py b/challenges/medium/164_snapkv_importance_scores/starter/starter.cute.py
new file mode 100644
index 00000000..03c4b0b5
--- /dev/null
+++ b/challenges/medium/164_snapkv_importance_scores/starter/starter.cute.py
@@ -0,0 +1,17 @@
+import cutlass
+import cutlass.cute as cute
+
+
+# Q, K, scores are tensors on the GPU
+@cute.jit
+def solve(
+ Q: cute.Tensor,
+ K: cute.Tensor,
+ scores: cute.Tensor,
+ num_q_heads: cute.Int32,
+ num_kv_heads: cute.Int32,
+ window: cute.Int32,
+ seq_len: cute.Int32,
+ head_dim: cute.Int32,
+):
+ pass
diff --git a/challenges/medium/164_snapkv_importance_scores/starter/starter.jax.py b/challenges/medium/164_snapkv_importance_scores/starter/starter.jax.py
new file mode 100644
index 00000000..82ee063b
--- /dev/null
+++ b/challenges/medium/164_snapkv_importance_scores/starter/starter.jax.py
@@ -0,0 +1,17 @@
+import jax
+import jax.numpy as jnp
+
+
+# Q, K are tensors on device
+@jax.jit
+def solve(
+ Q: jax.Array,
+ K: jax.Array,
+ num_q_heads: int,
+ num_kv_heads: int,
+ window: int,
+ seq_len: int,
+ head_dim: int,
+) -> jax.Array:
+ # return output tensor directly
+ pass
diff --git a/challenges/medium/164_snapkv_importance_scores/starter/starter.mojo b/challenges/medium/164_snapkv_importance_scores/starter/starter.mojo
new file mode 100644
index 00000000..42ccd23d
--- /dev/null
+++ b/challenges/medium/164_snapkv_importance_scores/starter/starter.mojo
@@ -0,0 +1,17 @@
+from max.gpu.host import DeviceContext
+from std.memory import UnsafePointer
+
+
+# Q, K, scores are device pointers
+@export
+def solve(
+ Q: UnsafePointer[Float32, MutAnyOrigin],
+ K: UnsafePointer[Float32, MutAnyOrigin],
+ scores: UnsafePointer[Float32, MutAnyOrigin],
+ num_q_heads: Int32,
+ num_kv_heads: Int32,
+ window: Int32,
+ seq_len: Int32,
+ head_dim: Int32,
+) raises:
+ pass
diff --git a/challenges/medium/164_snapkv_importance_scores/starter/starter.pytorch.py b/challenges/medium/164_snapkv_importance_scores/starter/starter.pytorch.py
new file mode 100644
index 00000000..4233aa47
--- /dev/null
+++ b/challenges/medium/164_snapkv_importance_scores/starter/starter.pytorch.py
@@ -0,0 +1,15 @@
+import torch
+
+
+# Q, K, scores are tensors on the GPU
+def solve(
+ Q: torch.Tensor,
+ K: torch.Tensor,
+ scores: torch.Tensor,
+ num_q_heads: int,
+ num_kv_heads: int,
+ window: int,
+ seq_len: int,
+ head_dim: int,
+):
+ pass
diff --git a/challenges/medium/164_snapkv_importance_scores/starter/starter.triton.py b/challenges/medium/164_snapkv_importance_scores/starter/starter.triton.py
new file mode 100644
index 00000000..6c1006c9
--- /dev/null
+++ b/challenges/medium/164_snapkv_importance_scores/starter/starter.triton.py
@@ -0,0 +1,17 @@
+import torch
+import triton
+import triton.language as tl
+
+
+# Q, K, scores are tensors on the GPU
+def solve(
+ Q: torch.Tensor,
+ K: torch.Tensor,
+ scores: torch.Tensor,
+ num_q_heads: int,
+ num_kv_heads: int,
+ window: int,
+ seq_len: int,
+ head_dim: int,
+):
+ pass