Self-Attention and Positional Encoding

:label:sec_self-attention-and-positional-encoding

In deep learning, we often use CNNs or RNNs to encode a sequence. Now with attention mechanisms. imagine that we feed a sequence of tokens into attention pooling so that the same set of tokens act as queries, keys, and values. Specifically, each query attends to all the key-value pairs and generates one attention output. Since the queries, keys, and values come from the same place, this performs self-attention :cite:Lin.Feng.Santos.ea.2017,Vaswani.Shazeer.Parmar.ea.2017, which is also called intra-attention :cite:Cheng.Dong.Lapata.2016,Parikh.Tackstrom.Das.ea.2016,Paulus.Xiong.Socher.2017. In this section, we will discuss sequence encoding using self-attention, including using additional information for the sequence order.

```{.python .input} from d2l import mxnet as d2l import math from mxnet import autograd, 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

Self-Attention

Given a sequence of input tokens $\mathbf{x}_1, \ldots, \mathbf{x}_n$ where any $\mathbf{x}_i \in \mathbb{R}^d$ ($1 \leq i \leq n$), its self-attention outputs a sequence of the same length $\mathbf{y}_1, \ldots, \mathbf{y}_n$, where

\mathbf{y}_i = f(\mathbf{x}_i, (\mathbf{x}_1, \mathbf{x}_1), \ldots, (\mathbf{x}_n, \mathbf{x}_n)) \in \mathbb{R}^d

according to the definition of attention pooling $f$ in :eqref:eq_attn-pooling. Using multi-head attention, the following code snippet computes the self-attention of a tensor with shape (batch size, number of time steps or sequence length in tokens, $d$). The output tensor has the same shape.

```{.python .input} num_hiddens, num_heads = 100, 5 attention = d2l.MultiHeadAttention(num_hiddens, num_heads, 0.5) attention.initialize()

  1. ```{.python .input}
  2. #@tab pytorch
  3. num_hiddens, num_heads = 100, 5
  4. attention = d2l.MultiHeadAttention(num_hiddens, num_hiddens, num_hiddens,
  5. num_hiddens, num_heads, 0.5)
  6. attention.eval()

```{.python .input}

@tab all

