第 12 章 · Transformers
Understanding Deep Learning — Transformers
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)问题,其中网络输入是一系列表示单词或词片段的高维嵌入。语言数据集具有图像数据的一些特征。输入变量数量可能非常大,并且每个位置的统计特性相似;重新学习单词“狗”在一段文本中每个可能位置的含义并不合理。然而,语言数据集的复杂之处在于文本序列长度不一,而且不像图像那样,没有简单的方法来调整它们的大小。
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 的术语来说,前者应当注意后者。这意味着单词之间必须存在连接,而且这些连接的强度取决于单词本身。此外,这些连接需要跨越较大的文本跨度。例如,最后一句中的单词“他们的”也指的是餐厅。
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] 本身。

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 无关。
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 函数意味着键向量彼此“竞争”,以贡献于最终结果。查询和键必须具有相同的维度。然而,这些可以与 …… 的维度不同

the values, which is usually the same size as the input, so the representation doesn’t change size.
值,通常与输入大小相同,因此表征不会调整大小。

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

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 的列,则上述计算可以写成紧凑形式。值、查询和键可以计算为:
In the previous section, we described self-attention. Here, we introduce three extensions that are almost always used in practice.
在上一节中,我们介绍了自注意力。这里,我们介绍三个在实践中几乎总会用到的扩展。
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,并使用这些值,通过将其加入、与其相乘,或以其他某种方式修改注意力矩阵。
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
这被称为缩放点积自注意力。

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):

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.
多个头似乎对于使自注意力良好工作来说是必要的。这已被据推测,它们使自注意力网络对不良初始化更加稳健。
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):



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 层。
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 层。现在,我们依次考虑这些阶段中的每一个。

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))计算的,它根据频率贪婪地合并常见出现的子字符串。
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 中也有很多参数需要学习。
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 模型有三种类型。编码器将文本嵌入转换为一种能够支持各种任务的表示。解码器预测下一个词元以继续输入

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 节中描述。
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 架构的参数通过自监督从大规模文本语料中学习。这里的目标是让模型学习关于语言统计规律的一般信息。在微调阶段,所得网络被适配以使用较小的带标签训练数据来解决特定任务。
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 网络理解一些句法。例如,它可能会学到形容词“红色”通常出现在“房屋”或“汽车”等名词之前,但绝不会出现在动词“喊叫”之前。这也使模型能够学习关于世界的浅显的常识。例如,训练后,模型会给缺失的词“火车”在句子“该 < 掩码 > 驶入车站”中赋予更高的概率,而不是给词“花生”赋予更高的概率。然而,这种模型所能达到的“理解”程度是有限的。


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 函数。任意文本跨度作为答案的可能性可以通过组合在适当位置开始和结束的概率得到。
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 层组成。然而,目标不同。编码器旨在构建文本表示,该表示可经微调以解决各种更具体的自然语言处理任务。相反,解码器只有一个目的:生成序列中的下一个词元。它可以通过将扩展后的序列重新输入模型来生成连贯的文本段落。
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):
自回归表述展示了最大化词元联合概率与下一词元预测任务之间的联系。
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)。
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 个候选中随机抽取下一个词,以防止系统意外地从低概率词元的长尾中进行选择,从而进入不必要的语言死胡同。
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 个头的自注意力

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

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)。

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)。
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,

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 > 词元一样,这些不代表任何单词,而是用于提供长距离连接。
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 模型。
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),但考虑到输入图像尺寸较小,仍然令人印象深刻;不出所料,当目标物体较小或较细时,它会失败。
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 函数以产生类别概率。预训练后,系统通过替换此

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 错误率。然而,在没有监督预训练的情况下,它的表现不如当时最好的卷积网络。卷积网络强大的归纳式偏差只能通过使用极其大量的训练数据来取代。
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 模型。与卷积网络类似,这些模型通常从小的高分辨率图块和少量通道开始,并逐渐扩大感受野、降低空间分辨率并

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 中,这些窗口会进行移位,因此给定图块的有效感受野可以扩展到窗口边界之外。

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 上,并接近撰写时的最先进水平。
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 章回到无监督学习和生成模型。
Natural language processing:

Recurrent neural networks:


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: