Run this notebook online:\ |Binder| or Colab: |Colab| .. |Binder| image:: https://mybinder.org/badge_logo.svg :target: https://mybinder.org/v2/gh/deepjavalibrary/d2l-java/master?filepath=chapter_attention-mechanisms/self-attention-and-positional-encoding.ipynb .. |Colab| image:: https://colab.research.google.com/assets/colab-badge.svg :target: https://colab.research.google.com/github/deepjavalibrary/d2l-java/blob/colab/chapter_attention-mechanisms/self-attention-and-positional-encoding.ipynb .. _sec_self-attention-and-positional-encoding: 自注意力和位置编码 ================== 在深度学习中,我们经常使用卷积神经网络(CNN)或循环神经网络(RNN)对序列进行编码。现在想象一下,有了注意力机制之后,我们将词元序列输入注意力池化中,以便同一组词元同时充当查询、键和值。具体来说,每个查询都会关注所有的键-值对并生成一个注意力输出。由于查询、键和值来自同一组输入,因此被称为 *自注意力*\ (self-attention :cite:`Lin.Feng.Santos.ea.2017,Vaswani.Shazeer.Parmar.ea.2017`\ ),也被称为 *内部注意力*\ (intra-attention :cite:`Cheng.Dong.Lapata.2016,Parikh.Tackstrom.Das.ea.2016,Paulus.Xiong.Socher.2017`\ )。在本节中,我们将讨论使用自注意力进行序列编码,包括使用序列的顺序作为补充信息。 .. code:: java %load ../utils/djl-imports %load ../utils/plot-utils %load ../utils/Functions.java %load ../utils/PlotUtils.java %load ../utils/attention/Chap10Utils.java %load ../utils/attention/DotProductAttention.java %load ../utils/attention/MultiHeadAttention.java %load ../utils/attention/PositionalEncoding.java .. code:: java NDManager manager = NDManager.newBaseManager(); 自注意力 -------- 给定一个由词元组成的输入序列 :math:`\mathbf{x}_1, \ldots, \mathbf{x}_n`\ ,其中任意 :math:`\mathbf{x}_i \in \mathbb{R}^d` (:math:`1 \leq i \leq n`)。该序列的自注意力输出为一个长度相同的序列 :math:`\mathbf{y}_1, \ldots, \mathbf{y}_n`\ ,其中: .. math:: \mathbf{y}_i = f(\mathbf{x}_i, (\mathbf{x}_1, \mathbf{x}_1), \ldots, (\mathbf{x}_n, \mathbf{x}_n)) \in \mathbb{R}^d 根据 :eq:`eq_attn-pooling` 中定义的注意力池化函数 :math:`f` 。下面的代码片段是基于多头注意力对一个 ``NDArray`` 完成自注意力的计算,\ ``NDArray`` 的形状为 (批量大小, 时间步的数目或词元序列的长度 :math:`d`) 。输出与输入的 ``NDArray`` 形状相同。 .. code:: java int numHiddens = 100; int numHeads = 5; MultiHeadAttention attention = new MultiHeadAttention(numHiddens, numHeads, 0.5f, false); .. code:: java int batchSize = 2; int numQueries = 4; NDArray validLens = manager.create(new float[] {3, 2}); NDArray X = manager.ones(new Shape(batchSize, numQueries, numHiddens)); ParameterStore ps = new ParameterStore(manager, false); NDList input = new NDList(X, X, X, validLens); attention.initialize(manager, DataType.FLOAT32, input.getShapes()); NDList result = attention.forward(ps, input, false); result.get(0).getShape() .. parsed-literal:: :class: output (2, 4, 100) .. _subsec_cnn-rnn-self-attention: .. _fig_cnn-rnn-self-attention: 比较卷积神经网络、循环神经网络和自注意力 ---------------------------------------- 让我们比较下面几个架构,目标都是将由 :math:`n` 个词元组成的序列映射到另一个长度相等的序列,其中的每个输入词元或输出词元都由 :math:`d` 维向量表示。具体来说,我们将比较的是卷积神经网络、循环神经网络和自注意力这几个架构的计算复杂性、顺序操作和最大路径长度。请注意,顺序操作会妨碍并行计算,而任意的序列位置组合之间的路径越短,则能更轻松地学习序列中的远距离依赖关系 :cite:`Hochreiter.Bengio.Frasconi.ea.2001`\ 。 |比较卷积神经网络(填充词元被忽略)、循环神经网络和自注意力三种架构。| 考虑一个卷积核大小为 :math:`k` 的卷积层。我们将在后面的章节中提供关于使用卷积神经网络处理序列的更多详细信息。目前,我们只需要知道,由于序列长度是 :math:`n` ,输入和输出的通道数量都是 :math:`d`\ ,所以卷积层的计算复杂度为 :math:`\mathcal{O}(knd^2)` 。如 :numref:`fig_cnn-rnn-self-attention` 所示,卷积神经网络是分层的,因此为有 :math:`\mathcal{O}(1)` 个顺序操作,最大路径长度为 :math:`\mathcal{O}(n/k)`\ 。例如,\ :math:`\mathbf{x}_1` 和 :math:`\mathbf{x}_5` 处于 :numref:`fig_cnn-rnn-self-attention` 中卷积核大小为3的双层卷积神经网络的感受野内。 当更新循环神经网络的隐藏状态时,\ :math:`d \times d` 权重矩阵和 :math:`d` 维隐藏状态的乘法计算复杂度为 :math:`\mathcal{O}(d^2)` 。由于序列长度为 :math:`n`\ ,因此循环神经网络层的计算复杂度为 :math:`\mathcal{O}(nd^2)`\ 。根据 :numref:`fig_cnn-rnn-self-attention`\ ,有 :math:`\mathcal{O}(n)` 个顺序操作无法并行化,最大路径长度也是 :math:`\mathcal{O}(n)`\ 。 在自注意力中,查询、键和值都是 :math:`n \times d` 矩阵。考虑 :eq:`eq_softmax_QK_V` 中缩放的”点-积“注意力,其中 :math:`n \times d` 矩阵乘以 :math:`d \times n` 矩阵,然后输出的 :math:`n \times n` 矩阵乘以 :math:`n \times d` 矩阵。因此,自注意力具有 :math:`\mathcal{O}(n^2d)` 计算复杂性。正如我们在 :numref:`fig_cnn-rnn-self-attention` 中看到的那样,每个词元都通过自注意力直接连接到任何其他词元。因此,有 :math:`\mathcal{O}(1)` 个顺序操作可以并行计算,最大路径长度也是 :math:`\mathcal{O}(1)`\ 。 总而言之,卷积神经网络和自注意力都拥有并行计算的优势,而且自注意力的最大路径长度最短。但是因为其计算复杂度是关于序列长度的二次方,所以在很长的序列中计算会非常慢。 .. _subsec_positional-encoding: 位置编码 -------- 在处理词元序列时,循环神经网络是逐个的重复地处理词元的,而自注意力则因为并行计算而放弃了顺序操作。为了使用序列的顺序信息,我们通过在输入表示中添加 *位置编码(positional encoding)* 来注入绝对的或相对的位置信息。位置编码可以通过学习得到也可以直接固定得到。接下来,我们描述的是基于正弦函数和余弦函数的固定位置编码 :cite:`Vaswani.Shazeer.Parmar.ea.2017`\ 。 假设输入表示 :math:`\mathbf{X} \in \mathbb{R}^{n \times d}` 包含一个序列中 :math:`n` 个词元的 :math:`d` 维嵌入表示。位置编码使用相同形状的位置嵌入矩阵 :math:`\mathbf{X} + \mathbf{P}` 输出 :math:`\mathbf{P} \in \mathbb{R}^{n \times d}`\ ,矩阵第 :math:`i^\mathrm{th}` 行、第 :math:`(2j)^\mathrm{th}` 列和 :math:`(2j + 1)^\mathrm{th}` 列上的元素为: .. math:: \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} :label: eq_positional-encoding-def 乍一看,这种基于三角函数的设计看起来很奇怪。在解释这个设计之前,让我们先在下面的 ``PositionalEncoding`` 类中实现它。 .. |比较卷积神经网络(填充词元被忽略)、循环神经网络和自注意力三种架构。| image:: https://zh-v2.d2l.ai/_images/cnn-rnn-self-attention.svg .. code:: java public class PositionalEncoding extends AbstractBlock { private Dropout dropout; public NDArray P; public PositionalEncoding(int numHiddens, float dropout, int maxLen, NDManager manager) { this.dropout = Dropout.builder().optRate(dropout).build(); addChildBlock("dropout", this.dropout); // Create a long enough `P` P = manager.zeros(new Shape(1, maxLen, numHiddens)); NDArray X = manager.arange(maxLen) .reshape(-1, 1) .div( manager.create(10000) .pow(manager.arange(0, numHiddens, 2).div(numHiddens))); P.set(new NDIndex(":, :, {}::{}", 0, 2), X.sin()); P.set(new NDIndex(":, :, {}::{}", 1, 2), X.cos()); } @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList params) { NDArray X = inputs.get(0); X = X.add(P.get(":, :{}, :", X.getShape().get(1))); return new NDList( dropout.forward(parameterStore, new NDList(X), training, params).get(0)); } @Override public Shape[] getOutputShapes(Shape[] inputShapes) { throw new UnsupportedOperationException("Not implemented"); } @Override public void initializeChildBlocks(NDManager manager, DataType dataType, Shape... inputShapes) { try (NDManager sub = manager.newSubManager()) { NDArray X = sub.zeros(inputShapes[0], dataType); X = X.add(P.get(":, :{}, :", X.getShape().get(1))); dropout.initialize(manager, dataType, X.getShape()); } } } 在位置嵌入矩阵 :math:`\mathbf{P}` 中,行代表词元在序列中的位置,列代表位置编码的不同维度。在下面的例子中,我们可以看到位置嵌入矩阵的第 6 列和第 7列的频率高于第 8 列和第 9 列。第 6 列和第 7 列之间的偏移量(第 8 列和 第 9 列相同)是由于正弦函数和余弦函数的交替。 .. code:: java int encodingDim = 32; int numSteps = 60; PositionalEncoding posEncoding = new PositionalEncoding(encodingDim, 0, 1000, manager); input = new NDList(manager.zeros(new Shape(1, numSteps, encodingDim))); X = posEncoding.forward(ps, input, false).get(0); NDArray P = posEncoding.P.get(new NDIndex(":, :{}, :", X.getShape().get(1))); double[][] plotX = new double[4][]; double[][] plotY = new double[4][]; for (int i = 0; i < 4; i++) { if (i == 0) { plotX[i] = manager.arange(numSteps).toType(DataType.FLOAT64, false).toDoubleArray(); } else { plotX[i] = plotX[i - 1]; } plotY[i] = Functions.floatToDoubleArray( P.get(new NDIndex("0, :, {},", i + 6)).toFloatArray()); } PlotUtils.plot( plotX, plotY, new String[] {"Col6", "Col7", "Col8", "Col9"}, "Row (position)", ""); .. raw:: html
绝对位置信息 ~~~~~~~~~~~~ 为了明白沿着编码维度单调降低的频率与绝对位置信息的关系,让我们打印出 :math:`0, 1, \ldots, 7` 的二进制表示形式。正如我们所看到的,每个数字、每两个数字和每四个数字上的比特值在第一个最低位、第二个最低位和第三个最低位上分别交替。 .. code:: java for (int i = 0; i < 8; i++) { System.out.println(i + " in binary is " + Integer.toBinaryString(i)); } .. parsed-literal:: :class: output 0 in binary is 0 1 in binary is 1 2 in binary is 10 3 in binary is 11 4 in binary is 100 5 in binary is 101 6 in binary is 110 7 in binary is 111 在二进制表示中,较高比特位的交替频率低于较低比特位,与下面的热图所示相似,只是位置编码通过使用三角函数在编码维度上降低频率。由于输出是浮点数,因此此类连续表示比二进制表示法更节省空间。 .. code:: java P = P.get(new NDIndex("0, :, :")).expandDims(0).expandDims(0); PlotUtils.showHeatmaps( P, "Column (encoding dimension)", "Row (position)", new String[] {""}, 500, 700); .. raw:: html
相对位置信息 ~~~~~~~~~~~~ 除了捕获绝对位置信息之外,上述的位置编码还允许模型学习得到输入序列中相对位置信息。这是因为对于任何确定的位置偏移 :math:`\delta`\ ,位置 :math:`i + \delta` 处的位置编码可以线性投影位置 :math:`i` 处的位置编码来表示。 这种投影的数学解释是,令 :math:`\omega_j = 1/10000^{2j/d}`\ ,对于任何确定的位置偏移 :math:`\delta`\ ,:eqref:eq\_positional-encoding-def 中的任何一对 :math:`(p_{i, 2j}, p_{i, 2j+1})` 都可以线性投影到 :math:`(p_{i+\delta, 2j}, p_{i+\delta, 2j+1})`\ : .. math:: \begin{aligned} &\begin{bmatrix} \cos(\delta \omega_j) & \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} :math:`2\times 2` 投影矩阵不依赖于任何位置的索引 :math:`i`\ 。 小结 ---- - 在自注意力中,查询、键和值都来自同一组输入。 - 卷积神经网络和自注意力都拥有并行计算的优势,而且自注意力的最大路径长度最短。但是因为其计算复杂度是关于序列长度的二次方,所以在很长的序列中计算会非常慢。 - 为了使用序列的顺序信息,我们可以通过在输入表示中添加位置编码来注入绝对的或相对的位置信息。 练习 ---- 1. 假设我们设计一个深度架构,通过堆叠基于位置编码的自注意力层来表示序列。可能会存在什么问题? 2. 你能设计一种可学习的位置编码方法吗?