Lesson 3.3: Causal masking and multi-head attention
See why a language model must not look at future tokens, what happens when it does (a loss below the best possible), and how several heads split the work.
By the end of this lesson you will be able to build a causal mask and explain why next-token prediction needs it, recognise a model that cheats by its loss, test any model for leaks from the future, and explain how several heads split one attention layer and what they cost. You will show that a model trained without the mask reaches a validation loss of 0.1979, which is far below the best possible 0.988 and therefore impossible without cheating, that it puts 68.2% of its weight on the very token it must predict, that it scores 3.8774 when the mask is applied, worse than a uniform guess (3.5264), that a one-, two- and four-head layer have the same 2,112 numbers and reach 1.0061, 1.0058 and 1.0078, and that two heads are exactly two separate attentions glued side by side. You need Python and NumPy, helpers.py from Lesson 3.1 and attention.py from Lesson 3.2.
The attention layer of Lesson 3.2 already contained a mask, and we used it without much comment. This lesson explains it, by breaking it. It then returns to the one part of the layer that we kept fixed at one: the number of heads.
Why the future must be hidden
The training task is to predict the next token. In a window of tokens t0, t1, t2, t3, ..., the input at position 2 is t2, and the target is t3. But t3 is also the input at position 3. If position 2 is allowed to attend to position 3, then the answer to the question it is being asked is sitting in its own input. The model would not learn to predict anything. It would learn to copy the next input, and the loss would fall to nearly zero.
At generation time, the next token does not exist yet. A model that learned to rely on it has nothing to rely on, and fails. So each position may use itself and earlier positions only. That is the causal mask: a T by T pattern that allows position t to see positions 0 to t, and blocks the rest. It is the lower triangle of ones that appeared in Lesson 3.1.
The mask is applied to the scores, before the softmax. Entries for blocked positions are set to minus infinity, so that their weight is exactly zero, and the softmax spreads the whole weight over the allowed positions.
python
import numpy as np
from helpers import
rng = np.random.defaultrng(0)
T = 5
S = np.round(rng.standardnormal((T, T)), 1) # raw scores: every position against every position
print(S)
Smasked = np.where(np.triu(np.ones((T, T), dtype=bool), 1), -np.inf, S)
A = softmax(Smasked)
print(np.round(A, 3))
print(A.sum(axis=1)) # every row still sums to 1
print(np.round(softmax(S), 3)[0]) # position 0 without a mask: it sees all five tokens
The first matrix is the raw scores of five positions against five. The second is the weights after the mask and the softmax: the upper triangle is zero. Row 0 puts all of its weight on position 0, since that is all it may see (1.0). Row 1 splits it between positions 0 and 1 (0.289 and 0.711). Row 4 may see all five. The third line shows that every row still sums to 1. The last line shows what position 0 would do with no mask: 0.199, 0.163, 0.329, 0.199 and 0.109 on positions 0 to 4, spread over tokens it should never see.
Three details about the mask matter.
Mask before the softmax, not after. Zeroing weights after the softmax leaves rows that no longer sum to one, and the remaining weights are too small. Putting minus infinity in the scores makes the softmax renormalise over what is left.
Minus infinity or a large negative number. Both work. Minus infinity is exact. A large negative number such as minus one billion is safer in a hand-written backward pass, since it never produces a NaN, even if a row were entirely masked. In a causal mask each row keeps at least its own diagonal entry, so it cannot be.
The diagonal stays open. Position t can attend to itself. Closing it would leave position 0 with nothing to look at.
There are other kinds of mask. A padding mask blocks positions that hold padding to fill a batch, so that no real token attends to filler. And models used for understanding text, such as those that classify or embed a sentence, often use no causal mask, since they have the whole sentence and no next-token task. Those are called bidirectional or encoder models. A model that writes text one token at a time is called a decoder, and uses the causal mask. The rest of this course builds a decoder.
What happens without the mask
Let us train the same model with and without the mask, and look.
python
import numpy as np
from helpers import
from attention import
T, d = 16, 16
P = sinusoidal(T, d)
def train(causal, steps=3000, lr=0.01, seed=0):
p = init(V, d, seed=seed)
opt = Adam(p, lr)
rng = np.random.defaultrng(seed)
for step in range(steps):
x, y = getbatch(trainids, 32, T, rng)
loss, g = lossandgrads(p, x, y, 1, P, causal)
opt.step(g)
return p
def validation(p, causal):
x, y = getbatch(valids, 400, T, np.random.defaultrng(123))
logits, cache = forward(p, x, 1, P, causal)
return crossentropy(logits, y)[0], cache
def futureleak(p, causal):
"""Change the token at position 8. Do the outputs at positions 0..7 change?"""
x, = getbatch(valids, 4, T, np.random.defaultrng(7))
x2 = x.copy(); x2[:, 8] = (x2[:, 8] + 1) % V
a, = forward(p, x, 1, P, causal)
b, = forward(p, x2, 1, P, causal)
return not np.allclose(a[:, :8], b[:, :8])
masked, unmasked = train(True), train(False)
print("uniform guess", round(np.log(V), 4))
print("masked : validation", round(validation(masked, True)[0], 4), " leaks:", futureleak(masked, True))
loss, cache = validation(unmasked, False)
print("unmasked : validation", round(loss, 4), " leaks:", futureleak(unmasked, False))
A = cache["A"][:, 0] # (400, T, T)
future = np.mean([A[:, t, t + 1:].sum(axis=-1).mean() for t in range(T - 1)])
answer = np.mean([A[:, t, t + 1].mean() for t in range(T - 1)])
print("weight on later positions", round(float(future), 3), " on position t+1", round(float(answer), 3))
print("unmasked model, evaluated with the mask:", round(validation(unmasked, True)[0], 4))
The output:
uniform guess 3.5264
masked : validation 1.0061 leaks: False
unmasked : validation 0.1979 leaks: True
weight on later positions 0.749 on position t+1 0.682
unmasked model, evaluated with the mask: 3.8774
Look at the second line. The unmasked model reports a validation loss of 0.1979, against 1.0061 for the masked one. It looks five times better. It is not. On this language, the best any model can do is 0.988 (Lesson 1.1), because the next word is genuinely uncertain. A loss of 0.1979 is below that floor, which cannot be reached honestly. It is evidence of a leak.
The next line shows the leak. The unmasked model puts 74.9% of its attention on later positions, and 68.2% on position t+1 alone: the token it is asked to predict. And the last line shows the cost: when the mask is applied, as it would be at generation time, the same model scores 3.8774, worse than a uniform guess of 3.5264 (which is the logarithm of 34). It has learned nothing about language.
This is a lesson that applies far beyond masks. A loss that is better than the best possible is a bug. When a result looks too good, find the floor and compare. Here we know the floor from the structure of the language. In real data you may not, but you can always check for leaks directly.
A test for leaks
The futureleak function in the code is a general test. Change one token at position 8. If the model is causal, nothing at positions 0 to 7 can change, since they cannot see position 8. Compare the outputs before and after. For the masked model, leaks is False. For the unmasked model, it is True. Run this test on any model you build or modify. It takes a few lines, and it catches a whole family of mistakes: a mask applied to the wrong axis, a shift that is off by one, a batch that mixes sequences, a position vector that carries future information.
Several heads
So far each position makes one query, and gets one weighted average of values. That is one pattern of attention per position per layer. A real sentence needs several kinds of looking at once: the previous word, the subject of the verb, the matching bracket. A single weighted average can blend them, and a single softmax can only focus on one place sharply.
The remedy is to run several attentions side by side, called heads. The model width d is split into h slices of size dh equal to d divided by h. Each head has its own slice of the query, key and value matrices, so its own idea of what to look for. Each head produces an output of size dh. The h outputs are glued together into one vector of size d, and the output matrix Wo mixes them.
Nothing is added to the parameter count. A single head with width 16 uses four 16 by 16 matrices. Two heads with width 8 use the same matrices, read as two column blocks of eight. What changes is the number of score matrices: h of them, each T by T. We can check all of this.
python
import numpy as np
from helpers import
from attention import
T, d = 16, 16
P = sinusoidal(T, d)
def train(h, steps=3000, lr=0.01, seed=0):
p = init(V, d, seed=seed)
opt = Adam(p, lr)
rng = np.random.defaultrng(seed)
for step in range(steps):
x, y = getbatch(trainids, 32, T, rng)
loss, g = lossandgrads(p, x, y, h, P)
opt.step(g)
return p
models = {}
for h in (1, 2, 4):
p = train(h)
x, y = getbatch(valids, 400, T, np.random.defaultrng(123))
logits, cache = forward(p, x, h, P)
models[h] = (p, cache)
print(h, "heads: validation", round(crossentropy(logits, y)[0], 4),
" parameters", sum(w.size for w in p.values()), " head size", d // h)
what each head attends to: average weight by distance back
p, cache = models[2]
for head in range(2):
A = cache["A"][:, head]
print("head", head, [round(float(np.mean([A[:, t, t - o].mean() for t in range(8, T)])), 2) for o in range(6)])
one layer with two heads is two independent attentions side by side
x = cache["x"]; H0 = cache["H0"]; dh = cache["dh"]
outs = []
for head in range(2):
sl = slice(head dh, (head + 1) dh)
Q, K, Vv = H0 @ p["Wq"][:, sl], H0 @ p["Wk"][:, sl], H0 @ p["Wv"][:, sl]
S = Q @ K.transpose(0, 2, 1) / np.sqrt(dh)
S = np.where(np.triu(np.ones((T, T), dtype=bool), 1), -1e9, S)
A = softmax(S)
print("head", head, "matches the layer:", np.allclose(A, cache["A"][:, head]))
outs.append(A @ Vv)
print("glued heads match:", np.allclose(np.concatenate(outs, axis=-1), cache["Oc"]))
The output:
1 heads: validation 1.0061 parameters 2112 head size 16
2 heads: validation 1.0058 parameters 2112 head size 8
4 heads: validation 1.0078 parameters 2112 head size 4
head 0 [0.76, 0.14, 0.01, 0.09, 0.0, 0.0]
head 1 [0.83, 0.04, 0.14, 0.0, 0.0, 0.0]
head 0 matches the layer: True
head 1 matches the layer: True
glued heads match: True
Four findings.
The parameter count does not change. 2,112 in every case.
Two heads are two independent attentions. The last three lines rebuild head 0 and head 1 by hand, from separate column blocks of the matrices, each with its own softmax. Their weights match the layer's, and the glued outputs match its output. There is no extra magic: a multi-head layer is a loop over heads.
The heads look at different places. Each prints its average weight by distance back. Head 0 puts 0.76 on the current token, 0.14 on the previous token and 0.09 three back. Head 1 puts 0.83 on the current token and 0.14 two back. The patterns differ, which is the point.
There is no gain on this language. The validation loss is 1.0061, 1.0058 and 1.0078: the same, within the noise of different random starts. Four heads of size 4 are slightly worse, since each head has only four numbers to work with. We also tried a harder lookup, asking for two values at once, and one head solved that too. The toy language and our small tasks do not need several patterns at once, so the heads have nothing to specialise on.
Why real models use many heads anyway
In large trained transformers, researchers who open them up report heads with distinct jobs. Some attend mostly to the previous token. Some attend to an earlier occurrence of the current token and copy what followed it, a pattern called an induction head, studied by Olsson and colleagues. Some track position within a sentence. A single head cannot do all of these in a layer, because it makes one weighted average. With 12, 32 or 96 heads, a layer can hold many patterns at once, each in a small slice of the width.
Do not read that as a promise that more heads are always better. Our measurements show the opposite on a small task: nothing to gain, and a small loss with tiny heads. The number of heads is a design choice with a trade: more heads give more patterns, smaller heads give each less room. Common sizes keep each head around 64 to 128 numbers wide.
What the mask and the heads cost
Three numbers set the cost for a layer with width d, T tokens and h heads: the size of each head (d divided by h), the number of score entries (h times T times T), and how many of those the mask lets through.
The mask lets through T(T+1)/2 entries per head: 136 of 256 for T = 16, which is 53.1%. For a long sequence it approaches half. A straightforward implementation still computes the whole T by T matrix and throws half away. Better implementations skip the blocked half, which halves the work.
Key takeaways
Next-token prediction needs a causal mask. The target for position t is the input at position t+1, so position t must not attend to it. The mask sets the scores of future positions to minus infinity before the softmax, and each row still sums to one.
Apply the mask to the scores, not the weights. Keep the diagonal open.
Without the mask the model cheats. It reached a validation loss of 0.1979, below the best possible (0.988), with 68.2% of its attention on the answer. Evaluated with the mask it scored 3.8774, worse than a uniform guess (3.5264).
A loss better than the best possible is a bug. Compare with a known floor whenever a result looks too good.
Test for leaks: change the token at one position and check that outputs at earlier positions do not change. It passed for the masked model and failed for the unmasked one.
Heads run several attentions side by side on slices of the width, then glue the results. The parameter count is unchanged (2,112 for 1, 2 and 4 heads). A two-head layer matches two hand-built single heads.
On the toy language the heads attended to different distances and gave no gain: 1.0061, 1.0058 and 1.0078. Large models use many heads because they must track many relations at once.
The mask lets through (T+1)/2T of each score matrix: 53.1% for T = 16.
Common mistakes
Training without a mask and celebrating the loss. The loss will look excellent and the model will be useless.
Masking the weights after the softmax. Rows no longer sum to one.
Masking the wrong axis. The upper triangle of a score matrix, with rows as queries and columns as keys, is the future. Transposing it blocks the past.
A mask in the model but not in an evaluation script. Evaluate with the same mask you train with, or the numbers will not compare.
Off-by-one in the targets. If the target equals the input, a causal model learns to copy and the loss collapses. Lesson 2.4 asserts the shift for this reason.
Assuming more heads are free. Heads shrink as they multiply (d divided by h), and each needs its own score matrix.
Leaking across a batch. Sequences joined without a boundary can attend into each other. Use separators or masks that block them.
Check yourself
1. Why must position t not attend to position t+1 in a language model?
The target for position t is the token at t+1, which is also the input at t+1. Attending to it would hand the model the answer.
2. A masked row of scores is [0.5, 1.0, minus infinity, minus infinity]. What are the weights?
The softmax over the first two: e⁰·⁵ = 1.649 and e¹ = 2.718, which sum to 4.367, so about 0.378 and 0.622.
3. A model reports a validation loss of 0.2 on a task whose best possible loss is 0.9. What do you conclude, and what do you check?
The loss is impossibly good, so there is probably a leak. Check the mask, the target shift and whether validation data appears in the training input, and run the future-change test.
4. A layer has width 512 and 8 heads. How big is each head, and how many parameters do the four attention matrices have?
Each head is 512 ÷ 8 = 64. The four matrices have 4 × 512² = 1,048,576 parameters, whatever the number of heads.
5. For a sequence of 1,024 tokens, what share of each score matrix does the causal mask allow?
(1,024 + 1) ÷ (2 × 1,024) = 0.50049, about 50.05%.
6. Why might you use no causal mask in a model that classifies sentences?
It has the whole sentence and no next-token task, so each token may use the tokens on both sides. That gives more information and leaks nothing.
Try this
Set aside two hours. You need Python, NumPy, helpers.py and attention.py.
1. Run the mask demo with T = 8 and your own seed. Verify that the rows sum to one and that the upper triangle is zero.
2. Run the leak test on the masked model, and then change the mask in forward so that position t may also see position t+1. Which test shows it first, the loss or the future-change test?
3. Train the masked and unmasked models for only 300 steps. How soon does the unmasked loss fall below 1.0, the point where it has passed the floor?
4. Write a function that takes any model's forward function and a token position, and reports whether earlier outputs change. Use it as an assertion in your training script.
5. Train with 1, 2, 4 and 8 heads at width 16, and at width 32. Plot validation loss against the number of heads. Where do the tiny heads start to hurt?
6. Implement the padding mask: a batch where some sequences are shorter, padded with a special token, so that no position attends to padding. Check that padding does not change the outputs for the real tokens.
A good result is a mask demo with rows that sum to one, a leak test that fails for an unmasked model and passes for the masked one, and a table of losses for 1, 2 and 4 heads. The next lesson looks at what happens when sequences get long: the cost of the T by T matrix, and the cache that makes generation fast.
Read more
Ashish Vaswani and colleagues, "Attention Is All You Need" (2017), describes the masked self-attention of the decoder and the multi-head layer. Catherine Olsson and colleagues, "In-context Learning and Induction Heads" (2022), studies a head that copies from earlier in the text. Andrej Karpathy's lecture "Let's build GPT: from scratch, in code, spelled out" builds the mask and the multi-head layer step by step.
Tags: Build an LLM Causal mask Multi-head attention Data leakage Transformer