Lab: Package attention and test every claim
Module 2 · Lab · About 60 minutes · Needs: lessons 1 to 5 of this module, and Module 1's lab
What you are building
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
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).
git clone https://github.com/<your-account>/tinyformer-lab.gitCode walkthrough
git clonecopies the repository, its history and itsv0.1.0tag. 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.
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_INis True when no.gitfolder is here.SKELETONis Module 1's Step 1 files, written only where missing.
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_PYholds Module 1'stinyformer/data.py: shared block 1 and the start of block 9, unchanged. The next cell adds the rest of block 9.
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)%pip install -q -e . pytestCode walkthrough
data.pyis written only if missing. In stand-in mode the loop makes one commit taggedv0.1.0, so this lab's tag follows it as on a real repository.check=Truestops 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
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.
%%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_attentionis Lesson 2's version, thescaleswitch included;entropyis Lesson 2's saturation measure. Both are unchanged, so the lessons' numbers still apply.
%%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 - startCode walkthrough
- The five builders are Lesson 4's, unchanged.
document_positionsis new: Lesson 4 typed the restarted positions by hand ([0..4, 0..5]for Maya and Tariq); this computes them.torch.wherekeeps each<doc>token's index and 0 elsewhere;cummaxcarries the latest one forward, so every token knows where its document began.
Step 3: Add the head layers and the cost formulas
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.
%%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.weightskeeps the last attention weights for inspection;self.cache_shaperecords the keys a generator would cache, (batch, key/value heads, tokens, head width). repeat_interleave(g, dim=1)lends each key/value head togneighbouring query heads.
The cost formulas from Lesson 5 go in the same file, so a report can call them instead of retyping arithmetic.
%%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_modelfrom 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.
packedis 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
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.
%%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 tonn.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.
%%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 -m pytest -q testsCode walkthrough
future_leakis Lesson 3's, returning the largest move rather than a count. The threshold1e-6allows nothing beyond float32 rounding.test_packed_document_same_as_alonegives the attention layer token and position embeddings, so both of Lesson 4's fixes are needed:document_maskstops Tariq reading Maya, anddocument_positionsputs Tariq at 0 to 5.[:, None]adds the heads axis to the (B, T, T) mask.test_cost_formulasrunsnaive_attentionunderFlopCounterModeand 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
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.
%%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
Blockis Lesson 3's block withGroupedQueryAttentionin place ofMultiHeadAttention. Module 3 builds the real block.KVLabhas two blocks, learned positions and a causal mask from the package. With width 64 and 4 heads, each head is 16 wide.
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.
%%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
accuracyscores the 512 held-out rows.runseeds 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_100andfirst_step_0.95measure speed;accuracyis where the run ends.
%%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. recordis 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
Run it in a fresh Python process, as Kofi Mensah would.
!python experiments/m02_kv_heads.pyCode 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):
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.jsonEvery 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.
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
bygroups 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.beatsis Kofi's rule, applied to accuracy at step 100.
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.
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
The version moves with the tag, so tinyformer.__version__ always says which module's state you are running.
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"'))!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-filesCode walkthrough
- The first cell changes
0.1.0to0.2.0in the two files that state the version. git add -Astages the new and changed files,commitrecords them andtag v0.2.0names 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
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.runreruns 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
tinyformerbefore the bump keeps the old value.
You should see seven PASS lines and lab check passed.
Break it
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.
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_leakis imported from the test file, so this is exactly the checkpytestruns.load_state_dictgives the broken layer the correct layer's weights: any difference is the split alone.
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_attentionwithscale,entropy, five mask builders in one convention,document_positions,MultiHeadAttention,GroupedQueryAttentionand 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.pyandruns/m02_kv_heads.json: 4, 2 and 1 key/value heads on the reverse task, three seeds each.- Version
0.2.0, taggedv0.2.0.
Going further
- Add Lesson 5's
CrossAttentionandwindow_maskreach 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_maskwith left padding and positions counted from the mask gives every name the same outputs as alone (Lesson 4's exercise). - Add
scaleas an argument to both head classes and rerun Lesson 2's with-and-without comparison through the package.