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 everywhere else.
scores (3, 3)masked (3, 3)softmax (3, 3)A row is a query and a column is a key.
Since , 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 and the scores are square. That shared length is t in the code, and 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.