Why does self-attention have quadratic time and memory complexity with respect to sequence length?
Last updated
Every token attends to every other token. The score matrix QKᵀ therefore has n×n entries, each a d-dimensional dot product: O(n²·d) compute. Naively materializing that matrix (per head) costs O(n²) memory.
Where the n² comes from:
Q and K are each n×d, so
Q @ K.Tis n×n and costs about 2n²d FLOPs.Softmax runs over each row of the n×n matrix.
The weights (n×n) are multiplied by V (n×d), another 2n²d FLOPs.
Contrast with the rest of the layer: Projections and the FFN are per-token, so they cost O(n·d²): linear in n.
Memory:
The n×n score matrix per head per batch element is stored for softmax and backprop.
Example: at n=32K with 32 heads in fp16, that is about 64 GB per layer per sample.
What mitigations change:
FlashAttention: tiles the computation with an online softmax and never materializes n×n. Memory becomes O(n), but compute is still O(n²).
Sparse, sliding-window, or linear attention: reduce the compute itself, at some cost in quality or expressiveness.
KV cache at decode: each step is O(n), but generating n tokens is still O(n²) total. The cache grows linearly with n.
[lang:python]
scores = Q @ K.transpose(-2, -1) / d**0.5 # (n, n): n^2 entries, O(n^2 d) work
attn = scores.softmax(-1) # O(n^2) memory if materialized
out = attn @ V # (n, d): another O(n^2 d)