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

Lesson 1: Scaled dot-product attention, derived and built by hand

18 min read·
Module 2 · Lesson 1 · About 50 minutes · Needs: Module 1, Lessons 1 and 2 (tensors, dot products, softmax, the copy race)

The situation

Sol 404 at Aurora Station. In Module 1 your transformer beat the GRU, but its attention came from PyTorch's ready-made nn.TransformerEncoderLayer. Kofi Mensah will not sign off a part nobody in the lab has opened. "Write attention yourself," he says, "and show me it gives the same numbers."

This lesson starts tinyformer/attention.py. If you met attention in the ai-engineering course (Module 6, Lesson 1), skim sections 1 and 3; the checks, shapes and head survey are new.

A real case, first

On 8 March 2022 Catherine Olsson, Nelson Elhage, Neel Nanda and colleagues at Anthropic published "In-context Learning and Induction Heads" (transformer-circuits.pub). They describe a circuit of "a pair of attention heads in different layers". The first is a "previous token head" that copies information from each token into the next. The second, the induction head, makes "…[A][B]…[A] … more likely to be completed with [B]".

THE LOG LINE, AS GPT-2 READS IT Maya Lind ... Maya ? [A] [B] [A] again predict [B] look back at what followed [A] last time, copy it
Olsson and colleagues describe an induction head: at the second [A] it attends to the token that followed the first [A] (amber, a learnt weight) and raises the chance of predicting [B] (green).

They report that these heads form in "a phase change that occurs early in training for language models of every size" (with more than one layer), and may account for most in-context learning. They call their evidence "a circumstantial case", stronger for small models than large. The point for this lesson: a head's job can be read off its attention weights. By the end you will find an induction head in GPT-2 with your own code.

What you will be able to do

  • Derive attention from a dictionary lookup, checking each step in code.
  • Write naive_attention and match PyTorch's built-in.
  • Trace the five steps, naming every shape.
  • Read an attention matrix's rows, columns and axes, and catch the wrong-axis bug.
  • Read one GPT-2 head and sort all 144 by pattern.

1. Deriving scaled dot-product attention (Essential)

Every transformer runs one formula many times. Derive it once and every later variant (masks, heads, caches) is a small edit. Paste the torch setup cell and shared block 1 first.

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: PyTorch, the CPU, seed 11. 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().
query: Maya Maya greenhouse Kofi reactor bay Hana comms mast 1 value key value exact match or nothing: no notion of almost
A dictionary lookup returns the one value whose key matches exactly (green) and ignores the rest (grey), so there is no way to say a query was nearly right.

Start with a Python dictionary. Ask for "Maya" and you get Maya's value; every other row is ignored. The copy task needs exactly this. Its flaw for learning: a query is an exact match or nothing, so nothing says "you were close".

QUERY: 0.7 MAYA + 0.3 KOFI Maya score +1.012 0.651 Kofi score -0.251 0.184 Hana score -0.362 0.165 softmax: weights sum to 1 output = 0.651 Maya + 0.184 Kofi + 0.165 Hana
Attention scores every key, turns the scores into weights that sum to 1 with a softmax (amber, uncertain shares), and returns the weighted blend of the values.

Now make keys and query vectors. Score the query against each key, turn the scores into weights with a softmax, and return the weighted blend of the values: a soft lookup. Our query is mostly Maya, a little Kofi.

python
import torch.nn.functional as F

set_seed()
keys = torch.randn(3, 4) * 0.5                       # one key per crew member: Maya, Kofi, Hana
values = torch.eye(3)                                # what each hands over: Maya [1,0,0], Kofi [0,1,0] ...
query = (0.7 * keys[0] + 0.3 * keys[1]).requires_grad_()   # mostly "Maya", a little "Kofi"

scores = keys @ query                                # one similarity per key
hard = F.one_hot(scores.argmax(), 3).float()         # a dictionary: the best key wins outright
soft = scores.softmax(dim=-1)                        # attention: every key wins a share
print("scores", [round(s, 3) for s in scores.tolist()])
print("hard  ", hard.tolist(), "| can learn from it:", (hard @ values).requires_grad)
print("soft  ", [round(w, 3) for w in soft.tolist()])
(soft @ values)[0].backward()                        # how should the query move to read more of Maya?
print("gradient on the query", [round(g, 3) for g in query.grad.tolist()])
for sharpen in [1, 4, 16]:
    print(f"scores x{sharpen:2d}", [round(w, 3) for w in (sharpen * scores.detach()).softmax(-1).tolist()])

