学习资料 理解深度学习 第 12 章 · Transformers
学 习 资 料 · 中 英 对 照

第 12 章 · Transformers

Understanding Deep Learning — Transformers

第 12 章
Chapter 12

Transformers

Chapter 10 introduced convolutional networks, which are specialized for processing data that lie on a regular grid. They are particularly suited to processing images, which have a very large number of input variables, precluding the use of fully connected networks. Each layer of a convolutional network employs parameter sharing so that local image patches are processed similarly at every position in the image.

This chapter introduces transformers. These were initially targeted at natural language processing (NLP) problems, where the network input is a series of high-dimensional embeddings representing words or word fragments. Language datasets share some of the characteristics of image data. The number of input variables can be very large, and the statistics are similar at every position; it’s not sensible to re-learn the meaning of the word dog at every possible position in a body of text. However, language datasets have the complication that text sequences vary in length, and unlike images, there is no easy way to resize them.

Transformer 模型

第 10 章介绍了卷积网络,它专门用于处理位于规则网格上的数据。它们特别适合处理图像,因为图像具有大量的输入变量,使得无法使用全连接网络。卷积网络的每一层都采用参数共享,从而在图像中的每个位置以相似方式处理局部图像块。

本章介绍 Transformer 模型。这些模型最初面向自然语言处理(NLP)问题,其中网络输入是一系列表示单词或词片段的高维嵌入。语言数据集具有图像数据的一些特征。输入变量数量可能非常大,并且每个位置的统计特性相似;重新学习单词“狗”在一段文本中每个可能位置的含义并不合理。然而,语言数据集的复杂之处在于文本序列长度不一,而且不像图像那样,没有简单的方法来调整它们的大小。

12.1 处理文本数据
12.1 Processing text data

To motivate the transformer, consider the following passage:

The restaurant refused to serve me a ham sandwich because it only cooks vegetarian food. In the end, they just gave me two slices of bread. Their ambiance was just as good as the food and service.

The goal is to design a network to process this text into a representation suitable for downstream tasks. For example, it might be used to classify the review as positive or negative or to answer questions such as “Does the restaurant serve steak?”.

为了引出 Transformer 模型,请考虑以下段落:

这家餐厅拒绝给我上火腿三明治,因为它只做素食。最后,他们只给了我两片面包。这里的环境和食物与服务一样好。

目标是设计一个网络,将该文本处理为适合下游任务的表示。例如,它可用于将评论分类为正面或负面,或回答诸如“这家餐厅供应牛排吗?”等问题。

We can make three immediate observations. First, the encoded input can be surprisingly large. In this case, each of the 37 words might be represented by an embedding vector of length 1024, so the encoded input would be of length 37 × 1024 = 37888 even for this small passage. A more realistically sized body of text might have hundreds or even thousands of words, so fully connected neural networks are impractical.

Second, one of the defining characteristics of NLP problems is that each input (one or more sentences) is of a different length; hence, it’s not even obvious how to apply a fully connected network. These observations suggest that the network should share parameters across words at different input positions, similarly to how convolutional networks share parameters across different image positions.

Third, language is ambiguous; it is unclear from the syntax alone that the pronoun it refers to the restaurant and not to the ham sandwich. To understand the text, the word it should somehow be connected to the word restaurant. In the parlance of transformers, the former word should pay attention to the latter. This implies that there must be connections between the words and that the strength of these connections will depend on the words themselves. Moreover, these connections need to extend across large text spans. For example, the word their in the last sentence also refers to the restaurant.

我们可以立即得出三点观察。首先,编码后的输入可能大得惊人。在这种情况下, 37 个词中的每个词都可以用一个长度为 1024 的嵌入向量表示,因此即使对于这段小段落,编码后的输入长度也会是 37 × 1024 = 37888。更现实规模的文本可能包含数百甚至数千个词,因此全连接神经网络并不实际。

其次, NLP 问题的一个显著特征是,每个输入(一个或多个句子)的长度都不同;因此,甚至不清楚如何应用全连接网络。这些观察表明,网络应该在不同输入位置的词之间共享参数,类似于卷积网络在不同图像位置之间共享参数。

第三,语言具有歧义;仅凭语法无法判断代词“它”指的是餐厅,而不是火腿三明治。要理解文本,词语“它”必须以某种方式与词语“餐厅”相连接。用 Transformer 的术语来说,前者应当注意后者。这意味着单词之间必须存在连接,而且这些连接的强度取决于单词本身。此外,这些连接需要跨越较大的文本跨度。例如,最后一句中的单词“他们的”也指的是餐厅。

12.2 点积自注意力
12.2 Dot-product self-attention

The previous section argued that a model for processing text will (i) use parameter sharing to cope with long input passages of differing lengths and (ii) contain connections between word representations that depend on the words themselves. The transformer acquires both properties by using dot-product self-attention.

A standard neural network layer f[ x ], takes a D× 1 input x and applies a linear transformation followed by an activation function like a ReLU, so:

上一节论证了,用于处理文本的模型将(i)使用参数共享来应对长度不同的较长输入段落,并且(ii)包含取决于单词本身的词表示之间的连接。 Transformer 通过使用点积自注意力获得了这两个特性。

一个标准神经网络层 f[ x ], 接受一个 D× 1 输入 x,并应用线性变换,然后应用像 ReLU 这样的激活函数,因此:

where β contains the biases, and Ω contains the weights.

其中 β 包含偏差,而 Ω 包含权重。

A self-attention block sa[•] takes N inputs x 1,..., x N, each of dimension D × 1, and returns N outputs, each of which is also of size D ×1. In the context of NLP, each input represents a word or word fragment. First, a set of values are computed for each input:

where βv∈RD×1 and Ω v∈RD×D represent biases and weights, respectively.

Then the nth output sa n[ x 1,..., x N] is a weighted sum of all the values v 1,..., v N:

The scalar weight a[ x m, x n] is the attention that the nth output pays to input x m. The N weights a[•, x n] are non-negative and sum to one. Hence, self-attention can be thought of as routing the values in different proportions to create each output (figure 12.1).

:

标量权重 a[ x m, x n] 是 nth 输出对输入 x m 的注意力。 N 权重 a[•, x n] 非负且总和为 1。因此,自注意力可以被视为以不同比例路由这些值以生成每个输出(图 12.1)。

The following sections examine dot-product self-attention in more detail. First, we consider the computation of the values and their subsequent weighting (equation 12.3). Then we describe how to compute the attention weights a[ x m, x n] themselves.

以下各节将更详细地考察点积自注意力。首先,我们考虑值的计算及其后续的加权(式 12.3)。然后,我们描述如何计算注意力权重 a[ x m, x n] 本身。

图 12.1 自注意力作为路由。自注意力机制接受 N 个输入 x1、...、 x N∈RD (这里 N= 3 和 D = 4),并分别处理每个输入以计算 N 个
图 12.1 自注意力作为路由。自注意力机制接受 N 个输入 x1、...、 x N∈RD (这里 N= 3 和 D = 4),并分别处理每个输入以计算 N 个值向量。 nth 输出 sa n[ x1、...、 x N] (简写为 sa n[ x •])随后计算为 N 个值向量的加权和,其中权重为正且总和为 1。 a) 输出 sa 为 x x 乘以第一个值向量、 x x 乘以第二个值向量,以及 a[ x 3, x 1]=0.6 乘以第三个值向量。 b) 输出 sa 2[ x •] 以相同方式计算,但这次权重为 0.5、 0.2 和 0.3。 c) 输出 sa 3[ x •] 的加权再次不同。因此,每个输出都可被视为对 N 个值的不同路由。Figure 12.1 Self-attention as routing. inputs x 1,..., x N∈RD (here N= 3 and D = 4) and processes each separately to compute N value vectors. The nth output sa n[ x 1,... x N] (written as sa n[ x •] for short) is then computed as a weighted sum of the N value vectors, where the weights are positive and sum to one. a) Output sa 1[ x •] is computed as a[ x 1, x 1] = 0.1 times the first value vector, a[ x 2, x 1]=0.3 times the second value vector, and a[ x 3, x 1]=0.6 times the third value vector. b) Output sa 2[ x •] is computed in the same way, but this time with weights of 0.5, 0.2, and 0.3. c) The weighting for output sa 3[ x •] is different again. Each output can hence be thought of as a different routing of the N values.
12.2.1 计算和加权值
12.2.1 Computing and weighting values

Equation 12.2 shows that the same weights Ω v∈RD×D and biases βv∈RD are applied to each input x •∈RD. This computation scales linearly with the sequence length N, so it needs fewer parameters than a fully connected network relating all DN inputs to all DN values. In fact, the value computation can be viewed as a sparse matrix operation with shared parameters that relates these DN quantities (figure 12.2b).

The attention weights a[ x m, x n] combine the values from different inputs.

They are also sparse since there is only one weight for each ordered pair of inputs( x m, x n), regardless of the size of these inputs (figure 12.2c). It follows that the number of attention weights has a quadratic dependence on the sequence length N, but is independent of the length D of each input.

式 12.2 表明,相同的权重 Ω v∈RD×D 和偏差 βv∈RD 被应用于每个输入 x •∈RD。该计算随序列长度 N 线性扩展,因此所需的参数少于将所有 DN 输入与所有 DN 值相关联的全连接网络。事实上,值的计算可以看作一种具有共享参数的稀疏矩阵运算,它将这些 DN 量关联起来(图 12.2b)。

注意力权重 a[ x m, x n] 组合来自不同输入的值。它们也是稀疏的,因为每个有序输入对 (x m, x n) 只有一个权重,无论这些输入的大小如何(图 12.2c)。因此,注意力权重的数量与序列长度 N 呈二次依赖关系,但与每个输入的长度 D 无关。

12.2.2 计算注意力权重
12.2.2 Computing attention weights

