What are the time and memory costs of one self-attention layer for sequence length and model dimension ? For and , which part dominates?
Sequence models and transformers, Attention
Level L2 Elementary. Length Short. Nature Mat Mathematical.
What's being asked
Whether you can count the cost of the projections and of the attention matrix separately.
Key idea
The projections ( and output) cost multiply-adds. The products and , where is the attention matrix, cost each. Total time is , and the attention matrix needs memory for heads. The term dominates once , i.e. .
Steps
- Projections: four products of an matrix by a matrix, so .
- Scores : by , so . Weighted sum : by , so . Splitting into heads of size leaves the total unchanged.
- Numbers: and . Attention dominates by about (here ).
- Memory: the attention matrix has entries per head, per layer. This is why long contexts need tricks such as FlashAttention (which computes it in tiles and never stores it whole) or sparse or linear attention.
- Optional: adding a feed-forward block of width (cost ) moves the per-layer crossover to , i.e. .
Common mistakes
- Saying "" without the factor .
- Ignoring the projection cost, which dominates for short sequences.
- Thinking more heads multiply the cost. The head dimension shrinks to .
How long your answer should be
4–5 lines; 2 minutes.
Last checked on 4 December 2026.
Read this
- Dive into Deep Learning: The Cost of Attention: Section 10.5.1 'Quadratic Time and Memory' (FLOPs for projections vs scores, eq. 10.3.4's 8nd^2 + 4n^2 d, and the n^2 memory per head), then 10.5.2 on exact attention without storing the matrix (the FlashAttention idea).
- Attention Is All You Need (Vaswani et al., 2017): Section 4 'Why Self-Attention' and Table 1: per-layer complexity O(n^2 d) for self-attention vs O(n d^2) for recurrence, and when self-attention is cheaper.
Previous in Sequence models and transformers: How is causal (look-ahead) masking implemented in decoder self-attention? What is the mask for a sequence of length 4, and why are masked logits set to rather than the attention weights being set to 0?
Next in Sequence models and transformers: How many parameters does a multi-head self-attention layer with and heads have (with biases)? Does the number of heads change the count? How many does a full transformer encoder layer with feed-forward width have?