Code walkthrough

  • values = torch.eye(3) makes each value a label, so the output says how much of each person was read.
  • query is 0.7 of Maya's key plus 0.3 of Kofi's; requires_grad_() tracks its gradient.
  • keys @ query is three dot products. argmax then one_hot is the dictionary; softmax the soft version. argmax returns an index, so the hard output has no gradient.
  • backward() on Maya's share fills query.grad. The loop multiplies the scores by 1, 4 and 16 before the softmax.
THE SAME SCORES MULTIPLIED BEFORE THE SOFTMAX scores x1 0.651 scores x4 0.990 scores x16 1.000 Maya's share grows towards 1: the hard lookup is the limit
Multiplying the scores by 4 or 16 pushes Maya's weight from 0.651 to 0.990 and then 1.000, so the hard lookup is the extreme case of the soft one.

Scores 1.012, -0.251 and -0.362 give weights 0.651, 0.184 and 0.165. Multiply the scores by 4 and Maya's share is 0.990; by 16, 1.000. The dictionary is the extreme case of the soft lookup, so attention can learn to act like one.

hard: argmax weights [1, 0, 0] no gradient to the query soft: softmax weights [0.651, 0.184, 0.165] a gradient on the query training needs the second: it says which way to move
The argmax lookup (red) gives the query no gradient at all, while the softmax lookup (green) tells the query exactly how to move to read more of Maya.

The difference that matters is the gradient. The hard lookup printed False. The soft lookup gave the query a gradient, a direction to move to read more of Maya. Training can only shape what it can differentiate.

SCORE OF QUERY I AGAINST KEY J q1 k1 x q2 k2 x q3 k3 x q4 k4 x s_ij = sum one number
One attention score is a dot product: multiply query i and key j slot by slot and add the products, giving one number that is large when the two point the same way.

Which similarity? The dot product: multiply slot by slot and add. It is large when two vectors point the same way. Bahdanau's attention (Module 1, Lesson 3) used a small network per pair; the dot product wins because all pairs are one matrix product.

python
set_seed()
T, d = 4, 4                                          # 4 positions, 4 numbers per query, key and value
Q, K, V = torch.randn(T, d), torch.randn(T, d), torch.randn(T, d)

out_loops = torch.zeros(T, d)
for i in range(T):                                   # one query at a time
    s = torch.stack([sum(Q[i, c] * K[j, c] for c in range(d)) for j in range(T)]) / d ** 0.5
    a = s.exp() / s.exp().sum()                      # softmax over the keys, by hand
    out_loops[i] = sum(a[j] * V[j] for j in range(T))

out_matrix = torch.softmax(Q @ K.T / d ** 0.5, dim=-1) @ V   # the same thing as two matrix products
print("largest difference:", (out_loops - out_matrix).abs().max().item())
print("multiply-adds for scores and sum:", 2 * T * T * d)

Code walkthrough

  • In self-attention every position makes a query, a key and a value, so Q, K and V have one row per position.
  • The loop is the derivation written literally: a sum over slots c, divided by the square root of d, a hand-written softmax, a weighted sum of value rows.
  • Q @ K.T makes all 16 scores at once; softmax(dim=-1) normalises each row; @ V mixes. The last line counts the multiply-adds.
loops for i, for j, for c: multiply, add, softmax, mix two matrix products softmax(Q K^T / 2) V all 16 scores at once largest difference 1.2e-07: the same numbers
Writing every sum as a loop and writing the whole thing as two matrix products give outputs that agree to 1.2e-07 (measured here), which is float32 rounding.

The versions differ by 1.2e-07, float32 rounding. Both do 128 multiply-adds (arithmetic: 2 x 4 x 4 x 4), a count that grows with the square of the length (Module 10).

softmax( Q K^T / sqrt(d) ) V rows to weights all scores keep moderate values mixed d = 4 here; Lesson 2 derives why sqrt(d)
The whole derivation in one line: Q K^T makes every score, dividing by sqrt(d) keeps them moderate, the softmax turns each row into weights (amber), and V supplies what gets mixed (blue).