In the previous section, we saw that the outputs result from two chained linear transformations; the value vectors βv+ Ω v x m are computed independently for each input x m, and these vectors are combined linearly by the attention weights a[ x m, x n]. However, the overall self-attention computation is nonlinear. As we’ll see shortly, the attention weights are themselves nonlinear functions of the input. This is an example of a hypernetwork, where one network branch computes the weights of another. To compute the

attention, we apply two more linear transformations to the inputs: where{ q n} and{ k m} are termed queries and keys, respectively. Then we compute dot

在上一节中,我们看到输出是由两个串联的线性变换产生的;值向量 βv+ Ω v x m 针对每个输入 x m 独立计算,并且这些向量通过注意力权重 a[ x m, x n] 进行线性组合。然而,整体的自注意力计算是非线性的。稍后我们将看到,注意力权重本身也是输入的非线性函数。这是超网络的一个示例,其中一个网络分支计算另一个网络的权重。为了计算

注意力,我们对输入再施加两个线性变换:其中 { q n} 和 { k m} 分别被称为查询和键。然后我们计算点

products between the queries and keys and pass the results through a softmax function:

积在查询和键之间,并将结果通过 Softmax 函数传递:

so for each x n, they are positive and sum to one (figure 12.3). For obvious reasons, this is known as dot-product self-attention. The names “queries” and “keys” were inherited from the field of information retrieval and have the following interpretation: the dot product operation returns a measure of similarity between its inputs, so the weights a[ x •, x n] depend on the relative similarities between the nth query and all of the keys. The softmax function means that the key vectors “compete” with one another to contribute to the final result. The queries and keys must have the same dimensions. However, these can differ from the dimension of

因此,对于每个 x n,它们均为正数且总和为 1 (图 12.3)。显然,这被称为点积自注意力。 “查询”和“键”这些名称继承自信息检索领域,其含义如下:点积操作回报其输入之间的相似度度量,因此权重 a[ x •, x n] 取决于 nth 查询与所有键之间的相对相似度。 Softmax 函数意味着键向量彼此“竞争”,以贡献于最终结果。查询和键必须具有相同的维度。然而,这些可以与 …… 的维度不同

图 12.2 针对  N =3 个输入 x n 的自注意力,每个输入的维度为  D=4。 a) 每个输入 x m 由相同的权重 Ω v (同色表示同权重)和偏差
图 12.2 针对 N =3 个输入 x n 的自注意力,每个输入的维度为 D=4。 a) 每个输入 x m 由相同的权重 Ω v (同色表示同权重)和偏差 βv (未显示)独立处理,以形成值 βv+ Ω v x m。每个输出都是这些值的线性组合,其中注意力权重 a[ x m, x n] 定义了 mth 值对 nth 输出的贡献。 b) 显示输入与值之间线性变换 Ω v 的块稀疏性的矩阵。 c) 显示值与输出之间的注意力权重稀疏性的矩阵。Figure 12.2 Self-attention for N =3 inputs x n, each with dimension D=4. a) Each input x m is operated on independently by the same weights Ω v (same color equals same weight) and biases βv (not shown) to form the values βv+ Ω v x m. Each output is a linear combination of the values, with the attention weight a[ x m, x n] defining the contribution of the mth value to the nth output. b) Matrix showing block sparsity of linear transformation Ω v between inputs and values. c) Matrix showing sparsity of attention weights relating values and outputs.

the values, which is usually the same size as the input, so the representation doesn’t change size.

值,通常与输入大小相同,因此表征不会调整大小。

图 12.3 计算注意力权重。 a) 查询向量 q n=βq+ Ω q x n 和键向量 k n=βk+ Ω k x n 针对每个输入 x n 计算。 b) 每
图 12.3 计算注意力权重。 a) 查询向量 q n=βq+ Ω q x n 和键向量 k n=βk+ Ω k x n 针对每个输入 x n 计算。 b) 每个查询与三个键之间的点积通过 Softmax 函数,形成总和为 1 的非负注意力权重。 c) 这些注意力权重通过图 12.2c 中的稀疏矩阵路由值向量(图 12.1)。Figure 12.3 Computing attention weights. a) Query vectors q n=βq+ Ω q x n and key vectors k n=βk+ Ω k x n are computed for each input x n. b) The dot products between each query and the three keys are passed through a softmax function to form non-negative attentions that sum to one. c) These route the value vectors (figure 12.1) via the sparse matrix from figure 12.2c.
12.2.3 自注意力总结
12.2.3 Self-attention summary

The nth output is a weighted sum of the same linear transformation v •=βv+ Ω v x • applied to all of the inputs, where these attention weights are positive and sum to one. The weights depend on a measure of similarity between input x n and the other inputs. There is no activation function, but the mechanism is nonlinear due to the dot-product and a softmax operation used to compute the attention weights.

Note that this mechanism fulfills the initial requirements. First, there is a single shared set of parameters ϕ={βv, Ω v, βq, Ω q, βk, Ω k}. This is independent of the

nth 输出是对所有输入应用同一线性变换 v •=βv+ Ω v x • 所得结果的加权和,其中这些注意力权重为正且总和为 1。这些权重取决于输入 x n 与其他输入之间的相似度度量。不存在激活函数,但该机制是非线性的,因为计算注意力权重时使用了点积和 Softmax 操作。请注意,这一机制满足了最初的要求。首先,存在一组共享的参数 ϕ={βv, Ω v, βq, Ω q, βk, Ω k}。这独立于

number of inputs N, so the network can be applied to different sequence lengths. Second, there are connections between the inputs (words), and the strength of these connections depends on the inputs themselves via the attention weights.

输入数量 N,因此网络可以应用于不同的序列长度。其次,输入(单词)之间存在连接,而这些连接的强度通过注意力权重取决于输入本身。

图 12.4 自注意力的矩阵形式。如果我们将  N 输入向量 x n 存储为  D×N 矩阵 X 的列,则自注意力可以高效实现。输入 X 分别由查询矩阵 Q、键
图 12.4 自注意力的矩阵形式。如果我们将 N 输入向量 x n 存储为 D×N 矩阵 X 的列,则自注意力可以高效实现。输入 X 分别由查询矩阵 Q、键矩阵 K 和值矩阵 V 进行运算。然后使用矩阵乘法计算点积,并对结果矩阵的每一列独立应用 Softmax 操作,以计算注意力。最后,将值右乘注意力,得到与输入大小相同的输出。Figure 12.4 Self-attention in matrix form. efficiently if we store the N input vectors x n in the columns of the D×N matrix X. The input X is operated on separately by the query matrix Q, key matrix K, and value matrix V. The dot products are then computed using matrix multiplication, and a softmax operation is applied independently to each column of the resulting matrix to calculate the attentions. Finally, the values are post-multiplied by the attentions to create an output of the same size as the input.
12.2.4 矩阵形式
12.2.4 Matrix form

The above computation can be written in a compact form if the N inputs x n form the columns of the D × N matrix X. The values, queries, and keys can be computed as:

如果 N 输入 x n 构成 D × N 矩阵 X 的列,则上述计算可以写成紧凑形式。值、查询和键可以计算为:

12.3 点积自注意力的扩展
12.3 Extensions to dot-product self-attention

In the previous section, we described self-attention. Here, we introduce three extensions that are almost always used in practice.

在上一节中,我们介绍了自注意力。这里,我们介绍三个在实践中几乎总会用到的扩展。

12.3.1 位置编码
12.3.1 Positional encoding

Observant readers will have noticed that the self-attention mechanism overlooks impor-

tant information: the computation does not take into account the order of the inputs x n. More precisely, it is equivariant with respect to input permutations. However, order is important when the inputs correspond to the words in a sentence. The sentence The woman ate the raccoon has a different meaning than The raccoon ate the woman. There are two main approaches to incorporating position information.

细心的读者会注意到,自注意力机制忽略了重要 -

信息:计算没有考虑输入的次序 x n。更准确地说,它对输入排列是等变的。然而,次序很重要。当输入对应句子中的词语时,句子“女人吃了浣熊”的含义不同于“浣熊吃了女人”。有两种主要方法融入位置信息。

Absolute positional encodings:

A matrix Π is added to the input X that encodes positional information (figure 12.5). Each column of Π is unique and hence contains information about the absolute position in the input sequence.

This matrix can be chosen by hand or learned. It may be added to the network inputs or at every network layer. Sometimes it is added to X in the computation of the queries and keys but not to the values.

绝对位置编码:将矩阵 Π 添加到输入 X 中,以编码位置信息(图 12.5)。 Π 的每一列都是唯一的,因此包含有关输入序列中绝对位置的信息。该矩阵可以手工选择或学习得到。它可以被添加到网络输入中,也可以添加到每一层网络中。有时在计算查询和键时将其添加到 X 中,但不将其添加到值中。

Relative positional encodings:

The input to a self-attention mechanism may be an entire sentence, many sentences, or just a fragment of a sentence, and the absolute position of a word is much less important than the relative position between two words. Of course, this can be recovered if the system knows the absolute position of both, but relative positional encodings encode this information directly. Each element of the attention matrix corresponds to a particular offset between key position a and query position b. Relative positional encodings learn a parameter πa,b for each offset and use this to modify the attention matrix by adding these values, multiplying by them, or using them to alter the attention matrix in some other way.

相对位置编码:自注意力机制的输入可以是整个句子、多个句子,或仅仅是句子的一个片段,而一个词的绝对位置远不如两个词之间的相对位置重要。当然,如果系统知道两者的绝对位置,也可以恢复这种信息,但相对位置编码会直接编码该信息。注意力矩阵中的每个元素对应于键位置 a 与查询位置 b 之间的一个特定偏移。相对位置编码会为每个偏移学习一个参数 πa,b,并使用这些值,通过将其加入、与其相乘,或以其他某种方式修改注意力矩阵。

12.3.2 缩放点积自注意力
12.3.2 Scaled dot-product self-attention

The dot products in the attention computation can have large magnitudes and move the arguments to the softmax function into a region where the largest value completely dominates. Small changes to the inputs to the softmax function now have little effect on

注意力计算中的点积可能具有较大的量级,并使 Softmax 函数的参数进入最大值完全主导的区域。此时, Softmax 函数输入的小变化对

the output (i.e., the gradients are very small), making the model difficult to train. To prevent this, the dot products are scaled by the square root of the dimension Dq of the queries and keys (i.e., the number of rows in Ω q and Ω k, which must be the same): Sa[ X ] = V · Softmax

This is known as scaled dot-product self-attention.

输出(即梯度非常小)的影响,从而使模型难以训练。为防止这种情况,点积会按查询和键的维度 Dq 的平方根进行缩放(即 Ω q 和 Ω k 中的行数,二者必须相同): Sa[ X ] = V · Softmax

这被称为缩放点积自注意力。

公式
12.3.3 多头
12.3.3 Multiple heads

Multiple self-attention mechanisms are usually applied in parallel, and this is known as multi-head self-attention. Now H different sets of values, keys, and queries are computed:

多个自注意力机制通常并行应用,这被称为多头自注意力。现在计算 H 组不同的值、键和查询:

第 hth 个自注意力机制或头可以写成:

The hth self-attention mechanism or head can be written as:

where we have different parameters{βvh, Ω vh},{βqh, Ω qh}, and{βkh, Ω kh} for each head. Typically, if the dimension of the inputs x m is D and there are H heads, the values, queries, and keys will all be of size D/H, as this allows for an efficient implementation.

The outputs of these self-attention mechanisms are vertically concatenated, and another linear transform Ω c is applied to combine them (figure 12.6):

这些自注意力机制的输出被纵向拼接,并施加另一个线性变换 Ω c 来组合它们(图 12.6):

图 12.6 多头自注意力。自注意力在多个“头”上并行发生。每个头都有各自的查询、键和值。此处分别用青色和橙色框表示了两个头。输出沿垂直方向拼接,并使用另一个线
图 12.6 多头自注意力。自注意力在多个“头”上并行发生。每个头都有各自的查询、键和值。此处分别用青色和橙色框表示了两个头。输出沿垂直方向拼接,并使用另一个线性变换 Ω c 将它们重新组合。Figure 12.6 Multi-head self-attention. Self-attention occurs in parallel across multiple “heads.” Each has its own queries, keys, and values. Here two heads are depicted, in the cyan and orange boxes, respectively. The outputs are vertically concatenated, and another linear transformation Ω c is used to recombine them.

Multiple heads seem to be necessary to make self-attention work well.

It has been speculated that they make the self-attention network more robust to bad initializations.

多个头似乎对于使自注意力良好工作来说是必要的。这已被据推测,它们使自注意力网络对不良初始化更加稳健。

12.4 Transformer 层
12.4 Transformer layers

Self-attention is just one part of a larger transformer layer. This consists of a multihead self-attention unit (which allows the word representations to interact with each

自注意力只是更大的 Transformer 层的一部分。它由一个多头自注意力单元组成(该单元允许词表示相互

other) followed by a fully connected network mlp[ x •] (that operates separately on each word). Both units are residual networks (i.e., their output is added back to the original input).

In addition, it is typical to add a LayerNorm operation after both the selfattention and fully connected networks. This is similar to BatchNorm but normalizes each embedding in each batch element separately using statistics calculated across its D embedding dimensions (section 11.4 and figure 11.14). The complete layer can be described by the following series of operations (figure 12.7):

作用)后接一个全连接网络 MLP[ x •] (分别作用于每个词)。这两个单元都是残差网络(即它们的输出会被加回到原始输入)。此外,通常会在自注意力和全连接网络之后都添加一个 LayerNorm 操作。这类似于 BatchNorm,但会对每个批次元素中的每个嵌入分别进行归一化,使用跨其 D 嵌入维度计算的统计量(第 11.4 节和图 11.14)。完整层可由以下操作序列描述(图 12.7):

公式
图 12.7 Transformer 层。输入由一个 D × N 矩阵组成,该矩阵包含  N 个输入词元各自的  D 维词嵌入。输出是相同大小的矩阵。 Tran
图 12.7 Transformer 层。输入由一个 D × N 矩阵组成,该矩阵包含 N 个输入词元各自的 D 维词嵌入。输出是相同大小的矩阵。 Transformer 层由一系列操作组成。首先是一个多头注意力块,允许词嵌入彼此交互。这构成残差块处理,因此输入会被加回输出。其次,对每个嵌入分别应用 LayerNorm 操作。第三,存在第二个残差层,其中同一个全连接神经网络分别应用于 N 个词表示(列)。最后,再次应用 LayerNorm。Figure 12.7 Transformer layer. The input consists of a D × N matrix containing the D -dimensional word embeddings for each of the N input tokens. The output is a matrix of the same size. The transformer layer consists of a series of operations. First, there is a multi-head attention block, allowing the word embeddings to interact with one another. This forms the processing of a residual block, so the inputs are added back to the output. Second, a LayerNorm operation is applied separately to each embedding. Third, there is a second residual layer where the same fully connected neural network is applied separately to each of the N word representations (columns). Finally, LayerNorm is applied again.
公式

where the column vectors x n are separately taken from the full data matrix X. In a real network, the data passes through a series of these transformer layers.

其中列向量 x n 分别取自完整数据矩阵 X。在真实网络中,数据会依次经过一系列这样的 Transformer 层。

12.5 用于自然语言处理的 Transformer
12.5 Transformers for natural language processing

The previous section described the transformer layer. This section describes how it is used in natural language processing (NLP) tasks. A typical NLP pipeline starts with a tokenizer that splits the text into words or word fragments. Then each of these tokens

is mapped to a learned embedding. These embeddings are passed through a series of transformer layers. We now consider each of these stages in turn.

上一节描述了 Transformer 层。本节介绍它在自然语言处理 (NLP) 任务中的用法。典型的 NLP 流程以分词器开始,它将文本拆分为单词或词片段。然后,这些词元中的每一个

被映射为一个学习到的嵌入。这些嵌入被送入一系列 Transformer 层。现在,我们依次考虑这些阶段中的每一个。

图 12.8 子词分词。 a) 一段来自童谣的文本。词元最初只是字符和空白符(用下划线表示),它们的频率显示在表格中。 b) 在每次迭代中,子词分词器寻找出现频
图 12.8 子词分词。 a) 一段来自童谣的文本。词元最初只是字符和空白符(用下划线表示),它们的频率显示在表格中。 b) 在每次迭代中,子词分词器寻找出现频率最高的相邻词元对(在本例中, se)并将其合并。这会创建一个新词元,并降低原词元 s 和 e 的计数。请注意,待合并的第一个词元的最后一个字符不能是空白符,这可以防止跨词合并。 c) 在第二次迭代中,算法将 e 和空白符 _。 d) 经过 23 次迭代后,词元由字母、词片段和常见词混合组成。 e) 如果我们无限继续此过程,词元最终将表示完整单词。 f) 随着时间推移,当我们向字母中添加词片段时,词元数量会增加,然后随着合并这些片段而再次减少。在实际情况下,会有大量单词,当词表大小(词元数量)达到预设值时,算法将终止。标点符号和大写字母也会被视作独立的输入字符。Figure 12.8 Sub-word tokenization. a) A passage of text from a nursery rhyme. The tokens are initially just the characters and whitespace (represented by an underscore), and their frequencies are displayed in the table. b) At each iteration, the sub-word tokenizer looks for the most commonly occurring adjacent pair of tokens (in this case, se) and merges them. This creates a new token and decreases the counts for the original tokens s and e. Note that the last character of the first token to be merged cannot be whitespace, which prevents merging across words. c) At the second iteration, the algorithm merges e and the whitespace character _. d) After 23 iterations, the tokens consist of a mix of letters, word fragments, and commonly occurring words. e) If we continue this process indefinitely, the tokens eventually represent the full words. f) Over time, the number of tokens increases as we add word fragments to the letters and then decreases again as we merge these fragments. In a real situation, there would be a very large number of words, and the algorithm would terminate when the vocabulary size (number of tokens) reached a predetermined value. Punctuation and capital letters would also be treated as separate input characters.
12.5.1 分词
12.5.1 Tokenization

A text processing pipeline begins with a tokenizer.

This splits the text into smaller constituent units (tokens) from a vocabulary of possible tokens. In the discussion above, we have implied that these tokens represent words, but there are several difficulties.

• Inevitably, some words (e.g., names) will not be in the vocabulary. • It’s unclear how to handle punctuation, but this is important. If a sentence ends

• 不可避免地,一些单词(例如姓名)不会出现在词汇表中。 • 如何处理标点符号尚不明确,但这很重要。如果一个句子以问号结尾,我们必须对这

in a question mark, we must encode this information. • The vocabulary would need different tokens for versions of the same word with different suffixes (e.g., walk, walks, walked, walking), and there is no way to clarify

that these variations are related.

One approach would be to use letters and punctuation marks as the vocabulary, but this would mean splitting text into very small parts and requiring the subsequent network to re-learn the relations between them. In practice, a compromise between letters and full words is used, and the final vo- cabulary includes both common words and word fragments from which larger and less

一信息进行编码。 • 词汇表需要为同一单词带有不同后缀的不同形式使用不同的词元(例如, walk、

walks、 walked、 walking),而且无法说明这些变体之间是相关的。

一种方法是使用字母和标点符号作为词汇表,但这意味着将文本拆分成非常小的部分,并要求后续网络重新学习它们之间的关系。在实践中,通常采用字母和完整单词之间的折中方案,最终词 -汇表包括常见单词和词片段,从中可以组合出更长、更不常见的单词。词汇表是使用一

