Simple Algorithm
Artificial Intelligence · Deep Layer · 28 min

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 nn costs 24nd224nd^2 FLOPs for projections and MLP plus 4n2d4n^2d for scores and mixing, and O(hn2)\order{hn^2} memory if the attention matrices are stored (Attention & Transformers). Training and prefill are compute-bound, with attention dominant once n≳6dn\gtrsim6d. Decoding is different: each new token reads the whole KV cache, 2Ld2Ld 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, exe^x is well approximated by a low-degree polynomial, and a polynomial kernel factors into low-rank products, so the n×nn\times n matrix is never needed. When scores span a range of order log⁡n\log n, 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 O(nn)\order{n\sqrt n} 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 ww in each of LL layers reaches LwLw tokens, and some production models interleave sliding-window layers with global ones.

DerivationProof sketch
  1. ∣⟨Ru,Rv⟩−⟨u,v⟩∣≤ε ∥u∥2∥v∥2\big|\langle R\mathbf u,R\mathbf v\rangle-\langle\mathbf u,\mathbf v\rangle\big|\le\varepsilon\,\norm{\mathbf u}_2\norm{\mathbf v}_2

    Entry (i,c)(i,c) is the inner product of row pi\mathbf p_i of PP with vc\mathbf v_c, and the sketch replaces it by ⟨Rpi,Rvc⟩\langle R\mathbf p_i,R\mathbf v_c\rangle. The Johnson–Lindenstrauss lemma (Prompting, Retrieval & Tool Use) preserves the norms of fixed vectors within 1±ε1\pm\varepsilon except with probability e−Ω(kε2)e^{-\Omega(k\varepsilon^2)}; applied to u±v\mathbf u\pm\mathbf v and polarized, it preserves inner products:

  2. ∣(PR⊤RV)ic−(PV)ic∣≤ε ∥pi∥2∥vc∥2≤ε ∥vc∥2\big|(PR^\top RV)_{ic}-(PV)_{ic}\big|\le\varepsilon\,\norm{\mathbf p_i}_2\norm{\mathbf v_c}_2\le\varepsilon\,\norm{\mathbf v_c}_2

    A union bound over the ndvnd_v pairs sets kk. A probability vector has ∥pi∥2≤∥pi∥1=1\norm{\mathbf p_i}_2\le\norm{\mathbf p_i}_1=1, which gives the claim:

  3. O(n2d) ⟶ O(nkd),k=O(ε−2log⁡n)\order{n^2d}\ \longrightarrow\ \order{nkd},\qquad k=\order{\varepsilon^{-2}\log n}

    Linformer (Wang et al., 2020) builds a layer on this observation: it projects keys and values along the sequence axis with learned E,F∈Rk×nE,F\in\R^{k\times n} and computes softmax⁡(Q(EK)⊤/dk)FV\softmax\big(Q(EK)^\top/\sqrt{d_k}\big)FV. 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, zi=∑jκ(qi,kj)vj/∑jκ(qi,kj)\mathbf z_i=\sum_j\kappa(\mathbf q_i,\mathbf k_j)\mathbf v_j/\sum_j\kappa(\mathbf q_i,\mathbf k_j). If κ(q,k)=ϕ(q)⊤ϕ(k)\kappa(\mathbf q,\mathbf k)=\phi(\mathbf q)^\top\phi(\mathbf k) for a feature map ϕ:Rd→Rr\phi:\R^d\to\R^r, associativity removes the n×nn\times n matrix:

