Efficient Attention & Long Context
Sparse, linear and flash attention.
Double a transformer's context and its attention cost quadruples; during generation, a growing cache of keys and values, not arithmetic, sets the speed. Two families of fixes followed: approximate attention (sparse, low-rank, kernelized, and finally recurrent) and exact attention computed with far less memory traffic. Theory says where each must stop.
What you’ll learn
- Build a cost model of attention for training and decoding, and state the fine-grained hardness of exact and approximate attention.
- Analyze sparse and low-rank approximations, including a Johnson–Lindenstrauss argument for low-rank attention.
- Derive the Performer's positive random features and their variance, show that causal linear attention is a recurrent network, and bound what a fixed state can copy.
- Explain FlashAttention's online softmax and IO complexity, and quantify KV-cache savings from multi-query and grouped-query attention.
Where the cost goes
Per layer, a sequence of length costs FLOPs for projections and MLP plus for scores and mixing, and memory if the attention matrices are stored (Attention & Transformers). Training and prefill are compute-bound, with attention dominant once . Decoding is different: each new token reads the whole KV cache, numbers per earlier token, to do about two FLOPs per number read, so it is limited by memory bandwidth, not arithmetic.
The intuition: when scores span a small range, is well approximated by a low-degree polynomial, and a polynomial kernel factors into low-rank products, so the matrix is never needed. When scores span a range of order , as sharp attention requires (The Mathematics of Attention), that structure is gone. Subquadratic attention must therefore exploit structure (sparsity, low rank, bounded scores) or accept failures on some inputs.
Sparse and low-rank attention
Sparse patterns compute only the scores in a fixed set of pairs. The Sparse Transformer (Child et al., 2019) combines a local band with a strided pattern, so any position reaches any other in two hops, at cost. Longformer (Beltagy, Peters & Cohan, 2020) uses sliding windows plus a few global tokens that attend to, and are attended by, everything; BigBird (Zaheer et al., 2020) adds random links and proves that such sparse transformers remain universal approximators and Turing complete. A window of width in each of layers reaches tokens, and some production models interleave sliding-window layers with global ones.
Entry is the inner product of row of with , and the sketch replaces it by . The Johnson–Lindenstrauss lemma (Prompting, Retrieval & Tool Use) preserves the norms of fixed vectors within except with probability ; applied to and polarized, it preserves inner products:
A union bound over the pairs sets . A probability vector has , which gives the claim:
Linformer (Wang et al., 2020) builds a layer on this observation: it projects keys and values along the sequence axis with learned and computes . The learned projections tie the model to one length and mix future positions into every summary, so it does not apply to causal decoding.
Kernels, random features and recurrence
Write attention with a kernel, . If for a feature map , associativity removes the matrix:
Choromanski et al. (2021) keep the softmax kernel , applied to and . For the Gaussian moment-generating function , with , gives an exact identity:
So is an unbiased, strictly positive estimator. The same identity with gives its second moment, , and hence the variance:
The relative error does not depend on the kernel value, so small attention weights, which are most of them, are estimated as accurately as large ones. Rahimi–Recht trigonometric features are also unbiased, but they can return negative values and are least accurate exactly where is small, which destabilizes the normalization. Orthogonal reduce the variance further.
A linear-attention or state-space layer has a state fixed in advance, so copying fails once exceeds its size in bits. A transformer's KV cache grows with , which is why trained transformers copy long strings far better than state-space models (Jelassi et al., 2024). Modern recurrent layers add decay and gating to the state update; with scalar decay, a state-space model is exactly masked linear attention with a structured mask (Dao & Gu, 2024; S4 and Mamba are in Recurrent Networks & LSTMs).
Why does the Performer use positive random features rather than trigonometric ones?
- Trigonometric features are biased estimators of the softmax kernel
- Positive features are exact for any number of features
- Positive features keep every kernel estimate positive, and their relative error does not grow as the true kernel value shrinks
- Positive features make the cost quadratic again, which improves accuracy
Show the answer
C. Positive features keep every kernel estimate positive, and their relative error does not grow as the true kernel value shrinks
Both estimators are unbiased. The positive one has relative standard deviation whatever is, while trigonometric estimates can be negative and are least accurate where attention weights are small.
Exact attention, less memory traffic
FlashAttention (Dao et al., 2022) computes exact attention faster by targeting the real bottleneck on a GPU: moving data between high-bandwidth memory (HBM, tens of gigabytes) and on-chip SRAM (tens of megabytes in total, roughly ten times faster). Standard kernels write the scores to HBM, read them back for the softmax, write the weights and read them again for . FlashAttention tiles , and into blocks that fit in SRAM and never materializes the matrix, thanks to an online softmax (Milakov & Gimelshein, 2018):
For a block of keys keep the maximum score , the normalizer and the normalized output . Two blocks merge as
Since , the merge gives exactly the softmax-weighted sum over both blocks. Every exponent is at most , so it is numerically stable, and the merge is associative, so blocks can be processed in any order:
FLASH-ATTENTION-FORWARD(Q, K, V) // B_r query rows and B_c key rows fit in SRAM
for each query block Q_i, in parallel:
m ← −∞; ℓ ← 0; O ← 0 // one entry (or row) per query, in SRAM
for each key/value block K_j, V_j:
S ← Q_i·K_jᵀ / √d_k // B_r × B_c, never written to HBM
m_new ← max(m, rowmax(S))
P ← exp(S − m_new)
ℓ ← exp(m − m_new)·ℓ + rowsum(P)
O ← exp(m − m_new)·O + P·V_j // unnormalized accumulator
m ← m_new
write O/ℓ, m and ℓ to HBM // backward recomputes S from Q and KThe loop order follows FlashAttention-2 (Dao, 2023). The backward pass recomputes score blocks instead of storing them: slightly more FLOPs, far less memory traffic, and memory linear in .
Shrinking the KV cache. In decoding, the cost is reading the cache. Multi-query attention (MQA; Shazeer, 2019) shares one key head and one value head across all query heads. Grouped-query attention (GQA; Ainslie et al., 2023) shares each of key–value heads within a group of query heads, interpolating between MQA () and standard attention (). Ainslie et al. converted multi-head checkpoints by mean-pooling each group's key and value heads and uptraining with about 5% of the original pretraining compute, reaching quality close to multi-head attention at nearly the speed of MQA.
A model has layers, query heads of size and key–value heads, with 16-bit numbers. How many gigabytes does the KV cache of one 32,768-token sequence take?
Show the answer
10.7 GB
bytes, about GB. With all 64 heads keeping their own keys and values it would be about GB, more than many accelerators hold: the eight-fold saving is what makes such contexts servable.
Key takeaways
- Training and prefill pay attention FLOPs; decoding is bound by reading a KV cache of numbers per token. Under SETH, exact attention needs quadratic time, and fast approximation is possible only when scores span a small range.
- Sparse patterns (local, strided, global, random) and low-rank projections cut cost: a Johnson–Lindenstrauss argument shows survives a bottleneck of dimension , but local windows cut long-range links.
- Kernelized attention factors as ; the Performer's positive features estimate without bias, with relative error independent of its value. Causal linear attention is an RNN with a fixed state, and a fixed state cannot copy more bits than it holds.
- FlashAttention computes exact attention with an online softmax over SRAM tiles, memory accesses instead of ; MQA and GQA shrink the KV cache by .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Is FlashAttention an approximation of attention?
- Yes: it drops small attention weights
- Yes: it estimates the softmax kernel with random features
- No: it computes exact attention with fewer HBM accesses, recomputing scores in the backward pass instead of storing them
- No: it is exact because it uses higher-precision arithmetic
Show the answer
C. No: it computes exact attention with fewer HBM accesses, recomputing scores in the backward pass instead of storing them
Tiling plus the online-softmax merge gives the same output as standard attention, up to floating-point rounding, with instead of memory accesses.
Causal linear attention with feature map can be computed as a recurrence. What is its state?
- The running sums and , of fixed size
- The list of all earlier keys and values, growing with
- The attention matrix up to row
- Only the most recent key and value
Show the answer
A. The running sums and , of fixed size
Associativity turns into , with . The fixed state makes decoding cost constant per token and limits what can be recalled.
A recurrent layer keeps a state of bits. Can it reliably copy a uniformly random sequence of tokens from a vocabulary of ?
- Yes, if it is trained long enough
- Yes, because
- Only with a causal mask
- No: the sequence carries bits, more than the state holds, so it succeeds with probability at most
Show the answer
D. No: the sequence carries bits, more than the state holds, so it succeeds with probability at most
There are equally likely sequences and at most states, each with one output.
Compared with standard multi-head attention, how does grouped-query attention with query heads and key–value heads change the KV cache?
- It is 4 times smaller
- It is 8 times smaller
- It is unchanged, but faster to read
- It is 32 times smaller
Show the answer
B. It is 8 times smaller
The cache stores keys and values for heads instead of , a factor . Multi-query attention () would save a factor 32, at some cost in quality.
Further reading
- R. Child, S. Gray, A. Radford & I. Sutskever, "Generating long sequences with sparse transformers," arXiv:1904.10509 (2019).
- A. Katharopoulos, A. Vyas, N. Pappas & F. Fleuret, "Transformers are RNNs: Fast autoregressive transformers with linear attention," ICML (2020).
- K. Choromanski et al., "Rethinking attention with Performers," ICLR (2021).
- T. Dao, D. Y. Fu, S. Ermon, A. Rudra & C. Ré, "FlashAttention: Fast and memory-efficient exact attention with IO-awareness," NeurIPS (2022).
- Y. Tay, M. Dehghani, D. Bahri & D. Metzler, "Efficient transformers: A survey," ACM Computing Surveys (2022).