frequent words can be composed. The vocabulary is computed using a sub-word tokenizer such as byte pair encoding (figure 12.8) that greedily merges commonly occurring sub-strings based on their frequency.

个子词分词器(如字节对编码(图 12.8))计算的,它根据频率贪婪地合并常见出现的子字符串。

12.5.2 嵌入
12.5.2 Embeddings

Each token in the vocabulary V is mapped to a unique wordembedding, and the embeddings for the whole vocabulary are stored in a matrix Ω e∈RD×|V|. To accomplish this, the N input tokens are first encoded in the matrix T ∈R|V|×N, where the nth column corresponds to the nth token and is a |V| × 1one-hotvector (i.e., a vector where every entry is zero except for the entry corresponding to the token, which is set to one). The input embeddings are computed as X = Ω e T, and Ω e is learned like any other network parameter (figure 12.9). A typical embedding size D is 1024, and a typical total vocabulary size |V| is 30,000, so even before the main network, there are many parameters in Ω e to learn.

词表 V 中的每个词元都被映射到一个唯一的词嵌入,整个词表的嵌入存储在矩阵 Ω e∈RD×|V| 中。为此, N 输入词元首先被编码到矩阵 T ∈R|V|×N 中,其中 nth 列对应 nth 词元,并且是一个 |V| × 1 独热向量(即一个向量,其中每个元素都是零,只有对应词元的元素被设为 1)。输入嵌入计算为 X = Ω e T,并且 Ω e 像其他网络参数一样被学习(图 12.9)。典型的嵌入维度 D 为 1024,典型的总词表大小 |V| 为 30,000,因此即使在主网络之前, Ω e 中也有很多参数需要学习。

12.5.3 Transformer 模型
12.5.3 Transformer model

Finally, the embedding matrix X representing the text is passed through a series of K transformer layers, called a transformer model. There are three types of transformer models.

An encoder transforms the text embeddings into a representation that can support a variety of tasks. A decoder predicts the next token to continue the input

最后,表示文本的嵌入矩阵 X 经过一系列 K Transformer 层,称为 Transformer 模型。 Transformer 模型有三种类型。编码器将文本嵌入转换为一种能够支持各种任务的表示。解码器预测下一个词元以继续输入

图 12.9 输入嵌入矩阵 X ∈RD×N 包含 N 个长度为 D 的嵌入,由矩阵 Ω e 与一个列中包含对应于词或子词索引的独热向量的矩阵相乘得到,前者包含整
图 12.9 输入嵌入矩阵 X ∈RD×N 包含 N 个长度为 D 的嵌入,由矩阵 Ω e 与一个列中包含对应于词或子词索引的独热向量的矩阵相乘得到,前者包含整个词表的嵌入。词表矩阵 Ω e 被视为模型的参数,并与其他参数一起训练。注意,词 an 在 X 中的两个嵌入是相同的。Figure 12.9 The input embedding matrix X ∈RD×N contains N embeddings of length D and is created by multiplying a matrix Ω e containing the embeddings for the entire vocabulary with a matrix containing one-hot vectors in its columns that correspond to the word or sub-word indices. The vocabulary matrix Ω e is considered a parameter of the model and is learned along with the other parameters. Note that the two embeddings for the word an in X are the same.

text. Encoder-decoders are used in sequence-to-sequence tasks, where one text string is converted into another (e.g., machine translation). These variations are described in sections 12.6–12.8, respectively.

文本。编码器 - 解码器用于序列到序列任务,其中一个文本字符串被转换为另一个文本字符串(例如,机器翻译)。这些变体分别在第 12.6–12.8 节中描述。

12.6 编码器模型示例: BERT
12.6 Encoder model example: BERT

BERT is an encoder model that uses a vocabulary of 30,000 tokens. Input tokens are converted to 1024-dimensional word embeddings and passed through 24 transformer layers. Each contains a self-attention mechanism with 16 heads. The queries, keys, and values for each head are of dimension 64 (i.e., the matrices Ω vh, Ω qh, Ω kh are 64×1024). The dimension of the single hidden layer in the fully connected networks is 4096. The total number of parameters is ∼340 million. When BERT was introduced, this was considered large, but it is now much smaller than state-of-the-art models.

Encoder models like BERT exploit transfer learning (section 9.3.6).

During pretraining, the parameters of the transformer architecture are learned using self-supervision from a large corpus of text. The goal here is for the model to learn general information about the statistics of language. In the fine-tuning stage, the resulting network is adapted to solve a particular task using a smaller body of labelled training data.

BERT 是一个编码器模型,使用包含 30,000 个词元的词表。输入词元被转换为 1024 维词嵌入,并经过 24 个 Transformer 层。每一层都包含一个具有 16 个头的自注意力机制。每个头的查询、键和值的维度均为 64 (即矩阵 Ω vh、 Ω qh、 Ω kh 为 64×1024)。全连接网络中单个隐藏层的维度为 4096。参数总数为 ∼340 百万。 BERT 推出时,这被认为是较大的规模,但现在远小于当前最先进模型。

像 BERT 这样的编码器模型利用迁移学习(第 9.3.6 节)。在预训练期间, Transformer 架构的参数通过自监督从大规模文本语料中学习。这里的目标是让模型学习关于语言统计规律的一般信息。在微调阶段,所得网络被适配以使用较小的带标签训练数据来解决特定任务。

12.6.1 预训练
12.6.1 Pre-training

In the pre-training stage, the network is trained using self-supervision. This allows the use of enormous amounts of data without the need for manual labels. For BERT, the selfsupervision task consists of predicting missing words from sentences from a large internet

在预训练阶段,网络使用自监督进行训练。这使得无需人工标签即可使用海量数据。对于 BERT,自监督任务包括从来自大型互联网的句子中预测缺失的词语

corpus (figure 12.10). 1 During training, the maximum input length is 512 tokens, and the batch size is 256. The system is trained for a million steps, corresponding to roughly 50 epochs of the 3.3-billion word corpus.

Predicting missing words forces the transformer network to understand some syntax. For example, it might learn that the adjective red is often found before nouns like house or car but never before a verb like shout. It also allows the model to learn superficial common sense about the world. For example, after training, the model will assign a higher probability to the missing word train in the sentence The < mask > pulled into the station than it would to the word peanut. However, the degree of “understanding” this type of model can ever have is limited.

语料库(图 12.10)。 1 在训练期间,最大输入长度为 512 个词元,批量大小为 256。该系统训练 100 万步,大约相当于 33 亿词规模语料库的 50 个训练轮次。

预测缺失的词语会迫使 Transformer 网络理解一些句法。例如,它可能会学到形容词“红色”通常出现在“房屋”或“汽车”等名词之前,但绝不会出现在动词“喊叫”之前。这也使模型能够学习关于世界的浅显的常识。例如,训练后,模型会给缺失的词“火车”在句子“该 < 掩码 > 驶入车站”中赋予更高的概率,而不是给词“花生”赋予更高的概率。然而,这种模型所能达到的“理解”程度是有限的。

图 12.10 类 BERT 编码器的预训练。输入词元(以及一个特殊的 &lt; cls &gt; 词元,表示序列的开头)被转换为词嵌入。这里,它们表示为行而不
图 12.10 类 BERT 编码器的预训练。输入词元(以及一个特殊的 < cls > 词元,表示序列的开头)被转换为词嵌入。这里,它们表示为行而不是列,因此标记为“词嵌入”的方框是 X T。这些嵌入经过一系列 Transformer 层(橙色连接表示在这些层中,每个词元都会关注其他所有词元),生成一组输出嵌入。一小部分输入词元被随机替换为通用的 < mask > 词元。在预训练中,目标是根据相应的输出嵌入预测缺失的词。为此,与被掩码词元对应的输出会经过 Softmax 函数,并对每个输出施加多分类损失(第 5.24 节)。该任务的优点是同时使用左侧和右侧上下文来预测缺失词,但缺点是不能高效利用数据;这里需要处理七个词元才能为损失函数添加两个项。 1 BERT 还使用一项辅助任务,预测两句话在原始文本中是否相邻,但这只能略微提升性能。Figure 12.10 Pre-training for BERT-like encoder. The input tokens (and a special < cls > token denoting the start of the sequence) are converted to word embeddings. Here, these are represented as rows rather than columns, so the box labeled “word embeddings” is X T. These embeddings are passed through a series of transformer layers (orange connections indicate that every token attends to every other token in these layers) to create a set of output embeddings. A small fraction of the input tokens are randomly replaced with a generic < mask > token. In pre-training, the goal is to predict the missing word from the associated output embedding. To this end, the outputs corresponding to the masked tokens are passed through softmax functions, and a multiclass classification loss (section 5.24) is applied to each. This task has the advantage that it uses both the left and right context to predict the missing word but has the disadvantage that it does not make efficient use of data; here, seven tokens need to be processed to add two terms to the loss function. 1 BERT also uses a secondary task that predicts whether two sentences were originally adjacent in the text or not, but this only marginally improves performance.
图 12.11 预训练后,编码器使用人工标注的数据进行微调,以解决特定任务。通常,会在编码器后附加一个线性变换或多层感知机(MLP),以生成所需的输出。 a)
图 12.11 预训练后,编码器使用人工标注的数据进行微调,以解决特定任务。通常,会在编码器后附加一个线性变换或多层感知机(MLP),以生成所需的输出。 a) 文本分类任务示例。在该情感分类任务中, < cls > 词元嵌入用于预测评论为正面的概率。 b) 词语分类任务示例。在该命名实体识别问题中,每个词的嵌入用于预测该词是否对应人物、地点或组织,或者不是实体。Figure 12.11 After pre-training, the encoder is fine-tuned using manually labeled data to solve a particular task. Usually, a linear transformation or a multi-layer perceptron (MLP) is appended to the encoder to produce whatever output is required. a) Example text classification task. task, the < cls > token embedding is used to predict the probability that the review is positive. b) Example word classification task. recognition problem, the embedding for each word is used to predict whether the word corresponds to a person, place, or organization, or is not an entity.
12.6.2 微调
12.6.2 Fine-tuning

