Manuscript Offprint

arXiv:2611.07232

Recursive Sparse Attention: Million-Token Length Extrapolation at Logarithmic Cost

Ruitian Wang, Xinyu Yang, Minshen Zhang, Hao Zhang

Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.

ABSTRACT

At context lengths of about 1M tokens, dense attention is costly in prefill and decoding, and training typically relies on long documents, which become scarcer as the target length increases. Most sparse attention methods score all preceding blocks or tokens, so their selection cost per query is O(L)O(L) at context length LL; hierarchical selection reduces it to O(log⁡L)O(\log L), but prior trainable hierarchical methods report accuracy only within their training length. We propose RecSA (Recursive Sparse Attention), which builds a tree over the KV cache in which each node summarizes its subtree with one key and one mean-pooled value. The keys come from one pooler per layer, shared by all levels and distilled from dense attention. Each level above the tokens selects at most kk candidates, so each query has O(log⁡L)O(\log L) selection cost and reads O(log⁡L)O(\log L) entries; the summaries of unselected candidates share one softmax with the exact tokens. Each entry's RoPE position is its index among the candidates of its level, so at any length every relative distance stays within the range seen during training. Initialized from Qwen3-4B and trained on 0.62B tokens at the original model's 32K training length, RecSA outperforms all baselines on RULER at every length from 131K to 2M; at 1M, it scores 60.5, compared with 40.0 for the best baseline, Dense + DCA. With our optimized kernels, RecSA is faster than dense attention in end-to-end prefill and decoding from 64K to 2M; at 524K on one H200 GPU, it accelerates prefill by 3.2×3.2\times and decoding by 3.8×3.8\times.

1 INTRODUCTION

State-of-the-art language models now support context windows of about 1M tokens (DeepSeek-AI et al., 2026). At such lengths, inference is costly and training data is scarce. In prefill, the computation of dense attention grows quadratically with length, and in decoding, every generated token reads the entire KV cache. Training at the target length relies on sufficiently long documents, which become scarcer as the length increases (Gao et al., 2025a). Some of these models reduce the inference cost with sparse attention (DeepSeek-AI et al., 2026). As language models continue to develop, the context they need is likely to keep growing. Longer contexts call for methods whose inference cost grows slowly with length and that need no training at the target length.

Trainable sparse attention methods such as MoBA (Lu et al., 2025), NSA (Yuan et al., 2025) and DSA (DeepSeek-AI et al., 2025) are trained at the target length. HSA (Hu et al., 2025; Leng et al., 2026; Hu et al., 2026b) and HiLS (Hu et al., 2026a) train only on short sequences, and InfLLM (Xiao et al., 2024a) and InfiniteHiP (Lee et al., 2025b) are training-free; neither group needs long docu-

(a) RULER score

Figure

(b) Decoding latency (ms per token)

Figure 1. RULER score and decoding latency from 32K to 2M. (b) End-to-end latency on one H200 GPU with batch size 1; Dense uses FlashAttention in the same framework. At 1M and 2M, host memory holds the exact tokens of RecSA (§4.3) and the part of the Dense KV cache beyond GPU memory; hollow markers indicate offloading. Arrows mark off-scale values. Percentages show the token budget of RecSA as a fraction of the context length.

*Equal contribution ¹University of California, San Diego ²Carnegie Mellon University. Correspondence to: Hao Zhang haozhang@ucsd.edu.

Preprint.

ments to run far beyond the training length. All of these methods score every preceding block or token at the first level, so at context length LL the selection cost per query is O(L)O(L). Hierarchical selection scores a top level of bounded size and then only the children of selected nodes, which reduces this cost to O(log⁡L)O(\log L). HiP (Lee et al., 2025a) and PISA (Tang et al., 2026) keep the original position of each key, so beyond the training length the distances to selected keys can exceed those seen in training. Hierarchical selection alone does not remove the need for context extension.

We propose RecSA, a Recursive Sparse Attention mechanism with hierarchical selection. It groups every 16 consecutive KV entries under a parent node and applies the same grouping to parent nodes, building a tree from the bottom up. Each node has one key and one mean-pooled value, which form the summary of its whole subtree. Selection starts at the top level, whose nodes form the first candidate list, and at each level scores every candidate against the query and selects at most kk of them. Their children form the candidate list of the next level, and this continues until the candidates are exact tokens. Unselected candidates also participate in the attention computation: their summaries and all exact tokens in the last candidate list share one softmax. Whenever the top level exceeds a fixed number of nodes, a level is added above it, so every candidate list has a bounded size, and the selection cost and the number of entries read per query are both O(log⁡L)O(\log L). RoPE (Su et al., 2024) is applied to every entry, summaries included, and the position of an entry is its index in the candidate list of its level, with the query at the last index. Every relative distance to the query is thus below 4,096, the maximum size of a candidate list with the default k=256k = 256. Longer sequences introduce no distance unseen during training at 32K.

