13/25
Part 3 of 6 · The maskLearn

Put minus infinity on the scores, before the softmax

The fix is a mask on the scores, built from a lower triangle.

scores = np.array([[1.0, 2.0, 3.0],
                   [4.0, 5.0, 6.0],
                   [7.0, 8.0, 9.0]])
t = scores.shape[-1]
# True where j <= i
allowed = np.tril(np.ones((t, t), dtype=bool))
masked = np.where(allowed, scores, -np.inf)
print(masked)
print(softmax(masked).round(2))
[[  1. -inf -inf]
 [  4.   5. -inf]
 [  7.   8.   9.]]
[[1.   0.   0.  ]
 [0.27 0.73 0.  ]
 [0.09 0.24 0.67]]

np.tril keeps the lower triangle, so allowed is True on and below the diagonal. np.where(allowed, scores, -np.inf) keeps each score where allowed is True, and puts −∞-\infty everywhere else.

Mask the future, then the softmax, row by row
scores (3, 3)
123456789
masked (3, 3)
1-∞-∞45-∞789
softmax (3, 3)
1.00000.270.7300.090.240.67

A row is a query and a column is a key.

Since e−∞=0e^{-\infty} = 0, the future keys get exactly zero weight. The visible weights still sum to 1.

In self-attention the queries and keys are the same positions, so Tq=TkT_q = T_k and the scores are square. That shared length is t in the code, and TT from here on.

The names are not the point. Any lower triangle of True works, for example np.arange(t)[:, None] >= np.arange(t).

The tempting shortcut is to softmax first and zero out the future afterwards. Switch the widget's mask to after softmax and watch the row sums.

An attention patternInteractive
Mask applied
The
cat
sat
on
the
mat
row sum
The
1.00
1.00
cat
0.99
0.01
1.00
sat
0.84
0.15
0.01
1.00
on
0.10
0.22
0.47
0.22
1.00
the
0.00
0.12
0.83
0.00
0.04
1.00
mat
0.08
0.03
0.04
0.58
0.13
0.15
1.00
Rows are queries, columns are keys. Hover a cell.
01