All courses

Causal masking

Add the mask M (−∞ above the diagonal) before the softmax so position t can only attend to positions ≤ t. Explain why this makes every position's output a valid next-token predictor.

Builds on: Scaled dot-product attention, Language modeling as next-token prediction

▶ Watch this lesson Start the whole course

What the animation says

The leak

One pass over a sentence should give a next-word guess at every position. Take the words: the cat sat. Position two, cat, has to predict the next word, sat. But plain attention lets position two mix in values from all three positions. One of those values is computed from sat itself, the very word it should predict. So position two can just copy the answer. That's no prediction at all. Tap the arrow that leaks the answer.

Rule the future out

The fix: each position looks only at itself and earlier words, as if a card covered everything to its right. We do it before the softmax. Every score for a later position becomes minus infinity. E to the minus infinity is zero, so those positions get exactly zero weight. Not small. Zero. The softmax then spreads all of the weight over the allowed positions. Row two has scores one, three, and two. The two is in the future. What are the weights?

A 3×3 worked case

Answer: 0.12, 0.88, and zero. E to the one and e to the three, each divided by their sum. Here's the full three by three score matrix, with minus infinity above the diagonal. Row one sees only itself: weight one, so its output is value one, which is one, zero. Row two mixes values one and two with weights 0.12 and 0.88, giving 0.12, 0.88. Row three sees everything: 0.16, 0.42, 0.42. Its output is 0.58, 0.84. Every row sums to one, and that future score of two changed nothing.

Deep stacks stay honest

In layer one, the output at a position depends only on the tokens up to that position. Everything else in the model, like the feed-forward part, works on each position alone. Nothing mixes across positions. Layer two, at position two, reads only layer-one outputs at positions one and two. And those were already built from tokens one and two. So, after two layers, can token three reach position two?

Causal attention in numpy

Answer: no. Every arrow points backward or straight up, at every depth, so the future never arrives. In numpy, this line builds the mask: minus infinity strictly above the diagonal, zero everywhere else. We add it to the scores, then take the softmax row by row. The printed weights show zeros above the diagonal. And the last line checks: outputs at the first three positions match running on only those three tokens. So one pass over T tokens gives T honest next-token predictions.

How can every position predict without peeking?

With plain attention, position $t$ mixes in value vectors from all $T$ positions. That includes position $t+1$, whose value is computed from $x_{t+1}$, the very token it should predict. Its "prediction" can then simply copy the answer, so it is not $p_\theta(x_{t+1}\mid x_{\le t})$. We still want one pass over a whole text to give a genuine next-token prediction at every position. What small change to attention makes that true?

Rule the future out before the softmax

Let each position look only backward, at itself and everything earlier, as if a card covered every word to its right. In practice, before the softmax we set the score for every later position to $-\infty$. Since $e^{-\infty}=0$, those positions get exactly zero weight. The softmax then spreads 100% of the weight over the allowed positions, so no future value can leak in, not even a little.

The mask and what it guarantees

$$A=\text{softmax}\!\left(\tfrac{QK^\top}{\sqrt{d_{head}}}+M\right),\quad M_{ts}=\begin{cases}0 & s\le t\\ -\infty & s>t\end{cases}$$ Row $t$ (the query position) has $A_{ts}=0$ for every key $s>t$ and sums to 1 over $s\le t$. So output row $t$ is $\sum_{s\le t}A_{ts}V_s$. In the first layer that depends on $x_{\le t}$ only. Every other part of the model works on each position on its own, with no mixing across positions. So a second masked layer at $t$ reads only first-layer outputs at $s\le t$, which themselves depend only on $x_{\le s}$. The same holds layer after layer. Output $t$ therefore equals what running the prefix $x_{\le t}$ alone would give, which makes it a valid predictor of $x_{t+1}$.

Masking a 3×3 score matrix

Scaled scores $S=\begin{bmatrix}2&1&0\\1&3&2\\0&1&1\end{bmatrix}$, values $v_1=[1,0]$, $v_2=[0,1]$, $v_3=[1,1]$. - Row 1: $[2,-\infty,-\infty]\to[1,0,0]$. Output $[1,0]$. - Row 2: $[1,3,-\infty]$ gives $e^1=2.72$, $e^3=20.09$, sum $22.81$, so weights $[0.12,0.88,0]$. Output $[0.12,0.88]$. - Row 3: $[0,1,1]$ gives $1,2.72,2.72$, sum $6.44$, so weights $[0.16,0.42,0.42]$. Output $[0.58,0.84]$. The future score of 2 in row 2 had no effect.

Causal attention in numpy

`np.triu(..., k=1)` puts $-\infty$ strictly above the diagonal and 0 elsewhere. The first print shows zeros above the diagonal. The last line checks the key property: outputs at the first 3 positions are identical to running attention on only those 3 tokens.
import numpy as np
def causal_attn(Q, K, V):
    T, d_head = Q.shape
    S = Q @ K.T / np.sqrt(d_head)
    M = np.triu(np.full((T, T), -np.inf), k=1)  # -inf above diagonal
    S = S + M
    A = np.exp(S - S.max(1, keepdims=True)); A /= A.sum(1, keepdims=True)
    return A @ V, A
rng = np.random.default_rng(0)
Q, K, V = (rng.standard_normal((5, 4)) for _ in range(3))
out, A = causal_attn(Q, K, V); print(np.round(A, 2))  # zeros above diagonal
print(np.allclose(out[:3], causal_attn(Q[:3], K[:3], V[:3])[0]))  # True

Remember

Add $M$ ($-\infty$ above the diagonal) to the scores before the softmax. Position $t$ then puts zero weight on positions $>t$ and all its weight on positions $\le t$. Its output depends only on $x_{\le t}$, so one pass over $T$ tokens yields $T$ honest next-token predictions, each one $p_\theta(x_{t+1}\mid x_{\le t})$.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.