Mask a future token in causal attention

Type the indices of each value in their original order. · 204 words

In a language model, causal attention means the token at position t may use only tokens at positions 1 through t. This prevents the model from peeking at an answer that it is supposed to predict. Suppose a row for the token cat attends to three positions: the past token A, the current token cat, and the future token runs. Before masking, suppose the raw attention scores are [1.0, 2.0, 3.0]. The future position is forbidden, so replace its score with negative infinity before applying softmax. Negative infinity is a marker meaning that no attention is allowed there.

After masking, the usable scores are [1.0, 2.0]. Softmax gives exp(1) / (exp(1) + exp(2)) = 2.718 / 10.107 = 0.269 for the past token and exp(2) / 10.107 = 0.731 for the current token. The masked future position receives weight 0. The current token therefore receives about 73 percent of the attention, and the past token receives about 27 percent. If you use a large finite negative number, such as -1000, softmax makes the forbidden weight extremely small rather than mathematically zero. For exact causal behavior, mask with negative infinity before softmax. The mask removes future context without removing the current token or earlier context.

Check your recall

How should position 3 be prevented from attending to position 4?

Check your answer

Replace position 4's score with negative infinity before softmax. After softmax, position 4 has weight exactly 0, while positions 1 through 3 share all the attention.

Sources and credits

Original KeyTouch lesson. Background reading · Vaswani et al. · Attention Is All You Need.