Computational Complexity of Attention

2 min read

Standard Self-Attention has O(n2)O(n^2) time and memory in sequence length nn. This is the fundamental bottleneck of transformers.

Where the n2n^2 comes from:

  • Each of nn tokens attends to all nn tokens → the attention matrix softmax(QK/dk)\text{softmax}(QK^\top / \sqrt{d_k}) is n×nn \times n
  • Full cost per layer: O(n2d)O(n^2 d) FLOPs, O(n2)O(n^2) memory for the score matrix

The scaling problem:

Sequence lengthAttention entriesRelative cost
512262K1x
2,0484.2M16x
32,7681.07B4,096x
128,00016.4B62,500x

Approaches to break the quadratic wall:

IO-aware exact attention:

  • FlashAttention — computes exact attention in O(n2d)O(n^2 d) FLOPs but O(n)O(n) memory by tiling and avoiding materializing the full n×nn \times n matrix. Doesn't change asymptotics but 2–4x faster in practice

Sparse attention:

  • Local / sliding window — each token attends to the last ww tokens → O(nw)O(nw), 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 kk-th token for long-range
  • Block-sparse — hand-crafted or learned sparsity patterns
  • Common design: interleave local attention with periodic global attention layers
Attention Patterns

Linear attention:

  • Replace softmax(QK)V\text{softmax}(QK^\top)V with ϕ(Q)(ϕ(K)V)\phi(Q)(\phi(K)^\top V) using the associativity trick → O(nd2)O(nd^2) instead of O(n2d)O(n^2 d)
  • Trade-off: weaker in practice, though active research (RetNet, RWKV, Mamba)

State-space models (SSMs):

  • Mamba, S4 — O(n)O(n) sequence processing via recurrence, competitive with transformers on long sequences

KV-cache for inference:

  • At generation time, cache K,VK, V from previous tokens → each new token costs O(nd)O(nd) instead of recomputing O(n2d)O(n^2 d)
  • Memory grows as O(ndL)O(n \cdot d \cdot L) where LL = layers. This is why long-context inference is memory-bound

See also: Self-Attention, Multi-Head Attention, Big-O and Complexity Analysis

Linked from