Implement top-k sparse attention per query

Why it matters Sparse attention variants that pick a few keys per query are a main route to cheaper long-context inference.

Top-k attention keeps only each query's k highest-scoring keys and renormalises the softmax over them, so most weights become exactly zero.

Write topk_attention(q, k, v, top_k). q is (Tq, d), k is (Tk, d), v is (Tk, dv). Scores = q @ k.T / sqrt(d). For each query keep the top_k largest scores (ties go to the lower key index), apply softmax over the kept scores only, set every other weight to 0 and return the (Tq, dv) output. If top_k >= Tk this is ordinary attention.

Signaturedef topk_attention(q, k, v, top_k)

Example

q = [[1, 0]], k = [[1, 0], [0, 1], [2, 0]], v = [[1], [2], [3]], top_k = 2 keeps keys 2 and 0 and returns about [[2.3395]].

Understand the idea

Most attention weight usually lands on a handful of keys. Top-k attention bets on that: each query keeps only its k best keys and ignores the rest, like a shortlist at a job interview.

Example: q = [1, 0], keys [1,0], [0,1], [2,0], scale 1/sqrt(2). Scores are 0.707, 0 and 1.414. With k = 2 we keep keys 2 and 0. Softmax over just those two: e^1.414 and e^0.707 give weights 0.67 and 0.33. Output = 0.67 * 3 + 0.33 * 1 = 2.34. Key 1 gets weight exactly 0.

Rule: S = qK^T / sqrt(d); keep the top k entries per row; set the others to -inf; weights = softmax(S); out = weights V.

The renormalisation step matters: the kept weights must sum to 1. Real sparse attention systems avoid computing all scores by using a cheap indexer or block summaries first, but the selection and softmax logic is the same.

Shapes and data flow

q (Tq, d), k (Tk, d) -> scores (Tq, Tk) -> keep (Tq, top_k) -> weights (Tq, Tk) mostly zero -> out (Tq, dv)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampletopk_attention([[1.0, 0.0]], [[1.0, 0.0], [0.0, 1.0], [2.0, 0.0]], [[1.0], [2.0], [3.0]], 2)
  • Sample 2: randomtopk_attention(Q, K, Vv, 2)