4.1.13 · D4Transformer Architecture

Exercises — Computational complexity of attention

3,149 words14 min readBack to topic
Figure — Computational complexity of attention

Level 1 — Recognition

Goal: can you read off and plug into the formula?

L1.1 — Which term is which?

State, in words, what the two terms and in the time complexity each represent. Name which of contribute to each.

Recall Solution
  • ::: the attention cost — every one of the tokens forms a score with every other of the tokens ( pairs), and each score touches a -length vector. This is the score step and the -weighting step.
  • ::: the linear projection cost — for each of the tokens we multiply its -vector by a weight matrix (that costs ), and we do this to build Q, K, V and to apply the output projection. The word "quadratic bottleneck" always refers to the first term because of its .

L1.2 — Plug in the numbers

For and , compute the two time-terms and (as raw operation counts), and say which dominates. Locate this point on the figure.

Recall Solution

The attention term (M) dominates the projection term (M). On the figure: sits to the right of the yellow crossover line (), where the red parabola has already climbed above the blue line — exactly the region attention wins.

L1.3 — Memory of one score matrix

A single attention head stores the full score matrix in FP32 (4 bytes each). For , how many megabytes is that? (Use bytes.)

Recall Solution

Number of floats . Bytes bytes. So 16 MB per head — this is the memory term, kept for backpropagation, and it is why long sequences explode memory. See 4.5.1-Memory-optimization-techniques.


Level 2 — Application

Goal: run the formula on realistic model configs.

L2.1 — Crossover point

At what sequence length does the attention term equal the projection term (treating , single-head form)? Interpret the answer.

Recall Solution

Set them equal. Since (a sequence has at least one token) we are allowed to divide by : (Dividing by is legal precisely because ; likewise .) Interpretation: the crossover happens exactly at . For (short sequences) projections dominate; for (long sequences) attention dominates. This is why long-context models are the ones that fear the term.

L2.2 — GPT-2 Medium FLOPs

GPT-2 Medium uses , with heads. Note that in this model the per-head width is , so smaller than . This is a real design choice (the concatenated head output is , then a projection maps it back up/into the -wide residual stream); it is not the idealised we assumed in L2.1. So here we use the parent's exact convention: attention and projections (with the full ). For , compute (a) attention FLOPs , and (b) projection FLOPs .

Recall Solution

(a) Attention: (b) Projections (use full , since projections act on the model dimension, not the per-head width): Ratio attention/projection . Projections still dominate at — consistent with the parent table.

L2.3 — Doubling the sequence

You measured that attention takes 10 ms at . Estimate the attention time at , assuming everything else fixed.

Recall Solution

Attention scales as . Going from multiplies by , so time multiplies by . What it looks like: a 4× longer input is a 16× taller point on the red parabola of the figure — this is the whole reason 4.3.2-Sparse-attention-patterns exist.


Level 3 — Analysis

Goal: reason about why a term behaves as it does.

L3.1 — Multi-head asymptotics

Show algebraically that -head attention (in the idealised case ) has the same asymptotic time complexity as single-head attention.

Recall Solution
  • Single head, full dimension: attention cost .
  • heads, each dimension : each head costs , and there are of them: The cancels (legal since ). Projections are done once over , giving in both cases. Therefore both are . Splitting into heads reshapes the same work; it does not multiply it.

L3.2 — Memory budget failure

A training run has a GPU with 8 GB free for attention activations. Using the parent's figure of MB per head at , and a model with 12 heads over 12 layers, does the forward-pass attention memory fit? By how much does it miss/spare?

Recall Solution

Per-head-per-layer MB. Total heads-layers . GB GB, so it fits, with GB to spare — but only for the attention scores; weights, optimizer states, and other activations eat the rest. This is why gradient checkpointing exists.

L3.3 — The other memory term: activations

Besides the score matrix, each layer must also keep the token-vector activations (this is the memory term). For , , FP32: (a) how many MB is one such activation tensor? (b) Compare it to the MB score matrix of L1.3 — which term dominates here, and at what would they be equal?

Recall Solution

