Chapter 2 · Attention Variants and Efficient Attention¶
2.1 What are the differences among MHA, MQA and GQA? ★★¶
One-sentence answer
The three differ in how many query heads share one set of K/V heads: in MHA every query head has its own K/V, in MQA all query heads share a single K/V, and GQA splits the query heads into groups that share K/V within each group. The motivation is that every decode step must read the entire KV cache, so a smaller KV cache means less pressure on memory bandwidth and room for larger batches and longer contexts; GQA buys a several-fold reduction in KV cache at a very small cost in quality, which is why it is the mainstream choice today.
I will address three aspects: why we want fewer K/V heads, how each of the three works, and the trade-off in quality.
(1) Motivation: the bottleneck at decode time is the memory bandwidth spent reading the KV cache, and the size of the KV cache is proportional to the number of K/V heads.
During autoregressive generation, each step computes a query only for the new token, yet it must attend to the keys and values of all previous tokens; to avoid recomputing them, these K and V are cached, which is the KV cache (its mechanics and memory management are covered in Chapter 1 of the "Inference, Evaluation & Deployment" direction). Each token caches \(2 \times n_{kv} \times d_h\) numbers per layer, where \(n_{kv}\) is the number of K/V heads, \(d_h\) is the dimension of each head, and the 2 stands for one copy each of K and V. Each decode step does very little computation but must read the entire KV cache from GPU memory (HBM), so this phase is limited by memory bandwidth rather than compute. It follows that the larger the KV cache, the slower each step; and the more memory it occupies, the fewer requests can be served at once and the shorter the context that fits. In MHA, \(n_{kv}\) equals the number of query heads \(h\); the idea of MQA and GQA is to reduce \(n_{kv}\) while keeping the number of query heads unchanged.
(2) Mechanism: the three are the same design with different degrees of sharing.
- MHA (multi-head attention): every query head has its own K and V projections, so \(n_{kv}=h\). It is the most expressive and has the largest KV cache.
- MQA (multi-query attention, Shazeer 2019): all query heads share one K and one V, so \(n_{kv}=1\) and the KV cache shrinks to \(1/h\) of MHA's. For example, with 32 query heads the KV cache is only 1/32 of the original.
- GQA (grouped-query attention, Ainslie et al. 2023): the \(h\) query heads are split into \(g\) groups, and each group shares one K/V, so \(n_{kv}=g\). With \(g=h\) it is MHA, and with \(g=1\) it is MQA. For example, with 32 query heads and 8 KV heads, every 4 query heads share one K/V, and the KV cache is only 1/4 of MHA's.
(3) Trade-off: MQA compresses the most but loses quality, while GQA keeps most of the benefit at a small cost and can be converted from MHA.
The cost of sharing K/V is that the heads are forced to attend over the same keys and values and can only differ in how they score, so the diversity of information they extract drops. MQA pushes this sharing to the extreme, so its quality drop is more noticeable and training can be less stable. The GQA paper found that with around 8 KV heads, quality is already very close to MHA while inference speed is close to MQA; this is why Llama 2 70B, Llama 3, Mistral 7B, Qwen and others adopt GQA. In addition, an already-trained MHA model can be converted to GQA: the original K/V projection matrices within each group are averaged to initialize the shared projection, and training then continues with about 5% of the original pretraining compute (called uptraining), which recovers most of the quality.
In summary: the three differ only in how much the K/V heads are shared; GQA trades an almost negligible loss in quality for a several-fold reduction in KV cache and faster decoding, which is why it has become the default choice.
Comparing the three:
| MHA | GQA | MQA | |
|---|---|---|---|
| Number of K/V heads | \(h\) | \(g\) (\(1<g<h\)) | 1 |
| Numbers cached per token per layer | \(2hd_h\) | \(2gd_h\) | \(2d_h\) |
| KV cache relative to MHA | 1 | \(g/h\) | \(1/h\) |
| Quality | Baseline | Close to MHA | Some degradation |
| Example models | GPT-3, Llama 2 7B | Llama 3, Mistral 7B, Qwen | PaLM, Falcon-7B |
Going deeper: a worked example, why the benefit appears only at decode time, and details of uptraining
(1) Example: the KV cache of Llama 3 8B.
Llama 3 8B has 32 layers, 32 query heads and 8 KV heads of 128 dimensions each, stored in bf16 (2 bytes per number). The KV cache per token is \(2 \times 32 \times 8 \times 128 \times 2\) bytes, i.e. 128 KB, so one sequence of 8K tokens needs about 1 GB; with MHA (32 KV heads) it would need about 4 GB.
(2) GQA reduces memory traffic, not the compute of attention.
The compute of \(QK^\top\) and of the multiplication by \(V\) is determined by the number of query heads, which GQA does not change; what it reduces is only the parameters of the K/V projections and the K/V that must be cached and read. In training and prefill, many tokens are processed in parallel and the bottleneck is compute, while the K/V projections are a small share of total compute, so GQA gives them almost no speedup. Decode, by contrast, is limited by memory bandwidth: every K/V head that is loaded is used by \(h/g\) query heads, so the compute per byte (the arithmetic intensity) rises by a factor of \(h/g\), and the bytes read per step fall to \(g/h\) of the original.
(3) Details of uptraining.
On T5-XXL, the GQA paper compared several ways to initialize one K/V head from several, and found that averaging (mean pooling) works better than keeping just one of the heads or initializing randomly. Starting from this, continued training with about 5% of the original pretraining compute brings the GQA model's quality close to that of the original MHA model.
Follow-up questions
Follow-up 1: Does GQA speed up training?
Not much. During training many tokens are processed in parallel, so the bottleneck is compute rather than memory reads; and GQA does not reduce the scoring or the weighted sum in attention, only the K/V projections, which are a small share of compute. GQA's benefit lies mainly in the decode phase of inference, and in the larger batches and longer contexts that a smaller KV cache allows.
Follow-up 2: Why is the number of KV heads often 8?
Partly empirical quality, partly an engineering consideration from tensor parallelism. The GQA paper shows that 8 groups of K/V already keep enough diversity for quality close to MHA. On the engineering side, inference for large models often uses tensor parallelism within one 8-GPU machine, splitting attention across GPUs by head; if there are fewer KV heads than GPUs in the tensor-parallel group, the same KV head must be stored on several GPUs, wasting memory. With 8 KV heads, each GPU gets exactly one.
Follow-up 3: Can an already-trained MHA model be converted to GQA without any training?
The heads can be merged directly, but quality drops noticeably, so uptraining is needed. Once the K/V projections within a group are averaged, the different keys and values the heads had learned are forcibly merged, and the model needs to readapt. The GQA paper continues training with about 5% of the original pretraining compute, recovering most of the quality at low cost.
Common mistakes
- Do not say that GQA reduces the number of query heads: The number of query heads is unchanged; only the K/V heads are reduced.
- Do not say that MQA and GQA reduce the compute of attention: The compute of scoring and the weighted sum is determined by the number of query heads and is essentially unchanged; the gains come from memory traffic and memory capacity.
- Do not say that a smaller KV cache only saves memory: Every decode step reads the entire KV cache, so its size directly determines the latency per generated token and the achievable batch size.
- Do not say that GQA also speeds up training significantly: Training is compute-bound; GQA's benefit is mainly at inference.
2.2 How does MLA compress the KV cache? ★★¶
One-sentence answer
MLA (multi-head latent attention, introduced in DeepSeek-V2) does not make heads share K/V; instead it jointly compresses each token's K and V into one low-dimensional latent vector and caches only that vector. At inference, using the associativity of matrix multiplication, the up-projection matrices of K and V are absorbed into the query projection and the output projection respectively, so attention is computed directly on the latent without decompression. Its KV cache is thus of the same order as MQA's, while its expressiveness is close to or even better than MHA's.
I will address three aspects: what MLA caches, why no decompression is needed at inference, and its gains and costs compared with GQA.
(1) MLA jointly compresses K and V into one low-dimensional latent vector and caches only that vector.
Here \(h_t\) is the hidden state of the \(t\)-th token, \(W^{DKV}\) is the down-projection matrix, and \(c_t\) is the compressed latent vector, whose dimension \(d_c\) is much smaller than the total K and V dimension \(2hd_h\) in MHA; \(W^{UK}_i\) and \(W^{UV}_i\) are the up-projection matrices of head \(i\), and \(k_t^{(i)}\) and \(v_t^{(i)}\) are that head's key and value. GQA makes several heads use the very same K/V, so all heads in a group see identical keys; MLA instead lets all heads share one compressed "raw material" \(c_t\), from which each head reconstructs its own, different key and value with its own up-projection. MLA is therefore essentially a low-rank factorization of K/V: the keys and values of different heads remain different, but they all live in the same \(d_c\)-dimensional subspace.
(2) At inference, the up-projections can be absorbed into the query and output projections, so attention runs directly on the latent without decompression.
If every step had to decompress the cached \(c\) into the K and V of all heads, it would add a great deal of compute and intermediate memory, defeating the purpose of compression. The key to MLA is the associativity of matrix multiplication: the score of head \(i\) is \(q_t^{(i)\top} k_s^{(i)} = q_t^{(i)\top} W^{UK}_i c_s = \big(W^{UK\top}_i q_t^{(i)}\big)^\top c_s\), so the query can first be mapped into the latent space and then dotted directly with the cached \(c_s\); since \(W^{UK}_i\) is a fixed parameter, it can be merged into the query projection ahead of time. Likewise, the weighted sum of values is \(\sum_s a_{ts} W^{UV}_i c_s = W^{UV}_i \sum_s a_{ts} c_s\), where \(a_{ts}\) is the attention weight, so the weighted sum can be taken over the latents first and \(W^{UV}_i\) merged into the output projection \(W_O\). At decode time, all heads therefore attend over the same latent cache, which has the same form as MQA (each head has its own query, and all share one set of keys and values), only with larger shared keys and values. (The RoPE rotation sits between the query and \(W^{UK}\) and breaks this absorption, so DeepSeek additionally uses a small separate key that carries RoPE, called decoupled RoPE.)
(3) Gains and costs: a KV cache of the same order as MQA's and quality no worse than MHA's, at the price of a more complex structure and implementation.
- A very small KV cache: DeepSeek-V2 caches only 576 numbers per token per layer (a 512-dimensional latent plus a 64-dimensional RoPE key), whereas MHA with the same 128 heads of 128 dimensions caches 32,768 numbers, so MLA needs about 1/57 as much.
- More expressive than GQA at the same cache size: under the same KV cache budget, GQA can offer only a few sets of K/V shared by several heads each, while MLA gives every head its own K/V. DeepSeek-V2 reports that MLA is no worse than, and even better than, MHA; TransMLA (Meng et al. 2025) also shows theoretically that at the same KV cache size GQA can always be written as MLA, but not the other way round.
- A more complex implementation: it needs two forms of computation (decompress and compute as ordinary MHA during training and prefill, use the absorbed form during decode), extra handling for compatibility with RoPE, and specially optimized kernels.
In summary: the core of MLA is caching a low-dimensional latent instead of the full K/V, and avoiding decompression through matrix absorption, trading a more complex implementation for a cache size close to MQA's and expressiveness close to MHA's.
Comparing three ways of handling the KV cache:
| MHA | GQA | MLA | |
|---|---|---|---|
| What is cached | K and V of every head | K and V shared by each group | One low-dimensional latent vector plus a small RoPE key |
| Numbers cached per token per layer | \(2hd_h\) | \(2gd_h\) | \(d_c + d_h^R\) |
| Do heads have different K/V? | All different | Identical within a group | All different, but in one low-dimensional subspace |
| Example models | Llama 2 7B | Llama 3, Qwen3 | DeepSeek-V2/V3, Kimi K2 |
Going deeper: the DeepSeek-V2 configuration and the two forms of computation
(1) DeepSeek-V2's configuration and reported gains.
DeepSeek-V2 (DeepSeek-AI 2024) has 128 heads of 128 dimensions each; the latent dimension is \(d_c = 512\) (i.e. \(4d_h\)), and the separate RoPE-carrying key has dimension \(d_h^R = 64\). Each token caches \(d_c + d_h^R = 576\) numbers per layer, i.e. \(4.5\,d_h\), equivalent to GQA with only 2.25 groups. The paper reports that, compared with DeepSeek 67B, the KV cache is 93.3% smaller and maximum generation throughput rises to 5.76 times. The query is also low-rank compressed (latent dimension 1536), but this only reduces activation memory during training and has nothing to do with the KV cache. DeepSeek-V3 keeps the same MLA configuration.
(2) Training and prefill use the decompressed form; decode uses the absorbed form.
| Decompressed form | Absorbed form | |
|---|---|---|
| How it works | Up-project the latent into per-head K and V, then compute as ordinary MHA | Merge the up-projections into the query and output projections, then compute directly on the latent |
| Scoring dimension per head | \(128 + 64 = 192\) | \(512 + 64 = 576\) |
| Phase | Training and prefill: many queries in parallel, compute-bound | Decode: one query per step, bandwidth-bound |
| Property | Lower total compute | Reads only the latent cache; every number loaded is used by all 128 heads |
During training and prefill there are many queries, and the absorbed form would raise each head's dot-product dimension from 192 to 576, costing more compute, so decompressing first is cheaper. At decode time the situation reverses: the bottleneck is reading the cache, and although the absorbed form adds compute, it reads only the 576-dimensional latent, which all 128 heads share, so the arithmetic intensity is high and the otherwise idle compute of the decode phase is put to use.
Follow-up questions
Follow-up 1: Both MLA and GQA compress the KV cache. What is the essential difference?
GQA uses "hard sharing", while MLA uses "low-rank sharing". GQA makes the heads in a group use exactly the same K and V, compressing by reducing the number of distinct K/V; MLA has all heads share one low-dimensional latent, but each head obtains a different K and V through its own up-projection, compressing by restricting the subspace the K/V live in. At the same cache size MLA is therefore more expressive, at the cost of matrix absorption and specialized kernels.
Follow-up 2: MLA actually does more compute at decode time. Why is it still faster?
Because decode is limited by memory bandwidth, not compute. Each decode step has only one new token, so most of the GPU's compute sits idle and the time goes mainly into reading the cache from HBM. MLA reads far less data than MHA or GQA, and its extra compute simply uses up the idle capacity, so it is faster overall.
Follow-up 3: Can existing GQA models be converted to MLA?
Yes; existing work does it through a conversion plus a small amount of continued training. TransMLA (Meng et al. 2025) first shows that, at the same KV cache size, GQA can be written equivalently as MLA, then applies a low-rank factorization to the key and value projections to convert the model to the MLA structure, and recovers quality with a small amount of continued training. Existing GQA models can then reuse inference systems optimized for MLA.
Common mistakes
- Do not say that MLA makes several heads share one set of K/V: Each head's K/V are different; only the low-dimensional latent is shared.
- Do not say that MLA must decompress the latent into the full K/V at inference: At decode time the up-projections are absorbed into the query and output projections, and attention runs directly on the latent.
- Do not say that MLA reduces the compute of attention: At decode time its compute is actually larger; the gain comes from reading less memory.
- Do not say that MLA caches only \(d_c\) dimensions: DeepSeek-V2 also caches a 64-dimensional RoPE key, for 576 dimensions in total.
2.3 How does FlashAttention work, and why is it faster? ★★¶
One-sentence answer
FlashAttention is an IO-aware implementation of exact attention: it splits Q, K and V into small blocks loaded into the GPU's on-chip SRAM, accumulates the result block by block with online softmax, never writes the \(n\times n\) attention matrix back to GPU memory (HBM), and recomputes those blocks in the backward pass. It does not change the result, and its FLOPs even increase slightly; the speedup comes entirely from a large reduction in memory reads and writes, and attention's memory footprint drops from \(O(n^2)\) to \(O(n)\).
I will address three aspects: why standard attention is slow, how FlashAttention works, and its gains and later evolution.
(1) The bottleneck of standard attention is not compute but reading and writing the \(n\times n\) intermediate matrices in memory.
A GPU has two main levels of memory: HBM is large (tens of GB) but has limited bandwidth (about 1.5–2.0 TB/s on an A100), while on-chip SRAM has roughly ten times the bandwidth (about 19 TB/s on an A100) but only about 192 KB per SM. A standard implementation works in three steps: compute \(S=QK^\top\) and write it to HBM, read \(S\) back to compute the softmax \(P\) and write it to HBM, then read \(P\) back and multiply it by \(V\) (the basic computation of attention is covered in Chapter 1). The element-wise operations, such as softmax and masking, involve very little compute, so almost all the time goes into reading and writing the \(n\times n\) matrices, which makes the operation memory-bound; moreover, training must store \(P\) for the backward pass, so memory grows quadratically with sequence length. The real bottleneck of attention is therefore data movement, not the matrix multiplications themselves.
(2) FlashAttention uses tiled computation with online softmax so the intermediate matrices always stay in SRAM, and replaces storage with recomputation in the backward pass.
- Tiling: Q is split by rows into several blocks, and K and V are split into blocks as well. Each time, one block of Q and one block of K and V are loaded into SRAM, where the scoring, the softmax and the multiplication by V are completed before moving to the next block of K and V. The whole of attention is fused into one kernel, and the \(n\times n\) matrix exists only briefly, in small blocks, in SRAM; it is never written back to HBM.
- Online softmax: the difficulty with tiling is that softmax needs the maximum and the sum of exponentials over the whole row as its normalizer, but block-by-block processing never sees the whole row at once. The solution is to keep two statistics per row: the maximum seen so far, \(m\), and the sum of exponentials, \(\ell\). Each new block of K updates \(m\) and \(\ell\), and a scaling factor corrects the output accumulated so far; at the end, everything is divided by \(\ell\) once. Mathematically, this gives exactly the same result as computing the whole row and then applying softmax (the recurrence is in "Going deeper").
- Recomputation in the backward pass: the forward pass stores only the output \(O\) and each row's softmax statistics, which are \(O(n)\) in size, not the \(n\times n\) matrix \(P\); the backward pass uses these statistics to recompute the needed blocks of \(P\) in SRAM. This adds some FLOPs but removes the HBM traffic of reading and writing \(P\), so the backward pass actually becomes faster.
(3) Gains: exact results, linear memory, higher speed, and continued evolution with new hardware.
Because every step is computed exactly, FlashAttention's output is mathematically identical to standard attention, differing only by tiny floating-point rounding, so it is not an approximation and can be swapped in without affecting model quality. Its FLOPs are still \(O(n^2 d)\), but HBM accesses drop sharply, and the original paper reports about a 3× training speedup on GPT-2 (Dao et al. 2022); memory drops from \(O(n^2)\) to \(O(n)\), which makes training with longer contexts possible. Later versions mainly raise utilization on new hardware: FlashAttention-2 (Dao 2023) reduces non-matmul computation, parallelizes over the sequence dimension and improves how work is divided among GPU thread groups, running about twice as fast as its predecessor; FlashAttention-3 (Shah et al. 2024) targets the H100, overlapping data movement and compute asynchronously, interleaving matrix multiplication with softmax, and supporting FP8; FlashAttention-4 (Zadouri et al. 2026) redesigns the algorithm and pipeline for Blackwell GPUs, where matrix-multiply throughput has grown much faster than other units such as those computing exponentials.
In summary: the essence of FlashAttention is paying for a little recomputation to get a large reduction in HBM reads and writes; it changes how the computation is organized, not what is computed.
Going deeper: the online-softmax recurrence, IO complexity and numbers for each version
(1) The online-softmax recurrence.
For one query row, let \(s^{(j)}\) be the vector of scores after processing the \(j\)-th block of keys, and \(V^{(j)}\) the corresponding block of values. Then:
Here \(m^{(j)}\) is the largest score seen so far, subtracted to prevent overflow in the exponential; \(\ell^{(j)}\) is the running sum of exponentials; \(o^{(j)}\) is the unnormalized accumulated output; \(e^{m^{(j-1)} - m^{(j)}}\) is the factor that corrects the old results after the maximum is updated; and \(T\) is the total number of key blocks. The idea of online softmax goes back to Milakov & Gimelshein (2018); postponing the division by \(\ell\) to the very end is one of the ways FlashAttention-2 reduces non-matmul computation.
(2) IO complexity.
Let the sequence length be \(n\), the head dimension \(d\), and the SRAM size \(M\). Standard attention needs \(\Theta(nd + n^2)\) HBM accesses, and FlashAttention needs \(\Theta(n^2 d^2 / M)\). For typical \(d\) (64–128) and \(M\) (about 100 KB), \(d^2\) is considerably smaller than \(M\), so the number of HBM accesses drops substantially. The paper also proves that, over a range of SRAM sizes, no exact attention algorithm can do asymptotically better.
(3) Improvements and reported results of each version.
| Version | Target hardware | Main improvements | Reported results |
|---|---|---|---|
| FlashAttention (Dao et al. 2022) | A100 | Tiling, online softmax, recomputation in backward | About 3× faster GPT-2 training; BERT-large end to end 15% faster than the MLPerf 1.1 record |
| FlashAttention-2 (Dao 2023) | A100 | Less non-matmul computation; parallelism over the sequence dimension; better division of work among thread groups | About 2× its predecessor; 50–73% of the A100's theoretical peak |
| FlashAttention-3 (Shah et al. 2024) | H100 | Asynchronous overlap of data movement and compute; interleaved matmul and softmax; FP8 | 1.5–2.0× faster than FlashAttention-2; up to 740 TFLOPs/s in FP16 (75% utilization), close to 1.2 PFLOPs/s in FP8 |
| FlashAttention-4 (Zadouri et al. 2026) | B200 | Fully asynchronous pipeline; software emulation of part of the exponentials and conditional softmax rescaling | Up to about 1613 TFLOPs/s in BF16 (71% utilization) |
Follow-up questions
Follow-up 1: Does FlashAttention change the complexity of attention?
It does not change the computational complexity, only the memory complexity and the amount of IO. FLOPs remain \(O(n^2 d)\), and even rise slightly because of recomputation in the backward pass; what changes is that attention's memory footprint drops from \(O(n^2)\) to \(O(n)\) and the number of HBM reads and writes falls sharply. To really lower the computational complexity, attention itself must change, for example through sparse or linear attention (see 2.4 and 2.5).
Follow-up 2: Why is recomputing faster than storing?
Because reading and writing the \(n\times n\) matrix takes longer than recomputing it in SRAM. The backward pass of standard attention must read the stored \(P\) from HBM, which is limited by memory bandwidth; FlashAttention instead recomputes the blocks of \(P\) from the Q and K blocks already in SRAM and the saved softmax statistics, using the very fast matrix-multiply units. This is the same idea as activation recomputation in training (see Chapter 3 of the "LLM Training Pipeline" direction).
Follow-up 3: Is FlashAttention still useful in the decode phase?
Yes, but it needs a different way of parallelizing. FlashAttention originally parallelizes over the batch, the heads and the query blocks; at decode time each sequence has only one query, so with a small batch and a long context most of the GPU's compute units sit idle. Flash-Decoding (Dao et al. 2023) instead splits along the length of the KV, letting several thread blocks each compute partial results and softmax statistics for one segment of the KV, and then merges them with the same correction used in online softmax.
Common mistakes
- Do not say that FlashAttention is an approximate attention: Its result is mathematically identical to standard attention.
- Do not say that FlashAttention lowers the computational complexity: FLOPs remain \(O(n^2 d)\); what it lowers is memory footprint and HBM traffic.
- Do not say that FlashAttention is faster because it does less computation: It actually does slightly more computation; the speedup comes from less IO.
- Do not say that FlashAttention only saves memory: It also substantially speeds up training and prefill.
2.4 How do sparse attention and sliding-window attention work? ★¶
One-sentence answer
Both let each query attend to only part of the keys, reducing the compute and the memory reads of attention. Sliding-window attention uses a fixed local window and is usually interleaved with a few global attention layers (for example, Gemma 3 pairs every 5 local layers with 1 global layer); learned sparse attention instead picks the tokens or blocks to attend to dynamically based on content, for example DeepSeek-V3.2's DSA uses a lightweight indexer to select 2048 tokens for each query.
I will address three aspects: sliding-window attention, learned sparse attention that selects by content, and the trade-offs the two share.
(1) Sliding-window attention lets each token see only the most recent \(W\) tokens, and keeps long-range ability by interleaving with global layers.
In sliding-window attention, the query at position \(t\) attends only to keys in the range \([t-W+1,\ t]\). Each layer's compute therefore drops from \(O(n^2)\) to \(O(nW)\), and the KV cache needs to hold at most \(W\) tokens, no longer growing with the context. Information outside the window is not entirely lost: a token in one layer sees the outputs of the tokens within its window in the layer below, and those outputs already summarize earlier content, so after stacking \(L\) layers the theoretical receptive field is about \(L\times W\). This layer-by-layer relay is lossy, however, and the model struggles to recall distant details precisely. Recent models therefore usually interleave local window layers with a few global (full attention) layers: Gemma 2 alternates them 1:1, and Gemma 3 pairs every 5 local layers with a window of 1024 with 1 global layer. Most layers then have a capped KV cache, while the few global layers handle precise long-range retrieval.
(2) Learned sparse attention selects the positions to attend to dynamically based on content; representative methods are NSA and DeepSeek-V3.2's DSA.
Fixed windows or sparse patterns (such as the local windows plus global tokens of early work like Sparse Transformer and Longformer) cannot decide from content "which distant tokens matter". The idea of learned sparse attention is to use a very cheap scorer to roughly estimate the importance of each past position, and then compute full attention only over the small set of positions that score highest.
- NSA (native sparse attention, Yuan et al. 2025): for each query, three branches are computed in parallel: the history is compressed block by block into coarse representations that are attended to; the most important blocks, chosen by the scores of the compression branch, are attended to at fine granularity; and a sliding-window branch handles the local context; finally a gate combines the outputs of the three. Selecting by block keeps memory access contiguous, which suits GPU kernels, and the whole structure can be trained end to end from the start of pretraining. (MoBA, Lu et al. 2025, follows a similar idea.)
- DSA (DeepSeek sparse attention, DeepSeek-AI 2025): a lightning indexer (with only a few heads, computable in FP8) scores the query against every past token, then selects the 2048 highest-scoring tokens for each query, and MLA attention is computed only over those tokens. The complexity of core attention drops from \(O(n^2)\) to \(O(nk)\), where \(k\) is the number of selected tokens; the indexer itself is still \(O(n^2)\), but its compute is far smaller than that of the original attention. DSA was introduced into the already-trained DeepSeek-V3.1-Terminus through continued training.
(3) Trade-off: sparsity saves compute and memory reads but risks losing information, and the quality of the selection mechanism determines the result.
Sliding windows are simple and keep the KV cache bounded, but long-range retrieval depends entirely on a few global layers; learned sparse attention can dynamically find key content far away, but it is complex to implement, needs specialized kernels, and usually still has to store the entire KV cache, because any past token might be selected later, so what it mainly saves is compute and bandwidth rather than memory capacity. There is also a family of training-free methods that drop unimportant KV entries at inference time (such as H2O and SnapKV); they need no retraining but are approximate, and the discarded information cannot be recovered (see Chapter 1 of the "Inference, Evaluation & Deployment" direction).
In summary: the core of sparse attention is letting each query compute only the keys it really needs: sliding windows use a fixed local range, learned sparse attention uses a cheap scorer to choose by content, and both usually keep some global capability as a fallback.
Going deeper: configurations of specific models and how DSA is trained
(1) What each model does.
| Model | Approach | Key configuration |
|---|---|---|
| Mistral 7B (Jiang et al. 2023) | Sliding window in every layer | \(W=4096\) with 32 layers, a theoretical receptive field of about 131K tokens; the KV cache is overwritten cyclically at position modulo \(W\) (rolling buffer) |
| Gemma 2 (Gemma Team 2024) | Local and global layers alternate 1:1 | Local window 4096, global length 8192 |
| Gemma 3 (Gemma Team 2025) | 5 local layers per global layer | Local window 1024, context 128K |
| gpt-oss (OpenAI 2025) | Window layers alternate with global layers | Window of 128 tokens |
| NSA (Yuan et al. 2025) | Compression, selection and sliding-window branches with a gate | Selected block size 64, 16 blocks per query, window 512 |
| DeepSeek-V3.2 (DeepSeek-AI 2025) | Lightning indexer plus top-k selection | 2048 tokens selected per query, context 128K |
| DeepSeek-V4 (DeepSeek-AI 2026) | Compressed sparse attention (CSA) alternating with heavily compressed attention (HCA) | CSA compresses the KV 4× along the sequence and then applies top-k selection; HCA compresses 128× and attends densely; both have a sliding-window branch |
Gemma 3's ablation shows that for a 2B model with a 32K context, using only global layers costs about 60% extra memory for the KV cache, which falls below 15% with a 1:3 ratio and a window of 1024, with almost no effect on perplexity.
(2) DSA is introduced in two stages.
- Dense warm-up stage: dense attention is kept and every parameter except the indexer is frozen; the indexer's output distribution is trained with a KL divergence to match the main attention distribution (the attention scores summed over all heads and normalized); 1000 steps, about 2.1B tokens.
- Sparse training stage: top-2048 selection is turned on and all parameters are trained; the main model uses only the language-modeling loss, while the indexer's KL loss is computed only over the selected tokens and its input is detached from the main computation graph; about 944B tokens in total, at a sequence length of 128K.
DSA is built on the MQA form of MLA (see 2.2): each latent vector is shared by all query heads of the same token, so a single per-token selection serves every head, which makes an efficient implementation possible.
(3) Why NSA selects by block rather than by individual token.
GPUs read contiguous blocks of memory most efficiently; picking scattered individual tokens makes memory access non-contiguous, so theoretical savings in compute hardly turn into real speedups. NSA therefore selects in units of blocks and lets the heads within one GQA group share the selected blocks, so that one read is reused by several heads.
Follow-up questions
Follow-up 1: Why is sliding-window attention usually mixed with global layers?
Because a pure window model struggles to recall details outside the window precisely. Information outside the window can only be relayed indirectly from layer to layer and becomes blurrier as it goes; a few global layers can access the whole context directly and take on precise retrieval. After mixing, most layers have a capped KV cache, so the overall memory cost is close to that of a pure window model, while long-range ability is close to that of a full-attention model. Gemma 3 also found that, within a reasonable range, changing the ratio of local to global layers and the window size has very little effect on perplexity.
Follow-up 2: Can sparse attention reduce the memory used by the KV cache?
Sliding windows can; content-based sparse attention usually cannot. A sliding-window layer only stores the KV of the last \(W\) tokens, so its memory is bounded. Methods like DSA and NSA may select any past token at any step, so they must still store the full KV, and what they save is compute and the amount read per step. DeepSeek-V4 goes further and compresses the KV along the sequence dimension, which is what lets it also reduce KV cache memory.
Follow-up 3: How does sparse attention relate to FlashAttention?
They are complementary. FlashAttention is an exact, efficient implementation of a given attention pattern and does not change what is computed; sparse attention changes which positions are computed. Practical sparse-attention kernels are usually built on FlashAttention's tiling idea and compute only the selected blocks; the original FlashAttention paper already includes a block-sparse version.
Common mistakes
- Do not say that a sliding-window model cannot see anything outside the window: After stacking layers, the theoretical receptive field is about \(L\times W\); distant information is just hard to recall precisely.
- Do not say that learned sparse attention always reduces KV cache memory: It usually still stores the full KV; what it saves is compute and memory reads.
- Do not say that DSA makes all of attention linear: Core attention is \(O(nk)\), while the indexer is still \(O(n^2)\), only cheap.
- Do not confuse training-free methods that drop KV at inference with trainable sparse attention: The former are approximate and the dropped information cannot be recovered; in the latter the selection mechanism is learned and the KV is kept.
2.5 What are linear attention and state-space models (such as Mamba), and why have hybrid architectures emerged? ★★¶
One-sentence answer
Linear attention and state-space models (SSMs) both compress the entire history into a fixed-size state, and each new token triggers only one constant-cost state update, so neither compute nor memory grows with the context during generation, and training can still be parallelized. The cost is that a fixed-size state is a lossy compression of the history, which makes it hard to recall or copy distant details precisely. The mainstream approach in 2025–2026 is therefore the hybrid architecture: most layers use linear attention (such as Gated DeltaNet), while about a quarter or fewer remain full-attention layers that handle precise retrieval, as in Qwen3-Next, Kimi Linear and Qwen3.5.
I will address three aspects: how linear attention becomes a recurrence, where its weakness lies, and why hybrid architectures became the compromise.
(1) Without the softmax, linear attention can be rewritten as a recurrence in which the history accumulates into a fixed-size state matrix.
In softmax attention, every query must compute \(\exp(q^\top k)\) with every past key, so total compute is \(O(n^2)\) and the KV cache grows linearly with length. Linear attention (Katharopoulos et al. 2020) replaces the exponential in the softmax with a kernel function, or simply with the dot product, and the output can then be rewritten using the associativity of matrix multiplication:
Here \(q_t\), \(k_t\) and \(v_t\) are the query, key and value of the \(t\)-th token, and \(S_t\) is a \(d_v\times d_k\) state matrix (the normalization term is omitted for brevity). During generation, each step therefore only updates \(S_t\) with the new \(k_t\) and \(v_t\) and multiplies it by \(q_t\), so compute and memory are constant and do not grow with context length; during training, a parallel or chunkwise-parallel form can be used for efficient computation. State-space models arrive at a similar structure from another direction: Mamba (Gu & Dao 2023) uses the linear recurrence \(h_t = \bar A_t h_{t-1} + \bar B_t x_t\), \(y_t = C_t h_t\), where \(x_t\) is the input and \(h_t\) the hidden state, and makes the parameters \(\bar A_t\), \(\bar B_t\) and \(C_t\) depend on the input (called selective), so the model can decide from content what to remember or forget; Mamba-2 (Dao & Gu 2024) further showed that such SSMs are equivalent to a form of linear attention with decay.
(2) Weakness: a fixed-size state is a lossy compression of the history, so precise recall is weak.
Softmax attention keeps every token's K and V and can retrieve information from any position precisely at any time; linear attention and SSMs must squeeze an arbitrarily long history into a state of fixed size, so the longer the context, the harsher the compression, and different key-value associations interfere with each other inside the state. As a result, they clearly lag behind on tasks that require precise recall, such as copying a long passage, finding a phone number in a long document, or answering several associative-recall questions about key-value pairs. Jelassi et al. (2024) showed both theoretically and empirically that Transformers can copy very long strings while models with a fixed-size state cannot. Early linear attention had a further problem: the state can only keep accumulating and never forgets, so old information keeps interfering with new information. Later improvements eased this in two directions: adding data-dependent decay gates (as in Mamba-2 and GLA), so the model can actively forget; and using the delta rule (as in DeltaNet and Gated DeltaNet), which subtracts the value the state already holds for a key before writing the new key-value pair, so old associations are "overwritten" rather than "piled up". These improvements, however, only make better use of the state; they cannot change the fundamental fact that its size is fixed.
(3) Hybrid architectures: most layers use linear attention to lower cost, while a few full-attention layers keep precise retrieval.
Since linear layers are cheap but weak at recall, and full-attention layers are expensive but retrieve precisely, the natural compromise is to stack the two alternately in some ratio. Most layers then have compute and state size that do not grow with the context, and the KV cache comes only from the few full-attention layers, which greatly improves memory and speed for long-context inference while the model keeps its ability to recall precisely. A systematic study found that the ratio of linear to full-attention layers mainly affects recall, with comparatively little effect on language-modeling loss (Wang et al. 2025), so in practice ratios between 3:1 and 7:1 are common. For example, Qwen3-Next and Qwen3.5 alternate Gated DeltaNet layers with full-attention layers at 3:1, and Kimi Linear alternates its own Kimi Delta Attention with MLA at 3:1. This direction is not yet a consensus, however: MiniMax-M2 abandoned the hybrid architecture of its predecessors and returned to full attention, on the grounds that at larger scale the hybrid models fell behind on complex multi-hop reasoning; DeepSeek, meanwhile, chose the sparse-attention route (see 2.4).
In summary: linear attention and SSMs trade precise recall for \(O(n)\) compute and constant inference memory by using a fixed-size state; hybrid architectures make up for this weakness with a few full-attention layers and are the mainstream compromise between efficiency and capability today.
Going deeper: state-update rules, and hybrid models from 2024–2026
(1) How the state-update rule has evolved.
| Method | State update | Property |
|---|---|---|
| Linear attention (Katharopoulos et al. 2020) | \(S_t = S_{t-1} + v_t k_t^\top\) | Only accumulates, never forgets |
| Mamba-2 (Dao & Gu 2024), GLA (Yang et al. 2023) | \(S_t = \alpha_t S_{t-1} + v_t k_t^\top\) | Data-dependent decay gate (scalar in Mamba-2, per dimension in GLA) |
| DeltaNet (Schlag et al. 2021; Yang et al. 2024) | \(S_t = S_{t-1} + \beta_t\,(v_t - S_{t-1}k_t)\,k_t^\top\) | Subtracts the key's old value before writing, so old associations can be overwritten |
| Gated DeltaNet (Yang et al. 2024) | \(S_t = \alpha_t\, S_{t-1}\big(I - \beta_t k_t k_t^\top\big) + \beta_t v_t k_t^\top\) | Combines the decay gate with the delta rule |
Here \(\alpha_t \in (0,1)\) is the decay gate, which decides how much of the old state to keep; \(\beta_t \in (0,1)\) is the write strength; \(S_{t-1}k_t\) is the value the current state "remembers" for key \(k_t\); and \(I\) is the identity matrix. One can check that expanding DeltaNet's update gives \(S_{t-1}(I - \beta_t k_t k_t^\top) + \beta_t v_t k_t^\top\), and Gated DeltaNet simply multiplies the old state by the decay \(\alpha_t\) as well.
(2) An overview of hybrid models.
| Model | Linear part | Full-attention part | Ratio of linear to full-attention layers |
|---|---|---|---|
| Jamba (Lieber et al. 2024) | Mamba | GQA | 7:1 |
| MiniMax-01 (MiniMax 2025) | Lightning Attention | Softmax attention | 7:1 |
| Nemotron-H (NVIDIA 2025) | Mamba-2 | Self-attention | Self-attention in about 8% of layers |
| Qwen3-Next (Qwen Team 2025) | Gated DeltaNet | Gated attention | 3:1 |
| Kimi Linear (Kimi Team 2025) | Kimi Delta Attention | MLA | 3:1 |
| Qwen3.5 (Qwen Team 2026) | Gated DeltaNet | Gated attention | 3:1 |
Kimi Linear reports up to 75% less KV cache at long context and up to about 6× higher decoding throughput at a 1M context. The systematic analysis by Wang et al. (2025) found that recall degrades noticeably when fewer than a quarter of the layers are full attention (i.e. a ratio above 3:1), and recommends ratios from 3:1 to 6:1.
(3) A counterexample: MiniMax-M2 returned to full attention.
MiniMax-01 and M1 used a 7:1 hybrid architecture, but MiniMax-M2 (MiniMax 2025) went back to full attention. The team's explanation is that in small-scale experiments the hybrid models matched full attention, but at larger scale they showed a clear gap on complex multi-hop reasoning; moreover, the training and inference infrastructure for linear attention is far less mature than for full attention, and it is more sensitive to the numerical precision of the stored state. This shows that the benefit of hybrid architectures depends on the specific linear module, the ratio and the evaluation tasks, and it remains an open question.
Follow-up questions
Follow-up 1: If linear attention is so cheap, why hasn't it replaced softmax attention?
Because a fixed-size state cannot preserve an arbitrarily long history precisely. On average metrics such as perplexity, strong linear-attention models can come close to Transformers, but they clearly lag on tasks that require verbatim recall, such as copying, exact retrieval and multi-hop reasoning. In addition, the software and hardware ecosystem around softmax attention is very mature. The current approach is therefore to keep a few full-attention layers in a hybrid architecture rather than replace them entirely.
Follow-up 2: Is training linear attention also a step-by-step sequential process?
No; training uses a chunkwise-parallel form. The sequence is cut into chunks of length \(C\): within each chunk, an attention-like matrix form is computed in parallel (it is small and runs efficiently on matrix-multiply units), and only the state matrix \(S\) is passed from one chunk to the next. Total compute thus grows linearly with sequence length while still making full use of the GPU's parallelism. Generation uses the step-by-step recurrent form, with constant cost per step.
Follow-up 3: How much can a hybrid architecture reduce the KV cache?
The KV cache is roughly proportional to the number of full-attention layers. Linear layers keep only a fixed-size state that does not grow with the context; in a 3:1 hybrid model the KV cache is therefore about 1/4 of that of a full-attention model of the same depth, plus a small constant-size state. The longer the context, the larger this advantage, and Kimi Linear's reported "up to 75% less KV cache" corresponds exactly to the 3:1 ratio.
Common mistakes
- Do not say that linear attention is just an approximate implementation of softmax attention with the same quality: It changes the model itself, and its precise recall is clearly weaker.
- Do not say that SSMs and linear attention are two unrelated families: Mamba-2 showed a formal correspondence between them.
- Do not say that linear attention can only be trained sequentially: Training uses a chunkwise-parallel form; only generation runs the recurrence step by step.
- Do not say that the hybrid architecture is already the sole consensus: MiniMax-M2 returned to full attention, and DeepSeek chose the sparse-attention route.