Mask in Attention Mechanisms
Overview
In the realm of attention mechanisms, a mask is a crucial component used to control which parts of the input sequence are attended to. Specifically, in causal attention, masks are employed to ensure that future tokens do not influence the current token. This is achieved by zeroing out the attention weights above the diagonal of the attention matrix, effectively restricting the model to only consider past and present tokens.
Causal Attention and Mask Application
Causal attention masks are applied by creating a lower triangular matrix, which is accomplished using PyTorch's tril function. This function generates a mask that zeroes out the attention weights above the diagonal, ensuring that only the relevant tokens (past and present) are considered during the attention computation.
Efficient Masking Technique
An efficient way to implement this masking technique involves creating a mask with ones above the diagonal and then replacing these ones with negative infinity (-inf) values. This approach is illustrated in the following code snippet:
mask = torch.triu(torch.ones(context_length, context_length), diagonal=1)
masked = attn_scores.masked_fill(mask.bool(), -torch.inf)
print(masked)
This method results in a mask that effectively prevents future tokens from influencing the current token by assigning them a zero probability in the attention mechanism.
Efficient Computation of Masked Attention Weights
While the basic implementation of causal attention can be wrapped up with the above masking technique, further efficiency can be achieved by leveraging a mathematical property of the softmax function. As shown in Figure 3.21, the computation of the masked attention weights can be optimized by masking the attention scores with negative infinity values before applying the softmax function.
Figure 3.21 A more efficient way to obtain the masked attention weight matrix in causal attention is to mask the attention scores with negative infinity values before applying the softmax function.
The softmax function transforms its inputs into a probability distribution. When negative infinity values are present in a row, the softmax function interprets them as zero probability. This is because the mathematical expression e –∞ approaches zero, effectively excluding those positions from contributing to the attention output.