Attention Scoring Functions

:label:sec_attention-scoring-functions

In :numref:sec_nadaraya-waston, we used a Gaussian kernel to model interactions between queries and keys. Treating the exponent of the Gaussian kernel in :eqref:eq_nadaraya-waston-gaussian as an attention scoring function (or scoring function for short), the results of this function were essentially fed into a softmax operation. As a result, we obtained a probability distribution (attention weights) over values that are paired with keys. In the end, the output of the attention pooling is simply a weighted sum of the values based on these attention weights.

At a high level, we can use the above algorithm to instantiate the framework of attention mechanisms in :numref:fig_qkv. Denoting an attention scoring function by $a$, :numref:fig_attention_output illustrates how the output of attention pooling can be computed as a weighted sum of values. Since attention weights are a probability distribution, the weighted sum is essentially a weighted average.

Computing the output of attention pooling as a weighted average of values. :label:fig_attention_output

Mathematically, suppose that we have a query $\mathbf{q} \in \mathbb{R}^q$ and $m$ key-value pairs $(\mathbf{k}_1, \mathbf{v}_1), \ldots, (\mathbf{k}_m, \mathbf{v}_m)$, where any $\mathbf{k}_i \in \mathbb{R}^k$ and any $\mathbf{v}_i \in \mathbb{R}^v$. The attention pooling $f$ is instantiated as a weighted sum of the values:

f(\mathbf{q}, (\mathbf{k}1, \mathbf{v}_1), \ldots, (\mathbf{k}_m, \mathbf{v}_m)) = \sum{i=1}^m \alpha(\mathbf{q}, \mathbf{k}_i) \mathbf{v}_i \in \mathbb{R}^v, :eqlabel:eq_attn-pooling

where the attention weight (scalar) for the query $\mathbf{q}$ and key $\mathbf{k}_i$ is computed by the softmax operation of an attention scoring function $a$ that maps two vectors to a scalar:

\alpha(\mathbf{q}, \mathbf{k}i) = \mathrm{softmax}(a(\mathbf{q}, \mathbf{k}_i)) = \frac{\exp(a(\mathbf{q}, \mathbf{k}_i))}{\sum{j=1}^m \exp(a(\mathbf{q}, \mathbf{k}_j))} \in \mathbb{R}. :eqlabel:eq_attn-scoring-alpha

As we can see, different choices of the attention scoring function $a$ lead to different behaviors of attention pooling. In this section, we introduce two popular scoring functions that we will use to develop more sophisticated attention mechanisms later.

```{.python .input} import math from d2l import mxnet as d2l from mxnet import np, npx from mxnet.gluon import nn npx.set_np()

  1. ```{.python .input}
  2. #@tab pytorch
  3. from d2l import torch as d2l
  4. import math
  5. import torch
  6. from torch import nn

Masked Softmax Operation

As we just mentioned, a softmax operation is used to output a probability distribution as attention weights. In some cases, not all the values should be fed into attention pooling. For instance, for efficient minibatch processing in :numref:sec_machine_translation, some text sequences are padded with special tokens that do not carry meaning. To get an attention pooling over only meaningful tokens as values, we can specify a valid sequence length (in number of tokens) to filter out those beyond this specified range when computing softmax. In this way, we can implement such a masked softmax operation in the following masked_softmax function, where any value beyond the valid length is masked as zero.

```{.python .input}

@save

def masked_softmax(X, valid_lens): “””Perform softmax operation by masking elements on the last axis.”””

  1. # `X`: 3D tensor, `valid_lens`: 1D or 2D tensor
  2. if valid_lens is None:
  3. return npx.softmax(X)
  4. else:
  5. shape = X.shape
  6. if valid_lens.ndim == 1:
  7. valid_lens = valid_lens.repeat(shape[1])
  8. else:
  9. valid_lens = valid_lens.reshape(-1)
  10. # On the last axis, replace masked elements with a very large negative
  11. # value, whose exponentiation outputs 0
  12. X = npx.sequence_mask(X.reshape(-1, shape[-1]), valid_lens, True,
  13. value=-1e6, axis=1)
  14. return npx.softmax(X).reshape(shape)
  1. ```{.python .input}
  2. #@tab pytorch
  3. #@save
  4. def masked_softmax(X, valid_lens):
  5. """Perform softmax operation by masking elements on the last axis."""
  6. # `X`: 3D tensor, `valid_lens`: 1D or 2D tensor
  7. if valid_lens is None:
  8. return nn.functional.softmax(X, dim=-1)
  9. else:
  10. shape = X.shape
  11. if valid_lens.dim() == 1:
  12. valid_lens = torch.repeat_interleave(valid_lens, shape[1])
  13. else:
  14. valid_lens = valid_lens.reshape(-1)
  15. # On the last axis, replace masked elements with a very large negative
  16. # value, whose exponentiation outputs 0
  17. X = d2l.sequence_mask(X.reshape(-1, shape[-1]), valid_lens,
  18. value=-1e6)
  19. return nn.functional.softmax(X.reshape(shape), dim=-1)

To demonstrate how this function works, consider a minibatch of two $2 \times 4$ matrix examples, where the valid lengths for these two examples are two and three, respectively. As a result of the masked softmax operation, values beyond the valid lengths are all masked as zero.

```{.python .input} masked_softmax(np.random.uniform(size=(2, 2, 4)), d2l.tensor([2, 3]))

  1. ```{.python .input}
  2. #@tab pytorch
  3. masked_softmax(torch.rand(2, 2, 4), torch.tensor([2, 3]))

Similarly, we can also use a two-dimensional tensor to specify valid lengths for every row in each matrix example.

```{.python .input} masked_softmax(np.random.uniform(size=(2, 2, 4)), d2l.tensor([[1, 3], [2, 4]]))

  1. ```{.python .input}
  2. #@tab pytorch
  3. masked_softmax(torch.rand(2, 2, 4), d2l.tensor([[1, 3], [2, 4]]))

Additive Attention

:label:subsec_additive-attention

In general, when queries and keys are vectors of different lengths, we can use additive attention as the scoring function. Given a query $\mathbf{q} \in \mathbb{R}^q$ and a key $\mathbf{k} \in \mathbb{R}^k$, the additive attention scoring function

a(\mathbf q, \mathbf k) = \mathbf w_v^\top \text{tanh}(\mathbf W_q\mathbf q + \mathbf W_k \mathbf k) \in \mathbb{R}, :eqlabel:eq_additive-attn

where learnable parameters $\mathbf W_q\in\mathbb R^{h\times q}$, $\mathbf W_k\in\mathbb R^{h\times k}$, and $\mathbf w_v\in\mathbb R^{h}$. Equivalent to :eqref:eq_additive-attn, the query and the key are concatenated and fed into an MLP with a single hidden layer whose number of hidden units is $h$, a hyperparameter. By using $\tanh$ as the activation function and disabling bias terms, we implement additive attention in the following.

```{.python .input}

@save

class AdditiveAttention(nn.Block): “””Additive attention.””” def init(self, numhiddens, dropout, **kwargs): super(AdditiveAttention, self)._init(**kwargs)

  1. # Use `flatten=False` to only transform the last axis so that the
  2. # shapes for the other axes are kept the same
  3. self.W_k = nn.Dense(num_hiddens, use_bias=False, flatten=False)
  4. self.W_q = nn.Dense(num_hiddens, use_bias=False, flatten=False)
  5. self.w_v = nn.Dense(1, use_bias=False, flatten=False)
  6. self.dropout = nn.Dropout(dropout)
  7. def forward(self, queries, keys, values, valid_lens):
  8. queries, keys = self.W_q(queries), self.W_k(keys)
  9. # After dimension expansion, shape of `queries`: (`batch_size`, no. of
  10. # queries, 1, `num_hiddens`) and shape of `keys`: (`batch_size`, 1,
  11. # no. of key-value pairs, `num_hiddens`). Sum them up with
  12. # broadcasting
  13. features = np.expand_dims(queries, axis=2) + np.expand_dims(
  14. keys, axis=1)
  15. features = np.tanh(features)
  16. # There is only one output of `self.w_v`, so we remove the last
  17. # one-dimensional entry from the shape. Shape of `scores`:
  18. # (`batch_size`, no. of queries, no. of key-value pairs)
  19. scores = np.squeeze(self.w_v(features), axis=-1)
  20. self.attention_weights = masked_softmax(scores, valid_lens)
  21. # Shape of `values`: (`batch_size`, no. of key-value pairs, value
  22. # dimension)
  23. return npx.batch_dot(self.dropout(self.attention_weights), values)
  1. ```{.python .input}
  2. #@tab pytorch
  3. #@save
  4. class AdditiveAttention(nn.Module):
  5. def __init__(self, key_size, query_size, num_hiddens, dropout, **kwargs):
  6. super(AdditiveAttention, self).__init__(**kwargs)
  7. self.W_k = nn.Linear(key_size, num_hiddens, bias=False)
  8. self.W_q = nn.Linear(query_size, num_hiddens, bias=False)
  9. self.w_v = nn.Linear(num_hiddens, 1, bias=False)
  10. self.dropout = nn.Dropout(dropout)
  11. def forward(self, queries, keys, values, valid_lens):
  12. queries, keys = self.W_q(queries), self.W_k(keys)
  13. # After dimension expansion, shape of `queries`: (`batch_size`, no. of
  14. # queries, 1, `num_hiddens`) and shape of `keys`: (`batch_size`, 1,
  15. # no. of key-value pairs, `num_hiddens`). Sum them up with
  16. # broadcasting
  17. features = queries.unsqueeze(2) + keys.unsqueeze(1)
  18. features = torch.tanh(features)
  19. # There is only one output of `self.w_v`, so we remove the last
  20. # one-dimensional entry from the shape. Shape of `scores`:
  21. # (`batch_size`, no. of queries, no. of key-value pairs)
  22. scores = self.w_v(features).squeeze(-1)
  23. self.attention_weights = masked_softmax(scores, valid_lens)
  24. # Shape of `values`: (`batch_size`, no. of key-value pairs, value
  25. # dimension)
  26. return torch.bmm(self.dropout(self.attention_weights), values)

Let us demonstrate the above AdditiveAttention class with a toy example, where shapes (batch size, number of steps or sequence length in tokens, feature size) of queries, keys, and values are ($2$, $1$, $20$), ($2$, $10$, $2$), and ($2$, $10$, $4$), respectively. The attention pooling output has a shape of (batch size, number of steps for queries, feature size for values).

```{.python .input} queries, keys = d2l.normal(0, 1, (2, 1, 20)), d2l.ones((2, 10, 2))

The two value matrices in the values minibatch are identical

values = np.arange(40).reshape(1, 10, 4).repeat(2, axis=0) valid_lens = d2l.tensor([2, 6])

attention = AdditiveAttention(num_hiddens=8, dropout=0.1) attention.initialize() attention(queries, keys, values, valid_lens)

  1. ```{.python .input}
  2. #@tab pytorch
  3. queries, keys = d2l.normal(0, 1, (2, 1, 20)), d2l.ones((2, 10, 2))
  4. # The two value matrices in the `values` minibatch are identical
  5. values = torch.arange(40, dtype=torch.float32).reshape(1, 10, 4).repeat(
  6. 2, 1, 1)
  7. valid_lens = d2l.tensor([2, 6])
  8. attention = AdditiveAttention(key_size=2, query_size=20, num_hiddens=8,
  9. dropout=0.1)
  10. attention.eval()
  11. attention(queries, keys, values, valid_lens)

Although additive attention contains learnable parameters, since every key is the same in this example, the attention weights are uniform, determined by the specified valid lengths.

```{.python .input}

@tab all

d2l.show_heatmaps(d2l.reshape(attention.attention_weights, (1, 1, 2, 10)), xlabel=’Keys’, ylabel=’Queries’)

  1. ## Scaled Dot-Product Attention
  2. A more computationally efficient
  3. design for the scoring function can be
  4. simply dot product.
  5. However,
  6. the dot product operation
  7. requires that both the query and the key
  8. have the same vector length, say $d$.
  9. Assume that
  10. all the elements of the query and the key
  11. are independent random variables
  12. with zero mean and unit variance.
  13. The dot product of
  14. both vectors has zero mean and a variance of $d$.
  15. To ensure that the variance of the dot product
  16. still remains one regardless of vector length,
  17. the *scaled dot-product attention* scoring function
  18. $$a(\mathbf q, \mathbf k) = \mathbf{q}^\top \mathbf{k} /\sqrt{d}$$
  19. divides the dot product by $\sqrt{d}$.
  20. In practice,
  21. we often think in minibatches
  22. for efficiency,
  23. such as computing attention
  24. for
  25. $n$ queries and $m$ key-value pairs,
  26. where queries and keys are of length $d$
  27. and values are of length $v$.
  28. The scaled dot-product attention
  29. of queries $\mathbf Q\in\mathbb R^{n\times d}$,
  30. keys $\mathbf K\in\mathbb R^{m\times d}$,
  31. and values $\mathbf V\in\mathbb R^{m\times v}$
  32. is
  33. $$ \mathrm{softmax}\left(\frac{\mathbf Q \mathbf K^\top }{\sqrt{d}}\right) \mathbf V \in \mathbb{R}^{n\times v}.$$
  34. :eqlabel:`eq_softmax_QK_V`
  35. In the following implementation of the scaled dot product attention, we use dropout for model regularization.
  36. ```{.python .input}
  37. #@save
  38. class DotProductAttention(nn.Block):
  39. """Scaled dot product attention."""
  40. def __init__(self, dropout, **kwargs):
  41. super(DotProductAttention, self).__init__(**kwargs)
  42. self.dropout = nn.Dropout(dropout)
  43. # Shape of `queries`: (`batch_size`, no. of queries, `d`)
  44. # Shape of `keys`: (`batch_size`, no. of key-value pairs, `d`)
  45. # Shape of `values`: (`batch_size`, no. of key-value pairs, value
  46. # dimension)
  47. # Shape of `valid_lens`: (`batch_size`,) or (`batch_size`, no. of queries)
  48. def forward(self, queries, keys, values, valid_lens=None):
  49. d = queries.shape[-1]
  50. # Set `transpose_b=True` to swap the last two dimensions of `keys`
  51. scores = npx.batch_dot(queries, keys, transpose_b=True) / math.sqrt(d)
  52. self.attention_weights = masked_softmax(scores, valid_lens)
  53. return npx.batch_dot(self.dropout(self.attention_weights), values)

```{.python .input}

@tab pytorch

@save

class DotProductAttention(nn.Module): “””Scaled dot product attention.””” def init(self, dropout, kwargs): super(DotProductAttention, self).init(kwargs) self.dropout = nn.Dropout(dropout)

  1. # Shape of `queries`: (`batch_size`, no. of queries, `d`)
  2. # Shape of `keys`: (`batch_size`, no. of key-value pairs, `d`)
  3. # Shape of `values`: (`batch_size`, no. of key-value pairs, value
  4. # dimension)
  5. # Shape of `valid_lens`: (`batch_size`,) or (`batch_size`, no. of queries)
  6. def forward(self, queries, keys, values, valid_lens=None):
  7. d = queries.shape[-1]
  8. # Set `transpose_b=True` to swap the last two dimensions of `keys`
  9. scores = torch.bmm(queries, keys.transpose(1,2)) / math.sqrt(d)
  10. self.attention_weights = masked_softmax(scores, valid_lens)
  11. return torch.bmm(self.dropout(self.attention_weights), values)
  1. To demonstrate the above `DotProductAttention` class,
  2. we use the same keys, values, and valid lengths from the earlier toy example
  3. for additive attention.
  4. For the dot product operation,
  5. we make the feature size of queries
  6. the same as that of keys.
  7. ```{.python .input}
  8. queries = d2l.normal(0, 1, (2, 1, 2))
  9. attention = DotProductAttention(dropout=0.5)
  10. attention.initialize()
  11. attention(queries, keys, values, valid_lens)

```{.python .input}

@tab pytorch

queries = d2l.normal(0, 1, (2, 1, 2)) attention = DotProductAttention(dropout=0.5) attention.eval() attention(queries, keys, values, valid_lens)

  1. Same as in the additive attention demonstration,
  2. since `keys` contains the same element
  3. that cannot be differentiated by any query,
  4. uniform attention weights are obtained.
  5. ```{.python .input}
  6. #@tab all
  7. d2l.show_heatmaps(d2l.reshape(attention.attention_weights, (1, 1, 2, 10)),
  8. xlabel='Keys', ylabel='Queries')

Summary

  • We can compute the output of attention pooling as a weighted average of values, where different choices of the attention scoring function lead to different behaviors of attention pooling.
  • When queries and keys are vectors of different lengths, we can use the additive attention scoring function. When they are the same, the scaled dot-product attention scoring function is more computationally efficient.

Exercises

  1. Modify keys in the toy example and visualize attention weights. Do additive attention and scaled dot-product attention still output the same attention weights? Why or why not?
  2. Using matrix multiplications only, can you design a new scoring function for queries and keys with different vector lengths?
  3. When queries and keys have the same vector length, is vector summation a better design than dot product for the scoring function? Why or why not?

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab: