Standard Self-Attention has time and memory in sequence length . This is the fundamental bottleneck of transformers.
Where the comes from:
- Each of tokens attends to all tokens → the attention matrix is
- Full cost per layer: FLOPs, memory for the score matrix
The scaling problem:
| Sequence length | Attention entries | Relative cost |
|---|---|---|
| 512 | 262K | 1x |
| 2,048 | 4.2M | 16x |
| 32,768 | 1.07B | 4,096x |
| 128,000 | 16.4B | 62,500x |
Approaches to break the quadratic wall:
IO-aware exact attention:
- FlashAttention — computes exact attention in FLOPs but memory by tiling and avoiding materializing the full matrix. Doesn't change asymptotics but 2–4x faster in practice
Sparse attention:
- Local / sliding window — each token attends to the last tokens → , and the KV cache becomes independent of sequence length (tokens outside the window are discarded). Used in Mistral, Longformer
- Dilated / strided patterns — attend to every -th token for long-range
- Block-sparse — hand-crafted or learned sparsity patterns
- Common design: interleave local attention with periodic global attention layers

Linear attention:
- Replace with using the associativity trick → instead of
- Trade-off: weaker in practice, though active research (RetNet, RWKV, Mamba)
State-space models (SSMs):
- Mamba, S4 — sequence processing via recurrence, competitive with transformers on long sequences
KV-cache for inference:
- At generation time, cache from previous tokens → each new token costs instead of recomputing
- Memory grows as where = layers. This is why long-context inference is memory-bound
See also: Self-Attention, Multi-Head Attention, Big-O and Complexity Analysis