Sparse Attention: Filter Candidates First, Then Compute Precisely
Long-context workloads make standard self-attention the first bottleneck, since cost and memory grow with the square of sequence length. This article explains how sparse attention changes the computation graph rather than just trimming work: a cheap indexing stage scores query-key pairs, and an expensive fine-grained stage runs full similarity, normalization, and weighted aggregation only on the top-k candidates. It covers the two-stage design, block versus token-level selection, the real complexity and memory tradeoffs (including why a full pairwise index can keep the quadratic term alive), the three sources of approximation error, and practical guidance on choosing k, cache handling, precision, and distributed communication. It closes with when sparse attention is a fit and how to validate it with length buckets, probe recall, and index-time overhead.
Long context is now a routine requirement in dialogue, code completion, retrieval augmentation, and log analysis. Standard self-attention relates each query to every key in a sequence of length L, so both time and memory grow with L squared. As sequences expand from tens of thousands of tokens into the hundreds of thousands, the attention matrix itself often becomes the bottleneck before the feed-forward network does: compute goes up, but so do intermediate activations, communication volume, and cache hit behavior.
The point of sparse attention is not “compute a little less.” It changes the computation graph: first decide which past tokens are worth looking at, then restrict the expensive similarity and weighted aggregation to a small set. The common industry phrasing is “filter first, compute later.” The filter must be cheap enough that the savings on main attention are not eaten by indexing overhead, and accurate enough that the model does not degrade silently on long-range dependencies.
Why quadratic complexity is hard to avoid
For each query, standard attention does three things: compute similarity against all keys, normalize along the sequence dimension, and take a weighted sum over values. With H heads and head dimension d, the rough per-layer cost is O(L²·H·d). The quadratic term dominates as L grows. During inference the key-value cache stores past keys and values, but every new token still scans the existing cache, and the prefill phase faces the entire context at once.
Lowering precision, fusing operators, or increasing batch size does not change the structure in which every query looks at every key. Getting an order-of-magnitude improvement requires reducing the number of keys each query actually touches, or changing which queries need full computation. Sparse attention takes the first route: each query keeps roughly k keys, so main attention becomes O(L·k·H·d). When k is far smaller than L, arithmetic scales down by k/L. With k=2048 and L=131072 the ratio is about 1/64, leaving roughly 1.6% of the original multiply-accumulate count, or about a 98% reduction relative to full attention. This is a formula-level estimate, not an end-to-end speedup. Index scoring, sorting, irregular memory access, and communication all consume part of the gain, and on short sequences where k approaches L it can even be slower.
The two-stage structure
Practical designs split into indexing and fine-grained computation.
The indexing stage scores query-key pairs with a low-dimensional, low-cost representation. Common approaches project queries and keys into a space much smaller than d, or estimate relevance using only a few heads and a few sampled positions, producing a coarse score of length L. Its job is ranking and recall, not the final information mixing, so approximation is allowed, but systematically missing key evidence is not.
The fine-grained stage selects the top-k tokens or those above a threshold by coarse score, then computes full similarity, normalization, and weighted sum only on the candidates. Selection can be done independently per head or shared across layers; it can produce one candidate set per query or share one within a window to improve memory access. Causal settings must mask future positions and always retain the current token or a local window, otherwise generation loses nearby context.
“Fine-grained” means selection happens at token or even head granularity, not that whole segments are dropped. Document boundaries, function definitions, numbers in tables, and referents in dialogue often make up a tiny fraction of the sequence, but once missed, later layers can hardly recover them. Block-level sparsity is simple to implement and memory-access friendly, yet it easily mixes irrelevant tokens inside a block and cuts key sentences at block boundaries. Token-level selection has better recall at the cost of more irregular indexing. The common engineering compromise is to estimate hotness at block level first, then filter at token level inside hot blocks.
Complexity, memory, and the real bottleneck
Let the index feature dimension be d’, with d’ far smaller than d. Indexing costs about O(L²·d’), or less than full pairwise after sampling or local windows; fine-grained attention costs about O(L·k·d). Whether total cost drops depends on d’/d and k/L. Compressing main attention while doing a full pairwise index at comparable cost still leaves the quadratic term dominant on long sequences. The index must therefore be narrower, reusable, or combined with local windows and hierarchical summaries.
Memory matters just as much. If full attention materializes the score matrix, peak memory grows with L². The sparse path should avoid writing out the complete L×L scores and keep only top-k indices and their scores. During inference the key-value cache still holds historical state; sparsification reduces reads and computation, it does not mean the cache must be dropped, and discarding key-values too early makes later queries unable to recall them. Prefill and decode have different bottlenecks: prefill is throughput- and parallelism-bound, decode is bound by single-step latency and cache bandwidth. The same k is not necessarily optimal for both.
Irregular top-k selection hurts coalesced memory access and tensor-core utilization. Implementations should align candidates to blocks, cap the number of non-zeros per row, pad very short rows, and share index results across the heads of the same layer as much as possible in exchange for predictable memory access.
Where the error comes from
Sparse attention is an approximation, and the error falls into three categories.
Recall error: tokens that truly carry high weight never enter the candidate set. In multi-head models, different heads attend to positions, syntax, or rare entities, and ranking everything with a single coarse score hurts some heads. Mitigations include per-head selection, forcing retention of a sliding window and global special tokens, and increasing k for uncertain queries.
Normalization error: normalizing over a subset changes the distribution. In full attention, many near-zero scores still contribute to the denominator; subset normalization amplifies candidate weights. If the candidate distribution differs between training and inference, logits drift. Use the same selection rule in training as in inference, or apply a learnable decay to unselected positions, rather than training with full attention and truncating abruptly at serving time.
Selection is not differentiable: hard top-k indexing is discontinuous with respect to the input. In practice, straight-through estimators, computing the loss over candidates, or warming up with soft sparsity before switching to hard selection are used. The indexer and the backbone should be trained jointly; otherwise the scorer optimizes surface similarity rather than the downstream loss.
Quality regressions typically show up as near-lossless short context but worse factoid QA, cross-file references, and multi-hop constraints on long context. Evaluation should not look only at average loss: build a dedicated probe set where the answer exists in only a few distant tokens, and report recall, perplexity deltas, and task scores across different L and k.
Training and inference practice
k is the knob between quality and cost. Too small misses evidence; too large loses the sparsity benefit. A safer approach is to set k in bands by sequence length, or let k vary by layer: lower layers lean local, higher layers handle long-range aggregation and can afford a larger candidate set. Sliding window, global tokens, and sparse recall can be stacked, with the window covering local syntax and the sparse branch covering distant facts.
Cache policy must be defined explicitly. Computed key-values stay in the cache; at each step, run indexing only for the new query and score it against the low-dimensional index features of historical keys. Index features can be smaller than the full keys and are suitable for storage separate from the key-value cache. During batching, effective k and lengths differ across samples, so bucketing is needed to avoid heavy padding.
Numerically, subset attention has a narrower dynamic range, so low precision overflows or underflows more easily. Low precision for indexing is usually acceptable; fine-grained weighting should keep precision close to full attention, and normalization stability should be checked on long sequences.
In distributed training, if sequence parallelism still communicates as if fully connected, the compute savings from sparsification get eaten by communication volume. Index results should determine which key-value segments need to be exchanged rather than synchronizing the entire cache every step. This adds scheduling complexity and is best enabled after sequence length crosses a measured inflection point.
When to adopt it, and how to validate
Good fit: context far larger than k, sparse relevant information, and one set of weights that must serve both short QA and long documents. Poor fit: dense sequences where nearly every position is strongly relevant, very short inputs, and tasks with hard worst-case recall constraints where k cannot be increased.
Before launch, fix a set of length buckets and compare full attention against the sparse path on loss delta, probe recall, time to first token, and cost per token, and record the share of time spent in indexing. If arithmetic drops clearly but there is no end-to-end gain, check memory-access alignment and whether indexing is still quadratic. If speed improves but long-context tasks regress, check the forced local and global tokens, per-head selection, and whether training and inference use the same selection policy.
Sparse attention replaces “look at all history” with “recall cheaply first, aggregate precisely after.” It can substantially cut both the multiply-accumulate count of main attention and the memory for the score matrix when k is far smaller than L, but the benefit depends on whether indexing is genuinely cheaper, whether selection covers the key tokens, and whether training and inference agree. Treat k, the retention window, and evaluation probes as first-class configuration rather than post-launch patches, and you can hold both cost and quality in long context.
