Attention Complexity & Cost¶
Overview¶
Attention is quadratic in sequence length: every token attends to every other token. This single fact drives almost all LLM engineering โ kernels (FlashAttention), memory systems (KV cache, PagedAttention), architectural variants (GQA, sliding window), and long-context research. Understanding why it's quadratic, and where the costs land (training vs. inference, prompt vs. decode), is the key to reading the rest of this knowledge base.
- Compute: O(seqยฒ ยท d) per layer for QKแต and AV
- Memory: the NรN attention matrix (and the KV cache) scale with seqยฒ / seq
- Decode phase: only the quadratic part shrinks; memory grows linearly per token
- Optimization families: sparse, IO-aware, shared-head, cached โ see table below
The Quadratic Problem in One Picture¶
N tokens, every token attends to every token:
token โโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโบ
QแตขยทKโ QแตขยทKโ QแตขยทKโ ... QแตขยทK_N โ N scores
โผ โผ โผ โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ softmax + weighted sum of V โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
N tokens ร N scores each = Nยฒ attention weights
N = 8K โ Nยฒ = 67M weights per layer
N = 32K โ Nยฒ = 1.07B weights per layer (16ร more than 8K!)
Double the context โ quadruple the compute and memory. That's the whole story.
Compute: FLOPs Breakdown¶
Per layer (prompt/training phase โ full parallel attention)¶
N = sequence length (e.g., 8,192 tokens for LLaMA-2), d_k = 128
QKแต: N ร N ร d_k โ 8,192ยฒ ร 128 โ 8.6 ร 10โน mults
Softmax: N ร N โ 67M exps
AยทV: N ร N ร d_v โ 8,192ยฒ ร 128 โ 8.6 ร 10โน mults
Per layer total: โ 17 ร 10โน operations (~17 GFLOPs)
LLaMA-2 7B (32 layers): โ 550 ร 10โน operations (~550 GFLOPs per prompt)
Compare: the rest of the model is (nearly) linear¶
FFN (per layer): ~4 ยท N ยท d_modelยฒ
N = 8192, d_model = 4096 โ ~4 ร 8192 ร 4096ยฒ โ 550 GFLOPs
For LONG sequences, attention dominates:
seq = 8K: attention โ FFN (both ~550 GFLOPs total)
seq = 32K: attention ร 16 โ ~8.8 TFLOPs vs FFN ร 4 โ ~2.2 TFLOPs
โ attention is now ~80% of the compute
Why the quadratic term appears twice¶
S = QยทKแต โ (Nรd_k) ร (d_kรN) = NรN โ Nยฒd_k ops
Out = AยทV โ (NรN) ร (Nรd_v) = Nรd_v โ Nยฒd_v ops
Both terms scale with Nยฒ โ you can't dodge it by caching one part;
this is why sparse (SWA) and linear-attention ideas exist.
Memory: The NรN Matrix and the KV Cache¶
1. The attention matrix itself (training / long prompts)¶
Attention weights A: (N, N)
N = 8,192 โ 67M entries ร 4 bytes (fp32) โ 268 MB per head-layer
N = 32,768 โ 1B entries โ 4+ GB โ explodes quickly!
Per layer with 32 heads: ร32.
FlashAttention's core trick: never materialize A on GPU memory
โ recompute pieces on the fly, keep it in SRAM
(see [Flash Attention](/02-llm-modeling/01-architecture/02-attention-optimization/flash-attention/))
2. The KV cache (inference, autoregressive decoding)¶
During decode, every generated token needs to attend to ALL past tokens.
Instead of recomputing their K/V every step, cache them:
Cache size = N_tokens ร n_layers ร n_heads ร head_dim ร bytes
Concrete (LLaMA-2 7B, fp16, 8K context):
8,192 ร 32 ร 32 ร 128 ร 2 bytes = 2 ร 10โน bytes โ 2 GB per sequence!
This is why GQA/MQA (fewer KV heads) and PagedAttention (fragmentation
control) exist โ see [Kv Cache](/02-llm-modeling/01-architecture/03-memory-management/kv-cache/)
and [Pagedattention](/02-llm-modeling/01-architecture/03-memory-management/pagedattention/).
Training vs. Inference: Where the Quadratic Cost Hides¶
โโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Phase โ Compute pattern โ Quadratic term present? โ
โโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Training โ full NรN attention every step โ โ
fully โ Nยฒ on every batch โ
โ Inference: prompt โ process N input tokens at once โ โ
fully โ Nยฒ per request โ
โ Inference: decode โ generate 1 token; attend to N โ โ score is 1รN (linear) โ
โ โ past tokens โ but KV cache memory grows โ
โโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Decode step in detail:
Q_new: (1, d_k) vs K_cache: (N, d_k)
scores: 1 ร N โ linear in N โ
(this is why decode is "cheap" FLOPs-wise)
BUT: cache grows by 1 token per step โ memory grows with N
and the memory access pattern (read all K/V every step) becomes
the real bottleneck โ FlashAttention-style IO optimization helps here too
Scaling Rules (Memorize These)¶
Context length: N โ 2N
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Attention compute: ร4 (quadratic)
KV cache memory: ร2 (linear in tokens)
FFN compute: ร2 (linear in tokens)
End-to-end latency (long): โร2โ4 depending on phase
The Optimization Families (Attack the Quadratic)¶
| Family | Technique | What it fixes | Complexity |
|---|---|---|---|
| IO-aware | Flash Attention (v1/v2) | memory bandwidth, NรN materialization | O(Nยฒ) but ~10ร faster |
| Sparse | Sliding Window Attention | quadratic compute โ local window W | O(NยทW) |
| Shared | [Gqa](/02-llm-modeling/01-architecture/01-core-designs/multi-query-attention-(mqa)-&-grouped-query-attention-(gqa) | mqa/gqa/) | KV cache size (รทheads factor) |
| Cached | Kv Cache | decode recomputation | linear memory per token |
| Managed | Pagedattention | fragmentation, sharing | linear memory, better utilization |
| Kernel | Kernel Fusion | launch overhead, intermediate writes | โ |
Decision guide¶
Problem โ Technique
Training too slow โ FlashAttention, kernel fusion
Long context OOM (compute) โ Sliding window / sparse attention
Long context OOM (KV cache) โ GQA/MQA, KV quantization
Decode latency high โ KV cache, continuous batching
Many concurrent long requests โ PagedAttention (vLLM)
Worked Budget Example¶
Serve LLaMA-2 7B (32 layers, 32 heads, head_dim 128) at 8K context, fp16:
Attention FLOPs per token (prompt):
โ 4 ยท Nยฒ ยท d_k per layer โ 4 ร 67M ร 128 โ 34 GFLOPs
ร 32 layers โ 1.1 TFLOPs (prompt processing)
KV cache per token:
32 layers ร 32 heads ร 128 dim ร 2 bytes = 256 KB
8K tokens โ 2 GB per concurrent sequence
A server with 80 GB VRAM can host ~40 sequences' caches
(plus weights ~14 GB fp16, activations, etc.)
Moral: cache capacity, not FLOPs, often limits long-context serving โ
which is why GQA (รท8 cache) and PagedAttention are deployed in practice.
Key Takeaways¶
โณ Attention is O(Nยฒ) โ double context โ 4ร cost
๐งฎ Two quadratic terms: QKแต and AV both scale with Nยฒ
๐พ Two memory costs: the NรN matrix (training) + KV cache (inference)
๐ Phases differ: prompt is quadratic; decode is linear FLOPs but memory-bound
๐งฐ Every major technique is a fix for this one problem: FlashAttention, SWA, GQA, KV cache, PagedAttention
๐ Scale rules: Nโ2N โ compute ร4, cache ร2
Related Notes¶
- 00 Attention Mechanisms โ chapter overview
- 02 Scaled Dot Product Attention โ the formula with the quadratic cost
- Flash Attention โ IO-aware O(Nยฒ) with usable memory
- Sliding Window Attention โ O(NยทW) sparse alternative
- Mqa & Gqa โ KV-cache reduction
- Kv Cache and Pagedattention โ memory systems for decoding