No peeking allowed
During training the whole example sentence is already in memory. When the position “cat” is supposed to predict the next word, that word sits right next to it. Without precautions the model would simply copy it: an exam with the answer sheet on the desk. The error would be tiny, and nothing would be learned.
So the rule is: every position may only read itself and earlier positions. With three positions that means: position 1 reads only 1. Position 2 reads 1 and 2. Position 3 reads 1, 2 and 3. A table that records exactly these permissions is called a mask. And because no calculation depends on the future, this is called causal: cause before effect.
How do you block a source? You set its score to minus infinity (−∞) before softmax. The exponential function turns that into zero, so the source gets zero percent. Simple and effective.
Everything at once, and still fair
The clever part: we don't have to compute each piece of the sentence separately. All positions are processed at the same time; the mask only makes sure each one ignores its forbidden cells. So from a sentence with 100 tokens, the model learns 100 prediction tasks at once, each with exactly the context it is allowed to have.
Position t therefore sees all tokens up to and including t. Its target is the token at position t+1, one spot further right. And exactly this look to the right is what the mask forbids.
Why a position may see itself
The diagonal of the mask (every position reads itself) is allowed. Why? The position's own token is input, not the answer; the target is only the next token. If you blocked the diagonal too, the first position would have no source at all: all scores would be −∞, and softmax would produce nonsense (in PyTorch: NaN, “not a number”).
In code, the mask looks like this:
T = q.size(-2)
allowed = torch.ones(T, T, dtype=torch.bool, device=q.device).tril()
scores = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1))
scores = scores.masked_fill(~allowed, float('-inf'))
weights = scores.softmax(dim=-1)
out = weights @ vtril makes a triangle: lower left allowed, upper right forbidden. Important: forbidden scores have to be −∞, not 0. A score of 0 would still get a few percent from softmax.
A trap when programming
Different PyTorch functions interpret masks differently. For one, True means “may take part”, for another “is blocked”. So never copy masks blindly between functions!
For our decoder there is a shorter way:
out = F.scaled_dot_product_attention(
q, k, v,
dropout_p=0.0,
is_causal=True,
)is_causal=True builds the triangular mask automatically. Dropout is a training technique that randomly sets individual values to zero so the network doesn't rely on single connections. We don't use it, which is why 0.0 is stated explicitly; this function doesn't notice by itself whether training is happening.
Several heads: teamwork
A sentence contains many kinds of relationships at once: who does what? What does “she” refer to? What was the previous word? A single attention would have to settle on a mix. That is why there is multi-head attention: several “heads” that look in parallel and independently. One head might pay attention to the previous word, another to the start of the sentence.
How is it split? Each position's list of numbers (width D) is cut into H equal pieces. Each head gets its piece with width d = D/H. With D = 128 and H = 4, each head has 32 numbers. Each head has its own query, key and value projections and computes its own attention.
q = self.q_proj(x) # [B,T,D]
q = q.view(B, T, H, d).transpose(1, 2) # [B,H,T,d]
# same for k and v
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
out = out.transpose(1, 2).contiguous().view(B, T, D)
out = self.out_proj(out)Afterwards the results of all heads are laid side by side again, and an output layer mixes them. Nice: more heads don't cost more parameters. The heads simply get narrower.
The peeking test
How do you check that the mask really works? With a simple trick: two texts that are identical up to position 4 and only differ after that. In a correct model, the predictions up to position 4 must be exactly the same; whatever comes later must have no influence.
model.eval()
a = torch.tensor([[1, 5, 6, 7, 8, 9]])
b = torch.tensor([[1, 5, 6, 7, 8, 3]])
with torch.no_grad():
la, lb = model(a), model(b)
assert torch.allclose(la[:, :5], lb[:, :5], atol=1e-5)Our project has this test built in. It is far more reliable than looking at the loss. Quite the opposite: a missing mask even makes the loss look suspiciously good, because the model can cheat.
You can cheat elsewhere too
Attention isn't the only thing that can look into the future. If a normalization accidentally averaged over all positions of a text, later tokens would leak into earlier ones. And if the answer slips into the input during data preparation, even the best mask won't help. So always test the whole model, not just the attention part.
In the experiment
Click a row of the matrix. You see which positions this row may read. Then switch off the mask and look at which forbidden information suddenly becomes visible. Note: allowed only means “may be read”, not “gets a lot of attention”. Where the model actually looks, it learns by itself.
Build it yourself: in step 4 of part VII you program the mask and the heads yourself, including the peeking test.
Key points
- The causal mask stops a position from reading later tokens. Blocked scores are set to −∞.
- That way the model learns all positions of a text at once without cheating.
- Several heads look at different relationships in parallel. More heads means narrower heads, not more parameters.