Causal Masking: No Peeking at Future Tokens

TransformersMedium+20 XP+15

Causal Masking: No Peeking at Future Tokens

A language model predicting token 5 must not be allowed to look at token 6. Causal masking enforces that inside attention: before the softmax, every score pointing at a future position is set to -inf, so it comes out of the softmax as exactly zero weight.

Task: write causal_attention(scores), taking a square matrix of raw attention scores and returning the attention weights after masking and softmax, rounded to 4 decimal places.

  • Row i may attend to columns 0 through i only.
  • Each row's visible entries go through softmax and therefore sum to 1.
  • Masked positions are reported as 0.0.
  • Row 0 sees only itself, so it's always 1.0 followed by zeros.

Doing it this way is what lets a decoder train on a whole sequence in one pass: every position predicts its own next token simultaneously, and the mask is the only thing preventing each one from reading the answer.

the
cat
sat
down
the
✓
×
×
×
cat
✓
✓
×
×
sat
✓
✓
✓
×
down
✓
✓
✓
✓

A triangle of blocked cells. Each row may only look at itself and everything to its left.

Examples

scores = [[1.0, 2.0], [3.0, 4.0]]
returns [[1.0, 0.0], [0.2689, 0.7311]]
scores = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
returns [[1.0, 0.0, 0.0], [0.5, 0.5, 0.0], [0.3333, 0.3333, 0.3333]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run