QuiddityML

By · 11 November 2026 · 9 min read

Causal masking explained

Why a next-token model would cheat without a mask, how the mask matrix turns future scores into zero attention weights, worked through on a 4 by 4 example, and how to write it in PyTorch alongside a padding mask.

A causal mask stops each position in a sequence from attending to the positions after it, so a transformer can use only the tokens up to and including the current one. Decoder models such as GPT apply it in every self-attention layer, because they are trained to predict the next token and the next token must not be visible while the model predicts it. Models read tokens, which can be whole words or pieces of words, and the examples here use short words as tokens.

The next-token rule

A decoder-only language model learns by predicting the next token. Take the sequence the cute axolotl. At the position of the the target is cute, and at the position of cute the target is axolotl.

Training usually feeds the whole sequence in at once, because that is much faster than running it one token at a time. Self-attention lets every position look at every other position. Without a mask, the position of the could look at cute and copy it, and the model would learn to read its answers off the input. When the model later generates text, the next token does not exist yet, so a model trained that way has nothing to copy and does badly.

The rule that fixes this is short: position $t$ may use positions $0$ to $t$, and nothing after $t$.

The sequence the cute axolotl. The current position is the, with target cute. The tokens cute and axolotl sit behind a red barrier labeled future tokens are not available during generation. The permission strip for position 0 allows position 0 and blocks positions 1 and 2, under the rule position t may use positions ≤ t.

Why recurrent networks did not need a mask

A recurrent neural network (RNN) reads a sequence one step at a time. At step 1 it has built a hidden state from the first two tokens, and the hidden states for later steps have not been computed yet, so the order of the computation itself keeps the future out.

Self-attention computes all positions in one matrix operation. Every position gets a score against every other position, including the later ones. That parallel computation is what makes transformers fast to train, and it is also why the future has to be blocked on purpose.

Top: an RNN decoder builds hidden states h_0, h_1, h_2 step by step, and the states for later steps are not available yet. Bottom: self-attention computes a score for every pair of positions at once, so the cells where the key position comes after the query position are blocked with a causal mask, and the cells on or below the diagonal are allowed.

Where the mask goes

The mask lives inside the attention computation. Self-attention gives each token three vectors: a query $q$, a key $k$ and a value $v$. Stacked over the sequence they form the matrices $Q$, $K$ and $V$, with one row per token. Attention scores every query against every key, scales the scores, turns each row into weights with softmax and blends the value vectors with those weights:

$$\operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V$$

Here $d_k$ is the number of features in each query and key vector. A causal decoder adds one step between the scaling and the softmax:

$$S = \frac{QK^\top}{\sqrt{d_k}}$$

$$S_{\text{masked}} = S + M_{\text{causal}}$$

$$A = \operatorname{softmax}(S_{\text{masked}})$$

$$\text{out} = AV$$

$S$ is the matrix of scaled scores, $M_{\text{causal}}$ is the mask and $A$ holds the attention weights. The mask changes which scores can turn into weights, and everything else in attention stays the same.

The decoder block: token ids 4, 7, 9 become token embeddings plus positional encoding, then go through masked multi-head attention and the rest of the transformer block. Inside the attention box the order is scaled scores, then add causal mask, then softmax.

The mask matrix

Take a sequence of $T = 4$ positions. Rows are the positions being updated, and columns are the positions they might use. Written as a table of 1s and 0s, the mask is:

$$\begin{bmatrix} 1&0&0&0\\ 1&1&0&0\\ 1&1&1&0\\ 1&1&1&1 \end{bmatrix}$$

A 1 means allowed and a 0 means blocked. Row 0 can use only position 0. Row 2 can use positions 0, 1 and 2. The allowed cells form the lower triangle including the diagonal, so every position can use itself.

The same rule also shows up in an additive form, where the mask holds the numbers that get added to the scores:

$$M_{\text{causal}} = \begin{bmatrix} 0&-\infty&-\infty&-\infty\\ 0&0&-\infty&-\infty\\ 0&0&0&-\infty\\ 0&0&0&0 \end{bmatrix}$$

Here 0 means allowed because adding 0 leaves a score unchanged, and $-\infty$ means blocked. A 0 means the opposite thing in the two forms, so it is worth checking which one a codebase uses before reading its mask.

The mask matrix for T = 4. The boolean form holds 1 on and below the diagonal and 0 above it, where 1 means allowed. The additive form holds 0 on and below the diagonal and minus infinity above it, where 0 means allowed. Both grids encode one rule.

The masked attention equation: S = QKᵀ / √d_k, then S_masked = S + M_causal, then A = softmax(S_masked), then out = AV. On a 3 by 3 grid the cells on and below the diagonal are allowed and the cells above it hold minus infinity.

Blocked scores become negative infinity

Suppose the scaled scores for the four positions are:

$$S = \begin{bmatrix} 2&1&4&-1\\ 0&3&2&5\\ 1&-2&4&0\\ 2&0&1&3 \end{bmatrix}$$

