Computational complexity of attention
The fundamental cost breakdown
Memory and operations in standard self-attention
The self-attention mechanism computes three matrices for each token: queries (Q), keys (K), and values (V). The complexity comes from computing the attention scores between all pairs of tokens.
Let's derive the complexity from scratch.
Deriving the time complexity
Step 1: Linear projections
For input and weight matrices :
This is a matrix multiplication: output.
Cost: Each output element requires multiplications, total: operations.
For all three projections (Q, K, V): operations.
Why this step? We're transforming each token's embedding into query/key/value space. This is linear in sequence length—not the problem.
Step 2: Computing attention scores
Matrix dimensions:
Cost: Each of the output elements requires multiplications.
Total: operations.
Why this step? This is where every token compares itself to every other token. The output is inherently quadratic—this is the bottleneck.
Step 3: Softmax
For each row of (one query), compute:
Cost: per row, rows total: operations.
Why this step? Normalizing attention weights. Still quadratic in the number of scores.
Step 4: Weighted sum
Cost: operations.
Why this step? Each output token is a weighted combination of all value vectors.
Step 5: Output projection
After concatenating heads back into a -dimensional vector, we apply the output projection :
Cost: operations.
Why this step? The output projection mixes information across heads and maps back to model dimension. It contributes another term—don't forget it when counting linear-projection cost.
Memory complexity

Why each component matters
Linear projections:
This scales linearly with sequence length. Doubling doubles the work. Not a bottleneck for long sequences but dominates for very short sequences where . This term covers the Q, K, V projections and the output projection —together roughly operations, but asymptotically .
Attention matrix:
This is the core problem. The term means:
- 2× sequence length →4× compute
- 10× sequence length → 100× compute
Why it's unavoidable in standard attention: Every token needs a score with every other token to decide "who to pay attention to."
Multi-head attention scaling
With attention heads, each of dimension :
- Attention cost: heads each cost , so total (since ).
- Projection cost: The Q, K, V projections and output projection each operate on the full -dimensional space once, not once per head. So the projection cost stays — it is not multiplied by .
Key insight: Using more heads doesn't change the asymptotic complexity (still ), and does not add a factor of to the projection term. Splitting into heads just reshapes the same -dimensional projections.
Comparison with other architectures
| Architecture | Time complexity | Memory | Receptive field | |------------|-----------------|-----------------| | Self-attention | | | Global (all tokens) | | RNN (LSTM/GRU) | | | Sequential (limited) | | CNN (kernel ) | | | Local ( tokens) | | Sparse attention | | | Structured patterns | | Linear attention | | | Global (approximation) |
Trade-off: Self-attention gets global context instantly (depth-1 path between any tokens) but pays quadratic cost. RNNs are linear but require sequential steps to connect distant tokens.
Efficient attention variants
The bottleneck has sparked a research area:
-
Sparse attention (Sparse Transformer, Longformer): Only compute attention for subset of token pairs (e.g., local windows + global tokens). Reduces to or .
-
Linear attention (Performers, Linear Transformers): Approximate attention with kernel methods, achieving by never materializing the matrix.
-
Flash Attention: Keeps complexity but optimizes memory access patterns using tiling, reducing memory from to by not storing the full attention matrix.
Practical implications
Training vs. inference
Training: Requires storing for backpropagation. Memory is often the limiting factor, not compute.
Inference: Can attention on-the-fly without storing full matrices. KV-caching helps: store past keys/values to avoid recomputing them for each new token.
Why context length is expensive
Quadratic scaling means:
- GPT-3 (2K context): manageable
- GPT-4 (32K context): 16× memory and compute vs. 8K in the attention term
- 100K context: 625× cost vs. 4K
This is why long-context models either use sparse attention or are extremely expensive to run.
Recall Explain to a 12-year-old
Imagine you're in a class of students, and everyone needs to pass a note to everyone else to share information (that's attention). If there are 10 students, you need notes. Double the class to 20 students? Now you need notes—four times as many!
That's why transformers slow down with long texts: every word has to "talk to" every other word, so doubling the length quadruples the work. Smart researchers are finding ways to let words talk to only their neighbors or use tricks to avoid passing all those notes, making it much faster.
Connections
- 4.1.1-Self-attention-mechanism: The mechanism that causes this complexity
- 4.1.7-Multi-head-attention: How splitting heads affects computational cost
- 4.3.2-Sparse-attention-patterns: Solutions to reduce quadratic complexity
- 4.5.1-Memory-optimization-techniques: Flash Attention and gradient checkpointing
- 5.2.3-Positional-encoding-scaling: Why long sequences need efficient attention
#flashcards/ai-ml
What is the time complexity of standard self-attention? :: , dominated by for long sequences where the computation requires operations.
Why is self-attention quadratic in sequence length?
What is the memory complexity of self-attention?
How does doubling sequence length affect attention compute?
Compare time complexity of self-attention vs. RNN :: Self-attention is but parallel; RNN is but sequential. For long sequences (), attention is slower but has global receptive field in one step.
Does multi-head attention multiply the projection cost by h?
What is the computational bottleneck in self-attention? :: The matrix multiplication, which is . This all-to-all comparison between tokens is inherently quadratic and dominates for long sequences.
Which projections contribute to the O(nd^2) term?
How much memory for attention scores in one layer with n=2048?
Why can't you feed a full book into GPT naively?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Transformer attention ka sabse bada issue hai quadratic complexity—matlab jab ap sequence length double karte ho, compute aur memory requirement chaar guna ho jati hai. Kyun? Kyunki self-attention mein har token ko har dusre token ke saath compare karna padta hai