Assembled, this is the formula from Section 3.2.1 of "Attention Is All You Need" (Vaswani et al., 2017): scaled dot-product attention. The division by the square root of d keeps scores moderate as vectors get wider; Lesson 2 derives that factor and breaks it.

2. Naive attention, line by line (Essential)

The lab keeps two versions of attention: a plain one you can read and print, and the fast built-in later modules use. Kofi's test is that they agree.

NAIVE_ATTENTION DOES STEPS 2 TO 5 1 project x to q, k, v 2 score q @ k^T 3 scale / sqrt(d) 4 normalise mask, softmax 5 mix weights @ v step 1 belongs to the layer that owns the weights (Lesson 3)
Attention is five steps: project the tokens, score every pair, scale, mask and normalise each row into weights, and mix the values; the lab's naive_attention writes steps 2 to 5 one per line.

The five steps: project tokens into queries, keys and values; score every pair; scale; normalise each row with a softmax, after masking forbidden pairs; mix the values. Projection needs learned weights, so it lives in the layer (Lesson 3).

python
import math

def naive_attention(q, k, v, mask=None, return_weights=False):
    """Scaled dot-product attention, one step per line.
    q: (..., T_q, d_head); k and v: (..., T_k, d_head); mask: True where a query may look."""
    scores = q @ k.transpose(-2, -1)                        # step 2: every query against every key
    scores = scores / math.sqrt(q.shape[-1])                # step 3: divide by sqrt(d_head)
    if mask is not None:
        scores = scores.masked_fill(~mask, float("-inf"))   # step 4a: forbidden pairs score -inf
    weights = scores.softmax(dim=-1)                        # step 4b: each row sums to 1 over the keys
    out = weights @ v                                       # step 5: weighted sum of value rows
    return (out, weights) if return_weights else out

set_seed()
q, k, v = (torch.randn(32, 4, 128, 32) for _ in range(3))  # base sizes: batch 32, 4 heads, 128 tokens, 32 wide
causal = torch.ones(128, 128, dtype=torch.bool).tril()
for name, mine, theirs in [
        ("no mask", naive_attention(q, k, v), F.scaled_dot_product_attention(q, k, v)),
        ("causal ", naive_attention(q, k, v, causal), F.scaled_dot_product_attention(q, k, v, is_causal=True))]:
    print(name, tuple(mine.shape), "largest difference from PyTorch:", f"{(mine - theirs).abs().max().item():.1e}")

Code walkthrough

  • k.transpose(-2, -1) swaps the keys' last two axes, so q @ k^T scores every pair for every batch item and head at once; any leading axes work.
  • math.sqrt(q.shape[-1]) reads the head width from the tensor.
  • masked_fill(~mask, float("-inf")) sets forbidden scores to minus infinity, which the softmax turns into exactly 0. Lesson 4 builds every mask; here only the causal mask (each token sees itself and earlier ones) appears, made by torch.ones(...).tril().
  • softmax(dim=-1) normalises over the last axis, the keys. return_weights returns the weights for inspection.
  • The test uses the base model's sizes (course-guide/06): batch 32, 4 heads, 128 tokens, head width 32.
LARGEST DIFFERENCE FROM F.SCALED_DOT_PRODUCT_ATTENTION no mask 9.5e-07 causal 8.3e-07 shape (32, 4, 128, 32), float32, measured here
At the base model's sizes, naive_attention and PyTorch's built-in differ by under 1e-6 with and without the causal mask (green, passed): float32 rounding, not a bug.

The largest differences were 9.5e-07 and 8.3e-07: float32 rounding from adding in a different order. A real bug shows up as 1e-2 or worse.

3. Tracing the five steps on Maya (Essential)

Shapes are where attention code breaks. Tracing a tiny example, printing everything, shows what each line does.

ONE HEAD, THE FOUR CHARACTERS OF MAYA M 32 a 45 y 68 a 45 x (1, 4, 8) q (1, 4, 4) k (1, 4, 4) v (1, 4, 4) weights (1, 4, 4) out (1, 4, 4)
The running example: the four characters of Maya become a (1, 4, 8) tensor, then queries, keys and values of (1, 4, 4), a (1, 4, 4) weight grid (amber) and a (1, 4, 4) output (blue).

The running example is the name Maya: ids 32, 45, 68, 45 in the shared character tokeniser (course-guide/06, block 7 printed encode("Maya")), typed in so this lesson needs no corpus. One head, width 8, head width 4.

python
ids = torch.tensor([[32, 45, 68, 45]])          # "Maya" in the shared character tokeniser (block 7)
set_seed()
embed = torch.nn.Embedding(69, 8)               # 69 tokens in the vocabulary, 8 numbers each
W_q, W_k, W_v = (torch.randn(8, 4) / 8 ** 0.5 for _ in range(3))   # one head: 8 in, 4 out

with torch.no_grad():
    x = embed(ids)                              # (1, 4, 8): batch, tokens, width
    q, k, v = x @ W_q, x @ W_k, x @ W_v         # step 1: project            -> (1, 4, 4) each
    scores = q @ k.transpose(-2, -1)            # step 2: score              -> (1, 4, 4)
    scaled = scores / math.sqrt(4)              # step 3: scale
    mask = torch.ones(4, 4, dtype=torch.bool).tril()
    weights = scaled.masked_fill(~mask, float("-inf")).softmax(-1)   # step 4: mask and normalise
    out = weights @ v                           # step 5: mix the values     -> (1, 4, 4)

for name, t in [("x", x), ("q", q), ("scores", scores), ("weights", weights), ("out", out)]:
    print(f"{name:8}{tuple(t.shape)}")
print("scaled scores, row 3 (the second 'a'):", [round(s, 2) for s in scaled[0, 3].tolist()])
print(weights[0].numpy().round(2))
print("same as naive_attention:", torch.allclose(out, naive_attention(q, k, v, mask)))

Code walkthrough

  • nn.Embedding(69, 8) is a random table, one row per token in the shared vocabulary; embed(ids) picks four rows.
  • The projections are random, divided by the square root of the input width to keep values moderate; a trained model learns them. torch.no_grad() skips gradient tracking.
  • Each step is one line, its shape in the comment. The last line checks the trace against naive_attention.
SCALED SCORES (ROWS: QUERIES, COLUMNS: KEYS) M a y a M -1.19 -inf -inf -inf a 0.97 0.15 -inf -inf y 0.52 0.18 -0.47 -inf a 0.97 0.15 -0.35 0.15 row 1 = row 3: same letter a, same query
The scaled scores for Maya: grey cells are future positions set to minus infinity by the causal mask, and rows 1 and 3 are equal because both are the letter a.

Row 3, the second a, is [0.97, 0.15, -0.35, 0.15]. Row 1, the first a, is identical: same character, same query. Upper-triangle cells are minus infinity: no reading ahead.

ATTENTION WEIGHTS AFTER THE SOFTMAX M a y a M 1.00 0 0 0 sum 1 a 0.69 0.31 0 0 sum 1 y 0.48 0.34 0.18 0 sum 1 a 0.46 0.21 0.12 0.21 sum 1
After the softmax every row is a set of weights summing to 1 (darker amber means more weight), masked cells are exactly 0, and row 0 is [1, 0, 0, 0] whatever its score was.

After the softmax, row 0 is [1, 0, 0, 0] whatever its score of -1.19: a first token can only read itself. Row 3 is [0.46, 0.21, 0.12, 0.21], and the trace matches naive_attention.

OUTPUT FOR THE SECOND A (ROW 3) v of M x 0.46 v of a x 0.21 v of y x 0.12 v of a x 0.21 out row 3 [0.29, -0.48, -0.91, 0.88]
Step 5 for the second a: its output is 0.46 of M's value, 0.21 of each a's and 0.12 of y's, a weighted average that cannot leave the range of the values it mixes.

Step 5 for row 3 mixes 0.46 of M's value, 0.21 of each a's and 0.12 of y's. Weights are positive and sum to 1, so each output is an average: a head blends what it sees and cannot go outside that range.

4. Attention matrix shape and meaning (Essential)

The weight matrix is the one object you can print, plot and test. Knowing its rows, columns and axes turns a silent bug into a failed check.

READING THE WEIGHT GRID TWO WAYS a row: where one query reads from always sums to 1 a column: how much one key is read sums here: 2.64, 0.86, 0.30, 0.21
A row of the attention matrix is a probability distribution over keys and sums to 1; a column says how much one key is read and can sum to anything (2.64 for M here).

A row answers "where does this query read from?" and sums to 1. A column answers "how much is this key read?" and sums to anything. The rows and columns of an attention matrix are not interchangeable, and the next block proves it.

python
A = weights[0]                                   # (4, 4): rows are queries, columns are keys
print("row sums   ", A.sum(-1).tolist())
print("column sums", [round(c, 2) for c in A.sum(0).tolist()])
print("row 0      ", A[0].tolist())
print("'a' at 1 and 3, same key:", torch.equal(k[0, 1], k[0, 3]),
      "| row 3 weights on them:", round(A[3, 1].item(), 3), round(A[3, 3].item(), 3))

order = torch.tensor([2, 0, 3, 1])               # shuffle the four tokens: "yMaa"
with torch.no_grad():
    out_plain = naive_attention(q, k, v)                       # no mask, no positions
    out_shuffled = naive_attention(q[:, order], k[:, order], v[:, order])
print("shuffle in, same shuffle out:", torch.allclose(out_shuffled, out_plain[:, order], atol=1e-6))
print("the two 'a' outputs are identical:", torch.allclose(out_plain[0, 1], out_plain[0, 3]))

Code walkthrough

  • A.sum(-1) adds across rows; A.sum(0) down columns. torch.equal confirms the two a's share a key.
  • order rearranges the positions. Comparing attention on shuffled tokens (no mask) with the shuffled original output tests whether attention notices order.

Rows sum to 1 (one prints 0.99999994, rounding). Columns sum to 2.64, 0.86, 0.30 and 0.21: M is read most, partly because every row sees it. Row 3 gives each a exactly 0.206.

THE ATTENTION WEIGHT TENSOR batch 32 1 heads 4 12 queries 128 21 keys 128 21 base GPT-2 line the softmax runs over the last axis: keys
The attention weights form a (batch, heads, queries, keys) tensor: (32, 4, 128, 128) for one base batch and (1, 12, 21, 21) per layer for GPT-2 on the log line.

A real model adds two axes: (batch, heads, queries, keys). One base layer on a training batch holds 32 x 4 x 128 x 128 = 2,097,152 weights (arithmetic). Queries and keys can differ in length (see the exercise).

M a y a -> y M a a no mask, no positions outputs move with their tokens the two a's identical q, k, v identical outputs attention alone cannot see order (Module 4 adds it)
Without a mask or positions, shuffling Maya's letters only shuffles the outputs, and both a's produce identical outputs: attention by itself does not know order.

The shuffle printed True twice. Without a mask or positions, attention is permutation equivariant: reorder the inputs and the outputs reorder the same way, and the two a's get identical outputs. Module 4 adds positions.

Break it: softmax down the wrong axis

Normalise over queries instead of keys. It is one character, -2 for -1, and nothing crashes.

python
def wrong_axis_attention(q, k, v, mask):
    scores = (q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])).masked_fill(~mask, float("-inf"))
    return scores.softmax(dim=-2) @ v, scores.softmax(dim=-2)   # the bug: normalise down the columns

with torch.no_grad():
    bad_out, bad_w = wrong_axis_attention(q, k, v, mask)
print("shape still fine:", tuple(bad_out.shape))
print("row sums   ", [round(r, 2) for r in bad_w[0].sum(-1).tolist()])
print("column sums", [round(c, 2) for c in bad_w[0].sum(-2).tolist()])
print("row 0 now reads", round(bad_w[0, 0, 0].item(), 2), "of its own value")
assert torch.allclose(weights.sum(-1), torch.ones(1, 4)), "rows must sum to 1"
print("the row-sum test catches it:", not torch.allclose(bad_w.sum(-1), torch.ones(1, 4)))

Code walkthrough

  • wrong_axis_attention is naive_attention with softmax(dim=-2): each column now sums to 1 instead of each row.
  • The assert is the test that goes into the lab: correct weights pass it, and the last line shows the broken ones fail it.
softmax(dim=-1) row sums 1, 1, 1, 1 each query's weights softmax(dim=-2) row sums 0.04, 0.69, 1.04, 2.22 shape still (1, 4, 4) a one-line row-sum test catches it
Normalising down the wrong axis (red) keeps every shape correct, so nothing crashes, but rows now sum to 0.04 to 2.22; checking that rows sum to 1 catches it.

