Causal Masking
A language model predicts token from tokens . If position could attend to later positions during training, it would simply copy the answer. A causal mask forbids attention to the future by setting those scores to before the softmax. Thanks to the mask, one forward pass trains all positions of a sequence at once, which is the main reason transformers train so much faster than RNNs.
The mask
Add a matrix to the scores before the softmax:
Since , the masked entries get exactly zero weight, and each row still sums to 1 over the allowed positions. The weight matrix is lower triangular. In practice a large negative number (or the dtype's minimum) replaces to avoid nan from .
import numpy as np
rng = np.random.default_rng(0)
n, d = 5, 4
Q, K, V = rng.normal(size=(3, n, d))
S = Q @ K.T / np.sqrt(d)
M = np.triu(np.full((n, n), -np.inf), k=1)
P = S + M
A = np.exp(P - P.max(1, keepdims=True)); A /= A.sum(1, keepdims=True)
print("mask:\n", M)
print("attention weights (lower triangular):\n", np.round(A, 3))
print("rows sum to 1:", np.allclose(A.sum(1), 1))mask:
[[ 0. -inf -inf -inf -inf]
[ 0. 0. -inf -inf -inf]
[ 0. 0. 0. -inf -inf]
[ 0. 0. 0. 0. -inf]
[ 0. 0. 0. 0. 0.]]
attention weights (lower triangular):
[[1. 0. 0. 0. 0. ]
[0.761 0.239 0. 0. 0. ]
[0.196 0.304 0.5 0. 0. ]
[0.21 0.122 0.531 0.137 0. ]
[0.136 0.064 0.124 0.188 0.487]]
rows sum to 1: True
Training all positions in parallel
With the mask, output depends only on inputs . The model can therefore compute the predictions for every prefix of a sequence in a single pass, and the loss is the sum of next-token cross-entropies (Language Modeling). This is called teacher forcing: the true previous tokens are fed in, not the model's own samples.
We can verify causality directly: changing a later token must not change earlier outputs.
import numpy as np
rng = np.random.default_rng(1)
n, d = 6, 4
W = [rng.normal(size=(d, d)) for _ in range(3)]
def causal_attn(X):
Q, K, V = (X @ w for w in W)
S = Q @ K.T / np.sqrt(d) + np.triu(np.full((n, n), -1e9), k=1)
A = np.exp(S - S.max(1, keepdims=True)); A /= A.sum(1, keepdims=True)
return A @ V
X = rng.normal(size=(n, d))
X2 = X.copy(); X2[4] += 10.0 # change token 4
diff = np.abs(causal_attn(X) - causal_attn(X2)).max(axis=1)
print("max change per output position:", np.round(diff, 4))max change per output position: [0. 0. 0. 0. 1.8927 0.0036]
Positions 0 to 3 are unaffected; only positions 4 and 5, which may look at token 4, change.
Other masks
- Padding mask: in a batch of sequences padded to equal length, padding positions are masked out as keys.
- Bidirectional (no mask): encoder models such as BERT see the whole sequence; they are trained by masking tokens (filling in blanks) instead.
- Sliding window: each position attends only to the last positions (a band matrix), making the cost .
- Prefix-LM: bidirectional attention within a prompt, causal after it.
import numpy as np
n, w = 7, 3
i, j = np.indices((n, n))
allowed = (j <= i) & (j > i - w)
print("sliding-window causal mask (1 = may attend):\n", allowed.astype(int))
print("entries per row:", allowed.sum(1))sliding-window causal mask (1 = may attend):
[[1 0 0 0 0 0 0]
[1 1 0 0 0 0 0]
[1 1 1 0 0 0 0]
[0 1 1 1 0 0 0]
[0 0 1 1 1 0 0]
[0 0 0 1 1 1 0]
[0 0 0 0 1 1 1]]
entries per row: [1 2 3 3 3 3 3]
In software
F.scaled_dot_product_attention(q, k, v, is_causal=True)applies the causal mask inside the kernel; FlashAttention skips fully masked blocks, halving the work.- Hugging Face models take an
attention_mask(1 for real tokens, 0 for padding) and combine it with the causal mask. - During generation with a KV cache, the newest query attends to all cached keys, so no explicit mask is needed.
Exercises
Exercise 1: Count the allowed entries
How many nonzero attention weights does a causal mask allow for a sequence of length ?
Answer
.
Solution
Row (1-based) has allowed positions: .
Exercise 2: First position
What is row 0 of a causal attention weight matrix, whatever the scores?
Answer
.
Solution
Position 0 may only attend to itself, and the softmax over a single allowed entry gives 1. Its output is just its own value vector.
Exercise 3: Mask with a large negative number (code)
Compare a softmax of masked at the last entry with , with , and with no mask.
Answer
The two masked versions agree, about .
Solution
import numpy as np
def softmax(z): e = np.exp(z - z.max()); return e / e.sum()
z = np.array([2.0, 1.0, 3.0])
for m in (-np.inf, -1e9, 0.0):
print(m, np.round(softmax(z + np.array([0, 0, m])), 3))-inf [0.731 0.269 0. ]
-1000000000.0 [0.731 0.269 0. ]
0.0 [0.245 0.09 0.665]
Test yourself
What does a causal mask prevent?
- Attention to padding only
- Each position attending to later positions
- Attention to the first token
- Gradient flow
Why can a causal transformer train on all positions of a sequence in one pass?
- Because it uses an RNN
- Each output depends only on its prefix, so all next-token predictions are valid simultaneously
- Because the loss ignores positions
- It cannot
A causal attention weight matrix is…
- upper triangular
- lower triangular
- diagonal
- symmetric