InferenceAI

Enter at least two characters to search.

Start free

Causal Attention Mask

easyAttention12 min10 XP

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.

INTERACTIVE ENGINEERING · TEACHING MODEL

Causal attention

Inspect query-key scores, masking and normalized attention weights.

Rows: queries · columns: keys

Key 1
100.0%
Key 2
0.0%
Key 3
0.0%
Key 4
0.0%

Synthetic unscaled scores are [1, 2, 4, 0] × √dₖ. The mask is applied before normalization.

Change the experiment

Core calculation
scores = Q @ K.T / sqrt(d_k)
scores[future_positions] = -inf
weights = softmax(scores)
output = weights @ V
Try 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.

Open the full explainer and practice links

Examples

EXAMPLE WALKTHROUGHthree tokens

A guided view of the published example, not a trace of your code.

INPUT[3]
TASKcausal_mask()
EXPECTED OUTPUT[[true,false,false],[true,true,false],[true,true,true]]

Start with the input values shown in this example.

Example 1 of 2

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.

Topics

PythonAttentionTransformers