zi⊤=ϕ(qi)⊤(∑jϕ(kj)vj⊤)ϕ(qi)⊤∑jϕ(kj),cost O(n r d) instead of O(n2d)\mathbf z_i^\top=\frac{\phi(\mathbf q_i)^\top\big(\sum_j\phi(\mathbf k_j)\mathbf v_j^\top\big)}{\phi(\mathbf q_i)^\top\sum_j\phi(\mathbf k_j)},\qquad\text{cost }\order{n\,r\,d}\ \text{instead of}\ \order{n^2d}
Katharopoulos et al. (2020) used ϕ(x)=elu⁡(x)+1\phi(\mathbf x)=\operatorname{elu}(\mathbf x)+1. Under a causal mask the sums run over j≤ij\le i and become running states, Si=Si−1+ϕ(ki)vi⊤S_i=S_{i-1}+\phi(\mathbf k_i)\mathbf v_i^\top and ui=ui−1+ϕ(ki)\mathbf u_i=\mathbf u_{i-1}+\phi(\mathbf k_i). Causal linear attention is a recurrent network with an r×dr\times d matrix state: the fast-weight programmers of the early 1990s (Schlag, Irie & Schmidhuber, 2021).
DerivationThe Performer: positive random features for the softmax kernel
  1. Eω[eω⊤x−∥x∥2/2 eω⊤y−∥y∥2/2]=e12(∥x+y∥2−∥x∥2−∥y∥2)=ex⊤y\E_{\boldsymbol\omega}\Big[e^{\boldsymbol\omega^\top\mathbf x-\norm{\mathbf x}^2/2}\,e^{\boldsymbol\omega^\top\mathbf y-\norm{\mathbf y}^2/2}\Big]=e^{\frac12\left(\norm{\mathbf x+\mathbf y}^2-\norm{\mathbf x}^2-\norm{\mathbf y}^2\right)}=e^{\mathbf x^\top\mathbf y}

    Choromanski et al. (2021) keep the softmax kernel SM⁡(x,y)=ex⊤y\operatorname{SM}(\mathbf x,\mathbf y)=e^{\mathbf x^\top\mathbf y}, applied to q/dk1/4\mathbf q/d_k^{1/4} and k/dk1/4\mathbf k/d_k^{1/4}. For ω∼N(0,Id)\boldsymbol\omega\sim\mathcal N(0,I_d) the Gaussian moment-generating function E[eω⊤u]=e∥u∥2/2\E[e^{\boldsymbol\omega^\top\mathbf u}]=e^{\norm{\mathbf u}^2/2}, with u=x+y\mathbf u=\mathbf x+\mathbf y, gives an exact identity:

  2. Var⁡[ϕ(x)⊤ϕ(y)]=1r SM⁡(x,y)2(e∥x+y∥2−1)\Var\big[\phi(\mathbf x)^\top\phi(\mathbf y)\big]=\frac1r\,\operatorname{SM}(\mathbf x,\mathbf y)^2\Big(e^{\norm{\mathbf x+\mathbf y}^2}-1\Big)

    So ϕ(x)=r−1/2(eωl⊤x−∥x∥2/2)l=1r\phi(\mathbf x)=r^{-1/2}\big(e^{\boldsymbol\omega_l^\top\mathbf x-\norm{\mathbf x}^2/2}\big)_{l=1}^r is an unbiased, strictly positive estimator. The same identity with 2ω2\boldsymbol\omega gives its second moment, e∥x+y∥2SM⁡2e^{\norm{\mathbf x+\mathbf y}^2}\operatorname{SM}^2, and hence the variance:

  3. Var⁡SM⁡(x,y)=e∥x+y∥2−1r\frac{\sqrt{\Var}}{\operatorname{SM}(\mathbf x,\mathbf y)}=\sqrt{\frac{e^{\norm{\mathbf x+\mathbf y}^2}-1}{r}}

    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 SM⁡\operatorname{SM} is small, which destabilizes the normalization. Orthogonal ωl\boldsymbol\omega_l reduce the variance further.

A linear-attention or state-space layer has a state fixed in advance, so copying fails once nlog⁡2∣V∣n\log_2|V| exceeds its size in bits. A transformer's KV cache grows with nn, 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).

Check your understanding

Why does the Performer use positive random features eω⊤x−∥x∥2/2e^{\boldsymbol\omega^\top\mathbf x-\norm{\mathbf x}^2/2} rather than trigonometric ones?

  1. Trigonometric features are biased estimators of the softmax kernel
  2. Positive features are exact for any number of features
  3. Positive features keep every kernel estimate positive, and their relative error does not grow as the true kernel value shrinks
  4. 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 (e∥x+y∥2−1)/r\sqrt{(e^{\norm{\mathbf x+\mathbf y}^2}-1)/r} whatever SM⁡(x,y)\operatorname{SM}(\mathbf x,\mathbf y) 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 n×nn\times n scores to HBM, read them back for the softmax, write the weights and read them again for AVAV. FlashAttention tiles QQ, KK and VV into blocks that fit in SRAM and never materializes the n×nn\times n matrix, thanks to an online softmax (Milakov & Gimelshein, 2018):

DerivationMerging softmax blocks exactly
  1. m=max⁡(m1,m2),ℓ=em1−mℓ1+em2−mℓ2,o=em1−mℓ1 o1+em2−mℓ2 o2ℓm=\max(m_1,m_2),\qquad\ell=e^{m_1-m}\ell_1+e^{m_2-m}\ell_2,\qquad\mathbf o=\frac{e^{m_1-m}\ell_1\,\mathbf o_1+e^{m_2-m}\ell_2\,\mathbf o_2}{\ell}

    For a block bb of keys keep the maximum score mbm_b, the normalizer ℓb=∑j∈besj−mb\ell_b=\sum_{j\in b}e^{s_j-m_b} and the normalized output ob=∑j∈besj−mbvj/ℓb\mathbf o_b=\sum_{j\in b}e^{s_j-m_b}\mathbf v_j/\ell_b. Two blocks merge as

  2. o=∑j∈b1∪b2esj−m vj∑j∈b1∪b2esj−m=softmax⁡(s)⊤V\mathbf o=\frac{\sum_{j\in b_1\cup b_2}e^{s_j-m}\,\mathbf v_j}{\sum_{j\in b_1\cup b_2}e^{s_j-m}}=\softmax(\mathbf s)^\top V

    Since emb−mℓbob=∑j∈besj−mvje^{m_b-m}\ell_b\mathbf o_b=\sum_{j\in b}e^{s_j-m}\mathbf v_j, the merge gives exactly the softmax-weighted sum over both blocks. Every exponent is at most 00, so it is numerically stable, and the merge is associative, so blocks can be processed in any order:

