Causal Attention Mask
Implement causal_mask(length) and return a square boolean matrix. Row i represents a query at position i; column j is True exactly when j <= i. Return an empty list for length zero. length is nonnegative. This is the basic causal rule used during autoregressive training.
Explore the underlying concept with illustrative inputs. This experiment is separate from the problem’s test cases.
Causal attention
Inspect query-key scores, masking and normalized attention weights.
Rows: queries · columns: keys
Synthetic unscaled scores are [1, 2, 4, 0] × √dₖ. The mask is applied before normalization.
Change the experiment
scores = Q @ K.T / sqrt(d_k)
scores[future_positions] = -inf
weights = softmax(scores)
output = weights @ VTry it yourself
Select the last query, increase the key dimension and disable scaling. Watch the distribution sharpen.
Query 1 attends to 1 allowed positions. Future weights are zero.
Apply the causal mask before softmax. Scaling controls score magnitude; masked positions retain exactly zero weight.
Playback pauses in hidden tabs and offscreen. With reduced motion enabled, use the timeline or Next step.Examples
A guided view of the published example, not a trace of your code.
[3][[true,false,false],[true,true,false],[true,true,true]]Start with the input values shown in this example.
Input: length = 3
Output: [[true,false,false],[true,true,false],[true,true,true]]
Explanation: three tokens
Input: length = 1
Output: [[true]]
Explanation: single token
Hint 1
Position i can attend to positions 0 through i.