Efficient and Sparse Attention at Scale
local graph
Chapter 14 — Efficient and Sparse Attention at Scale
Section titled “Chapter 14 — Efficient and Sparse Attention at Scale”Attention has one stubborn weakness: every token attends to every other, so its cost grows with the square of the sequence length. At a few thousand tokens this is tolerable; at hundreds of thousands it dominates everything. The previous chapters shrank the cost of storing attention (MLA); this chapter shrinks the cost of computing it. We cover the two complementary approaches: making exact attention dramatically more efficient (FlashAttention), and abandoning exactness to attend to only the most relevant tokens (sparse attention, including DeepSeek’s latest work). Together they are what make million-token contexts practical.
14.1 The Quadratic Problem
Section titled “14.1 The Quadratic Problem”For a sequence of length T and model dimension d, the attention score matrix is T × T, and computing it costs on the order of T²d operations and, naively, T² memory to hold the scores. Double the context and the work quadruples. This is why early models capped context at 1K or 2K tokens, and why every long-context model relies on one or both of the techniques below. Table 14.1 frames the options by how their cost scales.
| Variant | Compute | Idea | Used by |
|---|---|---|---|
| Dense (exact) | O(T²d) | attend to everything | the standard |
| FlashAttention | O(T²d) | same result, IO-aware (no T×T in memory) | nearly all modern models |
| Sliding window | O(Twd) | attend to a local window of width w | Mistral, Gemma (some layers) |
| Sparse top-k | O(Tkd) | attend to k selected tokens | DeepSeek-V3.2 (DSA) |
| Linear / state-space | O(Td²) | recurrent summary, no pairwise scores | Qwen3.5 (hybrid) |
Table 14.1 — Attention variants by cost
14.2 FlashAttention: Exact but IO-Aware
Section titled “14.2 FlashAttention: Exact but IO-Aware”FlashAttention’s insight is that standard attention is memory-bound, not compute-bound (Chapter 2): the bottleneck is writing the giant T × T score matrix to high-bandwidth memory and reading it back for the softmax. FlashAttention never materializes that matrix. It processes the keys and values in blocks that fit in fast on-chip SRAM, and maintains a running softmax — tracking the running maximum and sum so it can rescale partial results as each block arrives. The output is bit-for-bit the same as standard attention, but memory traffic drops from quadratic to linear and the kernel runs several times faster. The algorithm in pseudocode:
for each query block Q_i: m, l, acc = -inf, 0, 0 # running max, sum, output for each key/value block (K_j, V_j): # streamed from HBM once S = Q_i @ K_j.T / sqrt(d) # block scores, stay in SRAM m_new = max(m, rowmax(S)) p = exp(S - m_new) # shifted for numerical safety l = l * exp(m - m_new) + rowsum(p) # rescale running sum acc = acc * exp(m - m_new) + p @ V_j # rescale running output m = m_new out_i = acc / l # final normalized resultPseudocode — FlashAttention: tiled attention with an online softmax
This is what F.scaled_dot_product_attention — used throughout Parts III and IV — calls under the hood, and it is the single most important systems advance behind long-context transformers. You will almost never implement it by hand, but understanding that it trades memory traffic for a clever running computation explains why it is fast and why it is exact.
14.3 Sparse Attention: Attending to Less
Section titled “14.3 Sparse Attention: Attending to Less”FlashAttention makes exact attention efficient but cannot escape the quadratic operation count. To break that, the model must attend to fewer tokens. The observation that licenses this: in long contexts, most attention weight concentrates on a small subset of tokens — most pairs simply do not matter. Sparse attention exploits that by selecting, for each query, only the tokens worth attending to.
DeepSeek-V3.2 introduces DeepSeek Sparse Attention (DSA), a clean realization of this idea. A lightweight “lightning indexer” computes cheap relevance scores between a query and the past tokens, the top-k most relevant are selected, and full attention is computed only over those. The cost falls from O(T²) to roughly O(Tk) with k fixed, so doubling the context no longer quadruples the work — while quality stays close to dense attention because the discarded tokens carried little weight anyway. This is the current frontier of making long context not merely possible but cheap, and it pairs naturally with MLA: MLA shrinks what is stored, DSA shrinks what is computed.
Dense: attend to all past Sparse (DSA): attend to top-k
query ■ ■ ■ ■ ■ ■ ■ ■ query ■ □ ■ □ □ ■ □ □
cost grows with context length (all cells) indexer keeps only the k relevant (shaded)
A cheap "lightning indexer" scores past tokens; only the top-k are attended to, turning O(T²) attention into roughly O(T·k) at long context.Figure 14.1. Dense versus sparse attention. Dense attention scores the query against every past token; DeepSeek Sparse Attention uses a lightweight indexer to keep only the most relevant k, making cost grow linearly rather than quadratically with context length.
14.4 The Long-Context Frontier
Section titled “14.4 The Long-Context Frontier”Sparse selection is one of several active directions, and 2025–2026 models mix them freely. Sliding-window attention (Mistral, parts of Gemma) restricts most layers to a local window and relies on depth to propagate information globally. Linear and state-space methods replace pairwise attention with a recurrent summary of fixed size; Qwen3.5’s hybrid design interleaves a Gated-DeltaNet-style linear mechanism with sparse full attention to get long-context efficiency without losing the precision of exact attention where it matters. DeepSeek-V4 continues this trend with a hybrid compressed-attention design aimed at roughly million-token contexts. The common thread is that the field no longer treats attention as a single fixed operation: models now combine cheap, approximate mixing for the bulk of the sequence with exact attention where precision is needed.
| Model | Long-context mechanism |
|---|---|
| Llama 4 Scout | chunked attention + position tricks (NoPE on some layers), 10M context |
| DeepSeek-V3.2 | DeepSeek Sparse Attention (indexer + top-k) |
| DeepSeek-V4 | hybrid compressed attention, ~1M context |
| Qwen3.5 | Gated-DeltaNet (linear) + sparse attention, hybrid |
| Mistral / Gemma | sliding-window (local) attention on most layers |
Table 14.2 — Long-context approaches in recent models
Code reference — Dao-AILab/flash-attention · deepseek-ai/DeepSeek-V3.2 (DSA) · deepseek-ai/FlashMLA · deepseek-ai/DeepSeek-V4 (report)
flash-attention is the reference IO-aware kernel; DeepSeek-V3.2’s modeling code implements the sparse indexer and selection; FlashMLA’s newer kernels support the sparse and long-context decode paths; and the DeepSeek-V4 report describes its hybrid compressed attention. Reading the DSA implementation against the dense attention of Chapter 7 is the clearest way to see what “sparse” changes and what it leaves alone.
The architecture is now, conceptually, complete: capacity (MoE), cheap memory (MLA), a dense training signal (MTP), and efficient long-context attention (this chapter). What remains is to revisit the smaller components we have treated as fixed — normalization, activations, and position — to see how the families differ in their details, and then to assemble the whole into a single model and trace it end to end. That is the work of the next two chapters, which close Part IV.
14.5 Worked Example: The Indexer’s Top-k Selection
Section titled “14.5 Worked Example: The Indexer’s Top-k Selection”Sparse attention rests on a bet: most of a query’s attention mass lands on a small fraction of past tokens, so if you can predict which ones cheaply, you can skip the rest. DeepSeek Sparse Attention (Section 14.3) makes the bet pay off with a lightweight indexer that scores every key with a small projection, then runs full attention over only the top-k it selects:
# 1. lightweight indexer scores all keys (small projections)index_scores = q_idx @ k_idx.transpose(-2, -1) # cheap, all T keys
# 2. keep only the k most relevant keys per querytopk = index_scores.topk(k=2048, dim=-1).indices
# 3. run full attention over those k keys, not all Tout = attention(q, k[topk], v[topk])Python — sparse/indexer.py: cheap scoring, then top-k (illustrative)
The economics are compelling at long context. The indexer touches every key but with tiny per-key cost; the expensive full-precision attention then runs over a fixed budget of, say, 2,048 keys regardless of whether the sequence is 10,000 tokens or 1,000,000. Attention’s quadratic term (Section 7.5) is thus capped: the model attends to a constant number of carefully chosen tokens rather than all of them. The risk — that the indexer’s cheap scores miss a key the full attention would have valued — is what the indexer is trained to avoid, and managing it is exactly the refinement that IndexShare (Section 44.7) optimizes further.
Predict what matters, then attend only there Sparse attention replaces “attend to everything” with “cheaply guess the few keys that matter, then attend fully to those.” It caps the quadratic cost at a fixed token budget — the key to attention at million-token context.
14.6 Sparse Attention Patterns: Sliding Window and Global Tokens
Section titled “14.6 Sparse Attention Patterns: Sliding Window and Global Tokens”Before learned indexers (Section 14.5), sparse attention was built from fixed patterns — hand-designed rules for which tokens may attend to which — and these remain instructive and, in some models, still in use. Two primitives compose into most of them. A sliding window lets each token attend only to the last W tokens, capturing local context at a cost that grows linearly with sequence length rather than quadratically. Global tokens are a handful of special positions that attend to, and are attended by, everything — carrying long-range summary information past the local windows.
The two combine naturally: most tokens see only their local window, while a few global tokens act as a shared channel that lets information jump across the whole sequence. This local-plus-global pattern approximates full attention at a fraction of the cost, on the bet that most of what a token needs is nearby and the rest can route through the global tokens. Its limitation is rigidity — the pattern is fixed in advance, blind to which distant tokens actually matter for a given input. That is precisely the limitation the learned indexer of DeepSeek Sparse Attention removes (Section 14.5): rather than a fixed window, it predicts the relevant tokens per query. Fixed patterns are the conceptual ancestor of learned sparsity, and understanding them clarifies what the learned version improves upon.
Local windows plus a few global tokens Fixed sparse attention assumes most context is nearby (a sliding window) with a few global tokens carrying long-range information. It is cheap and rigid; learned indexers (DSA) keep the cost while replacing the fixed pattern with a per-query prediction of what matters.
14.7 The Long-Context Problem, Assembled
Section titled “14.7 The Long-Context Problem, Assembled”Long context — a hundred thousand tokens or more — is not one problem with one solution but three distinct obstacles, each met by a different technique from this book. Seeing them together shows how the architecture’s pieces interlock to make million-token context practical.
The first obstacle is compute: attention is quadratic in sequence length (Section 7.5), so naively, doubling the context quadruples the attention cost. Sparse attention (this chapter) is the answer, attending only to a selected subset of tokens and turning the quadratic into something far cheaper. The second is memory: the KV cache grows linearly with length and comes to dominate (Section 12.9), which is met by MLA’s compression (Chapter 12) and, on top of it, cache quantization (Section 27.10). The third is position: the model must address positions far beyond those it trained on, which RoPE extension handles (Section 9.6). No single one of these suffices — a model with cheap attention but an exploding cache, or a manageable cache but no positional generalization, still cannot handle long context. It is the combination — sparse attention for compute, latent compression and quantization for memory, RoPE extension for position — that together makes long context real. This is the clearest illustration in the architecture chapters of a theme the whole book returns to: a frontier capability is rarely one idea, but several complementary techniques, each handling a different facet of the same hard problem, composed into a system that works where no single piece would.
Three obstacles, three techniques, one capability Long context demands cheap attention (sparse), a small cache (MLA plus quantization), and position generalization (RoPE extension) all at once. No one of them suffices; their combination is what makes million-token context practical — capability from composition.