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

Lab: Package attention and test every claim

20 min read·
Module 2 · Lab · About 60 minutes · Needs: lessons 1 to 5 of this module, and Module 1's lab

What you are building

TINYFORMER-LAB AFTER MODULE 2 attention.py attention, masks, heads test_m02_attention 7 claims m02_kv_heads.py 4, 2, 1 kv heads runs/ record 9 measured runs v0.1.0: data.py, Module 1 git tag v0.2.0
The lab adds one package file (blue) guarded by seven tests (green), a race whose nine runs land in a record (amber), and a v0.2.0 tag on top of Module 1's state (grey).

Sol 406 at Aurora Station. The five lessons wrote attention in notebooks: naive_attention with its scale switch, five masks, MultiHeadAttention, GroupedQueryAttention and the cost formulas. Each lesson ended "the module lab saves this". Today you do: one file, tinyformer/attention.py, and one test file, tests/test_m02_attention.py, holding the checks the lessons ran by hand, from agreement with PyTorch to the causal leak test and the "same as alone" packing check. Then you answer the question Hana Aoki asked in Lesson 5, "should we keep fewer key and value heads?", with a measured race on the shared reverse task, three seeds per setting, written to a run record. You commit and tag v0.2.0. Every number is labelled measured here, cited or arithmetic.

Step 1: Reopen the repository

TWO WAYS BACK TO MODULE 1 pushed in Module 1 git clone not pushed stand-in cells write skeleton and data.py v0.1.0 here pip install -e . existing files are never overwritten
Either route ends at a tagged v0.1.0 repository: a clone of your pushed work (blue) or a stand-in (grey) that writes only the files that are missing.

Colab wipes its disk, so first get Module 1's repository back. If you pushed it, clone it (not run here: the address is your own).

bash
git clone https://github.com/<your-account>/tinyformer-lab.git

Code walkthrough

  • git clone copies the repository, its history and its v0.1.0 tag. In Colab, put ! in front.

If you did not push it, the next cells rebuild a stand-in with the files this lab imports. On a cloned repository they write nothing.

python
import os, pathlib, subprocess
if pathlib.Path.cwd().name != "tinyformer-lab":          # safe to rerun: never nests a second copy
    os.makedirs("tinyformer-lab", exist_ok=True)
    os.chdir("tinyformer-lab")
STAND_IN = not pathlib.Path(".git").exists()             # True when Module 1's repository is not here
for folder in ["tinyformer", "tests", "experiments", "runs"]:
    pathlib.Path(folder).mkdir(exist_ok=True)
SKELETON = {
    "pyproject.toml": '[build-system]\nrequires = ["setuptools>=64"]\nbuild-backend = "setuptools.build_meta"\n\n'
                      '[project]\nname = "tinyformer"\nversion = "0.1.0"\nrequires-python = ">=3.10"\n'
                      'dependencies = ["torch"]\n\n[tool.setuptools]\npackages = ["tinyformer"]\n',
    ".gitignore": "__pycache__/\n*.pyc\n*.egg-info/\n.ipynb_checkpoints/\n",
    "README.md": "# tinyformer-lab\n\nA small transformer in which every design choice is a switch you can measure.\n"
                 "Every number in this repository is labelled measured here, cited or arithmetic.\n",
    "tinyformer/__init__.py": '"""tinyformer-lab: the package. Module 1 adds data.py."""\n__version__ = "0.1.0"\n',
}
for path, text in SKELETON.items():
    if not pathlib.Path(path).exists():                  # never overwrite Module 1's files
        pathlib.Path(path).write_text(text)
print("stand-in" if STAND_IN else "Module 1 repository", "|", os.getcwd().split("/")[-1])

Code walkthrough

  • STAND_IN is True when no .git folder is here. SKELETON is Module 1's Step 1 files, written only where missing.
python
DATA_PY = '''"""Shared data for tinyformer-lab, from course-guide/06. Module 1: seeds (block 1) and synthetic tasks (block 9)."""
import random
from typing import NamedTuple

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)

class TaskData(NamedTuple):
    name: str
    vocab_size: int
    inputs: torch.Tensor    # (n, T) token ids
    targets: torch.Tensor   # (n, T) the next token at every position
    mask: torch.Tensor      # (n, T) 1 where the answer is scored, 0 elsewhere
'''

Code walkthrough

  • DATA_PY holds Module 1's tinyformer/data.py: shared block 1 and the start of block 9, unchanged. The next cell adds the rest of block 9.
