Skip to content

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