All courses

Quadratic cost of attention in context length

Show that the score matrix costs O(T²·d_head) compute and O(T²) memory per head, adding about 4·L·T·d FLOPs per token on top of 2N. Estimate the context length at which attention FLOPs rival the parameter FLOPs.

Builds on: FLOPs per token: 2N forward, 6N training

▶ Watch this lesson Start the whole course

What the animation says

The missing cost

Our rule so far: a forward pass costs about two N FLOPs per token. That counts each token passing once through the weight matrices. It's the same whether the prompt is short or long. Yet long prompts cost more per token, and memory climbs fast. The extra comes from attention, where each new token looks back at every earlier one. So double the context length. What happens to attention work for one token?

Every query meets every key

It doubles. Each query takes a dot product with every key, then mixes that many value vectors. Stack all the queries and you get a table: one score for every query and key pair. That's T by T. With the causal mask, a token only needs keys up to itself. But the standard computation fills the whole table first, then masks the future. So every row pays for all T keys. Double T and the table holds four times the cells. Tap the part that's computed, then thrown away.

Counting the two matmuls

Now count it for one head. Q and K are each T rows by d-head columns. Q times K transposed builds the T by T score table. That costs two T squared d-head FLOPs. Then the attention weights A times V costs the same again: two T squared d-head. Add up all heads and the d-heads sum to d. Times L layers: four L T squared d for the whole sequence. Divide by T tokens: four L T d per token. The Q, K, V and output projections are already inside two N.

When attention rivals the weights

Compare that to the weights. With N about twelve L d squared, two N is about twenty-four L d squared. Divide four L T d by twenty-four L d squared. L cancels, and one d cancels. What's left is T over six d. Attention matches the weights when T is six times d. Take d of four thousand ninety-six. Crossover lands at 24,576 tokens. At four thousand ninety-six tokens it's one sixth, about seventeen percent extra. Same model, now at 8,192 tokens. What's the ratio?

Remember: T/(6d)

One third. Per token, the ratio grows linearly with length. This function computes both costs. Run it across lengths: point oh eight, point three three, one, then four. At a hundred thousand tokens, attention does four times the weight work. Memory bites too. At 32,768 tokens, one head's table holds about a billion numbers. At two bytes each that's 2.1 gigabytes, per head, per layer, if stored. Remember: the extra over two N is T over six d. Small when short, equal at six d, dominant beyond.

Why do long prompts cost more per token?

The $2N$ rule says a forward pass costs about $2N$ FLOPs per token, but it deliberately ignored the context. In practice, long prompts cost more per token, and memory grows sharply at long context. Where does the extra cost come from? How fast does it grow with $T$? And at what length does it stop being a rounding error?

Every query meets every key

The $2N$ rule counts each token passing once through the weight matrices. That cost is fixed no matter how long the text is. Attention is different: each query takes a dot product with the keys, then mixes that many value vectors. The causal mask means token $t$ only needs $t$ keys. But the standard computation builds the full $T\times T$ score table and then masks the future half, so each token pays for all $T$ keys. Per-token cost therefore grows linearly in $T$, and a whole sequence costs about $T^2$: one score per (query, key) pair, stored in a $T\times T$ table per head.

Counting the two T×T matmuls

Per head, with $Q,K,V\in\mathbb{R}^{T\times d_{head}}$: - Scores $QK^\top$: $(T\times d_{head})(d_{head}\times T)$ costs $2T^2d_{head}$ FLOPs and produces a $T\times T$ matrix, so $O(T^2)$ memory. - $AV$: $(T\times T)(T\times d_{head})$ costs $2T^2d_{head}$. Summing over $h$ heads ($h\,d_{head}=d$) and $L$ blocks gives $4LT^2d$ per sequence, or $4LTd$ per token. The projections $W_Q,W_K,W_V,W_O$ are already counted in $2N$.

When attention rivals the weights

Take $d=4096$, $L=32$. With $N\approx12Ld^2$, we get $2N\approx24Ld^2$. Ratio: $\frac{4LTd}{24Ld^2}=\frac{T}{6d}$, and $L$ cancels. - Crossover: $T=6d=24{,}576$ tokens. - At $T=4096$: the ratio is $1/6$, so attention adds about 17%. - Memory at $T=32{,}768$: one head's $A$ has $T^2\approx1.07\times10^9$ entries. At 2 bytes per number (a 16-bit format such as bf16), that is about 2.1 GB per head, per layer, if stored.

Attention vs parameter FLOPs by length

The ratio grows linearly with context length and reaches 1 at $T=6d$.
def flops_per_token(L, d, T):
    N = 12 * L * d**2        # non-embedding params
    param = 2 * N            # token times weight matrices
    attn = 4 * L * T * d     # QK^T scores + A@V, all heads
    return param, attn

for T in [2048, 8192, 24576, 100_000]:
    p, a = flops_per_token(L=32, d=4096, T=T)
    print(T, f"attn/param = {a/p:.2f}")
# 0.08, 0.33, 1.00, 4.07

Remember: T/(6d)

Per head, attention costs $4T^2d_{head}$ FLOPs and stores a $T\times T$ table ($T^2$ entries). That adds about $4LTd$ FLOPs per token on top of $2N$. Relative to $2N\approx24Ld^2$, the extra is $T/(6d)$: small for short contexts, equal at $T\approx6d$, and dominant beyond that.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.