python
DATA_PY += '''
def _shift(name, vocab, seq, scored_from):
    inputs, targets = seq[:, :-1], seq[:, 1:]
    mask = torch.zeros_like(inputs)
    mask[:, scored_from:] = 1
    return TaskData(name, vocab, inputs, targets, mask)

def make_task(name, n=4096, length=16, vocab=32, seed=SEED):
    """copy, reverse or induction. Token 0 is the separator; content tokens are 1 to vocab - 1."""
    g = torch.Generator().manual_seed(seed)
    body = torch.randint(1, vocab, (n, length), generator=g)
    sep = torch.zeros(n, 1, dtype=torch.long)
    if name == "copy":
        seq = torch.cat([body, sep, body], dim=1)
    elif name == "reverse":
        seq = torch.cat([body, sep, body.flip(1)], dim=1)
    elif name == "induction":                       # random tokens, then the same random tokens again
        seq = torch.cat([body, body], dim=1)
    return _shift(name, vocab, seq, scored_from=length)
TASKS = {name: make_task(name) for name in ["copy", "reverse", "induction"]}
'''
if not pathlib.Path("tinyformer/data.py").exists():
    pathlib.Path("tinyformer/data.py").write_text(DATA_PY)
if STAND_IN:                                             # record the stand-in as Module 1's tagged state
    for cmd in ["git init -q -b main", "git config user.name 'Your Name'", "git config user.email you@example.com",
                "git add -A", "git commit -q -m 'Module 1 stand-in: data package'", "git tag v0.1.0"]:
        subprocess.run(cmd, shell=True, check=True)
print(subprocess.run("git log --oneline --decorate", shell=True, capture_output=True, text=True).stdout)
python
%pip install -q -e . pytest

Code walkthrough

  • data.py is written only if missing. In stand-in mode the loop makes one commit tagged v0.1.0, so this lab's tag follows it as on a real repository.
  • check=True stops on a failed Git command. %pip install -e . installs the package in editable mode.

You should see one commit marked tag: v0.1.0: yours, or the stand-in.

Step 2: Write the attention core

PACKED ROW: <DOC>MAYA<DOC>TARIQ doc 0 M 1 a 2 y 3 a 4 doc 0 T 1 a 2 r 3 i 4 q 5 document_positions restart at each <doc> document_mask Tariq never reads Maya True = may read one convention, every mask
Packed Maya (blue) and Tariq (amber) need both of Lesson 4's fixes: positions that restart at each <doc> (grey) and a document mask, all in one True-means-read convention.

The core is the function every later module calls, plus its masks. One convention runs through the file, Lesson 4's: True means "this query may read this key". Other conventions are converted at the edge.

python
%%writefile tinyformer/attention.py
"""Attention for tinyformer-lab, Module 2. Masks are boolean: True means a query may read a key."""
import math

import torch
import torch.nn as nn

PAD, DOC = 0, 1                     # shared block 7: <pad> is id 0, <doc> is id 1

def naive_attention(q, k, v, mask=None, return_weights=False, scale=None):
    """Scaled dot-product attention, one step per line (Lessons 1 and 2).
    q: (..., T_q, d_head); k and v: (..., T_k, d_head). scale=None divides by sqrt(d_head)."""
    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

def entropy(w):
    """Entropy of each attention row in nats: 0 for one-hot, log(n) for uniform over n keys."""
    return -(w * w.clamp_min(1e-12).log()).sum(-1)

Code walkthrough

  • naive_attention is Lesson 2's version, the scale switch included; entropy is Lesson 2's saturation measure. Both are unchanged, so the lessons' numbers still apply.
python
%%writefile -a tinyformer/attention.py
def causal_mask(T):
    return torch.ones(T, T, dtype=torch.bool).tril()          # query i reads keys 0..i

def padding_mask(ids):
    return (ids != PAD)[:, None, :]                           # (B, 1, T): nobody reads a pad key

def prefix_mask(T, prefix):
    m = causal_mask(T)
    m[:prefix, :prefix] = True                                # the prefix reads itself both ways
    return m

def document_mask(ids):
    doc = (ids == DOC).cumsum(-1)                             # which document each token belongs to
    return (doc[:, :, None] == doc[:, None, :]) & causal_mask(ids.shape[1])

def sliding_window_mask(T, window):
    return causal_mask(T) & torch.ones(T, T, dtype=torch.bool).triu(-(window - 1))

def document_positions(ids):
    """Positions that restart at every <doc>, so a packed document sits where it would alone."""
    idx = torch.arange(ids.shape[-1]).expand_as(ids)
    start = torch.where(ids == DOC, idx, 0).cummax(-1).values  # where the current document began
    return idx - start

Code walkthrough

  • The five builders are Lesson 4's, unchanged.
  • document_positions is new: Lesson 4 typed the restarted positions by hand ([0..4, 0..5] for Maya and Tariq); this computes them. torch.where keeps each <doc> token's index and 0 elsewhere; cummax carries the latest one forward, so every token knows where its document began.

Step 3: Add the head layers and the cost formulas

