Lab: verify attention masks
A lab with no training. Prove a causal mask blocks the future with an intervention test, check permutation equivariance, then add padding masks and handle rows with every key masked.
What runs in CodeSplash
- DNN019Transformer Runs in CodeSplash (Experimental)
You will be able to
- Implement a causal mask and prove it blocks the future with an intervention test
- Test permutation equivariance and say when positions break it
- Combine a padding mask with a causal mask
- Handle a row whose keys are all masked
Read first
The question
ReadDoes an attention layer move information only where it should? This lab answers with checks, not training. Six tokens with four features go through fixed random query, key and value projections. Five checks follow:
- every row of attention weights sums to one;
- with a causal mask, every weight on a later token is exactly zero;
- adding 100 to tokens 4–6 leaves the causal outputs of tokens 1–3 unchanged;
- shuffling the tokens shuffles the full-attention outputs the same way;
- full and causal attention differ, so the mask did something.
Check 3 is an intervention: it tests the information flow directly instead of trusting the mask's code.
The masks
ReadAn attention maskAttention maskBlocks some query–key pairs before the softmax, such as future tokens (causal) or padding, so they get zero weight. removes query–key pairs before the softmax by setting their scores to −∞, so their weights come out as exactly zero. A causal mask removes every key later than the query: token t sees tokens 1 … t. That's what lets a language model learn to predict each next token from the ones before it.
The program below runs all five checks; each prints a maximum error or a difference.
import numpy as np
rng = np.random.default_rng(23)
X = rng.normal(size=(6, 4))
Wq, Wk, Wv = rng.normal(size=(4, 3)), rng.normal(size=(4, 3)), rng.normal(size=(4, 2))
def attention(x, causal=False):
Q, K, V = x @ Wq, x @ Wk, x @ Wv
s = Q @ K.T / np.sqrt(Q.shape[1])
if causal:
s = np.where(np.triu(np.ones(s.shape, dtype=bool), 1), -np.inf, s) # block later keys
w = np.exp(s - s.max(axis=1, keepdims=True)); w /= w.sum(axis=1, keepdims=True)
return w @ V, w
Y, A = attention(X); Yc, Ac = attention(X, causal=True)
later = X.copy(); later[3:] += 100 # change tokens 4–6
perm = np.array([3, 0, 5, 2, 1, 4])
print("1 row sums: ", np.abs(A.sum(1) - 1).max())
print("2 future weight: ", np.abs(Ac[np.triu_indices(6, 1)]).max())
print("3 past moved by: ", np.abs(Yc[:3] - attention(later, True)[0][:3]).max())
print("4 permutation: ", np.abs(attention(X[perm])[0] - Y[perm]).max())
print("5 full vs causal: ", np.abs(Y - Yc).max())set.seed(23)
X <- matrix(rnorm(24), 6, 4)
Wq <- matrix(rnorm(12), 4, 3); Wk <- matrix(rnorm(12), 4, 3); Wv <- matrix(rnorm(8), 4, 2)
attention <- function(x, causal = FALSE) {
Q <- x %*% Wq; K <- x %*% Wk; V <- x %*% Wv
s <- Q %*% t(K) / sqrt(ncol(Q))
if (causal) s[upper.tri(s)] <- -Inf # block later keys
w <- exp(s - apply(s, 1, max)); w <- w / rowSums(w)
list(out = w %*% V, w = w)
}
full <- attention(X); causal <- attention(X, TRUE)
later <- X; later[4:6, ] <- later[4:6, ] + 100
perm <- c(4, 1, 6, 3, 2, 5)
cat("1 row sums: ", max(abs(rowSums(full$w) - 1)), "\n")
cat("2 future weight: ", max(abs(causal$w[upper.tri(causal$w)])), "\n")
cat("3 past moved by: ", max(abs(causal$out[1:3, ] - attention(later, TRUE)$out[1:3, ])), "\n")
cat("4 permutation: ", max(abs(attention(X[perm, ])$out - full$out[perm, ])), "\n")
cat("5 full vs causal: ", max(abs(full$out - causal$out)), "\n")The two engines draw different random numbers, so checks 4 and 5 print different sizes. Checks 2 and 3 must be exactly zero in both; check 1 within rounding.
Notebook exercise · ~12 min
Test an attention mask by intervention
Write causal attention, check its rows still sum to one, prove the future can't move the past, and check permutation equivariance.
- Mask before the softmax
Write
causal_attention(x)that returns the weights and the outputs: compute the scores as infull_attention, set every score of a later token to −∞, then applysoftmax_rows. Store the six row sums of the causal weights forXinrow_sums.Show a solution
Pythondef causal_attention(x): s = (x @ Wq) @ (x @ Wk).T / math.sqrt(3) s[np.triu(np.ones(s.shape, dtype=bool), 1)] = -np.inf w = softmax_rows(s) return w, w @ (x @ Wv) row_sums = causal_attention(X)[0].sum(axis=1)Rcausal_attention <- function(x) { s <- (x %*% Wq) %*% t(x %*% Wk) / sqrt(3) s[upper.tri(s)] <- -Inf w <- softmax_rows(s) list(w = w, out = w %*% (x %*% Wv)) } row_sums <- rowSums(causal_attention(X)$w) - The future can't move the past
Add 100 to every feature of tokens 4, 5 and 6. Store the largest absolute change in the causal outputs of tokens 1, 2 and 3 in
past_moved.Show a solution
Pythonlater = X.copy() later[3:] += 100 past_moved = np.abs(causal_attention(later)[1][:3] - causal_attention(X)[1][:3]).max()Rlater <- X later[4:6, ] <- later[4:6, ] + 100 past_moved <- max(abs(causal_attention(later)$out[1:3, ] - causal_attention(X)$out[1:3, ])) - Shuffle in, shuffle out
Without positions, full attention is permutation equivariant. Shuffle the tokens into the order 4, 1, 6, 3, 2, 5, run
full_attentionon them, and compare with the original outputs shuffled the same way. StoreTrue(R:TRUE) inperm_okif the largest absolute difference is below 1e-9, elseFalse.Show a solution
Pythonperm = np.array([3, 0, 5, 2, 1, 4]) perm_ok = bool(np.abs(full_attention(X[perm]) - full_attention(X)[perm]).max() < 1e-9)Rperm <- c(4, 1, 6, 3, 2, 5) perm_ok <- max(abs(full_attention(X[perm, ]) - full_attention(X)[perm, ])) < 1e-9
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
Start with no mask, then add the padding and causal masks one at a time.
DExplorable · Attention: scores, masks and heads
Where does each word look, and what do the scaling and the masks change?
With this mask, how much of each word's attention lands on <pad>?
How many of the positions are <pad>.
Width d
Heads
Mask
Without masks or positions the output rows shuffle the same way.
- Little weight
- Most weight
- Masked: score set to −∞
Commit your prediction above to see the result
Make your prediction to see the result.
Which outputs move?
PredictPredict first
In causal attention, you add 100 to tokens 4, 5 and 6. Which tokens' outputs can change?
Reveal
Tokens 4–6 only. Token t attends to tokens 1 … t, so tokens 1–3 never see the change. In full attention every output would change.
Padding and empty rows
ReadBatches of different-length sequences are padded to one length. A padding mask removes the padding keys so real tokens never attend to filler. Masks combine by removing a pair if either mask removes it.
A query whose keys are all removed has every score at −∞. Its softmax is 0/0, which gives NaN and spreads through the next layer. Decide what such a row means, often a padding query whose output you ignore, and set it explicitly, for example to zeros. In causal attention each token always sees itself, so the problem appears only once padding is combined in.
What runs here
Read| Entry | In CodeSplash |
|---|---|
| Transformer (DNN019) | Runs in CodeSplash: the FT-Transformer uses full attention over a table's column tokens. Causal and padding masks are explained here; this lab's programs run in a Python or R notebook |
Check: the lab
CheckpointCheck yourself
Why does a causal mask set the blocked scores to −∞ rather than multiply the weights by zero after the softmax?
Show the answer
Answer: a
Zeroing after the softmax leaves rows that no longer sum to one. Masking before the softmax renormalizes over the allowed keys.
Check yourself
Why does the lab add 100 to future tokens instead of only checking that the masked weights are zero?
Show the answer
Answer: a
An intervention catches leaks the weight check misses, for example a normalization or a residual path that mixes positions.
Check yourself
Which change would make check 4, permutation equivariance, fail?
Show the answer
Answer: a
Positions tie each token to its place, so a shuffled input no longer gives shuffled outputs. Projections, heads and shared shifts keep the property.
Check yourself
A padded query has every key masked. What does a plain softmax give for its row?
Show the answer
Answer: a
exp(−∞) is 0 for every key, so the normalizer is 0. Handle such rows explicitly before they spread NaN.
Check yourself
You combine a causal mask with a padding mask. When is a query–key pair kept?
Show the answer
Answer: a
A pair must be in the past (or present) and must be a real token. Removing a pair if either mask removes it gives that.
Recap
Recap- Mask before the softmax with −∞: blocked weights are exactly zero and rows still sum to one.
- Test the flow with an intervention: changing the future must not move the past.
- Without positions, full attention is permutation equivariant; positions break that on purpose.
- Combine masks by removing a pair if either removes it, and decide what an all-masked row returns.
Concepts in this lesson