Why does self-attention have quadratic time and memory complexity with respect to sequence length?

Last updated 22 November 2026

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:

    1. Q and K are each n×d, so Q @ K.T is n×n and costs about 2n²d FLOPs.

    2. Softmax runs over each row of the n×n matrix.

    3. 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)

  • https://phosseini.github.io/transformers/quadratic-complexity/
  • https://medium.com/foundation-models-deep-dive/attention-part-2-of-5-the-scaling-challenge-why-standard-attention-hits-a-wall-12212ecaa404
  • https://medium.com/@wasowski.jarek/self-attention-query-key-value-transformer-b7266afbe730
All Transformers interview questions