4 QUERY HEADS, BASE SHAPE: CACHE FOR ONE 4,096-TOKEN LOG kv 4 q0 q1 q2 q3 kv0 kv1 kv2 kv3 16 MiB MHA kv 2 q0 q1 q2 q3 kv0 kv1 8 MiB GQA kv 1 q0 q1 q2 q3 kv0 4 MiB MQA
One class covers all three layouts: four query heads (amber) share four, two or one key/value heads (blue), and the cache for one 4,096-token log falls from 16 to 4 MiB (green, the smallest).

Two classes cover every head layout. MultiHeadAttention is Lesson 3's. GroupedQueryAttention is Lesson 5's: n_kv_heads equal to n_heads is MHA, 1 is MQA, between is GQA. Both call naive_attention, so scale and mask behave the same everywhere.

python
%%writefile -a tinyformer/attention.py
class MultiHeadAttention(nn.Module):
    """n_heads heads of width d_model // n_heads side by side, then one output projection (Lesson 3)."""
    def __init__(self, d_model, n_heads):
        super().__init__()
        assert d_model % n_heads == 0, "d_model must split evenly into heads"
        self.n_heads, self.d_head = n_heads, d_model // n_heads
        self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)   # every head's W_q, W_k, W_v in one matrix
        self.out = nn.Linear(d_model, d_model, bias=False)       # W_o

    def forward(self, x, mask=None):
        B, T, D = x.shape
        q, k, v = (t.view(B, T, self.n_heads, self.d_head).transpose(1, 2)    # split
                   for t in self.qkv(x).chunk(3, dim=-1))
        y, self.weights = naive_attention(q, k, v, mask, return_weights=True)   # (B, heads, T, d_head)
        return self.out(y.transpose(1, 2).reshape(B, T, D))                    # concatenate, project

class GroupedQueryAttention(nn.Module):
    """n_heads query heads share n_kv_heads key/value heads. n_kv_heads = n_heads is MHA, 1 is MQA (Lesson 5)."""
    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)
        k, v = self.kv(x).view(B, T, 2, self.kv_h, self.hd).permute(2, 0, 3, 1, 4)
        self.cache_shape = tuple(k.shape)                                      # what a generator would store
        g = self.h // self.kv_h
        k, v = k.repeat_interleave(g, dim=1), v.repeat_interleave(g, dim=1)
        return self.out(naive_attention(q, k, v, mask).transpose(1, 2).reshape(B, T, D))

Code walkthrough

  • Both classes are the lessons' versions, unchanged. self.weights keeps the last attention weights for inspection; self.cache_shape records the keys a generator would cache, (batch, key/value heads, tokens, head width).
  • repeat_interleave(g, dim=1) lends each key/value head to g neighbouring query heads.

The cost formulas from Lesson 5 go in the same file, so a report can call them instead of retyping arithmetic.

