6.12 — Compute and memory: O(T²d) attention, O(Td²) FFN
Goal: Count FLOPs and memory cost of one Transformer block as a function of (T, d, L); identify the attention-vs-FFN crossover at T ≈ 4d; understand why attention dominates long-context cost and FFN dominates short-context cost; quantify activation memory for training.
1. Why this session exists
Once you can write the forward pass (6.11) you owe yourself an answer to "how much does it cost to run it?" The cost has two halves — attention and FFN — that scale differently with sequence length and width :
The two costs cross at . For pretraining-length contexts and modern widths , FFN dominates compute. For long-context inference at , attention dominates. This single crossover dictates almost every architectural choice in modern LLMs: from sliding-window attention (6.13), to KV cache (6.14), to FlashAttention (Cap 10.5), to GQA/MQA (Cap 8.3) — they all chase one or the other of these terms.
This session counts the FLOPs precisely and counts the memory both for inference (KV cache) and for training (activation memory). After you have the numbers in hand, the architectural variants of Chapter 8 and Chapter 10 become straightforward optimisations of one of the two terms.
2. The two regimes, derived
Recall one Transformer block has two sub-layers, attention and FFN, each preceded by a LayerNorm. We will count matrix multiplications (matmuls) — they dominate every other cost (LN, softmax, biases, activations).
Conventions, fixed throughout:
- = sequence length (number of tokens in context).
- = residual-stream width ().
- = number of attention heads; is the head dimension.
- = FFN inner width.
- = number of blocks.
- One "FLOP" = one multiply-add (i.e. we count scalar ops per FMA, the standard convention).
A matmul of two matrices of shape and costs FLOPs.
2.1 Attention sub-layer FLOPs
The attention sub-layer of one block does (see 6.4 §3.1):
| Op | Shape | FLOPs | |---|---|---| | Project to | , three times | | | Score (per head) | | | | Apply (per head) | | | | Output projection | | | | Total attention | | |
The term is the four projections (). The term is the score-and-mix ( + ). RoPE, masking, and softmax are each and we drop them.
2.2 FFN sub-layer FLOPs
The FFN (6.8 §5) is two matmuls with :
| Op | Shape | FLOPs | |---|---|---| | : | | | | : | | | | Total FFN | | |
2.3 Per-block total
Summing:
For blocks, multiply by . Drop biases, norms, and the embedding/output (those are or ; the latter is comparable in magnitude only at very small models, e.g. GPT-2-small).
3. The crossover at
Setting attention compute equal to FFN compute:
(If we drop the projection cost of attention and only count the score-mix , the crossover is ; depending on what one chooses to "attribute" to attention, the crossover is in the band . Most authors use .)
For LLaMA-7B () this is . So:
- Pretraining at or → well below the crossover → FFN dominates.
- Long-context inference at or → well above the crossover → attention dominates.
This single inequality dictates where every "make Transformers efficient" effort focuses:
- Short context. Optimise FFN: SwiGLU (Cap 8.4) makes it expressive; MoE (Cap 8.6) makes it conditional.
- Long context. Optimise attention: sliding window (6.13), FlashAttention I/O (Cap 10.5), GQA/MQA (Cap 8.3), KV cache (6.14), linear attention (Mamba, Cap 8.7).
4. Memory: activations and KV cache
FLOPs are time; memory is space. Both bottleneck Transformer scaling, often before FLOPs do.
4.1 KV cache (inference)
At autoregressive inference (generating one token at a time), the keys and values of all previous tokens do not change. We cache them to avoid recomputation; the cache stores
The factor is for K and V together. For LLaMA-7B (one batch, fp16):
At : GB. At : GB. At : GB — larger than a single H100's 80 GB. This is why GQA (Cap 8.3) — sharing K, V heads across multiple Q heads — and MLA (Cap 8.5) — low-rank K, V compression — exist: shrinking the factor in the KV-cache formula.
For a full discussion of the KV cache see 6.14.
4.2 Activation memory (training)
During training we must store every intermediate activation for the backward pass (autodiff, 2.11). Per token, per block, the largest activations are:
- The output of each sub-layer: floats.
- The attention scores: floats — this is the memory cost.
- The FFN hidden: floats.
For long context, . A 32-head, model stores scores per block, in fp16: GB per block, GB across 32 blocks. This is the primary reason long-context training is hard, and the primary reason for FlashAttention (Cap 10.5), which recomputes the scores on-the-fly instead of materialising them.
4.3 The 4-quadrant cost grid
Putting it together:
| | Short () | Long () | |---|---|---| | Compute | FFN dominates () | Attention dominates () | | Memory | FFN hidden () | Attention scores () |
Most architectural choices in modern LLMs map onto one cell of this grid.
5. Worked example: LLaMA-7B
Numbers for one forward pass:
- .
- (LLaMA actually uses rounded to for SwiGLU; we'll use here for clarity).
5.1 (pretraining context)
FFN/attention ratio ; FFN dominates (matches §3 crossover prediction at ).
5.2 (long-context inference)
Attention/FFN ratio ; attention dominates — by a wide margin, and growing as .
This is the structural reason "long context is expensive". The cost is not abstract; it follows directly from the vs counting we just did.
6. Generation cost vs prefill cost
A subtlety specific to LLMs: during generation, the model processes one token at a time, with all previous keys/values cached. Per generated token, effective but is the cache length. The FLOPs become:
- Prefill (one forward over the prompt of length ): the cost we just derived, scaling as + .
- Per generated token: one row of attends to all cached K, V; the FFN runs on one position. Cost is FLOPs per token — linear in at the attention term.
Generating tokens, total cost . The cumulative cost scales as (attention term) — still quadratic in combined sequence length, but distributed across separate calls rather than one big one. This is what makes the KV cache an enormous practical win for inference; see 6.14.
7. Putting it together
Three numbers to remember:
- Per-block FLOPs: . Roughly: for FFN-and-projections, for the score-and-mix.
- Crossover: at to , the two terms are equal. Below: FFN dominates. Above: attention dominates.
- KV-cache memory: elements per batch. Linear in , quadratic in model depth × width product. The dominant memory of long-context inference.
Next session turns to the long-context regime — what architectural variants exist to bend the term back down to or , while preserving model quality.
(a) Re-derive the per-block FLOP count . Identify which matrix multiplications contribute the term and which contribute the term.
(b) For GPT-2 small (), compute the forward-pass FLOPs and identify whether attention or FFN dominates. Repeat at for the same model.
(c) The KV-cache size for LLaMA-7B at in fp16 is about GB. Verify this number from . Now compute the KV-cache size for LLaMA-70B at in fp16, given .
(d) Argue why the activation memory of the attention sub-layer scales as (per block) during training, and why this becomes the dominant memory cost at long context. Connect this to the FlashAttention motivation in Cap 10.5.
(e) Per generated token (after prefill), state the FLOPs as a function of (cache length). Why is this linear in rather than quadratic? What is the cumulative cost of generating tokens?