In the fine-tuning stage, the model parameters are adjusted to specialize the network to a particular task. An extra layer is appended onto the transformer network to convert the output vectors to the desired output format. Examples include:

Text classification:

In BERT, a special token known as the classification or < cls > token is placed at the start of each string during pre-training. For text classification tasks like sentiment analysis (in which the passage is labeled as having a positive or negative emotional tone), the vector associated with the < cls > token is mapped to a single number and passed through a logistic sigmoid (figure 12.11a). This contributes to a standard binary cross-entropy loss (section 5.4).

在微调阶段,会调整模型参数,使网络专门用于特定任务。会在 Transformer 网络上追加一个额外的层,将输出向量转换为所需的输出格式。示例包括:

文本分类:在 BERT 中,一个被称为分类词元或 < cls > 词元会在预训练期间被放置在每个字符串的开头。对于像情感分析(其中段落会被赋予正面或负面情感基调的标签),与 < cls > 词元相关联的向量会被映射到一个单一的数字,并经过一个逻辑 sigmoid (图 12.11a)。这会产生一个标准的二元交叉熵损失(第 5.4 节)。

Word classification:

The goal of named entity recognition is to classify each word as an entity type (e.g., person, place, organization, or no-entity). To this end, each input embedding x n is mapped to an E× 1 vector where the E entries correspond to the E entity types. This is passed through a softmax function to create probabilities for each class, which contribute to a multiclass cross-entropy loss (figure 12.11b).

词分类:命名实体识别的目标是将每个词分类为实体类型(例如,人物、地点、组织或无实体)。为此,每个输入嵌入 x n 会被映射到一个 E× 1 向量,其中 E 个条目对应 E 种实体类型。这会被传入一个 Softmax 函数,以生成每个类别的概率,这些概率会构成一个多分类交叉熵损失(图 12.11b)。

Text span prediction:

In the SQuAD 1.1 question answering task, the question and a passage from Wikipedia containing the answer are concatenated and tokenized. BERT is then used to predict the text span in the passage that contains the answer. Each token maps to two numbers indicating how likely it is that the text span begins and ends at this location. The resulting two sets of numbers are put through two softmax functions. The likelihood of any text span being the answer can be derived by combining the probability of starting and ending at the appropriate places.

文本跨度预测:在 SQuAD 1.1 问答任务中,问题和包含答案的维基百科段落会被拼接并进行词元化。随后使用 BERT 来预测段落中包含答案的文本跨度。每个词元映射到两个数字,分别表示文本跨度在该位置开始和结束的可能性。所得的两组数字分别经过两个 Softmax 函数。任意文本跨度作为答案的可能性可以通过组合在适当位置开始和结束的概率得到。

12.7 解码器模型示例: GPT3
12.7 Decoder model example: GPT3

This section presents a high-level description of GPT3, an example of a decoder model. The basic architecture is extremely similar to the encoder model and comprises a series of transformer layers that operate on learned word embeddings. However, the goal is different. The encoder aimed to build a representation of the text that could be finetuned to solve a variety of more specific NLP tasks. Conversely, the decoder has one purpose: to generate the next token in a sequence.

It can generate a coherent text passage by feeding the extended sequence back into the model.

本节给出 GPT3 的高层描述,它是解码器模型的一个示例。其基本架构与编码器模型极其相似,由一系列作用于学习得到的词嵌入的 Transformer 层组成。然而,目标不同。编码器旨在构建文本表示,该表示可经微调以解决各种更具体的自然语言处理任务。相反,解码器只有一个目的:生成序列中的下一个词元。它可以通过将扩展后的序列重新输入模型来生成连贯的文本段落。

12.7.1 语言建模
12.7.1 Language modeling

GPT3 is an autoregressive language model. This is easiest to understand with a concrete example. Consider the sentence It takes great courage to let yourself appear weak. For simplicity, let’s assume that the tokens are the full words. The probability of the full sentence can be factored as: Pr( It takes great courage to let yourself appear weak ) Pr( It ) × Pr( takes | It ) × Pr( great | It takes ) × Pr( courage | It takes great ) × Pr( to | It takes great courage ) × Pr( let | It takes great courage to ) × Pr( yourself | It takes great courage to let ) × Pr( appear | It takes great courage to let yourself ) × Pr( weak | It takes great courage to let yourself appear ).

GPT3 是一种自回归语言模型。这一点用一个具体示例最容易理解。考虑句子让自己显得软弱是需要极大的勇气。为简单起见,我们假设词元就是完整的单词。整个句子的概率可以分解为: Pr (让自己显得软弱是需要极大的勇气) =Pr (让) × Pr (自己 | 让) × Pr (显得 | 让自己) × Pr (软弱 | 让自己显得) ×Pr (是 | 让自己显得软弱) × Pr (需要 | 让自己显得软弱是) ×Pr (极大 | 让自己显得软弱是需要) ×Pr (的 | 让自己显得软弱是需

要极大) ×Pr (勇气 | 让自己显得软弱是需要极大的)。

An autoregressive model predicts the conditional distributions Pr(tn|t1,..., tn−1) of each token given all the prior tokens, and hence indirectly computes the joint probability Pr(t1, t2,..., tN) of all N tokens:

The autoregressive formulation demonstrates the connection between maximizing the joint probability of the tokens and the next token prediction task.

自回归模型预测在给定所有先前词元的情况下每个词元的条件分布 Pr (tn|t1,..., tn−1),因此间接计算所有 N 词元的联合概率 Pr (t1, t2,..., tN):

自回归表述展示了最大化词元联合概率与下一词元预测任务之间的联系。

12.7.2 掩码自注意力
12.7.2 Masked self-attention

To train a decoder, we seek parameters that maximize the log probability of the input text under the autoregressive model (i.e., that maximize the sum of the log conditional probability terms). Ideally, we would pass in the whole sentence and compute all the log probabilities and gradients in the same forward pass rather than doing a forward pass for each token in the sentence. However, if we pass in the full sentence, the term computing log [Pr( great | It takes )] would have access to both the answer great and the right context courage to let yourself appear weak. Hence, the system can cheat rather than learn to predict the following words and won’t train properly.

Fortunately, the tokens only interact in the self-attention layers in a transformer network.

Hence, the problem can be resolved by ensuring that the attention to the answer and the right context is zero. This can be achieved by setting the corresponding dot products in the self-attention computation (equation 12.5) to negative infinity before they are passed through the softmax[•] function. This is known as masked self-attention. The effect is to make the weight of all the upward-angled arrows in figure 12.1 zero.

要训练解码器,我们寻找能够最大化自回归模型下输入文本的对数概率的参数(即最大化对数条件概率项之和)。理想情况下,我们会输入整个句子,并在同一次前向传播中计算所有对数概率和梯度,而不是对句子中的每个词元分别进行一次前向传播。然而,如果输入整个句子,则计算 log[Pr( 极大 | 需要 )] 的项会同时看到答案极大以及右侧上下文勇气,让自己显得脆弱。因此,系统可以作弊,而不是学习预测后续词,无法正确训练。

幸运的是,词元仅在 Transformer 网络的自注意力层中相互作用。因此,可以通过确保对答案和右侧上下文的注意力为零来解决该问题。这可以通过在自注意力计算(公式 12.5)中,将相应的点积在传入 Softmax[•] 函数之前设置为负无穷来实现。这被称为掩码自注意力。其效果是使图 12.1 中所有向上倾斜的箭头的权重为零。

The entire decoder network operates as follows. The input text is tokenized, and the tokens are converted to embeddings. The embeddings are passed into the transformer network, but now the transformer layers use masked self-attention so that they can only attend to the current and previous tokens. Each of the output embeddings can be thought of as representing a partial sentence, and for each, the goal is to predict the next token in the sequence. Consequently, after the transformer layers, a single linear layer maps each output embedding to the size of the vocabulary, followed by a softmax[•] function that converts these values to probabilities. During training, we aim to maximize the sum of the log probabilities of the next token in the ground truth sequence at every position using a standard multiclass cross-entropy loss (figure 12.12).

整个解码器网络的工作方式如下。输入文本会被词元化,并且词元会被转换为嵌入。这些嵌入会传入 Transformer 网络,但此时 Transformer 层使用掩码自注意力,因此它们只能关注当前词元及之前的词元。每个输出嵌入都可以被视为表示一个部分句子,而对于每个输出嵌入,目标是预测序列中的下一个词元。因此,在 Transformer 层之后,一个线性层将每个输出嵌入映射到词表大小,随后是一个 Softmax[•] 函数,将这些值转换为概率。在训练期间,我们使用标准的多类交叉熵损失,最大化真值序列中每个位置上下一个词元的对数概率之和(图 12.12)。

12.7.3 从解码器生成文本
12.7.3 Generating text from a decoder

The autoregressive language model is the first example of a generative model discussed in this book. Since it defines a probability model over text sequences, it can be used to sample new examples of plausible text. To generate from the model, we start with an input sequence of text (which might be just the special < start > token indicating the beginning of the sequence) and feed this into the network, which then outputs the probabilities over possible subsequent tokens. We can then either pick the most likely token or sample from this probability distribution. The new extended sequence can be fed back into the decoder network to yield the probability distribution over the next token. By repeating this process, we can generate large bodies of text. The computation can be made quite efficient as prior embeddings do not depend on subsequent ones due to the masked self-attention. Hence, much of the earlier computation can be recycled as

