CourseTransformers: From Attention to Trained, Served and Interpreted Models · Module 2: Self-Attention Mechanics · part 17 of 111
Part 17 · Module 2: Self-Attention Mechanics

Lesson 5: Head variants and what attention really costs

23 min read·
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.

WMT14 EN-DE, 8 HEADS OF 128, ONE TPUV2 (SHAZEER 2019) multi-head multi-query decoder, per token 46 us 3.8 us training, per token 13.2 us 13.0 us dev BLEU 26.7 26.5
Shazeer (2019, cited): sharing one key/value head (green) cut decoder time from 46 to 3.8 microseconds per token, while training time and BLEU barely moved.

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.json for 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.

python
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 5 on the author's Mac.
python
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 = 11 and set_seed().
python
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 out

Code 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.

python
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: ModelConfig holds the base shape.
python
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_heads heads, lent to several query heads by repeat_interleave.
python
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.
WRITING TOKEN 6 OF A REPLY: ONE NEW QUERY k0, v0 stored k1, v1 stored k2, v2 stored k3, v3 stored k4, v4 stored k5, v5 new q5 used once the stored row is the KV cache; it grows by one per token
When generating, the new token's query (amber, the model's computation) reads the keys and values of every earlier token, which are kept (grey) in the KV cache and grow by one per step.

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.

ONE 4,096-CHARACTER TRANSMISSION IN BASE, FLOAT32 2 k and v x 4 layers x 4 kv heads x 32 head width x 4,096 tokens x 4 B per number = 16 MiB query heads are not in it
Cache bytes = 2 x layers x key/value heads x head width x tokens x 4, which is 16 MiB for one 4,096-character log in base (arithmetic); the key/value heads (grey) are the term head design can shrink.

So the cache grows with layers, key/value heads, head width and tokens, and query heads do not appear in it at all.

python
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_bytes is 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.
4 QUERY HEADS (AMBER) AND THEIR KEY/VALUE HEADS (BLUE) MHA: 4 kv q0 q1 q2 q3 kv0 kv1 kv2 kv3 GQA: 2 kv q0 q1 q2 q3 kv0 kv1 MQA: 1 kv q0 q1 q2 q3 kv0
MHA gives each query head (amber) its own key/value head (blue); GQA shares one per group of two; MQA shares one across all four.

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.

32 TRANSMISSIONS OF 4,096 CHARACTERS AT ONCE MHA, 4 kv 512 MiB GQA, 2 kv 256 MiB MQA, 1 kv 128 MiB attn weights 1.00 MiB
Serving 32 transmissions at once, the cache takes 512, 256 or 128 MiB depending on key/value heads, against 1.00 MiB of attention weights (blue): the cache, not the model, fills memory (arithmetic).

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.

python
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.kv makes keys and values for n_kv_heads heads only; permute splits them into (batch, key/value heads, tokens, 32).
  • self.cache_shape records 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.
GROUPEDQUERYATTENTION AGAINST SHARED BLOCK 16 kv heads cache shape weights difference 4 (2, 4, 128, 32) 65,536 9.3e-08 2 (2, 2, 128, 32) 49,152 1.5e-07 1 (2, 1, 128, 32) 40,960 1.2e-07
The lab's GroupedQueryAttention matches shared block 16 to about 1e-7 (green, passed) at 4, 2 and 1 key/value heads, while the cache and the weights shrink (measured here).

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.

python
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_step handles one new token. Instead of copying the cache, it groups the query heads with view, so each group meets its shared key/value head by broadcasting.
  • median_ms warms up once, times 15 runs and returns the median.
