AI / ML Theory
Chapter 6 · 22 min

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 TT and width dd:

#FLOPsattention∼T2d,#FLOPsFFN∼Td2.\#\text{FLOPs}_\text{attention} \sim T^2 d, \qquad \#\text{FLOPs}_\text{FFN} \sim T d^2.

The two costs cross at T∼dT \sim d. For pretraining-length contexts T=2,048,4,096T = 2{,}048, 4{,}096 and modern widths d=4096,8192d = 4096, 8192, FFN dominates compute. For long-context inference at T=32,768,128,000,1,000,000T = 32{,}768, 128{,}000, 1{,}000{,}000, 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:

  • TT = sequence length (number of tokens in context).
  • dd = residual-stream width (dmodeld_\text{model}).
  • hh = number of attention heads; dh=d/hd_h = d / h is the head dimension.
  • dff=4dd_\text{ff} = 4 d = FFN inner width.
  • LL = number of blocks.
  • One "FLOP" = one multiply-add (i.e. we count 22 scalar ops per FMA, the standard convention).

A matmul of two matrices of shape (A,B)(A, B) and (B,C)(B, C) costs 2⋅A⋅B⋅C2 \cdot A \cdot B \cdot C FLOPs.

2.1 Attention sub-layer FLOPs

The attention sub-layer of one block does (see 6.4 §3.1):

| Op | Shape | FLOPs | |---|---|---| | Project XX to Q,K,VQ, K, V | (T,d)⋅(d,d)(T, d) \cdot (d, d), three times | 6Td26 T d^2 | | Score S=QK⊤S = Q K^\top (per head) | h⋅(T,dh)⋅(dh,T)h \cdot (T, d_h) \cdot (d_h, T) | 2T2d2 T^2 d | | Apply SVS V (per head) | h⋅(T,T)⋅(T,dh)h \cdot (T, T) \cdot (T, d_h) | 2T2d2 T^2 d | | Output projection WOW_O | (T,d)⋅(d,d)(T, d) \cdot (d, d) | 2Td22 T d^2 | | Total attention | |  8Td2+4T2d \boxed{\ 8 T d^2 + 4 T^2 d \ } |

The 8Td28 T d^2 term is the four projections (Q,K,V,OQ, K, V, O). The 4T2d4 T^2 d term is the score-and-mix (QK⊤Q K^\top + SVS V). RoPE, masking, and softmax are O(T2)O(T^2) each and we drop them.

2.2 FFN sub-layer FLOPs

The FFN (6.8 §5) is two matmuls with dff=4dd_\text{ff} = 4 d:

| Op | Shape | FLOPs | |---|---|---| | W1W_1: (T,d)⋅(d,dff)(T, d) \cdot (d, d_\text{ff}) | (T,d)⋅(d,4d)(T, d) \cdot (d, 4d) | 8Td28 T d^2 | | W2W_2: (T,dff)⋅(dff,d)(T, d_\text{ff}) \cdot (d_\text{ff}, d) | (T,4d)⋅(4d,d)(T, 4d) \cdot (4d, d) | 8Td28 T d^2 | | Total FFN | |  16Td2 \boxed{\ 16 T d^2 \ } |

2.3 Per-block total

Summing:

 #FLOPs per block=8Td2+4T2d⏟attention+16Td2⏟FFN=24Td2+4T2d. \boxed{\ \#\text{FLOPs per block} = \underbrace{8 T d^2 + 4 T^2 d}_{\text{attention}} + \underbrace{16 T d^2}_{\text{FFN}} = 24 T d^2 + 4 T^2 d. \ }

For LL blocks, multiply by LL. Drop biases, norms, and the embedding/output (those are Θ(Ld)\Theta(L d) or Θ(VTd)\Theta(V T d); the latter is comparable in magnitude only at very small models, e.g. GPT-2-small).


3. The crossover at T=4dT = 4 d

Setting attention compute equal to FFN compute:

8Td2+4T2d  =  16Td2    ⟺    4Td  =  8d2    ⟺     T=2d. 8 T d^2 + 4 T^2 d \;=\; 16 T d^2 \;\;\Longleftrightarrow\;\; 4 T d \;=\; 8 d^2 \;\;\Longleftrightarrow\;\; \boxed{\ T = 2 d. \ }

(If we drop the 8Td28 T d^2 projection cost of attention and only count the score-mix 4T2d4 T^2 d, the crossover is T=4dT = 4 d; depending on what one chooses to "attribute" to attention, the crossover is in the band [2d,4d][2d, 4d]. Most authors use T≈4dT \approx 4d.)

For LLaMA-7B (d=4096d = 4096) this is T∈[8192,16384]T \in [8192, 16384]. So:

  • Pretraining at T=2048T = 2048 or T=4096T = 4096 → well below the crossover → FFN dominates.
  • Long-context inference at T=32768T = 32768 or T=128000T = 128000 → 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

 KV-cache size=2⋅L⋅h⋅dh⋅T⋅batch⋅(bytes/elem). \boxed{\ \text{KV-cache size} = 2 \cdot L \cdot h \cdot d_h \cdot T \cdot \text{batch} \cdot (\text{bytes/elem}). \ }

The factor 22 is for K and V together. For LLaMA-7B (one batch, fp16):

KV-cache=2⋅32⋅32⋅128⋅T⋅2 bytes=0.524 T MB.\text{KV-cache} = 2 \cdot 32 \cdot 32 \cdot 128 \cdot T \cdot 2 \text{ bytes} = 0.524\, T \text{ MB}.