A learnable pooler computes the key of a node from the keys of its children. Each attention layer has one pooler, applied recursively at every level of the tree, so adding a level requires no new parameters. Training starts from a pretrained dense model and has two stages. The first stage freezes the backbone and aligns the softmax over the scores of the candidate nodes at each level with the distribution of dense attention mass over their subtrees. The second stage freezes the pooler and trains the backbone under RecSA to adapt it to sparse attention. Both stages use only sequences at the training length of the original model.

We evaluate RecSA on Qwen3-4B (Yang et al., 2025), whose training length is 32K. The two stages process 0.62B tokens in total. For comparison, we train dense and sparse backbones on the same data and evaluate every backbone with each of two context extension methods, YaRN (Peng et al., 2024) and DCA (An et al., 2024); we also compare with two training-free methods. At every length, the token budget of each sparse method, i.e., the number of

entries a query attends to, is matched to that of RecSA. The evaluation covers synthetic long-context tasks, perplexity on long texts, real-world long-document tasks and short-context benchmarks. At 1M, the token budget of RecSA is only 1.16% of the context, and RecSA scores 60.5 on RULER (Hsieh et al., 2024), compared with 1.6 for Dense + YaRN, as shown in Figure 1a. The strongest of the other baselines, Dense + DCA, scores 40.0 (Table 1). At 32K, RecSA matches Dense + YaRN on RULER; on short-context benchmarks, RecSA performs comparably to the original model.

We implement prefill and decoding for RecSA in Triton (Tillet et al., 2019) and CUDA. In prefill, some existing block-sparse kernels group adjacent queries and load the union of their selected blocks once for the group (Hu et al., 2026a). This sharing reuses each key, already rotated by RoPE, for every query in the group, but in RecSA the index of a key, and hence its rotation, varies with the candidate list of each query. Because RoPE makes the attention score depend on positions only through the relative position, we split the rotation between keys and queries so that the part applied to each key is the same for all queries, and the group still loads each KV block once. On one H200 GPU with batch size 1, RecSA accelerates prefill by 3.2×3.2\times and decoding by 3.8×3.8\times at 524K, compared with dense FlashAttention (Dao, 2024) in the same framework, and its decoding latency stays nearly constant from 131K to 524K (Figure 1b).

We make the following contributions:

  • We propose RecSA, which combines hierarchical selection over a tree built on the KV cache with summaries for the unselected candidates and candidate-local RoPE (§3.1 and §3.2).

  • We distill the pooler, shared across levels, from dense attention and train RecSA only on sequences of 32K tokens (§3.3 and §3.4).

  • We provide prefill and decoding kernels for RecSA; in prefill, a group of adjacent queries loads each KV block once, although their candidate lists give its keys different positions (§4).

  • On Qwen3-4B, we compare RecSA from 32K to 2M with dense and sparse baselines, trained on the same data or training-free, at matched token budgets (§5).

