4.1.13 · D5Transformer Architecture

Question bank — Computational complexity of attention

2,555 words12 min readBack to topic

Before you start, here is the vocabulary reminder that makes every answer readable.

Read the two figures first — every answer below points back at them.

Figure 1 is the growth-curve picture. The horizontal axis is the sequence length ; the vertical axis is the number of operations (in millions) for a fixed . The black line is the projection cost (a straight line — linear in ). The red line is the attention cost (a parabola — quadratic in ). Follow the red parabola upward and notice it stays below the black line for small , then crosses it at the dashed vertical mark where , and shoots above it afterwards. That single crossing point is the whole story of "which term dominates": left of it, projections rule; right of it, attention rules.

Figure — Computational complexity of attention

Figure 2 is the score-matrix picture. Each little square is one entry = the score between query token (row) and key token (column). A filled square is a score we actually compute and store. On the left ("full attention") the entire grid is filled black — every token pair exists, which is why the cost is quadratic. On the right ("causal attention") only the red lower triangle is filled — token may only look at itself and earlier tokens, so roughly half the grid () is computed. Compare the two grids side by side: masking removes a constant fraction, but the grid is still in shape, so the asymptotic cost is unchanged.

Figure — Computational complexity of attention

True or false — justify

Multi-head attention is asymptotically times more expensive than single-head attention.
False. The heads split the dimension (), so heads each costing sum to — identical to one full-dimension head (the red parabola in Figure 1 does not move when you change ).
The linear projection cost gets multiplied by the number of heads .
False. Q, K, V and each act once on the full -dimensional space; splitting into heads is just a reshape, so the projection term stays (the black line in Figure 1), never .
Doubling the sequence length doubles the total compute.
False in general. The dominant term quadruples when you double (walk twice as far right on the red parabola in Figure 1); only the projection term doubles. For long sequences the quadratic term wins, so cost roughly quadruples.
For very short sequences (), the linear-projection term dominates, not attention.
True. When is small you are left of the crossover in Figure 1, where the black line sits above the red curve, so most work is in the Q/K/V/output projections, not the score matrix.
Doubling the batch size leaves the total cost unchanged.
False. Every sequence in the batch runs the full pipeline independently, so both time and memory scale linearly with : the true cost is . Batching improves hardware utilization, not the per-sequence cost.
The memory cost disappears at inference time.
Only under specific conditions. With batch size 1 and streaming/flash-style kernels that never materialize the full matrix, peak working memory can fall toward ; but any framework that caches the whole score matrix, or a batch of size , still holds , and training always must store it for backprop.
Self-attention connects any two tokens in a single step, unlike an RNN.
True. Attention has a depth-1 path between every pair of tokens — that is why the full grid in Figure 2 exists — whereas an RNN needs up to sequential steps to relay information across the sequence.
Sparse attention reduces the asymptotic time below .
True. Patterns like fill only a structured subset of the Figure 2 grid, trading global exactness for sub-quadratic cost — see 4.3.2-Sparse-attention-patterns.
A learned relative-position bias table is "free" because it is just an addition to the scores.
False. A relative/pairwise positional bias adds one bias term to every one of the scores, an extra compute and, for learned bias tables, extra memory of the same shape — it rides on top of the same quadratic bottleneck rather than removing it. See 5.2.3-Positional-encoding-scaling.
Linear attention removes the quadratic term entirely and is exact.
Half-true — sub-quadratic, but not exact. Full attention computes : forming first costs . Linear attention replaces softmax with a kernel feature map so the products can be reassociated as ; now is a small matrix built in , dodging the step. But softmax is non-linear and cannot be factored this way, so the kernel is an approximation of it — same shape of output, different function.

Spot the error

"Attention FLOPs are , because we do work per head across heads."
Error: double counting . Each head does work, and . The heads together give , not . The head factor cancels the split dimension.
"The output projection is free, so total projection cost is ."
Error: is not free. Q, K, V and the output projection each cost , giving . Forgetting undercounts the linear term by a quarter.
"Memory is because we store the score matrix and it depends on ."
Error: the stored matrix is , not . Scores are a single number per token pair (one square per cell in Figure 2), so memory is per sequence — total with a batch — plus for the Q/K/V/output activations.
"Since , we can just write total time as and drop ."
Error: dropping is wrong when . Left of the crossover in Figure 1 the term dominates, so both terms must be kept: .
"An RNN uses less memory () and less time, so it is strictly better for long sequences."
Error: better on memory, not on usable long-range connection. RNNs need sequential steps and suffer vanishing gradients over long distances — attention's cost buys instant global reach, which the RNN cannot match.
"The softmax step is the quadratic bottleneck."
Error: softmax is but cheap per element. The quadratic shape comes from building the score matrix (the step); softmax merely normalizes those already-computed scores.
"Adding a relative-position bias makes attention asymptotically slower."
Error: it is the same order. The bias adds additions on top of the score computation, so it inflates the constant factor and memory but does not change the growth shape.

