Issue 45 Β· Pick 07 AI / ML β read
Recursive Sparse Attention: Million-Token Length Extrapolation at Logarithmic Cost
TL;DR: RecSA organizes the KV cache as a 16-ary tree where every node carries a learned one-vector summary of its subtree, and each query descends the tree picking the top-k nodes per level β so both selection cost and the number of entries read per query grow as O(\log L). The genuinely new move is that positions are assigned per candidate list, not per token, so no relative distance ever exceeds ~4K regardless of context length. Trained on just 0.62B tokens at Qwen3-4B's native 32K length, it scores 60.5 on RULER at 1M tokens (vs. 40.0 for the best baseline) and 49.3 at 2M, while being 3.2Γ faster at prefill and 3.8Γ at decoding than dense attention at 524K on one H200. If this holds beyond retrieval-heavy benchmarks, it's a serious contender for long-context serving.
Two problems that are usually solved separately
Serving a million-token context has two independent pains. The first is cost: dense attention is quadratic in prefill, and at decode time every new token reads the whole KV cache β at 2M tokens that's 275 GiB of KV, which doesn't even fit on an H200. The second is length generalization: RoPE-based models see relative distances only up to their training length, and everything beyond is out-of-distribution. The standard fixes β YaRN rescales rotation frequencies, DCA remaps positions into chunks β are band-aids applied at inference time, and they degrade (Dense+YaRN collapses from 80.0 on RULER at 131K to 1.6 at 1M).
Sparse attention seems like it should help with both, but look at how existing methods actually select. MoBA, NSA, and DeepSeek's DSA score every preceding block or token for each query β the selection itself is O(L). Hierarchical methods like HiP and PISA get selection down to O(\log L) by descending a tree, but they keep each key's original absolute position, so beyond training length the query-to-key distances are still OOD. And trainable methods like NSA and DSA are trained at the target length, which requires long documents that get scarcer the longer you go.
RecSA's bet is that one mechanism can solve both problems at once: a recursive tree gives logarithmic cost, and β the key insight β if positions are defined within the tree traversal rather than within the sequence, the model literally never encounters a distance it didn't see at 32K.
The mechanism
Build a tree bottom-up over the KV cache: every 16 consecutive entries get a parent node, recursively, with a new top level added whenever the current top exceeds Ck = 4{,}096 nodes (C=16 children, k=256 selected per level). Each node stores one key and one value summarizing its entire subtree. The value is just the mean of the children's values. The key comes from a small learned pooler (~25K parameters per layer, shared across all levels and heads β adding a tree level adds zero parameters).
For a query, selection runs top-down. The top level (at most 4,096 nodes) is scored exhaustively; the top 256 nodes are expanded into their children, which form the next level's candidate list (at most 16 \times 256 = 4{,}096 entries); repeat until you reach exact tokens. Each level is bounded, and the number of levels is \log_{16} L-ish: three levels cover up to 1M tokens, four cover 2M.
Two details distinguish this from prior hierarchical methods. First, unselected candidates still attend. Their summaries enter the same softmax as the exact tokens, with their scores used directly as logits (no subtree-size correction). Because the top-level candidates cover the full prefix and each expanded node is replaced exactly by its children, the summaries and exact tokens partition the prefix β the query always "sees" everything, just at variable resolution. This is like Multipole Attention's centroid trick, but with learned summaries and bounded per-level cost. The ablation says summaries are worth ~2 points on average (72.3 vs 70.4 over 131Kβ1M), concentrated on aggregation tasks like counting common words (+15.5 on MK2, +7.8 on CWE), where a coarse view of the whole context genuinely matters.
Second, candidate-local RoPE, which is where the extrapolation comes from.
The aha: positions live in the candidate list, not the sequence
Standard RoPE rotates query and key by their absolute sequence positions, so scores depend on t - j. At 2M tokens with a 32K training length, nearly every distance is OOD. RecSA instead assigns each candidate β summary or token β its index within the current level's candidate list, with the query at the last index. Skipped stretches of the sequence between candidates get no positions at all. Since every list has at most 4,096 entries, every relative distance the model ever computes is below 4,096 β and training at 32K with k=256 covers exactly that range. Longer sequences add tree depth, not new distances.
A consequence worth noting: the same KV entry gets different positions for different queries, so the tree must store un-rotated keys, and the pooler pools position-free keys. This also breaks the standard kernel optimization where adjacent queries share RoPE-rotated key blocks. The authors fix it with a nice identity: since R_a^\top R_b = R_{b-a}, the rotation can be split so that the key-side part depends only on the child's offset within its block (same for all queries), and the query-side part absorbs the rest β each query's rotation just steps by R_{-C} per selected node. A group of 16 adjacent queries then loads each KV block once, as in dense block-sparse kernels.
Teaching the summaries what dense attention would do
A node's key must serve double duty: it drives top-k selection and it acts as the logit of the summary in the final softmax. Both should reflect how much dense attention mass the original model would put on that subtree. Mean-pooled keys are known to be bad at this, so RecSA trains the pooler by distillation: freeze the backbone, run dense attention, compute the true attention mass on each candidate's subtree, and minimize KL between that teacher distribution and the softmax over the pooler-derived candidate scores β at every level, through one shared pooler.
The pooler itself (Eq. 5) is a gated attention-pool plus a tiny MLP correction. One subtle failure mode they catch: under candidate-local RoPE, the MLP can shift all keys at a level by a common vector, which injects a query-dependent, content-independent positional bias that lowers the KL without learning anything about subtree content. They add a "shift penalty" on the level-wide mean of the MLP term; the ablation shows this matters (55.5 vs 45.3 at 524K with frozen backbone). Appendix A.4 has a lovely mechanistic analysis: the MLP term doesn't fix the score of its own node, but biases the next level's pooling weights toward needle-containing children β the weight on needle children jumps from 0.23 to 0.52, and level-2 needle recall rises from 0.47 to 0.63.
Stage 2 then freezes the pooler and fine-tunes the full backbone under RecSA with plain language modeling. Total training: 0.62B tokens, all at 32K length, ~9 hours on 8 H200s. That data-efficiency is itself remarkable β compare with methods that need continued pretraining at 1M.
The evidence
The headline comparison is carefully controlled: Dense, MoBA, and DSA backbones are trained from Qwen3-4B on the same data, same steps, each evaluated with both YaRN and DCA, at token budgets matched to RecSA's (only 1.16% of the context at 1M).
The degradation curve is what matters: RecSA loses ~34 points going from 131K to 2M; the best baseline loses ~51. Notably, DSA+DCA also keeps relative distances in-range and uses the same budget, yet trails RecSA by 24 points at 1M β so bounded distances alone don't explain the gap; the trained hierarchical selection and summaries carry real weight. Perplexity on PG-19 books is almost eerily flat: 10.87β11.12 from 131K to 1M, while Dense+DCA climbs to 14.57 and YaRN variants explode past 200. On InfiniteBench En.MC (real novels, 70Kβ746K), RecSA scores 66.8 vs 34.5 for Qwen3-4B+YaRN, edging out InfiniteHiP's 66.4. Short-context benchmarks (MMLU, GSM8K, HumanEval, etc.) stay within ~2 points of the original model β unsurprising since RecSA degenerates to exact dense attention below 4,096 tokens.
The systems results are equally compelling:
RecSA decodes at ~6.1 ms/token flat from 131K to 524K β the logarithmic structure made real. At 1M and 2M, exact tokens live in pinned host memory and only the (small) summary levels stay on GPU; per step, each query gathers at most 4,096 exact tokens per head per layer over PCIe, independent of context length. The whole 36-layer decode step runs as one replayed CUDA graph. The 2M Dense comparison (2.9 s/token) is somewhat unfair β Dense is drowning in PCIe copies it fundamentally can't avoid β but that's the point: dense attention at 2M on one GPU is not a thing, and RecSA at 10.7 ms/token is.
What to be skeptical about
The task mix favors retrieval. RULER is dominated by needle-finding, and the training data includes synthetic retrieval tasks structurally similar to RULER (inserted key-value records in books/code). The baselines were trained on the same data, which keeps the comparison fair, but it means the headline numbers tell us RecSA retrieves well, not that it reasons well over 1M tokens. The per-task breakdown at 1M is sobering where aggregation or multi-hop is required: CWE (counting common words) is 23.1, MK3 is 6.2, HotpotQA-style QA2 is 6.2. The tree summarizes; it doesn't integrate.
k may need to grow with task hardness. Evaluating the same trained model with k=512 improves every length (88.0 vs 83.3 at 131K; 65.0 vs 60.5 at 1M) at ~1.8Γ the budget β and interestingly works despite distances up to 8,191 exceeding the 4,095 seen in training. The sparsity-quality frontier hasn't been mapped for tasks needing broad aggregation, and the authors' own selection suggests this is the open question.
Scale. Everything is Qwen3-4B. Whether a 25K-parameter-per-layer pooler distilled from a 70B model's attention remains faithful, and whether candidate-local RoPE interacts well with long chain-of-thought generation (where the model writes into the tree it later queries), is untested. No multi-turn or agentic evaluations, no batch-size > 1 serving numbers.
Softmax calibration. Summary logits enter the softmax with no correction for subtree size β a level-3 summary covering 4,096 tokens competes on equal footing with a single token. That it works at all is interesting; that it's optimal seems unlikely.
Why it matters anyway
The compelling framing here is that length extrapolation and inference cost aren't separate problems β the same recursive structure that bounds per-query compute also bounds the positional distribution, and a bounded positional distribution is exactly what extrapolation needs. "Train at 32K, serve at 2M, faster than dense" from 0.62B tokens of adaptation is a dramatic cost profile compared to continued pretraining at target length, and the method retrofits onto an existing pretrained model. The approach also composes naturally with offloading, since the GPU only ever needs the summary levels (<7% of the KV cache).
If you read one section, make it Β§3.2 (candidate-local RoPE) together with Appendix A.4 β the first is the idea that does the extrapolation work, and the second is an unusually honest mechanistic dissection of what the learned pooler actually contributes.