ONE DECODE STEP: 8 HEADS OF 128, 4,096 TOKENS, BATCH 8 8 kv, 256 MiB 1.95 to 2.10 ms 2 kv, 64 MiB 1.36 to 1.47 ms 1 kv, 32 MiB 0.72 to 0.83 ms 8 times less read, about 2.7 times faster (author's Mac)
One decoding step read 256 MiB of cache in about 2 ms and 32 MiB in about 0.8 ms (measured here, four runs on the author's Mac): a smaller cache makes each step faster.

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.

CONVERTING GPT-2: AVERAGE NEIGHBOURING KEY PROJECTIONS Wk h0 Wk h1 Wk h2 Wk h3 mean h0, h1 mean h2, h3 every head in a group gets the mean
Mean pooling converts a checkpoint: the trained key (and value) projections (amber) of each group of heads are averaged, and every head in the group uses the average.
python
%pip install -q transformers==5.19.0
python
from 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

  • ORIGINAL keeps every weight so each setting starts from the real model. losses returns 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_heads views 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.
GPT-2 REPEAT-HALF LOSS, POOLED, NO RETRAINING 12 kv (original) 0.299 6 kv 10.998 4 kv 11.706 1 kv 12.993 uniform guessing: ln 50,257 = 10.8
Pooling GPT-2's key/value heads without retraining took the repeat-half loss from 0.299 (green) to 10.998 or worse (red), past uniform guessing (measured here): sharing must be trained in.

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.

LATENT ATTENTION AT WIDTH 128 x 128 down latent 32, cached up_k: 4 heads up_v: 4 heads
Multi-head latent attention caches only the 32-number latent (green) and rebuilds every head's keys and values from it with learnt up-projections (amber).

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.

python
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

  • down squeezes 128 numbers to 32; self.latent is everything a generator would keep. up_k and up_v rebuild 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).
NUMBERS CACHED PER TOKEN PER LAYER, WIDTH 128 MHA 256 GQA, 2 kv 128 MQA 64 latent 32
At width 128 the latent (green) caches 32 numbers per token per layer, half of MQA's 64, while keeping four distinct heads (measured here).

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.

A CARD BEING WRITTEN READS A LOG card: Maya 4 tokens -> queries log header 35 chars -> keys, values attention (1, 4, 4, 35) card out (1, 4, 128)
Cross-attention: queries come from the card being written (blue), keys and values from the log being read (grey), and the weights (amber) are 4 by 35.
python
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.q reads x; self.kv reads memory. 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. keep is a padding mask over the log's positions, broadcast to every query (Lesson 4).
WEIGHTS, ONE HEAD: 4 CARD TOKENS X 35 LOG SLOTS M a y a real slots: rows sum to 1 pad: 0.0
Cross-attention weights are rectangular, 4 rows by 35 columns, with no causal mask; the 5 padded log slots (grey) get exactly 0.0 (measured here).

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.

16 TOKENS SHOWN; COUNTS MEASURED ON 64 causal: 2,080 cells window 8: 484 cells
A causal mask opens every earlier cell (blue): 2,080 of them on 64 tokens; a window of 8 opens a band of 484 (measured here).
python
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_mask is the causal mask with one more condition: the key must be fewer than w places back.
  • reach starts as "each token sees itself". Multiplying by the mask once per layer spreads it the way information spreads through stacked layers.
HOW FAR BACK TOKEN 63 CAN SEE, WINDOW 8 1 layer back to 56 2 layers back to 49 3 layers back to 42 4 layers back to 35
With a window of 8, each stacked layer adds 7 tokens of reach: token 63 sees back to 56, 49, 42 and 35 (measured here).

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.

python
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.
ONE LAYER'S ATTENTION WEIGHTS, 4 HEADS, FLOAT32 T 128 0.25 MiB T 512 4 MiB T 1,024 16 MiB T 2,048 64 MiB T 4,096 256 MiB q, k and v together at 4,096: 6 MiB
One layer's attention weights grow with the square of length, from 0.25 MiB at 128 tokens to 256 MiB at 4,096 (red, danger), while q, k and v together reach only 6 MiB (arithmetic).

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.

python
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.
  • FlopCounterMode counts every matrix multiply inside the with block. proj is the four projections, linear in T.
FLOPS PER LAYER, 4 HEADS OF 32 T counted 4 T² d projections 128 8.4 M 8.4 M 16.8 M 512 134 M 134 M 67 M 2,048 2,147 M 2,147 M 268 M
PyTorch's FlopCounterMode agrees exactly with 4 T squared d (green); past 256 tokens the quadratic part outgrows the four projections (measured and arithmetic).

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.

python
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=True instead of a mask. Each ratio divides a time by the one before: purely quadratic cost prints x4.0.
BASE HEAD SHAPE, 4 HEADS OF 32, BATCH 1 naive 1,024 2.45 ms naive 2,048 9.28 ms (x3.8) fused 1,024 0.90 ms fused 2,048 2.33 ms (x2.6)
Doubling the length from 1,024 to 2,048 multiplied naive time (amber, red) by 3.4 to 3.8 and fused time (blue) by 2.6 to 2.7 over four runs; the bars show the last run (measured here, author's Mac).

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.

ATTENTION AT 2,048 TOKENS, 4 HEADS naive writes (1, 4, 2048, 2048) 64 MiB, then reads it back fused small tiles stay in cache never stores the matrix how it works: Module 10, Lesson 3
The naive path writes and rereads a 64 MiB weights tensor at 2,048 tokens (red); the fused kernel works in tiles and never stores it (green).

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.

FLOPS PER TOKEN, PER LAYER scores + sum 4 x T x 128 = SwiGLU feed-forward 6 x 128 x 344 T = 1.5 x 344 = 516
Per token, scores and sum (amber) cost 4 T d and the SwiGLU feed-forward block (blue) costs 6 d d_ff, so they cross at T = 516 for base (arithmetic).

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.

python
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_share is attention's predicted fraction of the block's FLOPs; the timings run blocks 16 and 17 on a batch of 8.
ATTENTION'S SHARE OF THE BLOCK: FLOPS (GREY) AND TIME (AMBER) T 128 43% 59% T 256 50% 64% T 512 60% 71% T 1,024 71% 75% T 2,048 82% 82%
Attention's predicted FLOP share (grey) rises from 43% to 82% and its measured time share (amber) from 57 to 59% to 82 to 83% between 128 and 2,048 tokens over four runs; bars show the last run (measured here).

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.

python
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_download fetches one file, not the weights. GPT-2 names its fields differently, hence the get fallbacks.
  • per_token is cached numbers per token over all layers: latent plus rotary part for MLA, otherwise 2 x layers x key/value heads x head width.
PUBLISHED CONFIG.JSON FILES, CHECKED OCTOBER 2026 model q heads kv heads window GPT-2 12 12 none SmolLM2-135M 9 3 none Mistral 7B 32 8 4,096 Qwen3-8B 32 8 none DeepSeek-V2 128 latent none
Of five published configs, only GPT-2 keeps one key/value head per query head; the newer ones share (green) or use a latent (cited, read from config.json).

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).

CACHE PER TOKEN, ALL LAYERS, IN NUMBERS GPT-2 18,432 SmolLM2-135M 11,520 Mistral 7B 65,536 Qwen3-8B 73,728 DeepSeek-V2 34,560 DeepSeek-V2 as plain MHA: 1,966,080
DeepSeek-V2 caches 34,560 numbers per token over 60 layers and 128 heads (green), about 57 times less than plain MHA would (arithmetic from the published configs).

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

TWO WAYS TO SHRINK THE CACHE cap it: Mistral 7B window 4,096, rolling buffer 8x less cache at 32k compress it: DeepSeek-V2 latent keys and values 93.3% less than 67B both cited from the papers
Two published ways to tame the cache: Mistral 7B caps it with a 4,096 window and a rolling buffer (8x less at 32k), DeepSeek-V2 compresses it into a latent (93.3% less than DeepSeek 67B), both cited.

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

  • GroupedQueryAttention for tinyformer/attention.py: one switch for MHA, GQA and MQA, checked against shared block 16.
  • CrossAttention and window_mask, with the reach check, for the same file.
  • kv_cache_bytes, attention_matrix_bytes and attention_flops, saved by the module lab with a test that compares the FLOP formula with FlopCounterMode.
  • 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

  1. Why do query heads not appear in the KV cache formula?
  2. GQA with 2 key/value heads halves the cache. Why did halving GPT-2's heads by averaging wreck it?
  3. 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?
  4. Four stacked layers with a window of 8: how far back can the last token reach?
  5. 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?
  1. A query is used once; keys and values are reused at every later step.
  2. Its heads were trained to differ, so the averages are keys no head expects. Sharing must be trained in.
  3. (1, 4, 4, 35). The log exists in full before the card is written.
  4. 28 tokens: 7 per layer.
  5. 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.

python
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

  • full runs every token under the window mask and keeps the last row; fast is your function. They must match.
python
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 printed check passed.

Key terms

TermMeaning
KV cacheStored 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 poolingAveraging 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-attentionQueries from one sequence, keys and values from another
Local attentionEach token reads only a window of the last w tokens
Rolling buffer cachePosition i overwrites slot i mod W
Quadratic timeDoubling 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.json files 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