Select key blocks by compressed scores, then attend inside them

Why it matters Block selection lets long-context models skip most of the cache while keeping exact attention on the parts that matter.

Block-selection sparse attention (in the style of Native Sparse Attention) scores whole blocks of keys with one summary vector each, keeps the best few blocks per query and runs exact attention only inside them.

Write block_select_attention(q, k, v, block, n_sel). q and k are (T, d), v is (T, dv), all for the same causal sequence. Block b covers keys b*block to (b+1)*block - 1 (the last block may be short). For the query at position t:
1. Candidate blocks are those with start b*block <= t. The block containing t is always selected.
2. Every other candidate gets score q_t . mean(k over the block). Add the best n_sel - 1 of them (ties go to the lower block index).
3. Attend with softmax(q_t . k_j / sqrt(d)) over keys j <= t that lie in the selected blocks.
Return (out, selected) where out is (T, dv) and selected is a list of T sorted lists of block indices.

Signaturedef block_select_attention(q, k, v, block, n_sel)

Example

with T = 4, block = 2, n_sel = 1, each query uses only its own block, so selected is [[0], [0], [1], [1]] and query 2 attends only to key 2.

Understand the idea

Scoring every key for every query is what makes long contexts slow. Block selection works like skimming a book by its chapter summaries: first score each block of keys by one summary vector, then read only the best chapters closely.

Example: 8 keys in blocks of 2, query at position 5. Its own block is 2 (keys 4, 5), always kept. Blocks 0 and 1 are candidates; if q . mean(block 1) beats block 0 and n_sel = 2, the query attends to keys 2, 3, 4, 5 with a normal softmax. Keys 6 and 7 are future and never visible.

Rule: summary_b = mean(k in block b); selected = {own block} + top (n_sel - 1) earlier blocks by q . summary_b; out = softmax over keys j <= t in selected blocks.

Forcing the local block keeps nearby context, which is usually the most important. Native Sparse Attention combines this kind of block selection with a compressed branch and a sliding window branch, and GPU kernels load whole blocks at once.

Shapes and data flow

k (T, d) -> block means (nb, d); per query: scores over candidate blocks (<= nb,) -> selected keys (m,) -> out row (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: exampleblock_select_attention(Q, K, Vv, 2, 1)[1]
  • Sample 2: select twoblock_select_attention(Q8, K8, V8, 2, 2)