Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions challenges/medium/164_snapkv_importance_scores/challenge.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<p>
Compute the per-key importance scores that SnapKV-style KV-cache compression uses to decide which
prompt tokens to keep after prefill. The last <code>window</code> queries of the prompt (the
<em>observation window</em>) attend causally over all <code>seq_len</code> 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 <code>Q</code> of shape
<code>num_q_heads &times; window &times; head_dim</code> and <code>K</code> of shape
<code>num_kv_heads &times; seq_len &times; head_dim</code>, write <code>scores</code> of shape
<code>num_kv_heads &times; seq_len</code>. All tensors are 32-bit floats.
</p>

<p>
With <code>G = num_q_heads / num_kv_heads</code>, query head <code>h</code> uses KV head
<code>g = &lfloor;h / G&rfloor;</code>. Window query <code>i</code> 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 &gt; 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
<code>G &times; window</code>.
</p>

<svg width="700" height="270" viewBox="0 0 700 270" xmlns="http://www.w3.org/2000/svg" style="display:block; margin:20px auto;">
<rect width="700" height="270" fill="#222"/>
<defs>
<marker id="arr164" markerWidth="6" markerHeight="6" refX="5" refY="3" orient="auto">
<path d="M0,0 L6,3 L0,6 Z" fill="#888"/>
</marker>
</defs>
<text x="350" y="22" text-anchor="middle" fill="#ccc" font-size="13" font-family="monospace">attention probabilities of one query head (seq_len = 12, window = 4)</text>
<text x="60" y="64" text-anchor="end" fill="#aaa" font-size="11" font-family="monospace">i=0</text>
<text x="60" y="94" text-anchor="end" fill="#aaa" font-size="11" font-family="monospace">i=1</text>
<text x="60" y="124" text-anchor="end" fill="#aaa" font-size="11" font-family="monospace">i=2</text>
<text x="60" y="154" text-anchor="end" fill="#aaa" font-size="11" font-family="monospace">i=3</text>
<!-- visible region: row i sees keys 0..8+i -->
<rect x="70" y="50" width="360" height="120" fill="#1a3a5c" stroke="#4a9eff" stroke-width="1.5"/>
<rect x="430" y="80" width="40" height="90" fill="#1a3a5c" stroke="#4a9eff" stroke-width="1"/>
<rect x="470" y="110" width="40" height="60" fill="#1a3a5c" stroke="#4a9eff" stroke-width="1"/>
<rect x="510" y="140" width="40" height="30" fill="#1a3a5c" stroke="#4a9eff" stroke-width="1"/>
<!-- masked region -->
<rect x="430" y="50" width="120" height="30" fill="#3a1a1a" stroke="#aa4444" stroke-width="1"/>
<rect x="470" y="80" width="80" height="30" fill="#3a1a1a" stroke="#aa4444" stroke-width="1"/>
<rect x="510" y="110" width="40" height="30" fill="#3a1a1a" stroke="#aa4444" stroke-width="1"/>
<text x="490" y="69" text-anchor="middle" fill="#e99" font-size="10" font-family="monospace">masked</text>
<text x="250" y="114" text-anchor="middle" fill="#cce" font-size="11" font-family="monospace">every row: softmax over visible keys, sums to 1</text>
<text x="560" y="69" fill="#aaa" font-size="10" font-family="monospace">p=8</text>
<text x="560" y="159" fill="#aaa" font-size="10" font-family="monospace">p=11</text>
<text x="70" y="45" fill="#888" font-size="10" font-family="monospace">key 0</text>
<text x="550" y="45" text-anchor="end" fill="#888" font-size="10" font-family="monospace">key 11</text>
<line x1="310" y1="175" x2="310" y2="210" stroke="#888" stroke-width="1.5" marker-end="url(#arr164)"/>
<text x="320" y="197" fill="#aaa" font-size="11" font-family="monospace">sum down each column (and over the G heads sharing the KV head)</text>
<rect x="70" y="220" width="480" height="24" fill="#1a4a2a" stroke="#44cc66" stroke-width="1.5"/>
<text x="310" y="237" text-anchor="middle" fill="#cec" font-size="11" font-family="monospace">scores[g, 0 .. seq_len-1]</text>
</svg>

<h2>Implementation Requirements</h2>
<ul>
<li>Implement the <code>solve</code> function; do not change its signature.</li>
<li>External libraries are not permitted.</li>
<li>Write the result into <code>scores</code> (row-major, <code>num_kv_heads &times; seq_len</code>).
<code>scores</code> is not zero-initialized; every element must be written.</li>
<li>All tensors are row-major and contiguous: <code>Q[h, i, d]</code> and <code>K[g, t, d]</code>
with <code>d</code> fastest.</li>
<li>Compute the dot products from the float32 inputs; rounding <code>Q</code> or <code>K</code>
to TF32, FP16 or BF16 is outside the tolerance.</li>
</ul>

<h2>Example</h2>
<p>
Input: <code>num_q_heads</code> = 2, <code>num_kv_heads</code> = 1, <code>window</code> = 2,
<code>seq_len</code> = 3, <code>head_dim</code> = 4 (so the scale is 1/2 and the window queries
sit at positions 1 and 2)
\[
Q_0 = \begin{bmatrix} 2 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 \end{bmatrix}, \quad
Q_1 = \begin{bmatrix} 0 & 0 & 0 & 0 \\ 0 & 0 & 2 & 2 \end{bmatrix}, \quad
K_0 = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 1 \end{bmatrix}
\]
Output:
\[
\text{scores} = \begin{bmatrix} 1.5495 & 1.4516 & 0.9989 \end{bmatrix}
\]
</p>
<p>
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
<code>G &times; window</code> = 4.
</p>

<h2>Constraints</h2>
<ul>
<li>1 &le; <code>num_kv_heads</code> &le; <code>num_q_heads</code> &le; 64, and
<code>num_q_heads</code> is a multiple of <code>num_kv_heads</code></li>
<li>1 &le; <code>window</code> &le; min(<code>seq_len</code>, 128)</li>
<li>1 &le; <code>seq_len</code> &le; 65,536</li>
<li>1 &le; <code>head_dim</code> &le; 128</li>
<li><code>Q</code> and <code>K</code> hold finite 32-bit floats; scaled logits can exceed 100 in
magnitude, so the softmax must be computed in a numerically stable way</li>
<li>Performance is measured with <code>num_q_heads</code> = 32, <code>num_kv_heads</code> = 8,
<code>window</code> = 64, <code>seq_len</code> = 32,768, <code>head_dim</code> = 128</li>
</ul>
187 changes: 187 additions & 0 deletions challenges/medium/164_snapkv_importance_scores/challenge.py
Original file line number Diff line number Diff line change
@@ -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,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#include <cuda_runtime.h>

// 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) {}
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Loading