batch_size, num_queries, valid_lens = 2, 4, d2l.tensor([3, 2]) X = d2l.ones((batch_size, num_queries, num_hiddens)) attention(X, X, X, valid_lens).shape

  1. ## Comparing CNNs, RNNs, and Self-Attention
  2. :label:`subsec_cnn-rnn-self-attention`
  3. Let us
  4. compare architectures for mapping
  5. a sequence of $n$ tokens
  6. to another sequence of equal length,
  7. where each input or output token is represented by
  8. a $d$-dimensional vector.
  9. Specifically,
  10. we will consider CNNs, RNNs, and self-attention.
  11. We will compare their
  12. computational complexity,
  13. sequential operations,
  14. and maximum path lengths.
  15. Note that sequential operations prevent parallel computation,
  16. while a shorter path between
  17. any combination of sequence positions
  18. makes it easier to learn long-range dependencies within the sequence :cite:`Hochreiter.Bengio.Frasconi.ea.2001`.
  19. ![Comparing CNN (padding tokens are omitted), RNN, and self-attention architectures.](/uploads/projects/d2l-ai-CN/img/cnn-rnn-self-attention.svg)
  20. :label:`fig_cnn-rnn-self-attention`
  21. Consider a convolutional layer whose kernel size is $k$.
  22. We will provide more details about sequence processing
  23. using CNNs in later chapters.
  24. For now,
  25. we only need to know that
  26. since the sequence length is $n$,
  27. the numbers of input and output channels are both $d$,
  28. the computational complexity of the convolutional layer is $\mathcal{O}(knd^2)$.
  29. As :numref:`fig_cnn-rnn-self-attention` shows,
  30. CNNs are hierarchical so
  31. there are $\mathcal{O}(1)$ sequential operations
  32. and the maximum path length is $\mathcal{O}(n/k)$.
  33. For example, $\mathbf{x}_1$ and $\mathbf{x}_5$
  34. are within the receptive field of a two-layer CNN
  35. with kernel size 3 in :numref:`fig_cnn-rnn-self-attention`.
  36. When updating the hidden state of RNNs,
  37. multiplication of the $d \times d$ weight matrix
  38. and the $d$-dimensional hidden state has
  39. a computational complexity of $\mathcal{O}(d^2)$.
  40. Since the sequence length is $n$,
  41. the computational complexity of the recurrent layer
  42. is $\mathcal{O}(nd^2)$.
  43. According to :numref:`fig_cnn-rnn-self-attention`,
  44. there are $\mathcal{O}(n)$ sequential operations
  45. that cannot be parallelized
  46. and the maximum path length is also $\mathcal{O}(n)$.
  47. In self-attention,
  48. the queries, keys, and values
  49. are all $n \times d$ matrices.
  50. Consider the scaled dot-product attention in
  51. :eqref:`eq_softmax_QK_V`,
  52. where a $n \times d$ matrix is multiplied by
  53. a $d \times n$ matrix,
  54. then the output $n \times n$ matrix is multiplied
  55. by a $n \times d$ matrix.
  56. As a result,
  57. the self-attention
  58. has a $\mathcal{O}(n^2d)$ computational complexity.
  59. As we can see in :numref:`fig_cnn-rnn-self-attention`,
  60. each token is directly connected
  61. to any other token via self-attention.
  62. Therefore,
  63. computation can be parallel with $\mathcal{O}(1)$ sequential operations
  64. and the maximum path length is also $\mathcal{O}(1)$.
  65. All in all,
  66. both CNNs and self-attention enjoy parallel computation
  67. and self-attention has the shortest maximum path length.
  68. However, the quadratic computational complexity with respect to the sequence length
  69. makes self-attention prohibitively slow for very long sequences.
  70. ## Positional Encoding
  71. :label:`subsec_positional-encoding`
  72. Unlike RNNs that recurrently process
  73. tokens of a sequence one by one,
  74. self-attention ditches
  75. sequential operations in favor of
  76. parallel computation.
  77. To use the sequence order information,
  78. we can inject
  79. absolute or relative
  80. positional information
  81. by adding *positional encoding*
  82. to the input representations.
  83. Positional encodings can be
  84. either learned or fixed.
  85. In the following,
  86. we describe a fixed positional encoding
  87. based on sine and cosine functions :cite:`Vaswani.Shazeer.Parmar.ea.2017`.
  88. Suppose that
  89. the input representation $\mathbf{X} \in \mathbb{R}^{n \times d}$ contains the $d$-dimensional embeddings for $n$ tokens of a sequence.
  90. The positional encoding outputs
  91. $\mathbf{X} + \mathbf{P}$
  92. using a positional embedding matrix $\mathbf{P} \in \mathbb{R}^{n \times d}$ of the same shape,
  93. whose element on the $i^\mathrm{th}$ row
  94. and the $(2j)^\mathrm{th}$
  95. or the $(2j + 1)^\mathrm{th}$ column is
  96. $$\begin{aligned} p_{i, 2j} &= \sin\left(\frac{i}{10000^{2j/d}}\right),\\p_{i, 2j+1} &= \cos\left(\frac{i}{10000^{2j/d}}\right).\end{aligned}$$
  97. :eqlabel:`eq_positional-encoding-def`
  98. At first glance,
  99. this trigonometric-function
  100. design looks weird.
  101. Before explanations of this design,
  102. let us first implement it in the following `PositionalEncoding` class.
  103. ```{.python .input}
  104. #@save
  105. class PositionalEncoding(nn.Block):
  106. def __init__(self, num_hiddens, dropout, max_len=1000):
  107. super(PositionalEncoding, self).__init__()
  108. self.dropout = nn.Dropout(dropout)
  109. # Create a long enough `P`
  110. self.P = d2l.zeros((1, max_len, num_hiddens))
  111. X = d2l.arange(max_len).reshape(-1, 1) / np.power(
  112. 10000, np.arange(0, num_hiddens, 2) / num_hiddens)
  113. self.P[:, :, 0::2] = np.sin(X)
  114. self.P[:, :, 1::2] = np.cos(X)
  115. def forward(self, X):
  116. X = X + self.P[:, :X.shape[1], :].as_in_ctx(X.ctx)
  117. return self.dropout(X)

```{.python .input}

@tab pytorch

@save

class PositionalEncoding(nn.Module): def init(self, numhiddens, dropout, maxlen=1000): super(PositionalEncoding, self).__init() self.dropout = nn.Dropout(dropout)

  1. # Create a long enough `P`
  2. self.P = d2l.zeros((1, max_len, num_hiddens))
  3. X = d2l.arange(max_len, dtype=torch.float32).reshape(
  4. -1, 1) / torch.pow(10000, torch.arange(
  5. 0, num_hiddens, 2, dtype=torch.float32) / num_hiddens)
  6. self.P[:, :, 0::2] = torch.sin(X)
  7. self.P[:, :, 1::2] = torch.cos(X)
  8. def forward(self, X):
  9. X = X + self.P[:, :X.shape[1], :].to(X.device)
  10. return self.dropout(X)
  1. In the positional embedding matrix $\mathbf{P}$,
  2. rows correspond to positions within a sequence
  3. and columns represent different positional encoding dimensions.
  4. In the example below,
  5. we can see that
  6. the $6^{\mathrm{th}}$ and the $7^{\mathrm{th}}$
  7. columns of the positional embedding matrix
  8. have a higher frequency than
  9. the $8^{\mathrm{th}}$ and the $9^{\mathrm{th}}$
  10. columns.
  11. The offset between
  12. the $6^{\mathrm{th}}$ and the $7^{\mathrm{th}}$ (same for the $8^{\mathrm{th}}$ and the $9^{\mathrm{th}}$) columns
  13. is due to the alternation of sine and cosine functions.
  14. ```{.python .input}
  15. encoding_dim, num_steps = 32, 60
  16. pos_encoding = PositionalEncoding(encoding_dim, 0)
  17. pos_encoding.initialize()
  18. X = pos_encoding(np.zeros((1, num_steps, encoding_dim)))
  19. P = pos_encoding.P[:, :X.shape[1], :]
  20. d2l.plot(d2l.arange(num_steps), P[0, :, 6:10].T, xlabel='Row (position)',
  21. figsize=(6, 2.5), legend=["Col %d" % d for d in d2l.arange(6, 10)])

```{.python .input}

