Linear and sub-quadratic attention
Approximate softmax attention in linear time via kernel feature maps (Linformer, Performer) and IO-aware kernels (FlashAttention).
The Transformer's quadratic cost in sequence length is the headline bottleneck. Two lines of work attack it: algorithmic approaches that approximate or restructure attention to be sub-quadratic, and systems approaches that keep exact attention but make it hardware-efficient. Both are now standard parts of large-scale training, and modern long-context models combine them with the SSM methods from the previous lesson.
The cost to attack
Standard attention computes [2]:
- : FLOPs, materializes an matrix.
- : FLOPs, requires the full matrix.
- : FLOPs.
Memory is for the attention matrix at training time. At , that is 10 GB just for one attention layer's intermediate.
Linformer: low-rank approximation
Wang et al. (2020). Project the keys and values to a small fixed dimension before computing attention:
Attention is then with size , which is cost: linear in for fixed .
Simple, works reasonably, but the low-rank assumption is empirical and may not hold for all input distributions.
Performer / Linear Attention: kernel feature map
Choromanski et al. (2021). Replace softmax with a kernel:
with a random feature map. Then attention rewrites:
Compute first ( cost), then multiply by ( cost). Total cost instead of . Reordering the products this way also exposes an exact recurrent form, making a linear-attention layer an RNN at inference time[1].
Performers use random features that approximate the softmax kernel unbiased. Other "linear attention" variants use elu+1, ReLU, or other kernels.
Practical quality on language modeling: 1-2 perplexity worse than full attention at the same parameter count, but the linear scaling lets you trade those points for longer context or more parameters.
Sparse attention
Restrict attention to a sparse pattern instead of all :
- Local attention: each token attends only to the nearest neighbors. cost.
- Strided attention: attend to every -th token plus a local window. Used in Sparse Transformer.
- Global tokens: a few special tokens attend to everything; everyone attends to them; otherwise local.
Longformer and BigBird combine local + global + random patterns to achieve linear cost with provable expressiveness.
FlashAttention: exact, IO-aware
Dao et al. (2022). Keep the exact softmax-attention computation, but implement it as a fused CUDA kernel that tiles the computation into chunks fitting in fast GPU SRAM:
- Split , , into blocks.
- For each block of , iterate over blocks of and , incrementally computing the softmax via online running statistics.
- Never materialize the full attention matrix in HBM (slow GPU memory); keep it in SRAM (fast).
Result: 2-4x faster than the standard implementation, memory instead of for the intermediate matrix.
FlashAttention is now the default in every production Transformer training pipeline. FlashAttention-2 further improves parallelism; FlashAttention-3 uses NVIDIA Hopper-specific instructions for another 1.5-2x speedup.
The key insight: attention is bottlenecked by memory bandwidth, not FLOPs. FlashAttention does the same FLOPs but moves much less data between memory tiers.
Approximate vs exact
Linear-attention methods make the FLOPs cheaper at some accuracy cost; FlashAttention makes the same exact computation faster by being kinder to the memory hierarchy.
For most production use cases as of 2024:
- FlashAttention is the no-brainer baseline.
- Linear / sparse attention is used when context length is so long ( tokens) that even FlashAttention is too expensive.
- SSMs and hybrids (next lesson) compete with all of the above for long-context modeling.
The KV-cache angle
At inference, attention's quadratic cost shows up differently: the KV cache stores keys and values for all preceding tokens, growing linearly with context length. Each generated token requires attention against the full cache, so per-token inference is even with linear-attention or FlashAttention.
For 1M-token contexts, the KV cache alone is gigabytes. Solutions:
- Multi-query attention (MQA) and grouped-query attention (GQA): share keys and values across heads, reducing cache size by factors of 8-64.
- Paged attention (vLLM): page the KV cache like virtual memory.
- SSMs: constant cache size regardless of context.
Exercises
Exercise 1. Linear attention replaces with a kernel feature map , so that . Count the FLOPs of computing the output two ways for tokens, feature dimension , and value dimension : (a) left-to-right as , and (b) right-to-left as . State the crossover that makes (b) the win.
Solution
Step 1. Left-to-right. First form , an matrix: each of its entries is an inner product of length , so FLOPs and memory. Then costs . Total , quadratic in .
Step 2. Right-to-left. First form , an matrix: a sum over the tokens of outer products, FLOPs and only memory. Then costs . Total , linear in .
Step 3. Associativity of matrix multiplication makes the two outputs identical, so the only difference is cost. Right-to-left wins whenever , i.e. roughly when : once the feature dimension is much smaller than the sequence length, reordering turns a quadratic cost into a linear one. The same reordering also collapses the intermediate, removing the memory.
Exercise 2. The right-to-left grouping exposes a recurrence that makes a linear-attention layer an RNN at inference. Define for causal attention and write the per-step update and output. Compare its per-token inference cost and memory with the KV cache of softmax attention.
Solution
Step 1. For causal attention the (unnormalized) output at position sums only over :
Step 2. obeys a rank-one recurrence:
a running sum updated by one outer product per step. The state has fixed size , independent of . Each step costs for the update plus for .
Step 3. So linear attention generates with time and memory per token, both constant in the context length. Softmax attention instead stores a KV cache that grows to length , costing time and memory at step . The constant-size state is exactly the "transformers are RNNs" result: the linear-attention layer carries a fixed recurrent state rather than an unbounded cache.
Exercise 3. Three methods cut attention's cost differently: Linformer projects to a fixed rank , Performer uses an -dimensional random feature map, and FlashAttention keeps the exact softmax but tiles the computation. Classify each as approximate or exact, give its asymptotic time and memory in , and explain why FlashAttention does not reduce per-token inference cost against a KV cache even though it reduces training memory.
Solution
Step 1. Linformer: approximate (the low-rank projection discards information when the true attention matrix is not rank-). Cost time, memory: linear in for fixed .
Step 2. Performer: approximate (random features estimate the softmax kernel with variance that vanishes only as ). Cost time, memory: linear in .
Step 3. FlashAttention: exact (it computes the same softmax attention, only reordering the arithmetic with online softmax statistics). Training cost FLOPs, but memory instead of because the matrix is never materialized in slow memory.
Step 4. At inference with a KV cache, generation is one token at a time and each new token still attends against all cached keys, an exact computation. FlashAttention reduces the constant (less data moved between memory tiers) but not the order: it does the same FLOPs, so the per-token cost stays . Only an approximate method (linear/sparse) or a recurrent replacement (SSM, linear attention) changes that asymptotic.
The big picture
The Transformer's quadratic attention has been attacked from every angle: lower-rank approximations, sparse patterns, kernel features, memory-aware kernels, and complete architectural replacements. The next lesson covers the synthesis: hybrid architectures that combine the strengths of multiple sequence-mixing operations.
References
- [1]Katharopoulos, A., Vyas, A., Pappas, N., & Fleuret, F. (2020). "Transformers are RNNs: fast autoregressive transformers with linear attention". ICML. arXiv:2006.16236. Replaces the softmax with a kernel feature map for linear-time attention.↩
- [2]Vaswani, A., et al. (2017). "Attention is all you need". NeurIPS. arXiv:1706.03762. The exact softmax attention whose quadratic cost these methods attack.↩