Lesson 5: Head variants and what attention really costs
Module 2 · Lesson 5 · About 55 minutes · Needs: Module 2, Lessons 1 to 3 (naive_attention,MultiHeadAttention, loading GPT-2); shared blocks 1 and 15 to 17
The situation
Sol 406 at Aurora Station. Tariq wants base to read whole transmissions from Earth, 4,096 characters each, not 128. Hana Aoki, the Compute Officer, owns the small CPU servers that would run it. "What does attention cost on my machines at that length, in memory and in time? And Lesson 3 ended by saying modern models keep fewer key and value heads. Should we?"
This lesson measures both on the base shape (4 layers, 4 heads of 32, width 128) and adds grouped heads, cross-attention and a sliding window to tinyformer/attention.py.
A real case, first
In "Fast Transformer Decoding: One Write-Head is All You Need" (Google, 2019, arXiv:1911.02150), Noam Shazeer noticed that generating text one token at a time was slow "due to the memory-bandwidth cost of repeatedly loading the large 'keys' and 'values' tensors". His fix, multi-query attention, keeps every query head but shares one key head and one value head between them.
On WMT14 English to German translation, with 8 heads of 128 on one TPUv2, the decoder took 46 microseconds per token with ordinary heads and 3.8 with shared ones. Training time barely moved (13.2 against 13.0). Dev BLEU went from 26.7 to 26.5: "only minor quality degradation". The arithmetic barely changed; the memory read did. Count what is stored and read, not only what is multiplied.
What you will be able to do
- Size the KV cache and shrink it with grouped, multi-query or latent heads.
- Build cross-attention and a sliding-window mask.
- Predict attention's memory and FLOPs, and check both in code.
- Measure attention time against length and against the feed-forward block.
- Read a published
config.jsonfor its attention cost.
1. Why the cache shapes head design (Essential)
A station server spends its time generating, and generation is limited by memory. The head layout changes that. Paste the torch setup cell, shared block 1 and Lesson 2's naive_attention.
import torch
DEVICE = "cuda" if torch.cuda.is_available() else "cpu" # every lesson runs on "cpu"; a GPU is optional
torch.manual_seed(11) # the course seed (see course-guide/06)
print("torch", torch.__version__, "| device", DEVICE, "| CPU threads", torch.get_num_threads())Code walkthrough
- The course's torch setup cell. It printed
torch 2.14.1 | device cpu | CPU threads 5on the author's Mac.
import random
import torch
COURSE_DATE = "2026-10-09" # versions, model names and prices checked on this day
SEED = 11 # every generator in the course starts from this seed
SNAPSHOT_SOL = 400 # the corpus is the station record up to sol 399
def set_seed(seed=SEED):
"""Seed Python and PyTorch so a cell gives the same numbers every run."""
random.seed(seed)
torch.manual_seed(seed)
set_seed()
print("torch", torch.__version__, "| threads", torch.get_num_threads())Code walkthrough
- Shared block 1, as written:
SEED = 11andset_seed().
import math
import torch.nn.functional as F
def naive_attention(q, k, v, mask=None, return_weights=False, scale=None):
"""Lesson 2's naive_attention: scale=None divides by sqrt(d_head); any number multiplies instead."""
scores = q @ k.transpose(-2, -1)
scores = scores * (1 / math.sqrt(q.shape[-1]) if scale is None else scale)
if mask is not None:
scores = scores.masked_fill(~mask, float("-inf"))
weights = scores.softmax(dim=-1)
out = weights @ v
return (out, weights) if return_weights else outCode walkthrough
- Lesson 2's function, unchanged.
Now paste shared blocks 15 to 17. Block 16 already has the n_kv_heads switch this section explains.
import math
from dataclasses import dataclass
import torch.nn as nn
import torch.nn.functional as F
@dataclass
class ModelConfig:
vocab_size: int = 69
context: int = 128
d_model: int = 128
n_layers: int = 4
n_heads: int = 4
n_kv_heads: int = 4 # fewer than n_heads gives grouped-query attention; 1 gives multi-query
d_ff: int = 344 # hidden width of the feed-forward network
position: str = "rope" # "rope", "learned" or "none"
norm: str = "rms" # "rms" or "layer"
ffn: str = "swiglu" # "swiglu" or "gelu"
tie_embeddings: bool = True
def make_norm(cfg):
return nn.RMSNorm(cfg.d_model) if cfg.norm == "rms" else nn.LayerNorm(cfg.d_model)
def rope(x, base=10000.0):
"""Rotate pairs of features by an angle that grows with position. x: (B, heads, T, head_dim)."""
T, d = x.shape[-2], x.shape[-1]
freqs = base ** (-torch.arange(0, d, 2, device=x.device).float() / d)
angles = torch.arange(T, device=x.device).float()[:, None] * freqs[None, :]
cos, sin = angles.cos().to(x.dtype), angles.sin().to(x.dtype) # keep 16-bit inputs 16-bit
x1, x2 = x[..., 0::2], x[..., 1::2]
return torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1).flatten(-2)Code walkthrough
- Shared block 15, as written:
ModelConfigholds thebaseshape.
class Attention(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg, self.hd = cfg, cfg.d_model // cfg.n_heads
self.q = nn.Linear(cfg.d_model, cfg.n_heads * self.hd, bias=False)
self.kv = nn.Linear(cfg.d_model, 2 * cfg.n_kv_heads * self.hd, bias=False)
self.out = nn.Linear(cfg.n_heads * self.hd, cfg.d_model, bias=False)
def forward(self, x):
B, T, _ = x.shape
q = self.q(x).view(B, T, self.cfg.n_heads, self.hd).transpose(1, 2)
k, v = self.kv(x).view(B, T, 2, self.cfg.n_kv_heads, self.hd).permute(2, 0, 3, 1, 4)
if self.cfg.position == "rope":
q, k = rope(q), rope(k)
repeat = self.cfg.n_heads // self.cfg.n_kv_heads # share each key/value head
k, v = k.repeat_interleave(repeat, dim=1), v.repeat_interleave(repeat, dim=1)
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return self.out(y.transpose(1, 2).reshape(B, T, -1))Code walkthrough
- Shared block 16, as written: keys and values for only
n_kv_headsheads, lent to several query heads byrepeat_interleave.
class FeedForward(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
self.up = nn.Linear(cfg.d_model, cfg.d_ff * (2 if cfg.ffn == "swiglu" else 1), bias=False)
self.down = nn.Linear(cfg.d_ff, cfg.d_model, bias=False)
def forward(self, x):
if self.cfg.ffn == "swiglu":
gate, value = self.up(x).chunk(2, dim=-1)
return self.down(F.silu(gate) * value)
return self.down(F.gelu(self.up(x)))
class Block(nn.Module):
def __init__(self, cfg):
super().__init__()
self.norm1, self.attn = make_norm(cfg), Attention(cfg)
self.norm2, self.ffn = make_norm(cfg), FeedForward(cfg)
def forward(self, x): # pre-norm: normalise, transform, add back to the stream
x = x + self.attn(self.norm1(x))
return x + self.ffn(self.norm2(x))Code walkthrough
- Shared block 17, as written. Section 7 times
FeedForward.
When base writes a reply, each new token needs the keys and values of every earlier token. Rather than recompute them every step, generators store them: the KV cache. Queries are used once; keys and values are kept.
So the cache grows with layers, key/value heads, head width and tokens, and query heads do not appear in it at all.
def kv_cache_bytes(n_layers, n_kv_heads, d_head, tokens, batch=1, bytes_per_number=4):
"""Keys and values kept for every layer, key/value head and cached token."""
return 2 * n_layers * n_kv_heads * d_head * tokens * batch * bytes_per_number
cfg = ModelConfig() # base: 4 layers, 4 heads of 32
d_head = cfg.d_model // cfg.n_heads
print(f"{'key/value heads':>16} {'per token':>10} {'one 4,096-char log':>19} {'32 logs at once':>16}")
for n_kv, name in [(4, "MHA"), (2, "GQA"), (1, "MQA")]:
per_token = kv_cache_bytes(cfg.n_layers, n_kv, d_head, 1)
one = kv_cache_bytes(cfg.n_layers, n_kv, d_head, 4096) / 2**20
many = kv_cache_bytes(cfg.n_layers, n_kv, d_head, 4096, batch=32) / 2**20
print(f"{name + ' ' + str(n_kv):>16} {per_token:>8,} B {one:>16.1f} MiB {many:>13.1f} MiB")
weights = sum(p.numel() for p in Attention(cfg).parameters()) * cfg.n_layers * 4 / 2**20
print(f"for scale: all attention weights in base are {weights:.2f} MiB")Code walkthrough
kv_cache_bytesis the formula in the figure: the 2 counts keys and values, and float32 numbers take 4 bytes.- The loop prints three head layouts, for one transmission and for 32 served together. The last line counts all attention weights.
The layouts have names. Multi-head attention (MHA) gives each query head its own key/value head. Multi-query attention (MQA) shares one across all of them. Grouped-query attention (GQA), from Ainslie et al. (Google, 2023), sits between: each group of query heads shares one.
At 4,096 characters, one transmission caches 16 MiB with MHA, 8 with GQA and 4 with MQA (arithmetic). Thirty-two at once need 512 MiB, against 1.00 MiB of attention weights. In generation the cache, not the model, fills memory.
Now the lab's version, built on naive_attention so you can see every step.
class GroupedQueryAttention(nn.Module):
"""n_heads query heads share n_kv_heads key/value heads. n_kv_heads = n_heads is plain MHA, 1 is MQA."""
def __init__(self, d_model, n_heads, n_kv_heads):
super().__init__()
assert d_model % n_heads == 0 and n_heads % n_kv_heads == 0
self.h, self.kv_h, self.hd = n_heads, n_kv_heads, d_model // n_heads
self.q = nn.Linear(d_model, d_model, bias=False)
self.kv = nn.Linear(d_model, 2 * n_kv_heads * self.hd, bias=False) # keys, then values
self.out = nn.Linear(d_model, d_model, bias=False)
def forward(self, x, mask=None):
B, T, D = x.shape
q = self.q(x).view(B, T, self.h, self.hd).transpose(1, 2) # (B, 4, T, 32)
k, v = self.kv(x).view(B, T, 2, self.kv_h, self.hd).permute(2, 0, 3, 1, 4) # (B, kv_h, T, 32) each
self.cache_shape = tuple(k.shape)
g = self.h // self.kv_h
k, v = k.repeat_interleave(g, dim=1), v.repeat_interleave(g, dim=1) # heads 0,1 -> kv 0; 2,3 -> kv 1
return self.out(naive_attention(q, k, v, mask).transpose(1, 2).reshape(B, T, D))
set_seed()
x = torch.randn(2, 128, 128)
causal = torch.ones(128, 128, dtype=torch.bool).tril()
for n_kv in (4, 2, 1):
mine = GroupedQueryAttention(128, 4, n_kv)
ref = Attention(ModelConfig(n_kv_heads=n_kv, position="none"))
ref.load_state_dict(mine.state_dict()) # same names, same shapes
with torch.no_grad():
diff = (mine(x, causal) - ref(x)).abs().max().item()
print(f"n_kv_heads {n_kv}: cache {mine.cache_shape} | weights {sum(p.numel() for p in mine.parameters()):,} | vs block 16: {diff:.1e}")Code walkthrough
self.kvmakes keys and values forn_kv_headsheads only;permutesplits them into (batch, key/value heads, tokens, 32).self.cache_shaperecords what a generator would store.repeat_interleave(g, dim=1)lends key/value head 0 to query heads 0 and 1.- The loop copies the weights into block 16's
Attention, positions off, and compares outputs.
All three agree with block 16 to about 1e-7, float32 rounding. The cache shape falls from (2, 4, 128, 32) to (2, 1, 128, 32), and weights from 65,536 to 40,960 (measured here). Does a smaller cache make a step faster? Time one decoding step with Shazeer's head shape.
import time
def decode_step(q, k_cache, v_cache):
"""One new token. q: (B, heads, d_head); caches: (B, n_kv, T, d_head). The cache is never copied."""
B, H, dh = q.shape
n_kv = k_cache.shape[1]
q = q.view(B, n_kv, H // n_kv, dh) # query heads grouped by the key/value head they share
w = (q @ k_cache.transpose(-2, -1) / dh ** 0.5).softmax(-1) # (B, n_kv, group, T)
return (w @ v_cache).view(B, H, dh)
def median_ms(fn, runs=15):
fn() # warm-up
times = []
for _ in range(runs):
t0 = time.perf_counter(); fn(); times.append(time.perf_counter() - t0)
return 1000 * sorted(times)[runs // 2]
B, H, dh, T = 8, 8, 128, 4096 # Shazeer's head shape: 8 heads of 128
q = torch.randn(B, H, dh)
for n_kv in (8, 2, 1):
k_cache, v_cache = torch.randn(B, n_kv, T, dh), torch.randn(B, n_kv, T, dh)
mb = 2 * k_cache.numel() * 4 / 2**20
print(f"n_kv {n_kv}: cache read per step {mb:6.1f} MiB | {median_ms(lambda: decode_step(q, k_cache, v_cache)):5.2f} ms per step")Code walkthrough
decode_stephandles one new token. Instead of copying the cache, it groups the query heads withview, so each group meets its shared key/value head by broadcasting.median_mswarms up once, times 15 runs and returns the median.
Reading 256 MiB took 1.95 to 2.10 ms per step; 32 MiB took 0.72 to 0.83 ms (four runs, the author's Mac, not Colab). Eight times less to read, about 2.7 times faster here. Shazeer's TPU saw 12 times; a CPU has other overheads. The direction holds.
Break it: share heads in a model trained without sharing
Ainslie et al. convert a trained MHA checkpoint by mean pooling: average the key and value projections in each group, then train a little more ("uptraining", about 5% of the original pre-training compute). Skip the training on GPT-2 small.
%pip install -q transformers==5.19.0from transformers import AutoModelForCausalLM, AutoTokenizer
REF = "openai-community/gpt2" # the course's reference model: GPT-2 small, MIT licence
tok = AutoTokenizer.from_pretrained(REF)
ref = AutoModelForCausalLM.from_pretrained(REF, attn_implementation="eager").eval()
ORIGINAL = {k: v.clone() for k, v in ref.state_dict().items()}
g = torch.Generator().manual_seed(SEED)
R = 50 # Lesson 1's test: 50 random tokens, then the same 50
rnd = torch.randint(1000, 10000, (4, R), generator=g)
seq = torch.cat([torch.full((4, 1), tok.bos_token_id), rnd, rnd], dim=1)
text = tok("The station keeps a written record of everything: maintenance logs, assignment sheets, "
"crew conversations, greenhouse reports and procedures.", return_tensors="pt").input_ids
def losses():
with torch.no_grad():
rep = F.cross_entropy(ref(seq).logits[:, R + 1:-1].flatten(0, 1), seq[:, R + 2:].flatten()).item()
eng = ref(text, labels=text).loss.item()
return rep, eng
def pool_kv_heads(n_kv):
"""Turn GPT-2's 12 key/value heads into n_kv by averaging neighbours, as Ainslie et al. convert a checkpoint."""
ref.load_state_dict(ORIGINAL)
g = 12 // n_kv
with torch.no_grad():
for block in ref.transformer.h:
W, b = block.attn.c_attn.weight, block.attn.c_attn.bias # (768, 2304): queries | keys | values
for part in (1, 2): # keys, then values
cols = slice(768 * part, 768 * (part + 1))
Wp = W[:, cols].view(768, n_kv, g, 64).mean(2, keepdim=True).expand(768, n_kv, g, 64)
W[:, cols] = Wp.reshape(768, 768)
b[cols] = b[cols].view(n_kv, g, 64).mean(1, keepdim=True).expand(n_kv, g, 64).reshape(768)
for n_kv in (12, 6, 4, 1):
pool_kv_heads(n_kv)
rep, eng = losses()
print(f"{n_kv:2d} key/value heads (cache x{n_kv / 12:.2f}): repeat-half loss {rep:.3f} | English sentence loss {eng:.3f}")
ref.load_state_dict(ORIGINAL)Code walkthrough
ORIGINALkeeps every weight so each setting starts from the real model.lossesreturns Lesson 3's repeat-half loss and the loss on one English sentence.- GPT-2 keeps queries, keys and values side by side in
c_attn, 768 columns each.pool_kv_headsviews the key and value columns as (key/value heads, group, 64), averages over the group and writes the average back to every head in it.
Halving the cache wrecked the model. The repeat-half loss went from 0.299 to 10.998, worse than guessing uniformly among 50,257 tokens (ln 50,257 = 10.8, arithmetic); the sentence loss went from 4.944 to 6.614 (measured here). GPT-2's heads were trained to differ; their averages are nothing any head expects. Sharing has to be learnt.
2. Multi-head latent attention, implemented (Optional)
GQA shrinks the cache by keeping fewer heads. DeepSeek-V2 (DeepSeek-AI, 2024) keeps every head and shrinks what is stored instead.
Multi-head latent attention (MLA) caches one small vector per token, the latent, and rebuilds every head's keys and values from it with two up-projections when it scores.
class LatentKV(nn.Module):
"""Multi-head latent attention, cache side only: keep a small latent per token, rebuild keys and values from it."""
def __init__(self, d_model=128, n_heads=4, d_latent=32):
super().__init__()
self.h, self.hd = n_heads, d_model // n_heads
self.down = nn.Linear(d_model, d_latent, bias=False) # this output is what gets cached
self.up_k = nn.Linear(d_latent, d_model, bias=False) # every head's keys, rebuilt
self.up_v = nn.Linear(d_latent, d_model, bias=False) # every head's values, rebuilt
self.q = nn.Linear(d_model, d_model, bias=False)
self.out = nn.Linear(d_model, d_model, bias=False)
def forward(self, x, mask=None):
B, T, D = x.shape
self.latent = self.down(x) # (B, T, 32): the whole cache
split = lambda t: t.view(B, T, self.h, self.hd).transpose(1, 2)
q, k, v = split(self.q(x)), split(self.up_k(self.latent)), split(self.up_v(self.latent))
return self.out(naive_attention(q, k, v, mask).transpose(1, 2).reshape(B, T, D))
set_seed()
mla = LatentKV()
y = mla(torch.randn(1, 128, 128), causal)
print("output", tuple(y.shape), "| cached per token per layer:", mla.latent.shape[-1], "numbers")
print("MHA caches", 2 * 4 * 32, "| GQA (2 kv heads)", 2 * 2 * 32, "| MQA", 2 * 1 * 32)Code walkthrough
downsqueezes 128 numbers to 32;self.latentis everything a generator would keep.up_kandup_vrebuild full keys and values for all four heads.- The rest is ordinary multi-head attention. DeepSeek-V2 adds a small separate key part for rotary positions, because a position-dependent rotation cannot be folded into a shared latent (Module 4 explains rotation).
At width 128 the latent stores 32 numbers per token per layer, half of MQA's 64, while keeping four distinct heads. DeepSeek-V2 reports a KV cache 93.3% smaller than DeepSeek 67B's (cited). Section 8 reads its config.
3. Cross-attention between sequences (Essential)
Maya's log cards (Module 12) could be written by a decoder that reads the log. That reading is cross-attention: queries come from the text being written, keys and values from a different sequence.
class CrossAttention(nn.Module):
"""Queries from x (the text being written); keys and values from memory (the text being read)."""
def __init__(self, d_model=128, n_heads=4):
super().__init__()
self.h, self.hd = n_heads, d_model // n_heads
self.q = nn.Linear(d_model, d_model, bias=False)
self.kv = nn.Linear(d_model, 2 * d_model, bias=False)
self.out = nn.Linear(d_model, d_model, bias=False)
def forward(self, x, memory, memory_mask=None):
B, T, D = x.shape
S = memory.shape[1]
q = self.q(x).view(B, T, self.h, self.hd).transpose(1, 2) # (B, 4, T, 32)
k, v = self.kv(memory).view(B, S, 2, self.h, self.hd).permute(2, 0, 3, 1, 4) # (B, 4, S, 32)
y, self.weights = naive_attention(q, k, v, memory_mask, return_weights=True)
return self.out(y.transpose(1, 2).reshape(B, T, D))
set_seed()
cross = CrossAttention()
card = torch.randn(1, 4, 128) # stands in for the 4 tokens of "Maya" in the card being written
log = torch.randn(1, 35, 128) # stands in for the 35 characters of "Log 4821, sol 212, the night shift."
y = cross(card, log)
print("weights", tuple(cross.weights.shape), "| every row sums to 1:", torch.allclose(cross.weights.sum(-1), torch.ones(1)))
keep = torch.ones(1, 1, 1, 35, dtype=torch.bool); keep[..., 30:] = False # last 5 log slots are padding
cross(card, log, keep)
print("weight on the 5 padded log slots:", cross.weights[..., 30:].max().item())Code walkthrough
self.qreadsx;self.kvreadsmemory. Nothing else changes from Lesson 3. The layer is untrained and the inputs are random stand-ins of the right lengths: shapes are the point.- There is no causal mask: the whole log already exists.
keepis a padding mask over the log's positions, broadcast to every query (Lesson 4).
The weights are (1, 4, 4, 35): rectangular, one row per card token, each summing to 1, and the padded slots get exactly 0.0. For cost, the log's keys and values are computed once and reused at every step of the card, so cross-attention's cache does not grow as the card is written.
4. Sliding-window and local attention (Recommended)
A window caps both the cache and the work: each token reads only the last w tokens. Lesson 4 drew this mask; here is what it buys and what it loses.
def window_mask(T, w):
"""Causal, and each query sees only itself and the w - 1 tokens before it."""
i = torch.arange(T)
return (i[None, :] <= i[:, None]) & (i[None, :] > i[:, None] - w)
T, w = 64, 8
m = window_mask(T, w)
print("open cells: causal", int(torch.ones(T, T).tril().sum()), "| window 8:", int(m.sum()))
reach = torch.eye(T, dtype=torch.bool)
for layer in range(1, 5):
reach = (m.float() @ reach.float()) > 0 # what the last token can see after this layer
print(f"after {layer} layer(s), token 63 reaches back to token {int(reach[63].nonzero().min())}")Code walkthrough
window_maskis the causal mask with one more condition: the key must be fewer thanwplaces back.reachstarts as "each token sees itself". Multiplying by the mask once per layer spreads it the way information spreads through stacked layers.
On 64 tokens the window opens 484 cells instead of 2,080. One layer reaches 7 tokens back; four reach 28 (measured here). This is local attention: cost and cache grow with w, not T, and long reach must come from depth. Mistral 7B uses W = 4,096 and states a theoretical span of about 131K tokens at its last layer (cited).
5. Attention matrix memory and compute cost (Essential)
Back to Hana's 4,096 characters. Two numbers decide whether a layer fits and how long it takes: bytes and FLOPs.
def attention_matrix_bytes(batch, heads, T, bytes_per_number=4):
return batch * heads * T * T * bytes_per_number
set_seed()
for T in (128, 512, 1024, 2048, 4096):
print(f"T {T:5d}: one layer's weights {attention_matrix_bytes(1, 4, T) / 2**20:7.2f} MiB"
f" | q, k, v together {3 * 4 * T * 32 * 4 / 2**20:5.2f} MiB")
q, k, v = (torch.randn(1, 4, 2048, 32) for _ in range(3))
_, w = naive_attention(q, k, v, torch.ones(2048, 2048, dtype=torch.bool).tril(), return_weights=True)
print("measured weights tensor at T 2048:", w.numel() * w.element_size() / 2**20, "MiB", tuple(w.shape))Code walkthrough
- Attention matrix memory is batch x heads x T x T numbers; q, k and v grow only with T. The last lines measure the real weights at 2,048 tokens.
At 128 tokens one layer's weights take 0.25 MiB; at 4,096, 256 MiB, while q, k and v together reach only 6 MiB (arithmetic). The measured tensor at 2,048 is 64.0 MiB, as the formula says. Double the length, four times the memory.
from torch.utils.flop_counter import FlopCounterMode
def attention_flops(T, d_model):
"""Scores (Q K^T) and the weighted sum (A V): each T x T x d_model multiply-adds, 2 FLOPs per multiply-add."""
return 2 * 2 * T * T * d_model
for T in (128, 512, 2048):
q, k, v = (torch.randn(1, 4, T, 32) for _ in range(3))
with FlopCounterMode(display=False) as counter:
naive_attention(q, k, v)
proj = 2 * T * 128 * (4 * 128) # W_q, W_k, W_v, W_o for MHA
print(f"T {T:5d}: counted {counter.get_total_flops():>12,} | formula {attention_flops(T, 128):>12,} | projections {proj:>11,}")Code walkthrough
- Attention compute cost: scores and weighted sum each do T x T x d_model multiply-adds, 2 FLOPs each.
FlopCounterModecounts every matrix multiply inside thewithblock.projis the four projections, linear in T.
Counted and formula agree exactly: 2,147,483,648 FLOPs at 2,048 tokens. The projections cost 8 T d squared, so the quadratic part passes them at T = 2d = 256 (arithmetic): at 512 tokens it is already twice their size.
6. Attention time against sequence length (Essential)
FLOPs predict; the clock decides. Time naive attention and PyTorch's fused kernel at the base head shape.
lengths = [256, 512, 1024, 2048]
naive_ms, fused_ms = [], []
for T in lengths:
q, k, v = (torch.randn(1, 4, T, 32) for _ in range(3))
mask = torch.ones(T, T, dtype=torch.bool).tril()
naive_ms.append(median_ms(lambda: naive_attention(q, k, v, mask), runs=7))
fused_ms.append(median_ms(lambda: F.scaled_dot_product_attention(q, k, v, is_causal=True), runs=7))
for i, T in enumerate(lengths):
ratio = "" if i == 0 else f" | x{naive_ms[i] / naive_ms[i - 1]:.1f} and x{fused_ms[i] / fused_ms[i - 1]:.1f} for twice the length"
print(f"T {T:5d}: naive {naive_ms[i]:7.2f} ms, fused {fused_ms[i]:6.2f} ms{ratio}")Code walkthrough
- The fused path uses
is_causal=Trueinstead of a mask. Each ratio divides a time by the one before: purely quadratic cost prints x4.0.
From 1,024 to 2,048 tokens the naive time rose from about 2.5 to 9.3 ms, x3.4 to x3.8 across four runs; the fused kernel went from 0.9 to 2.3 ms, x2.6 to x2.7 (the author's Mac, not Colab). At short lengths fixed overheads blur the doubling; at long lengths quadratic time shows.
The fused kernel is about four times faster at 2,048 because it never writes the 64 MiB weights tensor: it works in tiles that stay in cache, and skips tiles above the diagonal. That idea, FlashAttention, is Module 10, Lesson 3.
7. Attention cost against the feed-forward block (Essential)
"Attention is quadratic" does not mean attention dominates. The feed-forward block costs the same per token at any length, so the question is where the two cross.
Per token, the scores and weighted sum cost 4 T d FLOPs; the SwiGLU feed-forward block costs 6 d d_ff (three matrices). They are equal at T = 1.5 d_ff, which for base (d_ff 344) is 516 tokens (arithmetic). The full attention sub-layer also has its four projections, 8 d squared.
cfg = ModelConfig(position="none")
d, d_ff = cfg.d_model, cfg.d_ff
print("scores = feed-forward when 4 T d = 6 d d_ff, at T =", 6 * d * d_ff / (4 * d))
set_seed()
attn, ffn = Attention(cfg), FeedForward(cfg)
with torch.no_grad():
for T in (128, 256, 512, 1024, 2048):
flop_attn = 8 * d * d + 4 * T * d # per token: four projections, then scores and sum
flop_share = flop_attn / (flop_attn + 6 * d * d_ff)
x = torch.randn(8, T, d)
a, f = median_ms(lambda: attn(x), runs=5), median_ms(lambda: ffn(x), runs=5)
print(f"T {T:5d}: attention {a:6.2f} ms | feed-forward {f:5.2f} ms | attention share: FLOPs {flop_share:.0%}, time {a / (a + f):.0%}")Code walkthrough
flop_shareis attention's predicted fraction of the block's FLOPs; the timings run blocks 16 and 17 on a batch of 8.
The predicted share grows from 43% at 128 tokens to 82% at 2,048; the measured share from 57 to 59% to 82 to 83% (four runs). At 2,048 they agree. At short lengths reshaping and the softmax cost time that FLOP counts ignore. For base at 4,096 characters, attention is most of the bill.
8. Comparison with published model configs (Recommended)
Published models publish their configurations, so the same arithmetic works on them.
import json
from huggingface_hub import hf_hub_download
def published(repo):
c = json.load(open(hf_hub_download(repo, "config.json")))
d, L, h = c.get("hidden_size", c.get("n_embd")), c.get("num_hidden_layers", c.get("n_layer")), c.get("num_attention_heads", c.get("n_head"))
kv, hd = c.get("num_key_value_heads", h), c.get("head_dim", d // h)
per_token = L * (c["kv_lora_rank"] + c["qk_rope_head_dim"]) if "kv_lora_rank" in c else 2 * L * kv * hd
return d, L, h, kv, per_token, c.get("sliding_window")
print(f"{'model':<28} {'width':>6} {'layers':>6} {'q heads':>7} {'kv heads':>8} {'cache/token':>11} {'window':>7}")
for repo in ["openai-community/gpt2", "HuggingFaceTB/SmolLM2-135M", "mistralai/Mistral-7B-v0.1",
"Qwen/Qwen3-8B", "deepseek-ai/DeepSeek-V2"]:
d, L, h, kv, per_token, win = published(repo)
print(f"{repo.split('/')[1]:<28} {d:>6} {L:>6} {h:>7} {kv:>8} {per_token:>11,} {str(win):>7}")Code walkthrough
hf_hub_downloadfetches one file, not the weights. GPT-2 names its fields differently, hence thegetfallbacks.per_tokenis cached numbers per token over all layers: latent plus rotary part for MLA, otherwise 2 x layers x key/value heads x head width.
GPT-2 (2019) uses full MHA. SmolLM2-135M shares 3 key/value heads among 9 query heads; Mistral 7B and Qwen3-8B share 8 among 32; Mistral also sets a 4,096 window. DeepSeek-V2's config lists 128 key/value heads, but its cache is the latent (checked October 2026).
DeepSeek-V2 caches 34,560 numbers per token over 60 layers. Plain MHA at its 128 heads of 128 would cache 2 x 60 x 128 x 128 = 1,966,080, about 57 times more (arithmetic). Recent models choose the head layout for the cache.
In production
Mistral 7B (Jiang et al., 2023) keeps GQA and adds a rolling buffer cache: with a fixed window, position i overwrites slot i mod W, which "reduces the cache memory usage by 8x" at 32k tokens without hurting quality. DeepSeek-V2 compresses instead. Most teams start from GQA and train with it from the start. Module 10 measures quality against cache size; Module 11 builds the cache into a server.
What you added to tinyformer-lab
GroupedQueryAttentionfortinyformer/attention.py: one switch for MHA, GQA and MQA, checked against shared block 16.CrossAttentionandwindow_mask, with the reach check, for the same file.kv_cache_bytes,attention_matrix_bytesandattention_flops, saved by the module lab with a test that compares the FLOP formula withFlopCounterMode.- The length sweep and the attention against feed-forward table. They stay in this lesson; the module lab's one experiment,
experiments/m02_kv_heads.py, races this lesson's key/value head counts on the reverse task.
Check yourself
- Why do query heads not appear in the KV cache formula?
- GQA with 2 key/value heads halves the cache. Why did halving GPT-2's heads by averaging wreck it?
- What are the shapes of the cross-attention weights for a 4-token card reading a 35-character log, and why is there no causal mask?
- Four stacked layers with a window of 8: how far back can the last token reach?
- At what length do scores and weighted sum cost as much as
base's feed-forward block, and why does the measured share run higher at short lengths?
- A query is used once; keys and values are reused at every later step.
- Its heads were trained to differ, so the averages are keys no head expects. Sharing must be trained in.
- (1, 4, 4, 35). The log exists in full before the card is written.
- 28 tokens: 7 per layer.
- T = 1.5 d_ff = 516. Reshaping and softmax cost time that FLOP counts ignore.
Exercise
Write window_decode(q, k_cache, v_cache, w): one new token's output, reading only the last w cached keys and values. The check compares it with full attention under window_mask.
def check_window_decode(window_decode, T=64, w=8):
set_seed()
q, k, v = (torch.randn(1, 4, T, 32) for _ in range(3))
full = naive_attention(q, k, v, window_mask(T, w))[:, :, -1] # last token, full computation
fast = window_decode(q[:, :, -1], k, v, w) # last token, from the cache
assert fast.shape == (1, 4, 32) and torch.allclose(full, fast, atol=1e-6), (full - fast).abs().max()
return "check passed"Code walkthrough
fullruns every token under the window mask and keeps the last row;fastis your function. They must match.
def window_decode(q, k_cache, v_cache, w):
"""Read only the last w keys and values: a rolling buffer of size w is all the cache needed."""
k, v = k_cache[:, :, -w:], v_cache[:, :, -w:]
return naive_attention(q[:, :, None], k, v)[:, :, 0]
print(check_window_decode(window_decode))Code walkthrough
-w:keeps the last 8 positions;q[:, :, None]adds a one-token axis and[:, :, 0]removes it. It printedcheck passed.
Key terms
| Term | Meaning |
|---|---|
| KV cache | Stored keys and values of earlier tokens |
| Multi-head attention (MHA) | Every query head has its own key/value head |
| Multi-query attention (MQA) | All query heads share one key/value head |
| Grouped-query attention (GQA) | Each group of query heads shares one key/value head |
| Mean pooling | Averaging each group's key/value projections to convert a checkpoint |
| Multi-head latent attention (MLA) | Caches a small latent and rebuilds keys and values |
| Cross-attention | Queries from one sequence, keys and values from another |
| Local attention | Each token reads only a window of the last w tokens |
| Rolling buffer cache | Position i overwrites slot i mod W |
| Quadratic time | Doubling the length roughly quadruples the cost |
Sources
- Noam Shazeer (Google), "Fast Transformer Decoding: One Write-Head is All You Need", 2019, abstract, sections 4.1 to 4.3, Tables 1 and 2. https://arxiv.org/abs/1911.02150
- Joshua Ainslie, James Lee-Thorp, Michiel de Jong et al. (Google Research), "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints", 2023, section 2.1. https://arxiv.org/abs/2305.13245
- Albert Q. Jiang et al. (Mistral AI), "Mistral 7B", 2023, section 2 (sliding window attention, rolling buffer cache). https://arxiv.org/abs/2310.06825
- DeepSeek-AI, "DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model", 2024, abstract and Figure 1. https://arxiv.org/abs/2405.04434
- Published
config.jsonfiles for openai-community/gpt2, HuggingFaceTB/SmolLM2-135M, mistralai/Mistral-7B-v0.1, Qwen/Qwen3-8B and deepseek-ai/DeepSeek-V2 on the Hugging Face Hub, read in code, checked October 2026. https://huggingface.co