python
%%writefile -a tinyformer/attention.py
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 (Lesson 5)."""
    return 2 * n_layers * n_kv_heads * d_head * tokens * batch * bytes_per_number

def attention_matrix_bytes(batch, heads, T, bytes_per_number=4):
    """One layer's (batch, heads, T, T) weights."""
    return batch * heads * T * T * bytes_per_number

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 each."""
    return 2 * 2 * T * T * d_model
python
from tinyformer.attention import GroupedQueryAttention, document_positions, kv_cache_bytes, DOC
import torch
packed = torch.tensor([[DOC, 32, 45, 68, 45, DOC, 39, 45, 61, 53, 60]])   # <doc>Maya<doc>Tariq (Lesson 4)
print("restarted positions:", document_positions(packed)[0].tolist())
for n_kv in (4, 2, 1):
    layer = GroupedQueryAttention(128, 4, n_kv)
    layer(torch.randn(2, 128, 128))
    print(f"n_kv_heads {n_kv}: cache {layer.cache_shape} | base, one 4,096-token log: "
          f"{kv_cache_bytes(4, n_kv, 32, 4096) / 2**20:.0f} MiB")

Code walkthrough

  • The import comes from the package file, so this cell tests what the repository holds. packed is Lesson 4's row.

You should see restarted positions: [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5], the positions Lesson 4 typed by hand, then cache shapes from (2, 4, 128, 32) down to (2, 1, 128, 32) and 16, 8 and 4 MiB: Lesson 5's arithmetic, from the package.

Step 4: Turn the lessons' checks into tests

TESTS/TEST_M02_ATTENTION.PY: SEVEN CLAIMS matches SDPA no mask, causal, scale 1 L1, L2 rows sum to 1 weights are averages L1 MHA = PyTorch nn.MultiheadAttention L3 GQA(4) = MHA same weights, same out L5 no future leak MHA and GQA 4, 2, 1 L3 packed = alone mask and positions L4 cost formulas FLOPs and cache bytes L5
Each test (green) is a check a lesson ran once by hand: agreement with PyTorch, row sums, equal layers, the causal leak, packing and cost.

Each lesson ended a section with a check run once by hand. A test runs it on every change. The first four claims: the function matches PyTorch with and without a mask and with scale=1.0; every row of weights sums to 1; MultiHeadAttention matches nn.MultiheadAttention; grouped attention with all four key/value heads is exactly multi-head attention.

python
%%writefile tests/test_m02_attention.py
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.flop_counter import FlopCounterMode
from tinyformer.attention import (DOC, GroupedQueryAttention, MultiHeadAttention, attention_flops, causal_mask,
                                  document_mask, document_positions, kv_cache_bytes, naive_attention)

def qkv(shape=(2, 4, 16, 32), seed=11):
    g = torch.Generator().manual_seed(seed)
    return [torch.randn(*shape, generator=g) for _ in range(3)]

def test_matches_pytorch_with_mask_and_scale():
    q, k, v = qkv()
    for mine, theirs in [({}, {}), ({"mask": causal_mask(16)}, {"is_causal": True}), ({"scale": 1.0}, {"scale": 1.0})]:
        assert torch.allclose(naive_attention(q, k, v, **mine), F.scaled_dot_product_attention(q, k, v, **theirs), atol=1e-5)

def test_rows_sum_to_one():
    _, w = naive_attention(*qkv(), causal_mask(16), return_weights=True)
    assert torch.allclose(w.sum(-1), torch.ones(2, 4, 16))

def test_mha_matches_pytorch():
    torch.manual_seed(11)
    mha, ref = MultiHeadAttention(128, 4), nn.MultiheadAttention(128, 4, bias=False, batch_first=True)
    x = torch.randn(2, 32, 128)
    with torch.no_grad():
        ref.in_proj_weight.copy_(mha.qkv.weight); ref.out_proj.weight.copy_(mha.out.weight)
        theirs, _ = ref(x, x, x, attn_mask=~causal_mask(32), need_weights=False)   # PyTorch: True = blocked
        assert torch.allclose(mha(x, causal_mask(32)), theirs, atol=1e-5)

def test_gqa_with_every_kv_head_is_mha():
    torch.manual_seed(11)
    mha, gqa = MultiHeadAttention(128, 4), GroupedQueryAttention(128, 4, 4)
    with torch.no_grad():
        gqa.q.weight.copy_(mha.qkv.weight[:128]); gqa.kv.weight.copy_(mha.qkv.weight[128:])
        gqa.out.weight.copy_(mha.out.weight)
        x = torch.randn(2, 32, 128)
        assert torch.allclose(gqa(x, causal_mask(32)), mha(x, causal_mask(32)), atol=1e-6)

Code walkthrough

  • The first test loops over three settings, each paired with PyTorch's equivalent keyword: no mask, causal, and the factor removed.
  • ~causal_mask(32) converts to nn.MultiheadAttention's opposite convention at the edge, as Lesson 4 warned.
  • The last test copies MultiHeadAttention's one qkv matrix into the grouped layer's separate query and key/value matrices: rows 0 to 127 are queries, 128 to 383 keys then values, the layout both classes share.

The next claims check behaviour. The causal leak test (Lesson 3) nudges only the last token and requires every earlier output to stay put. The same-as-alone check (Lesson 4) requires packed Tariq to equal Tariq alone. The last pins the FLOP formula to PyTorch's counter.

python
%%writefile -a tests/test_m02_attention.py
def future_leak(layer, T=32, d=128):
    """Largest change in any earlier output when only the last token changes. Causal layers give 0."""
    torch.manual_seed(11)
    x = torch.randn(1, T, d)
    x2 = x.clone()
    x2[0, -1] += 1.0
    with torch.no_grad():
        moved = layer(x, causal_mask(T)) - layer(x2, causal_mask(T))
    return moved[0, :-1].abs().max().item()

def test_no_future_leak():
    for layer in [MultiHeadAttention(128, 4)] + [GroupedQueryAttention(128, 4, n) for n in (4, 2, 1)]:
        assert future_leak(layer) < 1e-6

def test_packed_document_same_as_alone():
    torch.manual_seed(11)
    embed, pos, attn = nn.Embedding(69, 64), nn.Embedding(16, 64), MultiHeadAttention(64, 4)
    maya, tariq = [DOC, 32, 45, 68, 45], [DOC, 39, 45, 61, 53, 60]
    packed, alone = torch.tensor([maya + tariq]), torch.tensor([tariq])
    with torch.no_grad():
        both = attn(embed(packed) + pos(document_positions(packed)), document_mask(packed)[:, None])
        solo = attn(embed(alone) + pos(torch.arange(6)), causal_mask(6))
    assert torch.allclose(both[0, 5:], solo[0], atol=1e-6)

def test_cost_formulas():
    q, k, v = qkv((1, 4, 128, 32))
    with FlopCounterMode(display=False) as counter:
        naive_attention(q, k, v)
    assert counter.get_total_flops() == attention_flops(128, 128)
    assert kv_cache_bytes(4, 4, 32, 4096) == 16 * 2**20          # base, MHA, one 4,096-token log (Lesson 5)
python
!python -m pytest -q tests

Code walkthrough

  • future_leak is Lesson 3's, returning the largest move rather than a count. The threshold 1e-6 allows nothing beyond float32 rounding.
  • test_packed_document_same_as_alone gives the attention layer token and position embeddings, so both of Lesson 4's fixes are needed: document_mask stops Tariq reading Maya, and document_positions puts Tariq at 0 to 5. [:, None] adds the heads axis to the (B, T, T) mask.
  • test_cost_formulas runs naive_attention under FlopCounterMode and requires the exact count Lesson 5 derived.

You should see 11 passed on a cloned repository (Module 1's four tests plus seven), or 7 passed on the stand-in.

Step 5: Write the key/value-head race

REVERSE TASK, 300 STEPS, LR 1E-3 seed 11 seed 12 seed 13 4 kv heads run run run 1,024 B 2 kv heads run run run 512 B 1 kv heads run run run 256 B cache/token same seeds, same batches; only n_kv_heads changes
Nine runs: three head layouts by three seeds, every run seeing the same batches for its seed, with the cache each layout needs per token (amber).

Lesson 5 left Hana's question half answered. Averaging a trained model's key/value heads wrecked GPT-2, because sharing has to be learnt. So train with sharing from the start: the same small decoder with 4, 2 or 1 key/value heads, on the shared reverse task (16 random tokens, a separator, the same tokens backwards), three seeds each. The head count is the only switch.

python
%%writefile experiments/m02_kv_heads.py
"""Module 2 race: 4, 2 or 1 key/value heads on the shared reverse task, three seeds each."""
import json, platform, time
import torch
import torch.nn as nn
import torch.nn.functional as F
from tinyformer.attention import GroupedQueryAttention, causal_mask, kv_cache_bytes
from tinyformer.data import TASKS, set_seed

class Block(nn.Module):
    """Pre-norm block: grouped-query attention, then a feed-forward layer, each added back."""
    def __init__(self, d, n_heads, n_kv_heads):
        super().__init__()
        self.norm1, self.norm2 = nn.LayerNorm(d), nn.LayerNorm(d)
        self.attn = GroupedQueryAttention(d, n_heads, n_kv_heads)
        self.ff = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))

    def forward(self, x, mask):
        x = x + self.attn(self.norm1(x), mask)
        return x + self.ff(self.norm2(x))

class KVLab(nn.Module):
    """Two blocks of width 64 with 4 query heads of 16; n_kv_heads is the only switch."""
    def __init__(self, n_kv_heads, vocab=32, d=64, n_heads=4, layers=2, context=32):
        super().__init__()
        self.embed, self.pos = nn.Embedding(vocab, d), nn.Embedding(context, d)
        self.blocks = nn.ModuleList(Block(d, n_heads, n_kv_heads) for _ in range(layers))
        self.head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, vocab))

    def forward(self, ids):
        x, mask = self.embed(ids) + self.pos(torch.arange(ids.shape[1])), causal_mask(ids.shape[1])
        for block in self.blocks:
            x = block(x, mask)
        return self.head(x)

Code walkthrough

  • Block is Lesson 3's block with GroupedQueryAttention in place of MultiHeadAttention. Module 3 builds the real block.
  • KVLab has two blocks, learned positions and a causal mask from the package. With width 64 and 4 heads, each head is 16 wide.
WHY THE RACE USES A LOWER LEARNING RATE lr 3e-3 (Module 1) all pass 95% by step 50 or 60 checks every 10 steps blur it lr 1e-3 (this lab) passes at step 90 to 110 a speed gap can show trial runs on the reverse task (measured here)
At Module 1's learning rate every layout learnt within the first checks (grey), so the lab slows learning to 1e-3, where a difference in speed has room to show (blue).

The race loop is Module 1's with two changes. A lower learning rate, 1e-3, slows learning enough that a difference in speed can show: in a trial at Module 1's 3e-3 every setting passed 95% by step 50 or 60, the first checks (measured here). And each run records its cache size next to its score, because the trade is accuracy against memory.

python
%%writefile -a experiments/m02_kv_heads.py

N_VALID, STEPS, LR, SEEDS = 512, 300, 1e-3, [11, 12, 13]

@torch.no_grad()
def accuracy(model, task):
    x, y, m = (t[-N_VALID:] for t in (task.inputs, task.targets, task.mask))
    return ((model(x).argmax(-1) == y).float() * m).sum().item() / m.sum().item()

def run(n_kv, task, seed):
    set_seed(seed); model, g = KVLab(n_kv), torch.Generator().manual_seed(seed)
    opt, curve, t0 = torch.optim.AdamW(model.parameters(), lr=LR), [], time.perf_counter()
    for step in range(1, STEPS + 1):
        i = torch.randint(0, len(task.inputs) - N_VALID, (64,), generator=g)
        losses = F.cross_entropy(model(task.inputs[i]).flatten(0, 1), task.targets[i].flatten(), reduction="none")
        loss = (losses * task.mask[i].flatten()).sum() / task.mask[i].sum()
        opt.zero_grad(); loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
        if step % 10 == 0:
            curve.append((step, round(accuracy(model, task), 4)))
    return {"n_kv_heads": n_kv, "seed": seed, "parameters": sum(p.numel() for p in model.parameters()),
            "cache_bytes_per_token": kv_cache_bytes(2, n_kv, 16, 1), "accuracy": curve[-1][1],
            "acc_step_100": dict(curve)[100], "first_step_0.95": next((s for s, a in curve if a >= 0.95), None),
            "seconds": round(time.perf_counter() - t0, 1), "curve": curve}

Code walkthrough

  • accuracy scores the 512 held-out rows. run seeds weights and batches, trains 300 steps of 64 rows, and checks every 10 steps.
  • kv_cache_bytes(2, n_kv, 16, 1) is the package's formula: bytes cached per token for two layers. acc_step_100 and first_step_0.95 measure speed; accuracy is where the run ends.
python
%%writefile -a experiments/m02_kv_heads.py

if __name__ == "__main__":
    task, runs = TASKS["reverse"], []
    for n_kv in (4, 2, 1):
        for seed in SEEDS:
            r = run(n_kv, task, seed)
            runs.append(r)
            print(f"kv heads {n_kv}  seed {seed}  params {r['parameters']:,}  cache/token {r['cache_bytes_per_token']} B"
                  f"  acc@100 {r['acc_step_100']:.3f}  first>=0.95 {r['first_step_0.95']}  final {r['accuracy']:.4f}"
                  f"  {r['seconds']} s", flush=True)
    record = {"experiment": "m02_kv_heads", "task": "reverse, length 16", "label": "measured here",
              "date": time.strftime("%Y-%m-%d"), "python": platform.python_version(), "torch": torch.__version__,
              "threads": torch.get_num_threads(), "machine": platform.platform(),
              "settings": {"steps": STEPS, "batch": 64, "lr": LR, "held_out": N_VALID, "seeds": SEEDS,
                           "d_model": 64, "n_heads": 4, "layers": 2}, "runs": runs}
    with open("runs/m02_kv_heads.json", "w") as f:
        json.dump(record, f, indent=1)
    print("wrote runs/m02_kv_heads.json")

Code walkthrough

  • The __main__ guard runs the race only when the file runs as a script.
  • record is a run record in Module 1's format: the runs, plus the versions, machine and settings that produced them.

Step 6: Run the race and read it against the noise floor

ONE SCRIPT, ONE RECORD fresh python no notebook state m02_kv_heads.py 9 runs, 22 to 23 s m02_kv_heads.json runs, curves, cache versions, settings
The race runs in a fresh process (ink) and writes every measured number (amber) beside the versions and settings that produced it, so Kofi can ask which run.

Run it in a fresh Python process, as Kofi Mensah would.

python
!python experiments/m02_kv_heads.py

Code walkthrough

  • ! runs the script in the shell, so nothing left in the notebook can change the result.

You should see nine lines and the file name. On the author's Mac (Apple silicon, 5 threads, torch 2.14.1; measured here, 10 October 2026):

text
kv heads 4  seed 11  params 105,760  cache/token 1024 B  acc@100 1.000  first>=0.95 90  final 1.0000  2.7 s
kv heads 4  seed 12  params 105,760  cache/token 1024 B  acc@100 0.999  first>=0.95 90  final 1.0000  2.4 s
kv heads 4  seed 13  params 105,760  cache/token 1024 B  acc@100 1.000  first>=0.95 90  final 1.0000  2.5 s
kv heads 2  seed 11  params 97,568  cache/token 512 B  acc@100 0.990  first>=0.95 100  final 1.0000  2.4 s
kv heads 2  seed 12  params 97,568  cache/token 512 B  acc@100 0.986  first>=0.95 100  final 1.0000  2.5 s
kv heads 2  seed 13  params 97,568  cache/token 512 B  acc@100 0.993  first>=0.95 100  final 1.0000  2.8 s
kv heads 1  seed 11  params 93,472  cache/token 256 B  acc@100 0.951  first>=0.95 100  final 1.0000  2.6 s
kv heads 1  seed 12  params 93,472  cache/token 256 B  acc@100 0.885  first>=0.95 110  final 1.0000  2.5 s
kv heads 1  seed 13  params 93,472  cache/token 256 B  acc@100 0.957  first>=0.95 100  final 1.0000  2.5 s
wrote runs/m02_kv_heads.json
FINAL HELD-OUT ACCURACY, STEP 300 (MEASURED HERE) 4 kv heads 2 kv heads 1 kv heads 0.90 0.95 1.00 all nine runs: 1.0000
Where the runs finish, the layouts tie: all nine reach 1.0000 held-out accuracy (green), so final accuracy cannot tell them apart on this task.

Every run ends at 1.0000 held-out accuracy, so on where they finish the three layouts tie. They differ in speed. Read the gap against Kofi's rule from Module 1: a setting beats another only if its worst seed beats the other's best.

python
import json
record = json.load(open("runs/m02_kv_heads.json"))
by = {}
for r in record["runs"]:
    by.setdefault(r["n_kv_heads"], []).append(r)

print(f"{'kv heads':>8} {'params':>8} {'cache/token':>11} {'acc@100 min..max':>17} {'first>=0.95':>12} {'final min':>9}")
for n, rs in by.items():
    acc = [r["acc_step_100"] for r in rs]
    print(f"{n:8d} {rs[0]['parameters']:8,} {rs[0]['cache_bytes_per_token']:9d} B {min(acc):8.3f}..{max(acc):.3f}"
          f" {str([r['first_step_0.95'] for r in rs]):>12} {min(r['accuracy'] for r in rs):9.4f}")

def beats(a, b, key="acc_step_100"):
    """a beats b only if a's worst seed is above b's best seed."""
    return min(r[key] for r in by[a]) > max(r[key] for r in by[b])

for a, b in [(4, 2), (2, 1), (4, 1)]:
    print(f"{a} kv heads beat {b} at step 100, outside the noise floor: {beats(a, b)}")

Code walkthrough

  • by groups the nine runs by key/value heads. The table prints parameters, cache per token, the range of accuracy at step 100, the first step at 95% for each seed, and the worst final accuracy.
  • beats is Kofi's rule, applied to accuracy at step 100.
ACCURACY AT STEP 100: RANGES DO NOT OVERLAP 4 kv heads 0.999 2 kv heads 0.986 1 kv heads 0.885 0.90 0.95 1.00
At step 100 each layout's seed range (blue) sits clear of the next: 0.999 to 1.000, 0.986 to 0.993, then 0.885 to 0.957, so each halving slows learning beyond the noise.

You should see accuracy at step 100 of 0.999 to 1.000 with four key/value heads, 0.986 to 0.993 with two and 0.885 to 0.957 with one. The ranges do not overlap, so beats prints True three times: each halving slows learning by more than the seed noise. Four key/value heads pass 95% at step 90 on every seed; two at step 100; one at 100, 110 and 100. The whole script took 22 to 23 seconds over two runs on the Mac (measured here); allow two to four times that on a free Colab CPU.

THE TRADE, PER LAYOUT (MEASURED HERE) 4 kv heads 1024 B cache 95% by step 90 2 kv heads 512 B cache 95% by step 100 1 kv heads 256 B cache 95% by step 100 to 110 final accuracy 1.0000 for all three
One key/value head cuts the cache per token to a quarter (amber) and costs 10 to 20 steps of learning (blue), with the same final accuracy (green).

So for Hana: on this task, at this size, sharing learnt from the start costs no final accuracy and 10 to 20 steps of speed, for a cache four times smaller (1,024 against 256 bytes per token). One key/value head also means fewer weights, 93,472 against 105,760, so speed and size are not fully separated. One small task, three seeds, one width: measured here, not a law. Module 10 asks again on the corpus.

Step 7: Commit and tag v0.2.0

GIT LOG AFTER THE LAB v0.1.0 Module 1: data v0.2.0 Module 2: attention tinyformer/attention.py tests/test_m02_attention.py m02_kv_heads.py and its record added in this commit, version 0.2.0
The v0.2.0 commit sits on Module 1's v0.1.0 and adds the package file (blue), its tests (green) and the experiment with its run record (amber).

The version moves with the tag, so tinyformer.__version__ always says which module's state you are running.

python
for path in ["pyproject.toml", "tinyformer/__init__.py"]:
    p = pathlib.Path(path)
    p.write_text(p.read_text().replace('"0.1.0"', '"0.2.0"'))
python
!git add -A && git commit -q -m "Module 2: attention.py, attention tests, key/value-head race with 3 seeds"
!git tag v0.2.0
!git log --oneline --decorate && git ls-files

Code walkthrough

  • The first cell changes 0.1.0 to 0.2.0 in the two files that state the version.
  • git add -A stages the new and changed files, commit records them and tag v0.2.0 names the commit. The last line lists the history and the tracked files.

You should see a new commit marked (HEAD -> main, tag: v0.2.0) above the v0.1.0 commit, and tinyformer/attention.py, tests/test_m02_attention.py, experiments/m02_kv_heads.py and runs/m02_kv_heads.json among the files. Push with git push origin main --tags, as in Module 1 (not run here).

Check your work

python
import json, subprocess, sys
import tinyformer
tests = subprocess.run([sys.executable, "-m", "pytest", "-q", "tests/test_m02_attention.py"], capture_output=True, text=True)
record = json.load(open("runs/m02_kv_heads.json"))
runs = record["runs"]
checks = {
    "seven attention tests pass": tests.returncode == 0 and "7 passed" in tests.stdout,
    "3 layouts x 3 seeds recorded": sorted((r["n_kv_heads"], r["seed"]) for r in runs) ==
        sorted((n, s) for n in (4, 2, 1) for s in (11, 12, 13)),
    "cache per token halves with each halving of kv heads": sorted({r["cache_bytes_per_token"] for r in runs}) == [256, 512, 1024],
    "every run finished above 0.99": all(r["accuracy"] > 0.99 for r in runs),
    "record names its versions": {"torch", "python", "threads", "machine"} <= record.keys(),
    "package says 0.2.0": tinyformer.__version__ == "0.2.0" or "0.2.0" in open("tinyformer/__init__.py").read(),
    "tagged v0.2.0": "v0.2.0" in subprocess.run(["git", "tag"], capture_output=True, text=True).stdout,
}
for name, ok in checks.items():
    print("PASS" if ok else "FAIL", name)
print("lab check passed" if all(checks.values()) else "lab check FAILED")

Code walkthrough

  • subprocess.run reruns the seven Module 2 tests in a fresh process; "7 passed" in its output confirms none was skipped.
  • The cache check is arithmetic: 2 layers x 2 x 16 numbers x 4 bytes x key/value heads.
  • The version check also reads the file, because a notebook that imported tinyformer before the bump keeps the old value.

You should see seven PASS lines and lab check passed.

Break it

TOKEN FEATURES IN MEMORY: T0 T1 T2 ... EACH 128 WIDE view, then transpose head h gets columns of every token: rows = tokens reshape straight to heads head 0 gets tokens 0 to 7 whole, read as 32 rows same shape (1, 4, 32, 32) either way
The correct split (green) gives each head a slice of every token; a bare reshape (red) hands each head whole blocks of tokens, so the causal mask's rows stop meaning tokens.

Lesson 3's bug, now against the test suite: split heads with a bare reshape instead of view then transpose. The shape is still right, so only a behaviour test can catch it.

python
import torch
from tinyformer.attention import MultiHeadAttention, naive_attention
from tests.test_m02_attention import future_leak

class WrongSplit(MultiHeadAttention):
    def forward(self, x, mask=None):
        B, T, D = x.shape
        q, k, v = (t.reshape(B, self.n_heads, T, self.d_head)      # the bug: reshape straight to heads
                   for t in self.qkv(x).chunk(3, dim=-1))
        return self.out(naive_attention(q, k, v, mask).transpose(1, 2).reshape(B, T, D))

torch.manual_seed(11)
good = MultiHeadAttention(128, 4)
bad = WrongSplit(128, 4)
bad.load_state_dict(good.state_dict())                              # same weights, only the split differs
x = torch.randn(1, 32, 128)
print("shapes:", tuple(good(x).shape), tuple(bad(x).shape))
print(f"future leak, correct split: {future_leak(good):.1e} | wrong split: {future_leak(bad):.1e}")

Code walkthrough

  • future_leak is imported from the test file, so this is exactly the check pytest runs.
  • load_state_dict gives the broken layer the correct layer's weights: any difference is the split alone.
LARGEST MOVE OF AN EARLIER OUTPUT (MEASURED HERE) correct split 0.0 passes: below 1e-6 wrong split 7.9e-02 fails: 79,000 x the limit both outputs are (1, 32, 128)
Nudging only the last token moves nothing earlier with the correct split (green) and up to 7.9e-02 with the wrong one (red): the leak test catches what a shape check cannot.

Both layers return (1, 32, 128). The correct split moves earlier outputs by exactly 0.0; the wrong one moves them by up to 7.9e-02 (measured here), about 79,000 times the test's 1e-6 threshold, so test_no_future_leak would fail. A shape check passes this bug; the leak test does not, which is why it lives in the suite rather than in a lesson.

What you added to tinyformer-lab

  • tinyformer/attention.py: naive_attention with scale, entropy, five mask builders in one convention, document_positions, MultiHeadAttention, GroupedQueryAttention and three cost formulas.
  • tests/test_m02_attention.py: seven tests, from agreement with PyTorch to the causal leak test, the same-as-alone packing check and the FLOP count.
  • experiments/m02_kv_heads.py and runs/m02_kv_heads.json: 4, 2 and 1 key/value heads on the reverse task, three seeds each.
  • Version 0.2.0, tagged v0.2.0.

Going further

  • Add Lesson 5's CrossAttention and window_mask reach check to the package, each with a test.
  • Rerun the race on TASKS["induction"] and see whether the ordering holds.
  • Add a test that padding_mask with left padding and positions counted from the mask gives every name the same outputs as alone (Lesson 4's exercise).
  • Add scale as an argument to both head classes and rerun Lesson 2's with-and-without comparison through the package.