(a) Floats . Bytes . In MB: MB. (b) The score matrix is MB vs the activation MB, so the score term already dominates at . They are equal when , i.e. (using to divide by ). For the activations dominate; for the scores do. This is the memory version of the L2.1 time crossover — same pivot.

L3.4 — CNN vs attention receptive field

A CNN with kernel costs and connects tokens only apart per layer. Self-attention costs but connects any two tokens in one layer. For , , , which is cheaper, and what does self-attention buy for the extra cost?

Recall Solution

CNN: . Attention: . The CNN is cheaper (B vs B). What attention buys: a depth-1 path between any pair of tokens (global receptive field instantly), whereas the CNN needs many stacked layers to connect distant tokens. You pay ~2.7× more compute for global context.


Level 4 — Synthesis

Goal: combine terms, choose regimes, design.

L4.1 — Total cost with all terms

Write the full per-layer forward FLOP count combining attention and all four projections (use for attention and for projections), then evaluate for , .

Recall Solution

Attention: . Projections: . Total FLOPs. Projections still lead at , but attention is closing in (ratio ).

L4.2 — When does sparse attention win?

Sparse attention costs instead of . Find the range of for which sparse attention does less attention-work than dense, given both use the same . (Ignore constants.)

Recall Solution

Compare vs ; since and we may cancel the common : Square both sides (both positive): , i.e. . So for every the sparse form has lower asymptotic order — but the hidden constants in sparse attention are larger, so in practice it only pays off once is large enough (typically thousands of tokens) that the growth overwhelms those constants. See 4.3.2-Sparse-attention-patterns.

L4.3 — Budget-driven design

You are limited to attention FLOPs per layer ( form) and must support . What is the largest sequence length you can serve with dense attention? What if you switch to sparse ?

Recall Solution

Dense: . So . Sparse: . Sparse lets you serve roughly 12.5× longer sequences under the same budget. That factor grows with the budget — the whole point of sub-quadratic attention.


Level 5 — Mastery

Goal: derive a novel result / prove a bound.

L5.1 — Prove the crossover is head-independent

Prove that the at which attention cost equals projection cost does not depend on the number of heads .

Recall Solution

Attention cost with heads: (since in the idealised case) — the has already vanished. Projection cost: , applied once over , independent of . Set equal and divide by (legal since ): . Neither side ever contained , so the crossover is head-independent. This is the rigorous version of the parent's "multi-head has the same asymptotic complexity."

L5.2 — Amortised memory with checkpointing

Naive training stores all layers' score matrices: memory . With gradient checkpointing you store only checkpoints and recompute the rest. Give the checkpointed memory and the extra compute cost, and evaluate memory saving for layer-heads at (16 MB each).

Recall Solution
  • Checkpointed memory ; extra compute extra forward pass, i.e. roughly the forward FLOPs.
  • Naive memory .
  • Checkpointed .
  • Saving factor (exactly ). You trade one recomputation for a -fold memory cut — the standard long-context bargain of 4.5.1-Memory-optimization-techniques.

L5.3 — Positional-encoding scaling sanity check

Attention itself is permutation-blind, so we add positional information whose storage is . Show this term never changes the asymptotic time or memory dominated by attention for long sequences, and state the one regime where it could matter.

Recall Solution
  • Time: attention costs while positional work is . Their ratio is (dividing by is legal since ). So attention beats positional work by a factor of , which grows without bound — the term is asymptotically absorbed for every .
  • Memory: attention scores are vs positional storage . The ratio , so once the score term dominates and positional storage is negligible.
  • The one regime where it matters: very short sequences (equivalently ). There is small, so the linear-in- terms (projections and positional storage) lead the cost; positional-encoding design — especially extrapolation to lengths unseen in training — then affects both output quality and the leading constant factor. See 5.2.3-Positional-encoding-scaling.

Recall Quick self-test (close the page, answer these)

The two time-terms of attention are ::: (attention) and (projections). Q, K, V stand for ::: query ("what I look for"), key ("what I offer"), value ("what I pass on"). Attention overtakes projections at equal to ::: . The two memory-terms cross over at equal to ::: (same pivot as time). Doubling multiplies attention cost by ::: . Multi-head changes the asymptotic cost by ::: nothing — it stays . Sparse attention's order is ::: .