Applying the mask replaces every score above the diagonal with $-\infty$:

$$S_{\text{masked}} = \begin{bmatrix} 2&-\infty&-\infty&-\infty\\ 0&3&-\infty&-\infty\\ 1&-2&4&-\infty\\ 2&0&1&3 \end{bmatrix}$$

Row 0 keeps one score, row 1 keeps two, row 2 keeps three and row 3 keeps all four.

Scaled scores S, a 4 by 4 matrix, become S_masked after the causal mask: every entry above the diagonal turns into minus infinity, so row 0 keeps one entry, row 1 keeps two, row 2 keeps three and row 3 keeps four.

The mask uses $-\infty$ because softmax exponentiates each score, and

$$e^{-\infty} = 0$$

A blocked score therefore contributes nothing to the sum in the softmax and gets a weight of exactly 0. Take row 1 by hand. Its kept scores are 0 and 3, and $e^{0} = 1$ and $e^{3} \approx 20.09$, so the weights are

$$\frac{1}{1 + 20.09} \approx 0.05 \qquad \frac{20.09}{1 + 20.09} \approx 0.95$$

and the two blocked positions get 0. Doing the same for every row gives:

$$A \approx \begin{bmatrix} 1.00&0.00&0.00&0.00\\ 0.05&0.95&0.00&0.00\\ 0.05&0.00&0.95&0.00\\ 0.24&0.03&0.09&0.64 \end{bmatrix}$$

Each row still sums to 1. Each position now blends only the value vectors of itself and the positions before it.

e to the minus infinity equals 0. A = softmax(S_masked) has rows 1.00, 0.00, 0.00, 0.00 then 0.05, 0.95, 0.00, 0.00 then 0.05, 0.00, 0.95, 0.00 then 0.24, 0.03, 0.09, 0.64, with every entry above the diagonal at zero. Each row is still a probability distribution, but it can blend only allowed value vectors.

Causal masking in PyTorch

torch.ones(T, T) is a $T \times T$ table of ones. torch.tril keeps its lower triangle, the diagonal and everything below it, and sets the rest to 0. .bool() turns 1 and 0 into True and False:

1import torch
2 
3T = 4
4mask = torch.tril(torch.ones(T, T)).bool()
5print(mask.int())
6additive = torch.zeros(T, T).masked_fill(~mask, float("-inf"))
7print(additive)
1tensor([[1, 0, 0, 0],
2        [1, 1, 0, 0],
3        [1, 1, 1, 0],
4        [1, 1, 1, 1]], dtype=torch.int32)
5tensor([[0., -inf, -inf, -inf],
6        [0., 0., -inf, -inf],
7        [0., 0., 0., -inf],
8        [0., 0., 0., 0.]])

~mask flips every True to False and back, so it is True exactly at the blocked cells. masked_fill(~mask, float("-inf")) writes $-\infty$ into those cells. The same two calls applied to the score matrix from the worked example give the weights from above:

1S = torch.tensor([[2., 1., 4., -1.],
2                  [0., 3., 2., 5.],
3                  [1., -2., 4., 0.],
4                  [2., 0., 1., 3.]])
5S_masked = S.masked_fill(~mask, float("-inf"))
6A = torch.softmax(S_masked, dim=-1)
7print(A.round(decimals=2))
8print(torch.allclose(torch.softmax(S + additive, dim=-1), A))
1tensor([[1.0000, 0.0000, 0.0000, 0.0000],
2        [0.0500, 0.9500, 0.0000, 0.0000],
3        [0.0500, 0.0000, 0.9500, 0.0000],
4        [0.2400, 0.0300, 0.0900, 0.6400]])
5True

The last line checks that adding the additive mask gives the same weights as masked_fill with the boolean one.

In a model, the mask becomes an optional argument of the attention function. With mask=None the function behaves exactly as unmasked attention, so one function covers both cases:

1def scaled_dot_product_attention(q, k, v, mask=None):
2    d_k = q.size(-1)
3    scores = q @ k.transpose(-2, -1)
4    scores = scores / (d_k ** 0.5)
5    if mask is not None:
6        scores = scores.masked_fill(~mask, float("-inf"))
7    weights = torch.softmax(scores, dim=-1)
8    return weights @ v

The helper scaled_dot_product_attention(q, k, v, mask=None): d_k = q.size(-1), scores = q @ k.transpose(-2, -1), scores divided by d_k ** 0.5, then masked_fill(~mask, float("-inf")) if a mask is given, then softmax and weights @ v. On a 3 by 3 grid, query 1 may use key 1, query 2 keys 1 and 2, and query 3 all three. masked_fill writes -inf, and softmax turns it into 0.

The mask's effect is easy to test. Change only the last token of a sequence and compare the outputs before and after. With a causal mask, the first three positions cannot see the last token, so their outputs should not move at all:

