Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Causal attention

In the previous chapter, we implemented the self-attention mechanism, and tokens can finally see each other. But we also found a fatal loophole: every token can see all positions, including the tokens after it.

What does this mean?

Suppose the model is processing the 3rd token and is about to predict the 4th. But now it can see not only the 1st and 2nd tokens, but also the 4th, 5th and 6th, that is, the answer itself. You can imagine that during training the model cheats with ease and the loss looks great; but at inference the answer does not exist yet, and the model gives itself away at once.

It is like a student who peeks at the standard answers while doing homework and gets good grades. But in the exam room there are no answers to copy, and the truth comes out.

Causal mask

The solution is actually straightforward: cover up the future information.

Specifically, after computing the attention score matrix, replace the values at all future positions of the matrix with a very large negative number (for example -109). After Softmax, the attention weights at these positions approach 0, which means they are completely ignored and do not take part in the prediction.

This treatment is called the causal mask: each position can see only itself and the positions before it, not the positions after it. This matches exactly the causal nature of language generation: the next word can only be determined by the words before it.

Causal attention weights: only the diagonal and the part below it of the weight matrix have values, and everything above the diagonal is 0
Figure: causal attention weights

Lower triangular matrix

How do we implement the causal mask?

Look at the shape of the attention score matrix: (context size, context size). The value in row ii and column jj is the relevance of the ii-th token to the jj-th token:

  • when j≤ij \leq i: the jj-th token is before the ii-th token, or is the token itself, and should be kept;

  • when j>ij > i: the jj-th token is after the ii-th token and should be masked.

That is, we only need to keep the diagonal and the lower triangular part below it, and replace the whole upper triangular part above the diagonal with -109. NumPy provides a ready-made lower-triangle function np.tril, which produces a matrix with 1 in the lower triangle and 0 in the upper triangle, and we can use it directly as the mask.

Causal attention

Self-attention with a causal mask is called causal attention, or masked self-attention. It is the standard configuration of decoder-only architectures such as GPT.

Dataset

Character-encoding dataset

Lower triangular matrix layer

We design the causal mask as a separate lower triangular matrix layer (Tril layer):

  • Forward pass: generate the lower triangular mask with np.tril and replace the values at the upper triangular positions with -109;

  • Backward pass: the gradient flows back only through the lower triangular positions. The upper triangular positions did not take part in the forward pass, so their gradient is 0.

Activation functions

Gaussian error linear unit (GELU)

Loss function

GPT cross-entropy loss function

Model

GPT embedding layer

GPT attention layer

In the GPT attention layer, we use the lower triangular mask to block the future positions of the attention score matrix scores.

weights = self.softmax(self.mask(scores))

GPT feed-forward network layer

GPT Transformer block

GPT output layer

GPT model

GPT trainer

Hyperparameters

Learning rate

Batch size

Number of epochs

Context size

Embedding size

Number of Transformer blocks

Modeling

Training

Evaluation

prediction:	1742 steps, each (4, 32, 65)
loss:	2.0406119945949857

Inference

ROMEO:
Famtany at!--will and, though this him at.

ISTARIO:
Hen ifthat not mid'dses mepion.

LERMIONA:
Sordecer, wor I tontlouce alsucitend waseres, It what you sor ande bust trune do's to whave with Me
In keal dies the is my antas;
I fill wak selse that of this

In this chapter, we closed the loophole of self-attention peeking at the answers with the causal mask. With this, the core of the self-attention mechanism is complete. From the inference result, we can already see obvious sentence patterns and dramatic structure.

Exercises

  1. Think about why the lower triangular matrix layer fills the future positions in the upper triangle with -109. Try changing it to 0 and observe how the training results change.