What are the time and memory costs of one self-attention layer for sequence length n and model dimension d? For n=4096 and d=1024, 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 (Q,K,V and output) cost 4nd2 multiply-adds. The products QK⊤ and AV, where A is the n×n attention matrix, cost n2d each. Total time is O(nd2+n2d), and the attention matrix needs O(hn2) memory for h heads. The n2d term dominates once 2n2d>4nd2, i.e. n>2d.

Steps

  1. Projections: four products of an n×d matrix by a d×d matrix, so 4nd2.
  2. Scores QK⊤: n×d by d×n, so n2d. Weighted sum AV: n×n by n×d, so n2d. Splitting into h heads of size d/h leaves the total unchanged.
  3. Numbers: 4nd2=4⋅4096⋅10242≈1.7×1010 and 2n2d=2⋅40962⋅1024≈3.4×1010. Attention dominates by about 2× (here n=4d>2d).
  4. Memory: the attention matrix has n2≈1.7×107 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.
  5. Optional: adding a feed-forward block of width 4d (cost 8nd2) moves the per-layer crossover to 2n2d=12nd2, i.e. n=6d.

Common mistakes

How long your answer should be

4–5 lines; 2 minutes.

Last checked on 4 December 2026.

Read this

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 dmodel=512 and h=8 heads have (with biases)? Does the number of heads change the count? How many does a full transformer encoder layer with feed-forward width dff=2048 have?