@tab pytorch

encoding_dim, num_steps = 32, 60 pos_encoding = PositionalEncoding(encoding_dim, 0) pos_encoding.eval() X = pos_encoding(d2l.zeros((1, num_steps, encoding_dim))) P = pos_encoding.P[:, :X.shape[1], :] d2l.plot(d2l.arange(num_steps), P[0, :, 6:10].T, xlabel=’Row (position)’, figsize=(6, 2.5), legend=[“Col %d” % d for d in d2l.arange(6, 10)])

  1. ### Absolute Positional Information
  2. To see how the monotonically decreased frequency
  3. along the encoding dimension relates to absolute positional information,
  4. let us print out the binary representations of $0, 1, \ldots, 7$.
  5. As we can see,
  6. the lowest bit, the second-lowest bit, and the third-lowest bit alternate on every number, every two numbers, and every four numbers, respectively.
  7. ```{.python .input}
  8. #@tab all
  9. for i in range(8):
  10. print(f'{i} in binary is {i:>03b}')

In binary representations, a higher bit has a lower frequency than a lower bit. Similarly, as demonstrated in the heat map below, the positional encoding decreases frequencies along the encoding dimension by using trigonometric functions. Since the outputs are float numbers, such continuous representations are more space-efficient than binary representations.

```{.python .input} P = np.expand_dims(np.expand_dims(P[0, :, :], 0), 0) d2l.show_heatmaps(P, xlabel=’Column (encoding dimension)’, ylabel=’Row (position)’, figsize=(3.5, 4), cmap=’Blues’)

  1. ```{.python .input}
  2. #@tab pytorch
  3. P = P[0, :, :].unsqueeze(0).unsqueeze(0)
  4. d2l.show_heatmaps(P, xlabel='Column (encoding dimension)',
  5. ylabel='Row (position)', figsize=(3.5, 4), cmap='Blues')

Relative Positional Information

Besides capturing absolute positional information, the above positional encoding also allows a model to easily learn to attend by relative positions. This is because for any fixed position offset $\delta$, the positional encoding at position $i + \delta$ can be represented by a linear projection of that at position $i$.

This projection can be explained mathematically. Denoting $\omegaj = 1/10000^{2j/d}$, any pair of $(p{i, 2j}, p{i, 2j+1})$ in :eqref:eq_positional-encoding-def can be linearly projected to $(p{i+\delta, 2j}, p_{i+\delta, 2j+1})$ for any fixed offset $\delta$:

$$\begin{aligned} &\begin{bmatrix} \cos(\delta \omegaj) & \sin(\delta \omega_j) \ -\sin(\delta \omega_j) & \cos(\delta \omega_j) \ \end{bmatrix} \begin{bmatrix} p{i, 2j} \ p{i, 2j+1} \ \end{bmatrix}\ =&\begin{bmatrix} \cos(\delta \omega_j) \sin(i \omega_j) + \sin(\delta \omega_j) \cos(i \omega_j) \ -\sin(\delta \omega_j) \sin(i \omega_j) + \cos(\delta \omega_j) \cos(i \omega_j) \ \end{bmatrix}\ =&\begin{bmatrix} \sin\left((i+\delta) \omega_j\right) \ \cos\left((i+\delta) \omega_j\right) \ \end{bmatrix}\ =& \begin{bmatrix} p{i+\delta, 2j} \ p_{i+\delta, 2j+1} \ \end{bmatrix}, \end{aligned}$$

where the $2\times 2$ projection matrix does not depend on any position index $i$.

Summary

  • In self-attention, the queries, keys, and values all come from the same place.
  • Both CNNs and self-attention enjoy parallel computation and self-attention has the shortest maximum path length. However, the quadratic computational complexity with respect to the sequence length makes self-attention prohibitively slow for very long sequences.
  • To use the sequence order information, we can inject absolute or relative positional information by adding positional encoding to the input representations.

Exercises

  1. Suppose that we design a deep architecture to represent a sequence by stacking self-attention layers with positional encoding. What could be issues?
  2. Can you design a learnable positional encoding method?

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab: