Lab: Build Multi-Head Causal Self-Attention from Scratch
Implement scaled dot-product attention and a multi-head causal self-attention module in PyTorch, verify shapes, causality and agreement with PyTorch built-ins, combine causal and padding masks without producing NaN, and train the layer on a tiny task to see its heads learn to look at the previous token.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Attention for any batch shape
- Step 2: The multi-head module
- Step 3: Test causality directly
- Step 4: Agree with nn.MultiheadAttention
- Step 5: Padding masks without NaN
- Step 6: Watch the heads learn
- Check your understanding
- Apply it
- Review prompt
Lessons of Transformer Architecture
- Attention as Soft Lookup: Queries, Keys and Values Concept · 20 min
- Lab: Build Multi-Head Causal Self-Attention from Scratch Lab · 30 min
- Anatomy of a Transformer Block and the Three Model Families Concept · 25 min
- Tokens In, Tokens Out: Tokenizers, Decoding Controls and the KV Cache Concept · 25 min
- Lab: Fine-Tune a Pretrained Encoder for Classification Lab · 30 min
- Check: Inside the Transformer Knowledge check · 8 questions
What you will learn
- Implement scaled dot-product and multi-head self-attention with causal masking in PyTorch and verify output shapes and masking behaviour.
Prerequisites: Deep Learning Fundamentals
01. Goal and setup
In the previous lesson you computed attention for one short sequence by hand. Real models run it on batches of sequences, with several heads in parallel, behind masks. In this lab you write that module yourself, about 30 lines, and then test it the way you would test any numerical code: shapes first, then the property that matters most (no position may see the future), then agreement with a trusted implementation, then the awkward cases (padding), and finally a small training run that shows the layer can learn.
Multi-head attention splits the model dimension into h smaller pieces and runs attention on each piece separately. With d_model = 32 and 4 heads, each head works with 8-dimensional queries, keys and values. Different heads can learn to look for different things, for example one head the previous token and another the start of the sentence, and their outputs are then placed side by side and mixed by a final linear layer.
You need: Python 3.12 and PyTorch 2 (CPU build). Every script is seeded; on PyTorch 2.15 your output should match, and on other versions or CPUs the last digit of a few numbers may differ.
attention-lab/
├── attention.py step 1: attention() and causal_mask()
├── test_attention.py step 1: shapes and a check against PyTorch
├── mha.py step 2: the CausalSelfAttention module
├── test_causal.py step 3: does any output depend on the future?
├── compare_torch.py step 4: same weights in nn.MultiheadAttention
├── padding.py step 5: padding masks and NaN rows
└── copy_task.py step 6: train the layer on a tiny taskmkdir attention-lab && cd attention-lab
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install "torch==2.15.*" \
--index-url https://download.pytorch.org/whl/cpu02. Step 1: Attention for any batch shape
attention is the formula from the previous lesson, written so that it works on tensors with any number of leading dimensions: (T, d) for one sequence, or (batch, heads, T, d) for many. k.transpose(-2, -1) swaps the last two axes only, and @ treats the leading axes as a batch. The mask is a boolean tensor where True means "this query may attend to this key"; forbidden scores become −∞ before the softmax. The test compares the output with torch.nn.functional.scaled_dot_product_attention and checks two properties of the weights.
import torch
def attention(q, k, v, allowed=None):
"""q, k, v: (..., T, d). allowed: bool (..., T, T), True = query may attend."""
scores = q @ k.transpose(-2, -1) / q.size(-1) ** 0.5
if allowed is not None:
scores = scores.masked_fill(~allowed, float("-inf"))
weights = torch.softmax(scores, dim=-1)
return weights @ v, weights
def causal_mask(T):
return torch.tril(torch.ones(T, T, dtype=torch.bool))import torch
import torch.nn.functional as F
from attention import attention, causal_mask
torch.manual_seed(0)
B, H, T, d = 2, 4, 6, 8
q, k, v = torch.randn(3, B, H, T, d).unbind(0)
out, weights = attention(q, k, v, causal_mask(T))
ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print("output", tuple(out.shape), "weights", tuple(weights.shape))
print("matches PyTorch:", torch.allclose(out, ref, atol=1e-6))
print("weights above the diagonal all zero:", bool((weights.triu(1) == 0).all()))
print("every row sums to 1:", torch.allclose(weights.sum(-1), torch.ones(B, H, T)))python test_attention.pyoutput (2, 4, 6, 8) weights (2, 4, 6, 6)
matches PyTorch: True
weights above the diagonal all zero: True
every row sums to 1: True03. Step 2: The multi-head module
The module computes the queries, keys and values of all heads with one linear layer of size d_model → 3 × d_model, because one large matrix product is faster than many small ones. The interesting part is the reshaping. view(B, T, heads, d_head) cuts each 32-number vector into 4 pieces of 8, and transpose(1, 2) moves the head axis in front of the time axis, so that attention sees each head as a separate batch entry: shape (B, heads, T, d_head). After attention, the reverse steps put the heads side by side again, and self.out mixes them. The mask has shape (T, T) and broadcasts over batch and heads.
import torch
from torch import nn
from attention import attention, causal_mask
class CausalSelfAttention(nn.Module):
def __init__(self, d_model, n_heads, causal=True):
super().__init__()
self.causal = causal
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) # all heads' q, k, v in one matmul
self.out = nn.Linear(d_model, d_model) # mixes the heads back together
def forward(self, x, allowed=None):
B, T, D = x.shape
q, k, v = self.qkv(x).split(D, dim=-1) # each (B, T, D)
# (B, T, D) -> (B, T, heads, d_head) -> (B, heads, T, d_head)
q, k, v = (t.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
for t in (q, k, v))
mask = causal_mask(T) if self.causal else torch.ones(T, T, dtype=torch.bool)
if allowed is not None: # e.g. a padding mask of shape (B, 1, 1, T)
mask = mask & allowed
y, self.last_weights = attention(q, k, v, mask) # (B, heads, T, d_head)
y = y.transpose(1, 2).reshape(B, T, D) # put the heads side by side again
return self.out(y)
if __name__ == "__main__":
torch.manual_seed(0)
layer = CausalSelfAttention(d_model=32, n_heads=4)
x = torch.randn(2, 5, 32)
y = layer(x)
print("input", tuple(x.shape), "-> output", tuple(y.shape))
print("attention weights", tuple(layer.last_weights.shape), "(batch, heads, T, T)")
print("parameters:", sum(p.numel() for p in layer.parameters()))python mha.pyinput (2, 5, 32) -> output (2, 5, 32)
attention weights (2, 4, 5, 5) (batch, heads, T, T)
parameters: 4224The output has the same shape as the input, (2, 5, 32), which is what lets transformer blocks be stacked. The weights have one 5 × 5 matrix per sequence and per head. The parameter count, 4,224, is 32 × 96 + 96 for qkv plus 32 × 32 + 32 for out; it does not depend on the number of heads, because the heads are slices of the same projection, not extra layers. The last reshape uses .reshape rather than .view: after transpose, the numbers are no longer laid out in memory in the new order, and view refuses to work on such a tensor, while reshape copies the data when it has to.
04. Step 3: Test causality directly
The defining property of causal attention is that the output at position t depends only on positions 0 to t. Checking that every row of weights sums to 1, or that the output differs from the input, would pass for a layer with no mask at all. The direct test changes one token and records which outputs move. The script runs it on the causal layer and on a copy with the same weights but no mask.
"""Does any output depend on a later token? Change one token and see what moves."""
import torch
from mha import CausalSelfAttention
torch.manual_seed(0)
causal = CausalSelfAttention(d_model=32, n_heads=4).eval()
full = CausalSelfAttention(d_model=32, n_heads=4, causal=False).eval()
full.load_state_dict(causal.state_dict()) # same weights, no causal mask
x = torch.randn(1, 6, 32)
x2 = x.clone()
x2[0, 3] += 1.0 # change only the token at position 3
for name, layer in (("causal", causal), ("no mask", full)):
with torch.no_grad():
change = (layer(x) - layer(x2)).abs().amax(-1)[0] # per position
print(f"{name:8} positions whose output changed:",
[int(c > 1e-6) for c in change.tolist()])python test_causal.pycausal positions whose output changed: [0, 0, 0, 1, 1, 1]
no mask positions whose output changed: [1, 1, 1, 1, 1, 1]With the mask, changing token 3 moves the outputs at positions 3, 4 and 5 and leaves 0, 1 and 2 untouched. Without it, every position moves, including the three that come before the change. Keep this test in your project: it catches a mask that is inverted, missing or broadcast along the wrong axis, which shape tests never notice. .eval() matters here only out of habit; the layer has no dropout, but in a full model dropout would make two forward passes differ for reasons unrelated to the mask.
05. Step 4: Agree with nn.MultiheadAttention
torch.nn.MultiheadAttention uses the same packed layout for its input projection (the rows for all queries, then all keys, then all values), so the weights can be copied straight across. One convention differs and causes many bugs: in its boolean attn_mask, True means the position is not allowed, the opposite of the mask in this lab and of scaled_dot_product_attention. The script therefore passes ~causal_mask(T).
"""Load the same weights into nn.MultiheadAttention and compare outputs."""
import torch
from torch import nn
from attention import causal_mask
from mha import CausalSelfAttention
torch.manual_seed(0)
ours = CausalSelfAttention(d_model=32, n_heads=4)
theirs = nn.MultiheadAttention(embed_dim=32, num_heads=4, batch_first=True)
with torch.no_grad(): # same packed layout: rows of q, then k, then v
theirs.in_proj_weight.copy_(ours.qkv.weight)
theirs.in_proj_bias.copy_(ours.qkv.bias)
theirs.out_proj.weight.copy_(ours.out.weight)
theirs.out_proj.bias.copy_(ours.out.bias)
x = torch.randn(2, 5, 32)
T = x.size(1)
# nn.MultiheadAttention: a True entry in a bool attn_mask means NOT allowed
y_theirs, _ = theirs(x, x, x, attn_mask=~causal_mask(T), need_weights=False)
print("max difference:", f"{(ours(x) - y_theirs).abs().max():.1e}")
print("same result:", torch.allclose(ours(x), y_theirs, atol=1e-6))python compare_torch.pymax difference: 8.9e-08
same result: TrueA difference of about 1e-7 is floating-point rounding: the two implementations add the same numbers in a slightly different order. When you compare implementations, use torch.allclose with a tolerance, never exact equality.
06. Step 5: Padding masks without NaN
Sequences in a batch have different lengths, so shorter ones are filled with pad tokens up to the longest. A padding mask hides the pad positions as keys, so that no query takes information from them. It has shape (B, 1, 1, T): one row per sequence, broadcast over heads and over query positions, and the module combines it with the causal mask using &. Pads can go at the end (right padding, common for training classifiers) or at the start (left padding, common when generating text in batches, so that every sequence ends at the same position).
"""Two sequences of length 5 and 3 in one batch, padded to 5 positions."""
import torch
from mha import CausalSelfAttention
torch.manual_seed(0)
layer = CausalSelfAttention(d_model=32, n_heads=4).eval()
lengths = torch.tensor([5, 3])
x = torch.randn(2, 5, 32)
pos = torch.arange(5)
cases = {
"right": pos[None, :] < lengths[:, None], # (B, T): True = real token
"left": pos[None, :] >= 5 - lengths[:, None],
}
for side, real in cases.items():
allowed = real[:, None, None, :] # (B, 1, 1, T): hide pad keys from every query
with torch.no_grad():
y = layer(x, allowed)
w = layer.last_weights[1, 0] # second sequence, first head
print(f"{side} padding, sequence 2 is real at {real[1].int().tolist()}")
print(" weight on pad keys:", f"{w[:, ~real[1]].nan_to_num().sum():.1f}",
"| rows with NaN:", torch.isnan(y[1]).any(-1).int().tolist())
real = cases["left"]
allowed = real[:, None, None, :] | torch.eye(5, dtype=torch.bool) # self is allowed
with torch.no_grad():
y = layer(x, allowed)
print("left padding, pads may see themselves | rows with NaN:",
torch.isnan(y[1]).any(-1).int().tolist())python padding.pyright padding, sequence 2 is real at [1, 1, 1, 0, 0]
weight on pad keys: 0.0 | rows with NaN: [0, 0, 0, 0, 0]
left padding, sequence 2 is real at [0, 0, 1, 1, 1]
weight on pad keys: 0.0 | rows with NaN: [1, 1, 0, 0, 0]
left padding, pads may see themselves | rows with NaN: [0, 0, 0, 0, 0]In both layouts the pad keys get zero weight. With left padding, though, the outputs at positions 0 and 1 of the short sequence are NaN. Those two positions are pads, so their own key is hidden, and the causal mask hides every later key. A query with every key masked has a softmax of −∞ values only, which is 0 divided by 0. Those outputs are never used for a prediction, but a NaN in the forward pass can still turn gradients into NaN in the backward pass. The fix in the last line lets each position attend to itself, so every row keeps at least one allowed key; another common fix is to fill with a large negative number instead of −∞.
07. Step 6: Watch the heads learn
Correct code should also be able to learn. The task here is to output, at each position, the token that came just before it. A model can only solve it by attending to the previous position, so the attention weights after training show directly whether the layer works. Token embeddings are added to learned position embeddings, one vector per position, because the attention scores themselves contain no information about where a key sits.
"""Train one attention layer to output the previous token, then look at its weights."""
import torch
from torch import nn
from mha import CausalSelfAttention
torch.manual_seed(0)
V, T, D = 10, 8, 32
class TinyModel(nn.Module):
def __init__(self):
super().__init__()
self.tok = nn.Embedding(V, D)
self.pos = nn.Embedding(T, D) # without positions, "previous" means nothing
self.attn = CausalSelfAttention(D, n_heads=2)
self.head = nn.Linear(D, V)
def forward(self, ids):
h = self.tok(ids) + self.pos(torch.arange(ids.size(1)))
return self.head(self.attn(h))
model = TinyModel()
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
for step in range(1, 201):
ids = torch.randint(0, V, (64, T))
logits = model(ids)[:, 1:] # position t predicts the token at t - 1
loss = nn.functional.cross_entropy(logits.reshape(-1, V), ids[:, :-1].reshape(-1))
opt.zero_grad()
loss.backward()
opt.step()
if step in (1, 50, 200):
print(f"step {step:3d}: loss {loss.item():.3f}")
with torch.no_grad():
ids = torch.randint(0, V, (256, T))
acc = (model(ids)[:, 1:].argmax(-1) == ids[:, :-1]).float().mean()
w = model.attn.last_weights.mean(0) # average over the batch: (heads, T, T)
print(f"accuracy on new sequences: {acc:.3f}")
for h in range(2):
prev = torch.stack([w[h, t, t - 1] for t in range(1, T)]).mean()
print(f"head {h}: average weight on the previous position {prev:.2f}")python copy_task.pystep 1: loss 2.323
step 50: loss 0.003
step 200: loss 0.000
accuracy on new sequences: 1.000
head 0: average weight on the previous position 0.99
head 1: average weight on the previous position 0.99The loss starts near ln 10 ≈ 2.30, the value for guessing one of 10 tokens at random, and falls to almost zero within 50 steps. On new random sequences the accuracy is 1.000, and both heads put 0.99 of their weight on the previous position: the layer has learned exactly the lookup the task needs. In a trained language model you find heads like this one next to others that track syntax or copy earlier phrases; the next lesson puts this layer into a full transformer block.
08. Check your understanding
09. Apply it
For the decoder-only transformer in your practice project:
- Replace the hand-written
attentioncall inCausalSelfAttentionwithF.scaled_dot_product_attention(q, k, v, is_causal=True)and check withtest_causal.pyandcompare_torch.pythat nothing changes. - Turn the three checks from steps 1, 3 and 5 into
pytesttests. - Train the copy task with a target three positions back instead of one, and inspect which heads learn it.
10. Review prompt
Without looking back, write down the shapes of x, q after the head split, the weights and the output of a multi-head layer; explain why heads add no parameters; describe the test that proves a layer is causal and why weaker tests are not enough; state the boolean mask convention of nn.MultiheadAttention and of scaled_dot_product_attention; and explain when padding masks produce NaN and two ways to avoid it.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.