TExcelTAD
Home › Math for Deep Learning & LLMs › Causal Masking

Causal Masking

A language model predicts token t+1t + 1 from tokens 1,…,t1, \ldots, t. If position tt 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 −∞-\infty 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 MM to the scores before the softmax:

Mij={0j≤i−∞j>i,A=softmax⁡ ⁣(QKTdk+M)M_{ij} = \begin{cases} 0 & j \le i \\ -\infty & j > i \end{cases}, \qquad A = \operatorname{softmax}\!\left(\frac{QK^T}{\sqrt{d_k}} + M\right)

Since e−∞=0e^{-\infty} = 0, the masked entries get exactly zero weight, and each row still sums to 1 over the allowed positions. The weight matrix AA is lower triangular. In practice a large negative number (or the dtype's minimum) replaces −∞-\infty to avoid nan from −∞−(−∞)-\infty - (-\infty).

python · try it yourself
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 ii depends only on inputs 1,…,i1, \ldots, i. The model can therefore compute the predictions for every prefix of a sequence in a single pass, and the loss is the sum of nn 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.

python · try it yourself
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 ww positions (a band matrix), making the cost O(nw)O(nw).
  • Prefix-LM: bidirectional attention within a prompt, causal after it.
python · try it yourself
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 nn?

Answer

n(n+1)/2n(n + 1)/2.

Solution

Row ii (1-based) has ii allowed positions: 1+2+⋯+n1 + 2 + \cdots + n.

Exercise 2: First position

What is row 0 of a causal attention weight matrix, whatever the scores?

Answer

(1,0,0,…,0)(1, 0, 0, \ldots, 0).

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 (2,1,3)(2, 1, 3) masked at the last entry with −∞-\infty, with −109-10^9, and with no mask.

Answer

The two masked versions agree, about (0.731,0.269,0)(0.731, 0.269, 0).

Solution
python · try it yourself
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?

  1. Attention to padding only
  2. Each position attending to later positions
  3. Attention to the first token
  4. Gradient flow

Why can a causal transformer train on all positions of a sequence in one pass?

  1. Because it uses an RNN
  2. Each output depends only on its prefix, so all next-token predictions are valid simultaneously
  3. Because the loss ignores positions
  4. It cannot

A causal attention weight matrix is…

  1. upper triangular
  2. lower triangular
  3. diagonal
  4. symmetric