text
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 K

The 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 nn.

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 HH query heads. Grouped-query attention (GQA; Ainslie et al., 2023) shares each of gg key–value heads within a group of H/gH/g query heads, interpolating between MQA (g=1g=1) and standard attention (g=Hg=H). 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.

KV bytes=2⋅L⋅n⋅g⋅dhead⋅(bytes per number),saving over multi-head=Hg\text{KV bytes}=2\cdot L\cdot n\cdot g\cdot d_{\text{head}}\cdot(\text{bytes per number}),\qquad\text{saving over multi-head}=\frac Hg
Other levers: lower-precision caches, paging the cache like virtual memory to serve many requests (Kwon et al., 2023), evicting or compressing old entries, and caching a low-rank latent instead of full keys and values.
Predict before you look

A model has L=80L=80 layers, H=64H=64 query heads of size dhead=128d_{\text{head}}=128 and g=8g=8 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

2×80×32,768×8×128×2≈1.07×10102\times80\times32{,}768\times8\times128\times2\approx1.07\times10^{10} bytes, about 10.710.7 GB. With all 64 heads keeping their own keys and values it would be about 8686 GB, more than many accelerators hold: the eight-fold saving is what makes such contexts servable.

Key takeaways

  • Training and prefill pay O(n2d)\order{n^2d} attention FLOPs; decoding is bound by reading a KV cache of 2Ld2Ld 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 PVPV survives a bottleneck of dimension O(ε−2log⁡n)\order{\varepsilon^{-2}\log n}, but local windows cut long-range links.
  • Kernelized attention factors as ϕ(Q)(ϕ(K)⊤V)\phi(Q)\big(\phi(K)^\top V\big); the Performer's positive features estimate ex⊤ye^{\mathbf x^\top\mathbf y} 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, Θ(n2d2/M)\Theta(n^2d^2/M) memory accesses instead of Θ(nd+n2)\Theta(nd+n^2); MQA and GQA shrink the KV cache by H/gH/g.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Is FlashAttention an approximation of attention?

  1. Yes: it drops small attention weights
  2. Yes: it estimates the softmax kernel with random features
  3. No: it computes exact attention with fewer HBM accesses, recomputing scores in the backward pass instead of storing them
  4. 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 Θ(n2d2/M)\Theta(n^2d^2/M) instead of Θ(nd+n2)\Theta(nd+n^2) memory accesses.

Question 2

Causal linear attention with feature map ϕ\phi can be computed as a recurrence. What is its state?

  1. The running sums Si=∑j≤iϕ(kj)vj⊤S_i=\sum_{j\le i}\phi(\mathbf k_j)\mathbf v_j^\top and ui=∑j≤iϕ(kj)\mathbf u_i=\sum_{j\le i}\phi(\mathbf k_j), of fixed size
  2. The list of all earlier keys and values, growing with ii
  3. The attention matrix up to row ii
  4. Only the most recent key and value
Show the answer

A. The running sums Si=∑j≤iϕ(kj)vj⊤S_i=\sum_{j\le i}\phi(\mathbf k_j)\mathbf v_j^\top and ui=∑j≤iϕ(kj)\mathbf u_i=\sum_{j\le i}\phi(\mathbf k_j), of fixed size

Associativity turns ∑jϕ(qi)⊤ϕ(kj) vj⊤\sum_j\phi(\mathbf q_i)^\top\phi(\mathbf k_j)\,\mathbf v_j^\top into ϕ(qi)⊤Si\phi(\mathbf q_i)^\top S_i, with Si=Si−1+ϕ(ki)vi⊤S_i=S_{i-1}+\phi(\mathbf k_i)\mathbf v_i^\top. The fixed r×dr\times d state makes decoding cost constant per token and limits what can be recalled.

Question 3

A recurrent layer keeps a state of 10610^6 bits. Can it reliably copy a uniformly random sequence of 10510^5 tokens from a vocabulary of 2162^{16}?

  1. Yes, if it is trained long enough
  2. Yes, because 105<10610^5<10^6
  3. Only with a causal mask
  4. No: the sequence carries 1.6×1061.6\times10^6 bits, more than the state holds, so it succeeds with probability at most 2−6×1052^{-6\times10^5}
Show the answer

D. No: the sequence carries 1.6×1061.6\times10^6 bits, more than the state holds, so it succeeds with probability at most 2−6×1052^{-6\times10^5}

There are 21.6×1062^{1.6\times10^6} equally likely sequences and at most 21062^{10^6} states, each with one output.

Question 4

Compared with standard multi-head attention, how does grouped-query attention with H=32H=32 query heads and g=4g=4 key–value heads change the KV cache?

  1. It is 4 times smaller
  2. It is 8 times smaller
  3. It is unchanged, but faster to read
  4. It is 32 times smaller
Show the answer

B. It is 8 times smaller

The cache stores keys and values for gg heads instead of HH, a factor H/g=8H/g=8. Multi-query attention (g=1g=1) 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).