At T=4096T = 4096: ≈2\approx 2 GB. At T=32,768T = 32{,}768: ≈17\approx 17 GB. At T=128,000T = 128{,}000: ≈67\approx 67 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 h⋅dhh \cdot d_h 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: T⋅dT \cdot d floats.
  • The attention scores: h⋅T⋅Th \cdot T \cdot T floats — this is the T2T^2 memory cost.
  • The FFN hidden: T⋅dff=T⋅4dT \cdot d_\text{ff} = T \cdot 4d floats.

For long context, hT2≫Tdffh T^2 \gg T d_\text{ff}. A 32-head, T=8192T = 8192 model stores 32⋅81922=2×10932 \cdot 8192^2 = 2 \times 10^9 scores per block, in fp16: 44 GB per block, 128128 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 TT (T≪4dT \ll 4d) | Long TT (T≫4dT \gg 4d) | |---|---|---| | Compute | FFN dominates (16Td216 T d^2) | Attention dominates (4T2d4 T^2 d) | | Memory | FFN hidden (4Td4 T d) | Attention scores (T2T^2) |

Most architectural choices in modern LLMs map onto one cell of this grid.


5. Worked example: LLaMA-7B

Numbers for one forward pass:

  • d=4096,L=32,h=32,dh=128d = 4096, L = 32, h = 32, d_h = 128.
  • dff=4d=16384d_\text{ff} = 4d = 16384 (LLaMA actually uses 23⋅4d=10922\frac{2}{3} \cdot 4d = 10922 rounded to 1100811008 for SwiGLU; we'll use 4d4d here for clarity).

5.1 T=2048T = 2048 (pretraining context)

Attn FLOPs/block=8⋅2048⋅40962+4⋅20482⋅4096=2.75×1011+6.87×1010=3.43×1011.FFN FLOPs/block=16⋅2048⋅40962=5.50×1011.Total/block=8.93×1011.Total/forward=32⋅8.93×1011=2.86×1013.\begin{aligned} \text{Attn FLOPs/block} &= 8 \cdot 2048 \cdot 4096^2 + 4 \cdot 2048^2 \cdot 4096 \\ &= 2.75 \times 10^{11} + 6.87 \times 10^{10} = 3.43 \times 10^{11}. \\ \text{FFN FLOPs/block} &= 16 \cdot 2048 \cdot 4096^2 = 5.50 \times 10^{11}. \\ \text{Total/block} &= 8.93 \times 10^{11}. \\ \text{Total/forward} &= 32 \cdot 8.93 \times 10^{11} = 2.86 \times 10^{13}. \end{aligned}

FFN/attention ratio ≈1.6\approx 1.6; FFN dominates (matches §3 crossover prediction at T<4dT < 4d).

5.2 T=32768T = 32768 (long-context inference)

Attn FLOPs/block=8⋅32768⋅40962+4⋅327682⋅4096=4.40×1012+1.76×1013=2.20×1013.FFN FLOPs/block=16⋅32768⋅40962=8.80×1012.\begin{aligned} \text{Attn FLOPs/block} &= 8 \cdot 32768 \cdot 4096^2 + 4 \cdot 32768^2 \cdot 4096 \\ &= 4.40 \times 10^{12} + 1.76 \times 10^{13} = 2.20 \times 10^{13}. \\ \text{FFN FLOPs/block} &= 16 \cdot 32768 \cdot 4096^2 = 8.80 \times 10^{12}. \end{aligned}

Attention/FFN ratio ≈2.5\approx 2.5; attention dominates — by a wide margin, and growing as T2T^2.

This is the structural reason "long context is expensive". The cost is not abstract; it follows directly from the T2dT^2 d vs Td2T d^2 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 Tgenerated=1T_\text{generated} = 1 but TcontextT_\text{context} is the cache length. The FLOPs become:

  • Prefill (one forward over the prompt of length TpT_p): the cost we just derived, scaling as Tpd2T_p d^2 + Tp2dT_p^2 d.
  • Per generated token: one row of QQ attends to all TT cached K, V; the FFN runs on one position. Cost is ∼8d2+4Td+16d2\sim 8 d^2 + 4 T d + 16 d^2 FLOPs per token — linear in TT at the attention term.

Generating NN tokens, total cost ∼N(24d2+4Td)\sim N (24 d^2 + 4 T d). The cumulative cost scales as N⋅TN \cdot T (attention term) — still quadratic in combined sequence length, but distributed across NN 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:

  1. Per-block FLOPs: 24Td2+4T2d24 T d^2 + 4 T^2 d. Roughly: 24Td224 T d^2 for FFN-and-projections, 4T2d4 T^2 d for the score-and-mix.
  2. Crossover: at T=2dT = 2d to 4d4d, the two terms are equal. Below: FFN dominates. Above: attention dominates.
  3. KV-cache memory: 2LhdhT2 L h d_h T elements per batch. Linear in TT, 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 T2dT^2 d term back down to TdT d or Tlog⁡TT \log T, while preserving model quality.

Self-test

(a) Re-derive the per-block FLOP count 24Td2+4T2d24 T d^2 + 4 T^2 d. Identify which matrix multiplications contribute the 24Td224 T d^2 term and which contribute the 4T2d4 T^2 d term.

(b) For GPT-2 small (d=768,L=12,T=1024d = 768, L = 12, T = 1024), compute the forward-pass FLOPs and identify whether attention or FFN dominates. Repeat at T=8192T = 8192 for the same model.

(c) The KV-cache size for LLaMA-7B at T=4096T = 4096 in fp16 is about 22 GB. Verify this number from 2LhdhT⋅22 L h d_h T \cdot 2. Now compute the KV-cache size for LLaMA-70B at T=32768T = 32768 in fp16, given L=80,h=64,dh=128L = 80, h = 64, d_h = 128.

(d) Argue why the activation memory of the attention sub-layer scales as hT2h T^2 (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 TT (cache length). Why is this linear in TT rather than quadratic? What is the cumulative cost of generating NN tokens?