we generate subsequent tokens. In practice, many strategies can make the output text more coherent. For example, beam search keeps track of multiple possible sentence completions to find the overall most likely sequence of words (which is not necessarily found by greedily choosing the most

自回归语言模型是本书中讨论的第一个生成模型示例。由于它定义了文本序列上的概率模型,因此可用于采样新的合理文本示例。要从模型中生成,我们从文本输入序列开始(可能只是特殊的 < 开始 > 词元,用于表示序列的开头),然后将其输入网络,网络随后输出可能后续词元的概率。然后,我们可以选择最可能的词元,或者从该概率分布中采样。新的扩展序列可以反馈给解码器网络,以得到下一个词元。通过重复这一过程,我们可以生成大量文本。由于掩码自注意力,先前的嵌入不依赖于后续的嵌入,因此计算可以变得相当高效。因此,大部分早期计算可以被复用为我们生成后续词元。在实践中,许多策略可以使输出文本更加连贯。例如,束搜索记录多个可能的句子补全,以寻找整体最可能的词序列(这不一定能通过每一步

likely word at each step). Top-k sampling randomly draws the next word from only the top-K most likely possibilities to prevent the system from accidentally choosing from the long tail of low-probability tokens and leading to an unnecessary linguistic dead end.

贪心地选择最可能的词来获得)。 Top-k 采样仅从最可能的 K 个候选中随机抽取下一个词,以防止系统意外地从低概率词元的长尾中进行选择,从而进入不必要的语言死胡同。

12.7.4 GPT-3 与少样本学习
12.7.4 GPT3 and few-shot learning

Large language models like GPT3 apply these ideas on a massive scale. In GPT3, the sequence lengths are 2048 tokens long, and the total batch size is 3.2 million tokens. There are 96 transformer layers (some of which implement a sparse version of attention), each processing a word embedding of size 12288. There are 96 heads in the self-attention

layers, and the value, query, and key dimension is 128. It is trained with 300 billion tokens and contains 175 billion parameters.

大语言模型如 GPT3 将这些理念大规模应用。在 GPT3 中,序列长度为 2048 个词元,总批量大小为 320 万个词元。有 96 个 Transformer 层(其中一些实现了稀疏版注意力),每层处理大小为 12288 的词嵌入。包含 96 个头的自注意力

图 12.12 训练 GPT3 型解码器网络。词元被映射为词嵌入,并在序列开头添加一个特殊的 &lt; 起始 &gt; 词元。这些嵌入经过一系列使用掩码自注意力
图 12.12 训练 GPT3 型解码器网络。词元被映射为词嵌入,并在序列开头添加一个特殊的 < 起始 > 词元。这些嵌入经过一系列使用掩码自注意力的 Transformer 层。在这里,句子中的每个位置只能关注其自身的嵌入以及序列中较早词元的嵌入(橙色连接)。每个位置的目标是最大化序列中下一个真值词元的概率。换言之,在位置一,我们希望最大化词元“它”;在位置二,我们希望最大化词元“需要”;依此类推。掩码自注意力确保系统不能通过查看后续输入来作弊。自回归任务的优势在于高效利用数据,因为每个词都对损失函数贡献一项。然而,它只利用了每个词的左侧上下文。Figure 12.12 Training GPT3-type decoder network. The tokens are mapped to word embeddings with a special < start > token at the beginning of the sequence. The embeddings are passed through a series of transformer layers that use masked self-attention. Here, each position in the sentence can only attend to its own embedding and those of tokens earlier in the sequence (orange connections). The goal at each position is to maximize the probability of the following ground truth token in the sequence. In other words, at position one, we want to maximize the probability of the token It; at position two, we want to maximize the probability of the token takes; and so on. Masked self-attention ensures the system cannot cheat by looking at subsequent inputs. The autoregressive task has the advantage of making efficient use of the data since every word contributes a term to the loss function. However, it only exploits the left context of each word.

Here’s an example of completing text from the GPT3 model where the text provided to the model is in orange, and the generated text is in cyan:

这里是来自 GPT3 模型的文本补全示例,其中提供给模型的文本为橙色,生成的文本为青色:

This continuation is plausible, albeit only partially accurate.

One surprising property of learning models on this scale is that they can perform many tasks without fine-tuning. If we provide several examples of correct question/answer pairs and then another question, they often answer the final question correctly by completing the sequence. One example is correcting English grammar:

这一续写看似合理,尽管只有部分准确。

这种规模的学习模型有一个令人惊讶的特性:它们无需微调就能完成许多任务。如果我们提供几个正确的问答对示例,然后再给出一个问题,它们通常能够通过补全序列来正确回答最后一个问题。一个例子是纠正英语语法:

Here, the text containing the paired examples in orange was provided as context for GPT3, and the system then generated the correct answer in cyan. This phenomenon extends to many situations, including generating code snippets based on natural language descriptions, arithmetic, translating between languages, and answering questions about text passages. Consequently, it is argued that enormous language models are few-shot learners; they can learn to do novel tasks based on just a few examples.

However, performance is erratic in practice, and the extent to which it is extrapolating from learned examples rather than merely interpolating or copying verbatim is unclear.

这里,包含配对示例的文本以橙色的形式作为上下文提供给 GPT3,随后系统生成了正确的答案,答案以青色显示。这一现象延伸到许多场景,包括根据自然语言描述生成代码片段、算术、语言间翻译,以及回答有关文本段落的问题。因此,人们认为超大规模语言模型是少样本学习器;它们能够仅根据少量示例学习执行新任务。然而,其实际表现很不稳定,而且它究竟在多大程度上是从已学习示例中进行外推,而非仅仅进行插值或逐字复制,这一点尚不清楚。

图 12.13 编码器 - 解码器架构。将两个句子传入系统,目标是将第一个句子翻译成第二个句子。 a) 第一个句子通过标准编码器。 b) 第二个句子通过一个解码
图 12.13 编码器 - 解码器架构。将两个句子传入系统,目标是将第一个句子翻译成第二个句子。 a) 第一个句子通过标准编码器。 b) 第二个句子通过一个解码器,该解码器使用掩码自注意力,同时也通过交叉注意力关注编码器的输出嵌入(橙色矩形)。损失函数与解码器模型相同;我们希望最大化输出序列中下一个词的概率。Figure 12.13 Encoder-decoder architecture. system with the goal of translating the first into the second. a) The first sentence is passed through a standard encoder. b) The second sentence is passed through a decoder that uses masked self-attention but also attends to the output embeddings of the encoder using cross-attention (orange rectangle). The loss function is the same as for the decoder model; we want to maximize the probability of the next word in the output sequence.
12.8 编码器 - 解码器模型示例:机器翻译
12.8 Encoder-decoder model example: machine translation

Translation between languages is an example of a sequence-to-sequence task. One common approach uses both an encoder (to compute a good representation of the source sentence) and a decoder (to generate the sentence in the target language). This is aptly called an encoder-decoder model.

Consider translating from English to French. The encoder receives the sentence in English and processes it through a series of transformer layers to create an output representation for each token. During training, the decoder receives the ground truth translation in French and passes it through a series of transformer layers that use masked self-attention and predict the following word at each position. However, the decoder layers also attend to the output of the encoder. Consequently, each French output word is

语言间翻译是序列到序列任务的一个例子。一种常见方法是同时使用编码器(用于计算源句子的良好表示)和解码器(用于生成目标语言句子)。这恰当地称为编码器 - 解码器模型。以英译法为例。编码器接收英语句子,并通过一系列 Transformer 层对其进行处理,为每个词元生成输出表示。在训练期间,解码器接收法语真值翻译,并将其通过一系列使用掩码自注意力的 Transformer 层,在每个位置预测后续词。然而,解码器层也会关注编码器的输出。因此,每个法语输出词都是

conditioned on the previous output words and the source English sentence (figure 12.13).

以先前的输出词和英语源句为条件(图 12.13)。

图 12.14 交叉注意力。计算流程与标准自注意力相同,但查询由解码器嵌入 X dec 计算得到,键和值由编码器嵌入 X enc 计算得到。对于翻译任务,编码器
图 12.14 交叉注意力。计算流程与标准自注意力相同,但查询由解码器嵌入 X dec 计算得到,键和值由编码器嵌入 X enc 计算得到。对于翻译任务,编码器包含源语言统计信息,解码器包含目标语言统计信息。Figure 12.14 Cross-attention. The flow of computation is the same as in standard self-attention, but the queries are calculated from the decoder embeddings X dec, and the keys and values from the encoder embeddings X enc. tasks, the encoder contains information about the source language statistics, and the decoder contains information about the target language statistics.

This is achieved by modifying the transformer layers in the decoder.

Originally, these consisted of a masked self-attention layer followed by a neural network applied individually to each embedding (figure 12.12). A new self-attention layer is added between these two components, in which the decoder embeddings attend to the encoder embeddings. This uses a version of self-attention known as encoder-decoder attention or cross-attention, where the queries are computed from the decoder embeddings and the keys and values from the encoder embeddings (figure 12.14).

这是通过修改解码器中的 Transformer 层来实现的。最初,这些层由一个掩码自注意力层后接一个分别应用于每个嵌入的神经网络组成(图 12.12)。在这两个组件之间新增了一个自注意力层,其中解码器嵌入关注编码器嵌入。这使用一种称为编码器解码器注意力或交叉注意力的自注意力,其中查询由解码器嵌入计算得到,键和值由编码器嵌入计算得到(图 12.14)。

12.9 用于长序列的 Transformer
12.9 Transformers for long sequences

Since each token in a transformer encoder model interacts with every other token, the computational complexity scales quadratically with the length of the sequence. For a decoder model, each token only interacts with previous tokens, so there are roughly half the number of interactions, but the complexity still scales quadratically.

These relationships can be visualized as interaction matrices (figure 12.15a–b). This quadratic increase in the amount of computation ultimately limits the length of sequences that can be used. Many methods have been developed to extend the trans-