Why questions

Why is the score matrix inherently quadratic in ?
Because every token's query must be compared against every token's key to decide who to attend to, producing all pairwise scores (the full grid in Figure 2) — there is no way to get a full attention weight without the pair existing.
Why does using more heads not change asymptotic complexity?
More heads reshape the same -dimensional space into blocks of size ; the total arithmetic is conserved because the per-head savings () exactly offset the head count. See 4.1.7-Multi-head-attention.
Why can Q, K, V be split across heads but is still applied once over the full ?
Because Q/K/V are inputs to independent attention computations, so they are literally sliced into blocks of width that each head consumes separately. acts after the heads are concatenated back into one -vector — there is only one full-width vector left to mix, so there is nothing to slice and it costs exactly once.
Why does attention overtake linear projections only at large ?
Projections grow like (linear in , the black line in Figure 1) while attention grows like (quadratic, the red curve); the ratio is , so attention wins once — exactly the crossover marked in the figure.
Why does the batch factor multiply cost but never appear in shorthand?
Each of the sequences runs the identical pipeline, so is a clean linear multiplier on both compute and memory (); we drop it when comparing the shape of two architectures because it multiplies them equally, but you must restore it when sizing a real GPU.
Why does reassociating into make linear attention cheap?
Matrix multiplication is associative, so the result is unchanged, but collapses the axis first into a tiny summary — you never build the grid of Figure 2, turning into . This only works once softmax is dropped, because softmax sits between and and blocks the reordering.
Why can streaming (row-by-row) attention cut peak memory from to at inference?
Process the score matrix of Figure 2 one query row at a time: for query compute its scores against all keys, softmax that single row, immediately multiply by to get that token's output, then discard the row before starting row . You only ever hold one length- row plus the length- running output, so working memory is overall, never the full grid — this is the core idea behind flash/streaming attention.
Why is gradient checkpointing important for long-context training?
The activation matrices across all layers dominate memory; checkpointing recomputes them in the backward pass instead of storing them, trading extra compute for much lower peak memory. See 4.5.1-Memory-optimization-techniques.
Why does the scaling inside softmax not affect the complexity?
It is a single scalar division applied per score — an operation with tiny constant — so it changes numerical stability, not the asymptotic cost.
Why can't we naively feed an entire novel into a standard transformer?
A novel is tens of thousands of tokens; the Figure 2 grid becomes enormous (e.g. billion entries per head per layer), exploding memory and compute past hardware limits — hence efficient-attention research exists.

Edge cases

What happens to the cost ratio when exactly?
Attention and projection terms are asymptotically balanced ( when ) — this is precisely the crossover mark in Figure 1; neither dominates, and constant factors (the in ) decide which is larger in practice.
What is the complexity when (a single token)?
Attention degenerates: the score grid of Figure 2 is a single square, softmax is trivial (weight ), and cost collapses to the projections — the quadratic term vanishes.
How does causal (masked) attention change the count?
In autoregressive models each token attends only to itself and earlier tokens — the red lower triangle in Figure 2, about scores. The constant halves but the asymptotic cost stays ; masking saves a factor of 2, not an order.
What if all keys are identical, so every score is equal?
The softmax outputs a uniform distribution and the output becomes the plain average of value vectors; complexity is unchanged — cost depends on shapes, not on the values inside the matrices.
How does adding a relative-position bias change the picture?
It adds an bias term (and, for a learned table, extra memory) on top of the score matrix — the same quadratic shape, a larger constant. See 5.2.3-Positional-encoding-scaling.
In the limit with fixed, which term governs everything?
The attention term (the red parabola in Figure 1), since it grows without bound faster than the linear term; asymptotically the projection cost becomes a rounding error.
What happens to memory if you compute attention but never store scores for backprop (inference only)?
You can process row-by-row and discard each row's scores after use (see the streaming Why-question), so peak working memory can drop toward per sequence.
If (one dimension per head, ), does the model get cheaper?
No — attention is still , unchanged; you have simply fragmented the representation as far as it can go without altering asymptotic cost.
Recall One-line summary to lock in

The true total is : the first term is the unavoidable all-pairs score grid, the second is the four full-width projections — multiplies everything, and neither term ever carries a factor of .