Two-Stage Routing Design for Long-Context Sparse Attention
Long-context models need to avoid dense scoring over the entire history. This article describes a two-stage routing design in which a cheap index stage selects top-k blocks or tokens and a full-precision compute stage attends only to those selected positions. It covers grouped-query attention routing, block max-pooling for needle-in-a-haystack recall, separation of index and compute paths, bandwidth and KV-cache constraints, training/inference consistency, and evaluation methods.
Long-context models need to change attention from “densely score the entire history” to “first decide which positions to look at, then perform high-precision computation only on the selected positions.” The value of this approach is not in a particular model code name. It is in reducing useless matrix multiplications during prefill, moving less invalid key-value cache during decode, and trying not to average away critical evidence. The following sections cover design motivation, computational structure, engineering constraints, and evaluation methods.
1. Where the Problem Comes From
For a sequence of length n, standard self-attention has an n×n score matrix, and both computation and memory grow quadratically with length. During decoding, each step also reads historical keys and values (KV). When context reaches 100K or even 1M tokens, the bottleneck often appears first in bandwidth and cache, not in parameter count.
The goals of sparse attention can be stated in three sentences:
- Routing must be cheap: the cost of deciding “who to look at” must be far below full attention.
- Computation must be precise: the keys and values that actually contribute to the output should remain at original precision, rather than being blended in advance into a vague summary.
- Recall must be stable: evidence may appear in only a very small number of tokens, and the scoring method must not flatten such spikes.
These three goals often conflict. Compression can save cache but loses detail. A pure sliding window preserves local precision but cannot see distant facts. Global low-rank or heavily pooled attention can cover the whole sequence but easily drowns needle-like evidence.
2. A Composable Hierarchy, Not a Single Operator
In engineering practice, a more robust approach is to stack attention with different fields of view in the same layer or adjacent layers, rather than expecting one sparse pattern to cover all dependencies.
Three common tiers can be understood as follows:
- Local sliding window: only looks at the most recent tokens, handling syntax, coreference, and short-range coherence. Computation is proportional to window width.
- Medium-budget selective attention: selects a small number of blocks or tokens from a longer history, handling cross-segment alignment and retrieval-style recall.
- Highly compressed global channel: scans the full sequence with very few summary states, handling topic, document-level constraints, and coarse localization.
There must be a clear information contract between tiers. The local layer does not promise long-range recall. The global layer does not promise literal precision. The selective layer is the main force for being both far-reaching and sharp. If the responsibilities of the three tiers overlap and there is no budget cap, sparsity is only nominal.
3. Two-Stage Routing Based on Grouped-Query Attention
Grouped-query attention (GQA) lets multiple query heads share the same group of keys and values. Sparse routing can follow this structure to reduce the number of decisions: instead of each head making its own “where to look” judgment, each group routes once, and heads within the group reuse the same selected indices.
The reason is straightforward. Queries in the same group face the same set of keys and values, and their relevant positions overlap heavily. If top-k is selected per head, index computation, index gathering, and cache reads are all amplified, while the additional recall is often limited. Deciding per group amounts to acknowledging that routing is coarse-grained set selection, and that differences between heads are left to the second stage of full-precision scoring.
The two stages can be formalized as follows:
- Index stage: dedicated index queries and index keys produce a routing score for each block or token, and top-k is selected.
- Compute stage: only the selected positions use full-precision queries, keys, and values for attention. Softmax and output projection both happen on this subset.
Sharing routing within a group also has an implementation benefit: gathered indices can be broadcast per group, reducing one indirect addressing step in the kernel. The cost is that if an individual head in a group needs very different distant evidence, it is constrained by the same top-k. Common mitigations are to slightly increase k, use different routing in different layers, or keep a lightweight global channel outside the local sliding window, rather than falling back to per-head dense scoring.
4. Why Block Max-Pooling Is Better Than Sum for Needle-Finding
The index branch often does not score all tokens directly. It first looks at blocks. Let the block-level similarity between index queries and index keys be a matrix S0, then aggregate each block to obtain block scores S. The aggregation method changes recall behavior.
- Sum or average: many weakly related tokens in a block can raise or lower the score, diluting the contribution of a single strongly related token.
- Block maximum: as long as one position in the block aligns strongly with the query, the whole block has a chance to enter top-k.
Therefore, block max-pooling is better suited to needle-in-a-haystack settings: short evidence, long noise. Its semantics are “does this block contain at least one position worth precise computation?” rather than “how relevant is this block on average?”
An illustrative computation is shown below. Dimensions and blocking are only for explanation, not a fixed interface of any implementation:
def block_max_pool_scores(q_idx, k_idx, block_size):# q_idx: [G, D], k_idx: [N, D]; G is the number of query groupslogits = q_idx @ k_idx.T # [G, N]n_blocks = logits.shape[-1] // block_sizelogits = logits[..., : n_blocks * block_size]blocked = logits.view(*logits.shape[:-1], n_blocks, block_size)return blocked.max(dim=-1).values # [G, n_blocks]
Block size is a bias-variance tradeoff. If the block is too large, max-pooling may still send irrelevant neighbors into precise computation, reducing the effective information density of top-k. If the block is too small, the number of index keys increases and routing becomes expensive again. In practice, block size should be aligned with KV paging and memory alignment, rather than disrupting cache lines for an algorithmically convenient block length.
After selection, there is a second-level choice: compute over whole blocks or select a few tokens within each block. Whole-block computation is simple and gives contiguous memory access. Token-level filtering saves computation but adds another index lookup and can cause irregular reads and writes in the kernel. For very long sequences with extremely sparse evidence, token-level filtering is often worth it. For medium lengths, whole-block precise computation is often more stable.
5. The Index Path and the Compute Path Must Be Separated
One easily confused design is to use compressed keys for both routing and output. This uses fewer parameters, but routing errors directly contaminate the representation. A clearer split is:
- Index keys and values serve ranking only. They can use lower dimension, independent projections, or even different normalization from the main branch.
- The sparse main branch always reads original (or paged) full-precision keys and values, just fewer entries.
- The two paths do not share parameters under a “shortcut assumption”: the index path learns separability, and the main branch learns weighted aggregation.
Compared with “first compress m tokens into a weighted average, then attend to the average vector,” selection-based sparsity has a structural difference: the attended entry is still the original vector, and information loss mainly comes from “not being selected,” not from “being flattened after selection.” Missed selection can be compensated by larger k, multi-layer complementarity, or a global channel. Spikes that have been averaged away are very hard to recover in later layers.
This also means evaluation cannot rely only on average loss. A compressed global channel may perform well on topic classification but be systematically weak on tasks that require quoting original sentences, numbers, or negation. The failure mode of selection-based design is recall miss: the relevant block score is not high enough to enter top-k, and later full-precision computation cannot see it even if it is strong.
6. Complexity and Caching: Look at Bandwidth, Not Just Multiply-Adds
Let G be the number of groups, N the sequence length, B the block size, K the number of blocks retained per group, and d the head dimension. The index stage is roughly grouped dot products over N index keys followed by block aggregation, on the order of O(G · N · d_idx). The precise stage is approximately O(G · H_g · K · B · d), where H_g is the number of heads per group. When K·B is much smaller than N, precise computation decreases relative to full attention. If the index dimension is not reduced, the index may still dominate prefill.
Therefore, index key dimension, whether quantization is used, and whether sparsity is enabled only in some layers are first-class design parameters. Common tradeoffs:
- Enable sparse long-range attention only in middle and later layers, and use sliding windows in early layers because shallow layers rely more on local patterns.
- Use lower-dimensional index keys while keeping main-branch keys at full dimension.
- During decoding, cache full-precision paged KV plus a lightweight index KV. At each step, update the index only for new tokens and compare historical block scores incrementally instead of recomputing the entire history.
Prefill and decode have different bottlenecks. Prefill involves large-batch matrix multiplication. Sparse gains come from skipping whole blocks of computation, but gathering indices lowers arithmetic intensity. If the kernel is poorly written, the speedup can be lost to memory access. Decode is latency-sensitive KV-cache reading. Gains come from reading less KV. Even if the operator appears faster from the user side, severe paging fragmentation can still keep tokens/s from improving. The optimization order should be: first ensure contiguous KV paging, then discuss top-k kernel fusion.
7. Training and Inference Need the Same Selection Semantics
If training uses dense attention or a larger k, and inference suddenly switches to a much smaller k, the distribution will shift. Possible strategies include:
- Train sparse from the start, using a curriculum that decreases k from large to small, to avoid highly noisy gradients caused by random routing at the beginning.
- Use straight-through estimation or a differentiable approximation for top-k on routing scores, so index parameters receive signal from the final loss rather than only from an auxiliary loss.
- Treat auxiliary losses only as stabilizers: for example, encourage score discrimination or penalize all block scores collapsing together. They cannot replace the main task, or the model will learn “routing looks sparse” while generation quality drops.
Masks also require care. If block max-pooling applies pooling before the causal mask, future tokens may raise the whole block score. The correct order is: first mask illegal positions according to causality, then take the maximum over visible positions. The same applies to variable-length sequences and padding: padding must not participate in the max.
8. How to Evaluate Without Being Misled by Averages
At least four behavior categories should be examined separately, and unreproduced speedup multiples should not be used in place of experiments:
- Local language modeling: is the sliding window sufficient, and does sparsity harm nearby tokens?
- Long-range fact recall: place single-point evidence at different depths and different block alignments, and observe the miss rate rather than only whether generation is “roughly relevant.”
- Multi-evidence composition: the answer depends on two or more distant facts; test whether the top-k budget can remember only one.
- Distractor robustness: insert many topically similar but incorrect passages, and see whether max-pooling puts similar blocks into the budget in bulk and pushes out true evidence.
When reporting results, include k, block size, the layer indices where sparsity is enabled, index dimension, and the time breakdown of prefill and decode separately (computation, gathering, KV reads). End-to-end speedup alone cannot show whether the gain comes from the algorithm, batch size, quantization, or cache layout.
When comparing “selection” and “compression,” use the same budget for a fairer comparison: for example, allow only M floating-point key-values to be read, with M original vectors on one side and fewer compressed vectors on the other, each summarizing more tokens. If compressed vectors save space, the saved capacity should be converted into the comparison; otherwise, one structure may be overestimated.
9. Deployment Checklist
- Route once per query group to avoid repeated gathering per head.
- Take the maximum after the causal mask and exclude padding.
- Use separate caches and precisions for index KV and main KV; the main path must not read averaged replacement vectors.
- Account separately for the budgets of top-k, sliding window, and global summary, to prevent the three paths from combining into something still close to dense.
- Keep k, block size, and layer configuration consistent between training and inference, or perform explicit calibration.
- Favor contiguous paged reads in kernels, keep index tensor lifetimes short, and avoid repeated host-device synchronization during each decode step.
Once these constraints are met, sparse attention becomes a maintainable system component: it uses a limited budget to gain long-range visibility and preserves fine-grained evidence by “selecting original vectors” rather than “mixing first and recalling later.” The actual speedup depends on sequence length, batch size, bandwidth, and kernel. It must be remeasured on the target hardware using the breakdown above, not extrapolated directly from an architecture sketch.