由于 Transformer 编码器模型中的每个词元都与所有其他词元交互,计算复杂度随序列长度呈二次增长。对于解码器模型,每个词元只与之前的词元交互,因此交互数量大约减半,但复杂度仍然呈二次增长。这些关系可以可视化为交互矩阵(图 12.15a–b)。这种计算量的二次增长最终限制了可使用的序列长度。已经开发了许多方法来扩展 Transformer,

图 12.15 自注意力的交互矩阵。 a) 在编码器中,每个词元与其他所有词元交互,计算量随词元数量呈二次方增长。 b) 在解码器中,每个词元只与之前的词元交互
图 12.15 自注意力的交互矩阵。 a) 在编码器中,每个词元与其他所有词元交互,计算量随词元数量呈二次方增长。 b) 在解码器中,每个词元只与之前的词元交互,但复杂度仍为二次方。 c) 可通过使用卷积结构(编码器情形)降低复杂度。 d) 解码器情形的卷积结构。 e–f) 膨胀率为二和三的卷积结构(解码器情形)。 g) 另一种策略是允许选定的词元与其他所有词元(编码器情形)或所有之前的词元(图示为解码器情形)交互。 h) 或者,可以引入全局词元(左侧两列和顶部两行)。它们与所有词元以及彼此交互。Figure 12.15 Interaction matrices for self-attention. a) In an encoder, every token interacts with every other token, and computation expands quadratically with the number of tokens. b) In a decoder, each token only interacts with the previous tokens, but complexity is still quadratic. c) Complexity can be reduced by using a convolutional structure (encoder case). d) Convolutional structure for decoder case. e–f) Convolutional structure with dilation rate of two and three (decoder case). g) Another strategy is to allow selected tokens to interact with all the other tokens (encoder case) or all the previous tokens (decoder case pictured). h) Alternatively, global tokens can be introduced (left two columns and top two rows). These interact with all of the tokens as well as with each other.

former to cope with longer sequences. One approach is to prune the self-attention interactions or, equivalently, to sparsify the interaction matrix (figures 12.15c-h).

For example, this can be restricted to a convolutional structure so that each token only interacts with a few neighboring tokens. Across multiple layers, tokens still interact at larger distances as the receptive field expands. As for convolution in images, the kernel can vary in size and dilation rate.

A pure convolutional approach requires many layers to integrate information over large distances. One way to speed up this process is to allow certain tokens (perhaps at the start of every sentence) to attend to all other tokens (encoder model) or all previous tokens (decoder model). A similar idea is to have a small number of global tokens that connect to all the other tokens and themselves. Like the < cls > token, these do not represent any word but serve to provide long-distance connections.

使其能够处理更长的序列。一种方法是对自注意力交互进行剪枝,或者等价地,将交互矩阵稀疏化(图 12.15c-h)。例如,可以将其限制为卷积结构,使每个词元只与少数相邻词元交互。在多个层中,随着感受野扩大,词元仍能在更大距离上交互。与图像中的卷积一样,卷积核的大小和膨胀率可以变化。

纯卷积方法需要许多层才能在长距离上整合信息。加快这一过程的一种方法是允许某些词元(也许位于每个句子的开头)关注所有其他词元(编码器模型)或所有先前词元(解码器模型)。类似的想法是拥有少量全局词元,它们与其他所有词元以及自身连接。像 < cls > 词元一样,这些不代表任何单词,而是用于提供长距离连接。

12.10 用于图像的 Transformer
12.10 Transformers for images

Transformers were initially developed for text data. Their enormous success in this area led to experimentation on images. This was not obviously a promising idea for two

reasons. First, there are many more pixels in an image than words in a sentence, so the quadratic complexity of self-attention poses a practical bottleneck. Second, convolutional nets have a good inductive bias because each layer is equivariant to spatial translation, and takes into account the 2D structure of the image. However, this must be learned in a transformer network.

Regardless of these apparent disadvantages, transformer networks for images have now eclipsed the performance of convolutional networks for image classification and other tasks. This is partly because of the enormous scale at which they can be constructed and the large amounts of data that can be used to pre-train the networks. This section describes transformer models for images.

这显然不是一个有前景的想法,有两个

原因。首先,图像中的像素数量远多于句子中的词数量,因此自注意力的二次复杂度构成了一个实际瓶颈。其次,卷积网络具有良好的归纳式偏差,因为每一层都对空间平移具有等变性,并考虑图像的二维结构。然而,这必须在 Transformer 网络中学习。

尽管存在这些明显的缺点,用于图像的 Transformer 网络如今已在图像分类和其他任务上超越了卷积网络的性能。这在一定程度上是因为它们可以构建的规模极其庞大,并且可以使用大量数据对网络进行预训练。本节介绍用于图像的 Transformer 模型。

12.10.1 ImageGPT
12.10.1 ImageGPT

ImageGPT is a transformer decoder; it builds an autoregressive model of image pixels that ingests a partial image and predicts the subsequent pixel value.

The quadratic complexity of the transformer network means that the largest model (which contained 6.8 billion parameters) could still only operate on 64 × 64 images. Moreover, to make this tractable, the original 24-bit RGB color space had to be quantized into a nine-bit color space, so the system ingests (and predicts) one of 512 possible tokens at each position.

Images are naturally 2D objects, but ImageGPT simply learns a different positional encoding at each pixel. Hence it must learn that each pixel has a close relationship with its preceding neighbors and also with nearby pixels in the row above. Figure 12.16 shows example generation results.

ImageGPT 是一个 Transformer 解码器;它构建了图像像素的自回归模型,接收部分图像并预测后续像素值。 Transformer 网络的二次复杂度意味着最大的模型(包含 68 亿个参数)也只能处理 64 × 64 图像。此外,为了使这一过程可行,原始的 24 位 RGB 色彩空间必须量化为 9 位色彩空间,因此系统在每个位置接收(并预测) 512 个可能词元中的一个。

图像自然是二维对象,但 ImageGPT 只是为每个像素学习不同的位置编码。因此,它必须学习到每个像素与其前序相邻像素以及上一行中附近像素具有紧密关系。图 12.16 展示了生成结果的示例。

The internal representation of this decoder was used as a basis for image classification. Each pixel’s final embedding is averaged, and a linear layer maps these values to activations which are passed through a softmax layer to predict class probabilities. The system is pre-trained on a large corpus of web images and then fine-tuned on the ImageNet database resized to 48 × 48 pixels using a loss function that contains both a cross-entropy term for image classification and a generative loss term for predicting the pixels. Despite using a large amount of external training data, the system achieved only a 27.4% top-1 error rate on ImageNet (figure 10.15). This was worse than convolutional architectures of the time (see figure 10.21) but is still impressive given the small input image size; unsurprisingly, it fails where the target object is small or thin.

该解码器的内部表示被用作图像分类的基础。每个像素的最终嵌入会被平均,然后由线性层将这些值映射为激活值,再经过 Softmax 层预测类别概率。该系统先在大规模网络图像语料库上进行预训练,然后在调整至 48 × 48 像素的 ImageNet 数据库上进行微调,使用的损失函数同时包含用于图像分类的交叉熵项和用于预测像素的生成损失项。尽管使用了大量外部训练数据,该系统在 ImageNet 上仅取得了 27.4% 的 top-1 错误率(图 10.15)。这比当时的卷积架构更差(见图 10.21),但考虑到输入图像尺寸较小,仍然令人印象深刻;不出所料,当目标物体较小或较细时,它会失败。

12.10.2 视觉 Transformer(ViT)
12.10.2 Vision Transformer (ViT)

The Vision Transformer tackled the problem of image resolution by dividing the image into 16 × 16 patches (figure 12.17). Each patch is mapped to an input embedding via

a learned linear transformation, and these representations are fed into the transformer network. Once again, standard 1D positional encodings are learned. This is an encoder model with a < cls > token (see figures 12.10–12.11). However, unlike BERT, it uses supervised pre-training on a large database of 303 million labeled images from 18,000 classes. The < cls > token is mapped via a final network layer to create activations that are fed into a softmax function to generate class probabilities. After pre-training, the system is applied to the final classification task by replacing this

这是一个带有 < cls > 词元(见图 12.10–12.11)。不过,与 BERT 不同,它使用监督预训练,基于一个包含来自 18,000 个类别的 3.03 亿张带标签图像的大型数据库。该 < cls > 词元通过最后一层网络进行映射,以生成激活值,这些激活值被送入 Softmax 函数以产生类别概率。预训练后,系统通过替换此

图 12.16 ImageGPT。 a) 由自回归 ImageGPT 模型生成的图像。左上角像素从该位置的估计经验分布中抽取。后续像素依次生成,并以之前的像素为
图 12.16 ImageGPT。 a) 由自回归 ImageGPT 模型生成的图像。左上角像素从该位置的估计经验分布中抽取。后续像素依次生成,并以之前的像素为条件,沿行推进,直到到达图像的右下角。对于每个像素, Transformer 解码器生成一个条件分布,如式 12.15 所示,然后抽取一个样本。随后将扩展后的序列重新输入网络,以生成下一个像素,依此类推。 b) 图像补全。在每种情况下,图像的下半部分被移除(第一行), ImageGPT 逐像素补全剩余部分(展示了三种不同的补全结果)。改编自 https://openai.com/blog/image-gpt/。Figure 12.16 ImageGPT. a) Images generated from the autoregressive ImageGPT model. The top-left pixel is drawn from the estimated empirical distribution at this position. Subsequent pixels are generated in turn, conditioned on the previous ones, working along the rows until the bottom-right of the image is reached. For each pixel, the transformer decoder generates a conditional distribution as in equation 12.15, and a sample is drawn. The extended sequence is then fed back into the network to generate the next pixel, and so on. b) Image completion. In each case, the lower half of the image is removed (top row), and ImageGPT completes the remaining part pixel by pixel (three different completions shown).

final layer with one that maps to the desired number of classes and is fine-tuned.