1torch.manual_seed(0)
2W_q, W_k, W_v = torch.randn(8, 8), torch.randn(8, 8), torch.randn(8, 8)
3 
4 
5def attention(x, causal):
6    q, k, v = x @ W_q, x @ W_k, x @ W_v
7    T = x.size(1)
8    mask = torch.tril(torch.ones(T, T, device=x.device)).bool() if causal else None
9    return scaled_dot_product_attention(q, k, v, mask)
10 
11 
12x = torch.randn(1, 4, 8)            # 1 sequence, 4 tokens, 8 features
13x_new = x.clone()
14x_new[0, 3] = torch.randn(8)        # replace only the last token
15 
16for causal in (False, True):
17    change = (attention(x, causal) - attention(x_new, causal)).abs()
18    print("causal" if causal else "no mask", change[0].amax(dim=-1).round(decimals=3))
1no mask tensor([2.2950, 0.0960, 3.1140, 4.2760])
2causal tensor([0.0000, 0.0000, 0.0000, 4.2760])

Each number is the largest change in one position's output. Without the mask every position changes, because every position was reading the last token. With the mask only the last position changes. Building the mask with device=x.device puts it on the same device as the input, so the code also runs on a GPU.

Training uses every position at once

Because of the mask, one forward pass over the cute axolotl trains three predictions at the same time. The position of the predicts cute from the alone, the position of cute predicts axolotl from the cute, and the last position predicts the end-of-sequence token from the whole sentence. Each prediction sees exactly what it would see during generation.

Generation still produces one token at a time, since each new token depends on the one before it. The mask is what lets training run all positions in parallel while staying faithful to that left-to-right order.

Training uses many positions at once. One shifted row: the inputs the, cute, axolotl (ids 4, 7, 9) are paired with the targets cute, axolotl, eos (ids 7, 9, 2). The causal mask over the, cute and axolotl lets every token see itself and all earlier tokens, and later ones are blocked. All three positions are trained in one forward pass.

Padding masks hide fake tokens

A second kind of mask uses the same $-\infty$ trick for a different job. Sequences in a batch often have different lengths, and a tensor needs every row to be the same length. Shorter sequences therefore get filled out with a special padding token, often written PAD:

$$\text{input ids} = \begin{bmatrix} 4 & 7 & 9 \\ 4 & 7 & 0 \end{bmatrix}$$

Here 0 is the PAD id. The padding mask marks the real tokens:

$$\text{padding mask} = \begin{bmatrix} 1 & 1 & 1 \\ 1 & 1 & 0 \end{bmatrix}$$

Attention should give the PAD position no weight, since it is not part of the text. Suppose the token cute in the second sequence has the scores $[1.0, 2.0, 0.5]$ for the, cute and PAD. Masking the PAD score to $-\infty$ and applying softmax gives $[0.27, 0.73, 0.00]$.

![Padding masks hide fake tokens. Input ids [[4, 7, 9], [4, 7, 0]] where 0 is PAD, and the padding mask [[1, 1, 1], [1, 1, 0]]. For the query token cute in sequence 2, raw scores the 1.00, cute 2.00, PAD 0.50 become masked scores 1.00, 2.00, minus infinity and weights 0.27, 0.73, 0.00 after softmax. The causal mask below it has another job: it blocks future tokens.](images/padding_mask_fake_tokens.png)

A padding mask blocks fake tokens, and a causal mask blocks future tokens. A decoder trained on padded batches uses both, and the combined mask allows a cell only when both masks allow it:

1ids = torch.tensor([[4, 7, 9],
2                    [4, 7, 0]])     # 0 is PAD
3real = ids != 0                     # (B, T): True for real tokens
4causal = torch.tril(torch.ones(3, 3)).bool()
5combined = causal[None, :, :] & real[:, None, :]   # (B, T, T)
6print(combined[1].int())
1tensor([[1, 0, 0],
2        [1, 1, 0],
3        [1, 1, 0]], dtype=torch.int32)

This is the mask for the second sequence. The first two rows follow the causal pattern. The last row belongs to the PAD position. The causal mask would allow all three columns there, and the padding mask removes the PAD column. [None, :, :] and [:, None, :] add a size-1 axis so the two masks line up into one $(B, T, T)$ table, one $T \times T$ grid per sequence.

Common mistakes

Self-attention is the computation the mask plugs into, and multi-head attention applies the same mask in every head. Positional encoding handles the order of tokens inside attention, while the causal mask handles which tokens each position may use. Encoder models such as BERT leave the causal mask out entirely, which encoder vs decoder vs encoder-decoder transformers compares side by side. Build a small GPT from scratch puts the masked attention layer inside a complete model that trains and generates text.

QuiddityML teaches causal masking as its own concept in the Intro to NLP track. The exercises on it include tracing which rows of the mask each position may use, spotting the bug in a masked attention class and typing a complete causal multi-head self-attention class from scratch.