The output keeps its (1, 4, 4) shape, so a shape check passes. But rows sum to 0.04, 0.69, 1.04 and 2.22. A model with this bug still trains, just badly. The one-line row-sum test goes into tests/test_m02_attention.py.

5. Reading one real attention head (Recommended)

Random weights show the arithmetic; a trained model shows its purpose. GPT-2 small, the course's reference model, has 12 layers of 12 heads.

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

text = "Log 4821, sol 212. Maya Lindqvist repaired the oxygen recycler. Maya Lindqvist"
ids = tok(text, return_tensors="pt")["input_ids"]
pieces = [tok.decode([i]) for i in ids[0]]
with torch.no_grad():
    run = ref(ids, output_attentions=True)
ATT = torch.stack(run.attentions)[:, 0]          # (layers, heads, T, T) for our one sentence
print(len(pieces), "tokens:", pieces)
print("one layer:", tuple(run.attentions[0].shape), "| all layers:", tuple(ATT.shape))

Code walkthrough

  • The loading lines are the course standard (course-guide/02, section 6). attn_implementation="eager" selects the plain path, the only one that returns weights.
  • text is a corpus-style log line with Maya's name twice: the [A][B] ... [A] pattern.
  • output_attentions=True returns one (1, 12, T, T) tensor per layer; torch.stack(...)[:, 0] makes one (12, 12, 21, 21) tensor.

The line is 21 tokens: ' Maya' at positions 7 and 17, then Lindqvist split into ' Lind', 'qv', 'ist'.

python
first, second = [i for i, p in enumerate(pieces) if p == " Maya"]
w = ATT[:, :, second, first + 1]                 # every head: weight from the 2nd " Maya" to the token after the 1st
layer, head = divmod(int(w.argmax()), 12)
row = ATT[layer, head, second, : second + 1]
print(f"layer {layer} head {head}, query {pieces[second]!r} at position {second}")
for j in row.topk(3).indices.tolist():
    print(f"   key {j:2d} {pieces[j]!r:12} weight {row[j].item():.3f}")
print("GPT-2's next-token guess after the 2nd ' Maya':", repr(tok.decode(run.logits[0, second].argmax())))
diag = ATT[layer, head].diagonal(offset=-(second - first - 1))   # the stripe "the token after my earlier copy"
print("weights on that stripe for the repeated name:", [round(x, 2) for x in diag[-4:].tolist()])

Code walkthrough

  • w is a (12, 12) table: for every head, the weight from the second ' Maya' to ' Lind' (key 8). divmod(..., 12) turns its largest entry's position into a layer and head.
  • row.topk(3) lists that head's three largest weights; run.logits[0, second].argmax() is GPT-2's next-token guess.
  • diagonal(offset=-9) reads cells nine below the diagonal: each repeated token looking at the token after its earlier copy.
GPT-2 SMALL, LAYER 5 HEAD 5, QUERY: THE SECOND MAYA Log pos 0 0.056 Maya pos 7 0.000 Lind pos 8 0.942 repaired pos 11 0.001 Maya pos 17 0.000 GPT-2 then predicts ' Lind'
In GPT-2 small, head 5 of layer 5 sends 0.942 of the second Maya's attention to Lind, the token after the first Maya, and the model's next-token guess is Lind (measured here).

Layer 5, head 5 puts 0.942 of the second Maya's attention on ' Lind', the token after the first Maya, and GPT-2's guess is ' Lind'. That is the induction pattern Olsson and colleagues describe, found in a published model with your own code.

LAYER 5 HEAD 5 ON THE LOG LINE (21 TOKENS) Maya Lind Maya Lind Log Lind Log stripe: 0.94, 1.00, 0.88, 0.95
The whole matrix of head 5.5: early rows park their weight on the first token, and once the name repeats each token reads the one after its earlier copy, an off-diagonal stripe of 0.88 to 1.00.

Along the repeated name the stripe reads 0.94, 1.00, 0.88 and 0.95. Still, one sentence is an anecdote; section 6 tests every head properly.

6. Every head at a glance (Recommended)

You cannot read 144 heads one by one; you can read one summary number per head. Clark and colleagues did this for BERT ("What Does BERT Look At?", 2019, arXiv:1906.04341) and found heads attending to delimiter tokens, fixed offsets, or broadly.

previous token (4.11) induction (5.5) first token (5.7)
Three GPT-2 heads on the same log line: 4.11 reads the previous token (a line under the diagonal), 5.5 is the induction head, and 5.7 parks its weight on the first token (darker amber is more weight).

Three heads, one line: 4.11 reads the token just before, 5.5 is the induction stripe, 5.7 puts nearly everything on the first token. Each pattern becomes a score: weight on the previous position, on the token after an earlier copy, on position 0.

python
g = torch.Generator().manual_seed(SEED)
R = 50                                                     # 50 random tokens, then the same 50 again
rnd = torch.randint(1000, 10000, (4, R), generator=g)
seq = torch.cat([torch.full((4, 1), tok.bos_token_id), rnd, rnd], dim=1)   # (4, 101)
with torch.no_grad():
    A = torch.stack(ref(seq, output_attentions=True).attentions)          # (12, 4, 12, 101, 101)
pos = torch.arange(R + 1, 2 * R + 1)                       # positions in the repeat
score = {"induction": A[..., pos, pos - R + 1].mean((1, 3)),          # the token after my earlier copy
         "previous":  A[..., torch.arange(1, 2 * R + 1), torch.arange(0, 2 * R)].mean((1, 3)),
         "first":     A[..., 1:, 0].mean((1, 3))}                      # parked on position 0
kind = torch.full((12, 12), 3)                              # 3 = mixed
kind[score["first"] > 0.5] = 2
kind[score["previous"] > 0.4] = 1
kind[score["induction"] > 0.4] = 0
for name, n in zip(["induction", "previous", "first", "mixed"], torch.bincount(kind.flatten(), minlength=4)):
    print(f"{name:10}{n.item():4d} heads")
print(f"head {layer}.{head} induction score {score['induction'][layer, head]:.3f}")
print("first-token share by layer", [round(x, 2) for x in score["first"].mean(1).tolist()])

Code walkthrough

  • As in Olsson and colleagues' test, the input is random tokens repeated: four rows of 50 random ids, written twice after GPT-2's <|endoftext|> token (bos_token_id). Only copying can predict the repeat.
  • A[..., pos, pos - R + 1] picks each repeated position's weight on the token after its earlier copy; .mean((1, 3)) averages over rows and positions, leaving a (12, 12) score.
  • The previous-token score takes cells one below the diagonal; the first-token score takes column 0.
  • kind labels each head by the tests it passes (thresholds 0.4 and 0.5, chosen here, not standard); bincount counts labels.
GPT-2 SMALL: 12 LAYERS (ROWS) X 12 HEADS 0 1 2 3 4 5 6 7 8 9 10 11 induction previous token first token mixed measured on 50 random tokens, repeated
Every head of GPT-2 small sorted by one rule on repeated random tokens: induction heads (amber) first appear in layer 5, just after the previous-token heads (blue) they need.

Head 5.5 scored 0.922, so the anecdote holds on data built for the test. The induction heads begin in layer 5; previous-token heads appear from layer 2. That order fits the two-layer circuit, though it does not prove it.

144 HEADS, ONE LABEL EACH first token 53 induction 11 previous token 6 mixed 74
Of 144 heads, 53 park most weight on the first token, 11 are induction heads, 6 read the previous token and 74 fit none of the three tests (measured here).

The labels rest on two thresholds chosen here, so treat them as a map, not a census. Module 14 measures what heads do by switching them off.

AVERAGE WEIGHT PARKED ON POSITION 0, BY LAYER 0.08 0 0.18 1 0.23 2 0.33 3 0.48 4 0.54 5 0.47 6 0.61 7 0.63 8 0.59 9 0.52 10 0.42 11 layer
The share of attention parked on the first position (grey, background) rises from 0.08 in layer 0 to 0.63 in layer 8 (measured here on repeated random tokens).

The biggest group is the surprise: weight parked on position 0 rises from 0.08 in layer 0 to 0.63 in layer 8. One common reading: rows must sum to 1, so a head needs somewhere to put weight when nothing matches, and the first token is always visible.

In production

fused kernel (default) returns the output only weights never stored eager / naive path returns output and weights (B, H, T, T) kept in memory train and serve on the left, inspect on the right
Production code runs a fused kernel that never stores the weight matrix (blue); reading heads needs the eager path, which keeps every (B, H, T, T) weight (amber).

Nobody serves naive_attention. PyTorch's documentation for scaled_dot_product_attention (version 2.14, checked October 2026) lists three implementations it may pick (FlashAttention-2, a memory-efficient kernel, a C++ version of the formula) and says it returns the attention output only. Fused kernels never store the (B, H, T, T) matrix; Module 10 measures why. So transformers 5, fused by default, needs attn_implementation="eager" to return weights. The lab keeps both paths and a test that they agree.

What you added to tinyformer-lab

  • naive_attention for tinyformer/attention.py: steps 2 to 5, any leading axes, optional mask and weights.
  • A check against F.scaled_dot_product_attention and a row-sum test, for tests/test_m02_attention.py.
  • A head survey of GPT-2 small: three scores for all 144 heads.
  • The module lab saves all three into the package.

Check yourself

  1. Why can a dictionary lookup not be trained, and what replaces it?
  2. Why is row 0 of a causal attention matrix always [1, 0, 0, 0]?
  3. A column of the weight matrix sums to 2.64. Is that a bug?
  4. Why did the two a's in Maya get identical outputs without a mask?
  5. Head 5.5 put 0.942 on ' Lind'. Why is one sentence not enough to call it an induction head?
  1. argmax returns an index, which has no gradient. The softmax gives every key a share that changes smoothly, so the query gets a gradient.
  2. The mask leaves one allowed key, and the softmax of a single number is 1.
  3. No. Rows are distributions and must sum to 1; columns count how much a key is read and can sum to anything.
  4. Same character, so same query, key and value; nothing marks position.
  5. One sentence is an anecdote. On repeated random tokens (200 positions, no meaning to lean on) it scored 0.922.

Exercise

Queries and keys need not match in number: a new token reading a cache has one query and many keys. Predict the weight and output shapes when 2 queries read 4 keys, then run the check.

python
def cross_attention_check(n_queries=2, n_keys=4, d_head=8):
    set_seed()
    q = torch.randn(1, n_queries, d_head)                 # 2 queries ...
    k, v = torch.randn(1, n_keys, d_head), torch.randn(1, n_keys, d_head)   # ... reading 4 keys
    out, w = naive_attention(q, k, v, return_weights=True)
    assert w.shape == (1, n_queries, n_keys), "weights are (queries, keys)"
    assert out.shape == (1, n_queries, d_head), "one output per query"
    assert torch.allclose(w.sum(-1), torch.ones(1, n_queries)), "each query's row sums to 1"
    assert torch.allclose(out, F.scaled_dot_product_attention(q, k, v), atol=1e-6)
    return tuple(w.shape), tuple(out.shape)
print(cross_attention_check(), "check passed")

Code walkthrough

  • q has 2 rows; k and v have 4. The asserts check both shapes, the row sums and agreement with PyTorch.
  • It printed ((1, 2, 4), (1, 2, 8)) check passed. Then set n_keys to 7 and predict before rerunning.

Key terms

TermMeaning
Soft lookupScore every key, weight every value by its softmax share, return the blend
Scaled dot-product attentionsoftmax(QK^T / sqrt(d)) V
Causal maskEach token may read itself and earlier tokens only
Attention matrix(queries, keys) weights; each row sums to 1
Permutation equivariantShuffle the inputs and the outputs shuffle the same way
Previous-token headA head whose weight sits on the token just before
Induction headA head that reads the token after an earlier copy of the current one

Sources

  • Catherine Olsson, Nelson Elhage, Neel Nanda et al. (Anthropic), "In-context Learning and Induction Heads", 2022. https://transformer-circuits.pub/2022/in-context-learning-and-induction-heads/index.html
  • Ashish Vaswani et al., "Attention Is All You Need", 2017, Section 3.2.1. https://arxiv.org/abs/1706.03762
  • Kevin Clark, Urvashi Khandelwal, Omer Levy, Christopher D. Manning, "What Does BERT Look At? An Analysis of BERT's Attention", 2019. https://arxiv.org/abs/1906.04341
  • PyTorch, torch.nn.functional.scaled_dot_product_attention, documentation for version 2.14, checked October 2026. https://docs.pytorch.org/docs/2.14/generated/torch.nn.functional.scaled_dot_product_attention.html