For the ImageNet benchmark, this system achieved an 11.45% top-1 error rate. However, it did not perform as well as the best contemporary convolutional networks without supervised pre-training. The strong inductive bias of convolutional networks can only be superseded by employing extremely large amounts of training data.

最后一层,改为一个映射到所需类别数量并进行微调的层。

在 ImageNet 基准测试中,该系统取得了 11.45% 的 top-1 错误率。然而,在没有监督预训练的情况下,它的表现不如当时最好的卷积网络。卷积网络强大的归纳式偏差只能通过使用极其大量的训练数据来取代。

12.10.3 多尺度视觉 Transformer
12.10.3 Multi-scale vision transformers

The Vision Transformer differs from convolutional architectures in that it operates on a single scale and has a receptive field that covers the whole image. Several transformer models that process the image at multiple scales have been proposed. Similarly to convolutional networks, these generally start with small high resolution patches and few channels and gradually enlarge the receptive field, decrease the spatial resolution and

视觉 Transformer 与卷积架构不同,它在单一尺度上运行,并且感受野覆盖整幅图像。已提出若干在多个尺度上处理图像的 Transformer 模型。与卷积网络类似,这些模型通常从小的高分辨率图块和少量通道开始,并逐渐扩大感受野、降低空间分辨率并

图 12.17 视觉 Transformer。视觉 Transformer (ViT)将图像分割为图块网格(16 × 16 在原始实现中)。每个图块通过一个学习
图 12.17 视觉 Transformer。视觉 Transformer (ViT)将图像分割为图块网格(16 × 16 在原始实现中)。每个图块通过一个学习到的线性变换进行投影,从而成为图块嵌入。这些图块嵌入被输入到 Transformer 编码器网络中,并且 < cls > 词元用于预测类别概率。Figure 12.17 Vision transformer. The Vision Transformer (ViT) breaks the image into a grid of patches (16 × 16 in the original implementation). is projected via a learned linear transformation to become a patch embedding. These patch embeddings are fed into a transformer encoder network, and the < cls > token is used to predict the class probabilities.

increase the number of channels (embedding dimension).

A representative example of a multi-scale transformer is the shifted-window or SWin transformer. This is an encoder transformer that divides the image into patches and groups these patches into a grid of windows within which self-attention is applied independently (figure 12.18). These windows are shifted in adjacent transformers, so the effective receptive field at a given patch can expand beyond the window border.

增加通道数(嵌入维度)。

多尺度 Transformer 的一个代表性示例是移位窗口或 SWin Transformer。这是一种编码器 Transformer,它将图像划分为图块,并将这些图块分组为窗口网格,在窗口内独立应用自注意力(图 12.18)。在相邻 Transformer 中,这些窗口会进行移位,因此给定图块的有效感受野可以扩展到窗口边界之外。

图 12.18 移位窗口(SWin) Transformer (Liu 等, 2021c)。 a) 原始图像。 b) SWin Transformer 将图像分
图 12.18 移位窗口(SWin) Transformer (Liu 等, 2021c)。 a) 原始图像。 b) SWin Transformer 将图像分割为窗口网格,并将每个窗口分割为图块子网格。 Transformer 网络独立地对每个窗口内的图块应用自注意力(即,图块仅关注同一窗口内的其他图块)。 c) 每隔一层会移动窗口,从而使彼此交互的图块子集发生变化,并且信息可以传播到整幅图像。 d) 经过若干层后, 2×2 个图块表示块被拼接起来,以增大有效图块(以及窗口)尺寸。 e) 每隔一层在这个新的较低分辨率下使用移位窗口。 f) 最终,分辨率使得只有一个窗口,并且图块覆盖整幅图像。Figure 12.18 Shifted window (SWin) transformer (Liu et al., 2021c). a) Original image. b) The SWin transformer breaks the image into a grid of windows and each of these windows into a sub-grid of patches. The transformer network applies self-attention to the patches within each window independently (i.e., patches only attend to other patches in the same window). c) Each alternate layer shifts the windows so that the subsets of patches that interact with one another change, and information can propagate across the whole image. d) After several layers, the 2×2 blocks of patch representations are concatenated to increase the effective patch (and window) size. e) Alternate layers use shifted windows at this new lower resolution. f) Eventually, the resolution is such that there is just a single window, and the patches span the entire image. Each of these

The scale is reduced periodically by concatenating features from non-overlapping 2 × 2 patches and applying a linear transformation that maps these concatenated features to twice the original number of channels. This architecture does not have a < cls > token but instead averages the output features at the last layer. These are then mapped via a linear layer to the desired number of classes and passed through a softmax function to output class probabilities. At the time of writing, the most sophisticated version of this architecture achieves a 9.89% top-1 error rate on the ImageNet database. A related idea is periodically to integrate information from across the whole image. Dual attention vision transformers (DaViT) alternate two types of transformers. In the first, image patches attend to one another, and the self-attention computation uses all the channels. In the second, the channels attend to one another, and the self-attention computation uses all the image patches. This architecture reaches a 9.60% top-1 error

rate on ImageNet and is close to the state-of-the-art at the time of writing.

尺度会定期降低,方法是将来自不重叠的 2 × 2 图块的特征拼接起来,并应用线性变换,将这些拼接后的特征映射到原始通道数的两倍。该架构没有 < cls > 词元,而是对最后一层的输出特征求平均。然后通过线性层将这些特征映射到所需的类别数,并经过 Softmax 函数输出类别概率。截至撰写时,该架构最复杂的版本在 ImageNet 数据库上达到了 9.89% 的 top-1 错误率。一个相关想法是周期性地整合来自整幅图像的信息。双注意力视觉 Transformer (DaViT) 交替使用两种类型的 Transformer。在第一种中,图像块相互关注,且自注意力计算使用所有通道。在第二种中,通道相互关注,且自注意力计算使用所有图像块。该架构达到了 9.60% 的 top-1 错误

率,在 ImageNet 上,并接近撰写时的最先进水平。

12.11 小结
12.11 Summary

This chapter introduced self-attention and the transformer architecture. Encoder, decoder, and encoder-decoder models were then described. The transformer operates on sets of high-dimensional embeddings. It has a low computational complexity per layer, and much of the computation can be performed in parallel using the matrix form. Since every input embedding interacts with every other, it can describe long-range dependencies in text. Ultimately, the computation scales quadratically with the sequence length; one approach to reducing the complexity is sparsifying the interaction matrix.

The training of transformers with very large unlabeled datasets is the first example of unsupervised learning (learning without labels) in this book. Encoders learn a representation that can be used for other tasks by predicting missing tokens. Decoders build an autoregressive model over the inputs and are the first example of a generative model in this book. The generative decoders can be used to create new data examples.

Chapter 13 considers networks for processing graph data. These have connections with transformers in that the nodes of the graph attend to one another in each network layer. Chapters 14–18 return to unsupervised learning and generative models.

本章介绍了自注意力和 Transformer 架构。随后描述了编码器、解码器和编码器 - 解码器模型。 Transformer 处理高维嵌入集合。它每层的计算复杂度较低,并且大部分计算可以使用矩阵形式并行执行。由于每个输入嵌入都会与其他所有嵌入交互,因此它可以描述文本中的长程依赖。最终,计算量随序列长度呈二次方增长;降低复杂度的一种方法是稀疏化交互矩阵。

使用超大规模无标签数据集训练 Transformer,是本书中第一个无监督学习(没有标签的学习)示例。编码器通过预测缺失的词元,学习一种可用于其他任务的表示。解码器基于输入构建自回归模型,是本书中第一个生成模型示例。生成式解码器可用于创建新的数据示例。

第 13 章探讨用于处理图数据的网络。这些网络与 Transformer 有联系,因为图的节点在每一层网络中相互关注。第 14–18 章回到无监督学习和生成模型。

注释
Notes

Natural language processing:

Recurrent neural networks:

图 12.19 循环神经网络(RNN)。词嵌入会依次通过一系列相同的神经网络。每个网络有两个输出;一个是输出嵌入,另一个(橙色箭头)会连同下一个词嵌入一起反馈给
图 12.19 循环神经网络(RNN)。词嵌入会依次通过一系列相同的神经网络。每个网络有两个输出;一个是输出嵌入,另一个(橙色箭头)会连同下一个词嵌入一起反馈给下一个神经网络。每个输出嵌入都包含该词本身的信息及其在前文片段中的上下文信息。原则上,最终输出包含关于整个句子的信息,并且可以像 cls > 词元那样,在 Transformer 编码器模型中支持分类任务。然而, RNN 有时会逐渐“忘记”更早出现的词元。实体识别(人物、地点、公司等)、文本摘要、问答、词义消歧和文档聚类。 NLP 最初由利用语法结构和统计信息的基于规则的方法来处理。早期方法可参见 Manning & Schutze (1999) 和 Jurafsky & Martin (2000)。Figure 12.19 Recurrent neural networks (RNNs). passed sequentially through a series of identical neural networks. Each network has two outputs; one is the output embedding, and the other (orange arrows) feeds back into the next neural network, along with the next word embedding. Each output embedding contains information about the word itself and its context in the preceding sentence fragment. In principle, the final output contains information about the entire sentence and could be used to support classification tasks similarly to the < cls > token in a transformer encoder model. However, RNNs sometimes gradually “forget” about tokens that are further back in time. entity recognition (people, places, companies, etc.), text summarization, question answering, word sense disambiguation, and document clustering. NLP was initially tackled by rule-based methods that exploited the structure and statistics of grammar. See Manning & Schutze (1999) and Jurafsky & Martin (2000) for early approaches.

From RNNs to transformers:

Applications:

Large language models:

Tokenizers:

Decoding algorithms:

Types of attention:

Relationship of self-attention to other models:

Positional encoding:

公式

Extending transformers to longer sequences:

Training transformers:

Applications in vision:

Transformers and convolutional networks:

From pixels to video:

Combining images and text:

问题
Problems