References (79)

  • GQA: Training generalized multi-query transformer models from multi-head checkpoints
  • Training-free long-context scaling of large language models
  • Program Synthesis with Large Language Models
  • LongBench: A bilingual, multitask benchmark for long context understanding
  • Extending context window of large language models via positional interpolation (opens arXiv in a new tab)
  • Think you have Solved Question Answering? Try ARC, the AI2 Reasoning Challenge
  • Training Verifiers to Solve Math Word Problems
  • FlashAttention-2: Faster attention with better parallelism and work partitioning
  • Flash-Decoding for long-context inference
  • A dataset of information-seeking questions and answers anchored in research papers
  • DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence
  • LongRoPE: Extending LLM context window beyond 2 million tokens
  • NExtLong: Toward effective long-context training without long documents
  • The language model evaluation harness
  • SeerAttention: Self-distilled attention gating for efficient long-context prefilling
  • Sparse attention adaptation for long reasoning
  • Measuring massive multitask language understanding
  • Multi-pole attention for efficient long context reasoning
  • RULER: What's the real context size of your long-context language models?
  • Hardware-aligned hierarchical sparse attention for efficient long-term memory access
  • Hierarchical sparse attention done right: Toward infinite context modeling (opens arXiv in a new tab)
  • Every token counts: Generalizing 16M ultra-long context in large language models
  • MInference 1.0: Accelerating pre-filling for long-context LLMs via dynamic sparse attention
  • LLM maybe LongLM: SelfExtend LLM context window without tuning
  • The impact of positional encoding on length generalization in transformers
  • Efficient memory management for large language model serving with PagedAttention
  • FlexPrefill: A context-aware sparse attention mechanism for efficient long-sequence inference
  • A training-free sub-quadratic cost transformer model serving framework with hierarchically pruned attention
  • InfiniteHiP: Extending language model context up to 3 million tokens on a single GPU (opens arXiv in a new tab)
  • Understanding and improving length generalization in hierarchical sparse attention models
  • DataComp-LM: In search of the next generation of training sets for language models
  • MoBA: Mixture of block attention for long-context LLMs
  • Random-access infinite context length for transformers
  • PyTorch: An imperative style, high-performance deep learning library
  • YaRN: Efficient context window extension of large language models
  • Compressive transformers for long-range sequence modelling
  • SQuAD: 100,000+ questions for machine comprehension of text
  • Rectified rotary position embeddings
  • RoFormer: Enhanced transformer with rotary position embedding
  • Block Sparse Attention with Log-Linear Complexity
  • QUEST: Query-aware sparsity for efficient long-context LLM inference
  • Triton: An intermediate language and compiler for tiled neural network computations
  • MuSiQue: Multihop questions via single-hop question composition
  • Length generalization of causal transformers without position encoding (opens arXiv in a new tab)
  • Transformers: State-of-the-art natural language processing
  • InfLLM: Training-free long-context extrapolation for LLMs with an efficient context memory
  • Efficient streaming language models with attention sinks
  • HotpotQA: A dataset for diverse, explainable multi-hop question answering
  • Native sparse attention: Hardware-aligned and natively trainable sparse attention
  • $\infty$Bench: Extending long context evaluation beyond 100K tokens
  • Instruction-Following Evaluation for Large Language Models
  • (5)), and clamps $\sigma$ and $\rho$ to a minimum of $10^{-6}$
  • (6)) include the current node, whose key is pooled from all of its children (Eq
  • When the position $t$ of the new token is a multiple of $C^\ell$, RecSA adds a node with one child at level $\ell$
  • $\mathbf{w}$ is a unit vector in a random direction, $\tau = 0.05$, $g = 1$, the elements of $W_1$ are drawn independently and uniformly from $[-1/16, 1/16]$, $\mathbf{b}_1 = \mathbf{0}$ and $W_2 = 0$
  • From these keys we recomputed levels 1 (16 tokens) and 2 (256 tokens) with and without the MLP term ($W_2 = 0$, all other parameters unchanged)
  • The generative benchmarks use the chat template of Qwen3-4B in non-thinking mode with greedy decoding
  • We compare the log-likelihoods of the option letters A–D
  • As in MMLU, the prompt gives the question and its options labeled with letters, without the chat template, and we compare the log-likelihoods of the letters
  • Please reason step by step, and put your final answer within \boxed{}
  • The checkers draw random numbers, so we set the seed of Python’s random module to 0, of NumPy to 1234 and of langdetect to 0
  • the humaneval_instruct and mbpp_instruct formats of lm-evaluation-harness, 0-shot, pass@1, with at most 1,024 and 512 generated tokens, respectively
  • We then decode token by token, and each step includes the output logits
  • Dense uses the Flash-Decoding kernel (Dao et al., 2023) of FlashAttention-2 with a preallocated KV cache, and the number of splits is that of the default heuristic of FlashAttention or 32, whichever is faster
  • RecSA keeps the exact tokens in host memory and caches the most recent exact tokens on the GPU (Section 4.3)
  • Up to 524K, the work of a step depends only on its position, so we profile 8 steps after the timed steps of Appendix D.1
  • At 1M and 2M, this writes the new key and value to host memory and to the GPU cache and copies the children of the last level-1 node to the GPU
  • scoring, top-$k$ selection and attention over the summaries at that level
  • ><tr><td rowspan=
  • For longer contexts, Table D.3 compares RecSA with a two-level variant, which scores every level-1 node at each step
  • [R248624] E407003 code V153512
  • ><tr><td>Data</td><td>Pool</td><td>Stage 1</td><td>Stage 2</td><td>Length</td></tr><tr><td colspan=
  • The sequences of each kind of data are shuffled with a fixed seed, and the synthetic retrieval and document QA sequences are then shuffled into one order
  • ></td><td colspan=
  • It applies to the 982 of the 6,400 sequences that have a single piece of evidence starting before $t_a$
  • Gradient clipping applies jointly to the poolers of all layers
  • The indexer has 202M parameters in total, runs in fp32 and takes the normalized input of the attention layer, detached from the backbone
  • The configuration files in the official code of InfLLM set 128 initial tokens, a 4,096-token local window and 16 retrieved blocks; the 3K setting of the InfiniteHiP paper has 256 sink tokens, a 1,024-token window and 2,048 selected tokens
  • Its perplexity on the nine PG-19 books (Table 3) is 11.24, 10.88, 11.00, 11.02 and 11.07 from 32K to 1M, compared with 11.24, 10.87, 11.00, 11.08 and 11.12 for RecSA