目录参数化程序

第 4 章 参数化程序Chapter 4 Parameterized programs

神经网络可以被视为参数化程序:即带有可学习参数的程序。在本章中,我们首先回顾如何用数学方式表示程序。随后,我们回顾若干关键的神经网络架构与组件。Neural networks can be thought of as parameterized programs: programs with learnable parameters. In this chapter, we begin by reviewing how to represent programs mathematically. We then review several key neural network architectures and components.

4.1 表示计算机程序4.1 Representing computer programs

4.1.1 计算链Computation chains

首先,我们考虑这样一类简单程序:它对输入 s0∈S0{\bm{s}}_{0}\in\mathcal{S}_{0} 依次施加一系列函数 f1,…,fKf_{1},\dots,f_{K}。我们将这类程序称为计算链。例如,一张图像可以经历一系列变换,如裁剪、旋转、归一化等。在神经网络中,这些变换通常是参数化的,且参数是可学习的,由此得到 4.2 节介绍的前馈网络。函数序列的另一个例子是 for 循环,将在 5.8 节介绍。To begin with, we consider simple programs that apply a sequence of functions f1,…,fKf_{1},\dots,f_{K} to an input s0∈S0{\bm{s}}_{0}\in\mathcal{S}_{0}. We call such programs computation chains. For example, an image may go through a sequence of transformations such as cropping, rotation, normalization, and so on. In neural networks, the transformations are typically parameterized, and the parameters are learned, leading to feedforward networks, presented in Section 4.2. Another example of a sequence of functions is a for loop, presented in Section 5.8.

形式上,计算链可以写为Formally, a computation chain can be written as

s0\displaystyle{\bm{s}}_{0} ∈S0\displaystyle\in\mathcal{S}_{0}
s1\displaystyle{\bm{s}}_{1} :=f1(s0)∈S1\displaystyle\coloneqq f_{1}({\bm{s}}_{0})\in\mathcal{S}_{1}
⋮\displaystyle\hskip 6.0pt\vdots
sK\displaystyle{\bm{s}}_{K} :=fK(sK−1)∈SK\displaystyle\coloneqq f_{K}({\bm{s}}_{K-1})\in\mathcal{S}_{K}
f(s0)\displaystyle f({\bm{s}}_{0}) :=sK.\displaystyle\coloneqq{\bm{s}}_{K}. (4.1)

这里,s0{\bm{s}}_{0} 是输入,sk∈Sk{\bm{s}}_{k}\in\mathcal{S}_{k} 是程序的中间状态,sK∈SK{\bm{s}}_{K}\in\mathcal{S}_{K} 是最终输出。当然,fkf_{k} 的定义域(输入空间)必须与 fk−1f_{k-1} 的像(输出空间)相容。也就是说,应当有 fk ⁣:Sk−1→Skf_{k}\colon\mathcal{S}_{k-1}\to\mathcal{S}_{k}。我们可以将计算链等价地写为Here, s0{\bm{s}}_{0} is the input, sk∈Sk{\bm{s}}_{k}\in\mathcal{S}_{k} is an intermediate state of the program, and sK∈SK{\bm{s}}_{K}\in\mathcal{S}_{K} is the final output. Of course, the domain (input space) of fkf_{k} must be compatible with the image (output space) of fk−1f_{k-1}. That is, we should have fk ⁣:Sk−1→Skf_{k}\colon\mathcal{S}_{k-1}\to\mathcal{S}_{k}. We can write a computation chain equivalently as

f(s0)\displaystyle f({\bm{s}}_{0}) =(fK∘⋯∘f2∘f1)(s0)\displaystyle=(f_{K}\circ\dots\circ f_{2}\circ f_{1})({\bm{s}}_{0})
=fK(…f2(f1(s0))).\displaystyle=f_{K}(\dots f_{2}(f_{1}({\bm{s}}_{0}))).

计算链可以用有向图表示,如图 4.1 所示。链中的边定义了一种全序。之所以是全序,是因为任意两个节点之间必然由一条路径相连。A computation chain can be represented by a directed graph, shown in Fig. 4.1. The edges in the chain define a total order. The order is total, since two nodes are necessarily linked to each other by a path.

图 4.1:计算链是函数复合的序列。在上图中,每个中间节点表示单个函数。第一个节点表示输入,最后一个节点表示输出。边表示函数对先前输出或初始输入的依赖关系。Figure 4.1: A computation chain is a sequence of function compositions. In the graph above, each intermediate node represents a single function. The first node represents the input, the last node the output. Edges represent the dependencies of the functions with respect to previous outputs or to the initial input.

4.1.2 有向无环图Directed acyclic graphs

在一般程序中,中间函数不仅可能依赖于前一个函数的输出,还可能依赖于若干不同函数的输出。这类依赖关系最好用图来表示。In generic programs, intermediate functions may depend, not only on the previous function output, but on the outputs of several different functions. Such dependencies are best expressed using graphs.

有向图 G=(V,E)\mathcal{G}=(\mathcal{V},\mathcal{E}) 由一组顶点(或称节点)V\mathcal{V} 以及一组刻画顶点之间有向依赖关系的边 E\mathcal{E} 共同定义。一条边 (i,j)∈E(i,j)\in\mathcal{E} 是一个有序的顶点对 i∈Vi\in\mathcal{V} 与 j∈Vj\in\mathcal{V}。它也可记作 i→ji\rightarrow j,表示 jj 依赖于 ii。为便于表示输入与输出,使用入半边 →j\rightarrow j 和出半边 i→i\rightarrow 会更为方便。A directed graph G=(V,E)\mathcal{G}=(\mathcal{V},\mathcal{E}) is defined by a set of vertices or nodes V\mathcal{V} and a set of edges E\mathcal{E} defining directed dependencies between vertices. An edge (i,j)∈E(i,j)\in\mathcal{E} is an ordered pair of vertices i∈Vi\in\mathcal{V} and j∈Vj\in\mathcal{V}. It is also denoted i→ji\rightarrow j, to indicate that jj depends on ii. For representing inputs and outputs, it will be convenient to use incoming half-edges →j\rightarrow j and outgoing half-edges i→i\rightarrow.

在图 G=(V,E)\mathcal{G}=(\mathcal{V},\mathcal{E}) 中,顶点 jj 的父节点是指向 jj 的那些节点所构成的集合,记作 pa⁡(j):={i:i→j}{\operatorname{pa}}(j)\coloneqq\{i:i\rightarrow j\}。顶点 ii 的子节点则是 ii 所指向的那些节点所构成的集合,即 ch⁡(i):={j ⁣:i→j}{\operatorname{ch}}(i)\coloneqq\{j\colon i\rightarrow j\}。没有父节点的顶点称为根,没有子节点的顶点称为叶。In a graph G=(V,E)\mathcal{G}=(\mathcal{V},\mathcal{E}), the parents of a vertex jj are the set of nodes pointing to jj, denoted pa⁡(j):={i:i→j}{\operatorname{pa}}(j)\coloneqq\{i:i\rightarrow j\}. The children of a vertex ii are the set of nodes ii is pointing to, that is, ch⁡(i):={j ⁣:i→j}{\operatorname{ch}}(i)\coloneqq\{j\colon i\rightarrow j\}. Vertices without parents are called roots and vertices without children are called leaves.

从 ii 到 jj 的路径由一个顶点序列 j1,…,jmj_{1},\ldots,j_{m}(可以为空)定义,且满足 i→j1→…→jm→ji\rightarrow j_{1}\rightarrow\ldots\rightarrow j_{m}\rightarrow j。无环图是指这样的图:其中不存在顶点 ii,使得存在从 ii 到 ii 的路径。有向无环图(DAG)则是指既是有向图、又是无环图的图。A path from ii to jj is defined by a sequence of vertices j1,…,jmj_{1},\ldots,j_{m}, potentially empty, such that i→j1→…→jm→ji\rightarrow j_{1}\rightarrow\ldots\rightarrow j_{m}\rightarrow j. An acyclic graph is a graph such that there exists no vertex ii with a path from ii to ii. A directed acyclic graph (DAG) is a graph that is both directed and acyclic.

DAG 的边定义了顶点的一个偏序:若存在从 ii 到 jj 的路径,则记作 i⪯ji\preceq j。该序是偏序,因为两个顶点不一定通过路径相互连接。尽管如此,我们可以定义一个称为拓扑序的全序:任意一种顺序,使得 i≤ji\leq j 当且仅当不存在从 jj 到 ii 的路径。The edges of a DAG define a partial order of the vertices, denoted i⪯ji\preceq j if there exists a path from ii to jj. The order is partial, since two vertices may not necessarily be linked to each other by a path. Nevertheless, we can define a total order called a topological order: any order such that i≤ji\leq j if and only if there is no path from jj to ii.

图 4.2:一个有向无环图的示例。图中节点为 V={0,1,2,3,4}\mathcal{V}=\{0,1,2,3,4\},边为 E={(0,1),(0,2),(0,3),(1,3),(2,3),(1,4),(3,4)}\mathcal{E}=\{(0,1),(0,2),(0,3),(1,3),(2,3),(1,4),(3,4)\}。节点 33 的父节点是 pa⁡(3)={0,1,2}{\operatorname{pa}}(3)=\{0,1,2\},节点 11 的子节点是 ch⁡(1)={3,4}{\operatorname{ch}}(1)=\{3,4\}。该图有唯一的根 00 和唯一的叶 44;0→3→40\rightarrow 3\rightarrow 4 是一条从 00 到 44 的路径。图中不存在环(即从某个节点出发又回到该节点的路径),因此这是一个无环图。由于从 33 到 00 不存在路径,我们可以把节点 00 与 33 排序为 0≤30\leq 3;同理,由于从 22 到 11 不存在路径,我们也可以把 11 与 22 排序为 1≤21\leq 2。节点有两种可能的拓扑序,分别为 (0,1,2,3,4)(0,1,2,3,4) 和 (0,2,1,3,4)(0,2,1,3,4)。Figure 4.2: Example of a directed acyclic graph. Here the nodes are V={0,1,2,3,4}\mathcal{V}=\{0,1,2,3,4\}, the edges are E={(0,1),(0,2),(0,3),(1,3),(2,3),(1,4),(3,4)}\mathcal{E}=\{(0,1),(0,2),(0,3),(1,3),(2,3),(1,4),(3,4)\}. Parents of the node 33 are pa⁡(3)={0,1,2}{\operatorname{pa}}(3)=\{0,1,2\}. Children of node 11 are ch⁡(1)={3,4}{\operatorname{ch}}(1)=\{3,4\}. There is a unique root, 00, and a unique leaf, 44; 0→3→40\rightarrow 3\rightarrow 4 is a path from 00 to 44. This is an acyclic graph since there is no cycle (i.e., a path from a node to itself). We can order nodes 00 and 33 as 0≤30\leq 3 since there is no path from 33 to 00. Similarly, we can order 11 and 22 as 1≤21\leq 2 since there is no path from 22 to 11. Two possible topological orders of the nodes are (0,1,2,3,4)(0,1,2,3,4) and (0,2,1,3,4)(0,2,1,3,4).

4.1.3 以 DAG 表示计算机程序Computer programs as DAGs

我们假定程序所定义的是一个数学上合法的函数(即纯函数):对相同的参数,程序返回相同的值,且不产生任何副作用。我们还假定程序会停机,即在有限步内终止。这样的程序由有限个中间函数与中间变量构成,因此函数与变量之间的依赖关系可以用有向无环图(DAG)来表示。不失一般性,我们作出如下简化假设:We assume that a program defines a mathematically valid function (a.k.a. pure function): the program should return identical values for identical arguments and should not have any side effects. We also assume that the program halts, i.e., that it terminates in a finite number of steps. As such a program is made of a finite number of intermediate functions and intermediate variables, the dependencies between functions and variables can be expressed using a directed acyclic graph (DAG). Without loss of generality, we make the following simplifying assumptions:

  1. 1.

    程序只有一个输入 s0∈S0{\bm{s}}_{0}\in\mathcal{S}_{0}。There is a single input s0∈S0{\bm{s}}_{0}\in\mathcal{S}_{0}.

  2. 2.

    程序只有一个输出 sK∈SK{\bm{s}}_{K}\in\mathcal{S}_{K}。There is a single output sK∈SK{\bm{s}}_{K}\in\mathcal{S}_{K}.

  3. 3.

    程序中的每个中间函数 fkf_{k} 都只输出一个变量 sk∈Sk{\bm{s}}_{k}\in\mathcal{S}_{k}。Each intermediate function fkf_{k} in the program outputs a single variable sk∈Sk{\bm{s}}_{k}\in\mathcal{S}_{k}.

我们将各节点依次编号为 V:={0,1,…,K}\mathcal{V}\coloneqq\{0,1,\dots,K\}。其中,节点 00 是根,对应输入 s0∈S0{\bm{s}}_{0}\in\mathcal{S}_{0};节点 KK 是叶,对应最终的输出 sK∈SK{\bm{s}}_{K}\in\mathcal{S}_{K}。根据上述第三条假设,除 s0{\bm{s}}_{0} 外,每个变量 sk{\bm{s}}_{k} 都与一个函数 fkf_{k} 一一对应。因此,节点 00 表示输入 s0{\bm{s}}_{0},而节点 1,…,K1,\dots,K 则既表示函数 fkf_{k},又表示输出变量 sk{\bm{s}}_{k}。We number the nodes as V:={0,1,…,K}\mathcal{V}\coloneqq\{0,1,\dots,K\}. Node 00 is the root, corresponding to the input s0∈S0{\bm{s}}_{0}\in\mathcal{S}_{0}. Node KK is the leaf, corresponding to the final output sK∈SK{\bm{s}}_{K}\in\mathcal{S}_{K}. Because of the third assumption above, apart from s0{\bm{s}}_{0}, each variable sk{\bm{s}}_{k} is in bijection with a function fkf_{k}. Therefore, node 00 represents the input s0{\bm{s}}_{0}, and nodes 1,…,K1,\dots,K represent both a function fkf_{k} and an output variable sk{\bm{s}}_{k}.

图 4.3:将 f(x1,x2)=x2ex1x1+x2ex1f(x_{1},x_{2})=x_{2}e^{x_{1}}\sqrt{x_{1}+x_{2}e^{x_{1}}} 表示为 DAG,以函数与变量为节点。边表示函数与变量之间的依赖关系。函数 ff 按拓扑序分解为 88 个基本函数。Figure 4.3: Representation of f(x1,x2)=x2ex1x1+x2ex1f(x_{1},x_{2})=x_{2}e^{x_{1}}\sqrt{x_{1}+x_{2}e^{x_{1}}} as a DAG, with functions and variables as nodes. Edges indicate function and variable dependencies. The function ff is decomposed as 88 elementary functions in topological order.

DAG 中的边表示依赖关系。节点 kk 的父节点 i1,…,ipk:=pa⁡(k)i_{1},\dots,i_{p_{k}}\coloneqq{\operatorname{pa}}(k)(其中 pk:=∣pa⁡(k)∣p_{k}\coloneqq|{\operatorname{pa}}(k)|)所表示的,正是函数 fkf_{k} 完成计算所需的变量 spa⁡(k):=si1,…,sipk{\bm{s}}_{{\operatorname{pa}}(k)}\coloneqq{\bm{s}}_{i_{1}},\dots,{\bm{s}}_{i_{p_{k}}}。换言之,父节点 i1,…,ipki_{1},\dots,i_{p_{k}} 表示在求解 fkf_{k} 之前必须先求值的函数 fi1,…,fipkf_{i_{1}},\ldots,f_{i_{p_{k}}}。图 4.3 给出了这一形式体系下的一个计算图示例。Edges in the DAG represent dependencies. The parents i1,…,ipk:=pa⁡(k)i_{1},\dots,i_{p_{k}}\coloneqq{\operatorname{pa}}(k) of node kk, where pk:=∣pa⁡(k)∣p_{k}\coloneqq|{\operatorname{pa}}(k)|, indicate the variables spa⁡(k):=si1,…,sipk{\bm{s}}_{{\operatorname{pa}}(k)}\coloneqq{\bm{s}}_{i_{1}},\dots,{\bm{s}}_{i_{p_{k}}} that the function fkf_{k} needs to perform its computation. Put differently, the parents i1,…,ipki_{1},\dots,i_{p_{k}} indicate the functions fi1,…,fipkf_{i_{1}},\ldots,f_{i_{p_{k}}} that need to be evaluated, prior to evaluating fkf_{k}. An example of a computation graph in our formalism is presented in Fig. 4.3.

执行程序Executing a program

要执行程序,必须保证按正确顺序对中间函数求值。为此,我们假定节点 0,1,…,K0,1,\dots,K 已按拓扑序排列(若非如此,则需先进行拓扑排序)。于是,只要对 k∈[K]k\in[K] 依次求值,便可执行程序To execute a program, we need to ensure that we evaluate the intermediate functions in the correct order. Therefore, we assume that the nodes 0,1,…,K0,1,\dots,K are in a topological order (if this is not the case, we need to perform a topological sort first). We can then execute a program by evaluating for k∈[K]k\in[K]

sk:=fk(spa⁡(k)):=fk(si1,…,sipk)∈Sk.\displaystyle{\bm{s}}_{k}\coloneqq f_{k}({\bm{s}}_{{\operatorname{pa}}(k)})\coloneqq f_{k}({\bm{s}}_{i_{1}},\dots,{\bm{s}}_{i_{p_{k}}})\in\mathcal{S}_{k}.

注意,fkf_{k} 既可视为以元素元组 spa⁡(k){\bm{s}}_{{\operatorname{pa}}(k)} 为输入的单输入函数,也可视为以 si1,…,sipk{\bm{s}}_{i_{1}},\dots,{\bm{s}}_{i_{p_{k}}} 为输入的多输入函数;这两种视角本质上是等价的。Note that we can either view fkf_{k} as a single-input function of spa⁡(k){\bm{s}}_{{\operatorname{pa}}(k)}, which is a tuple of elements, or as a multi-input function of si1,…,sipk{\bm{s}}_{i_{1}},\dots,{\bm{s}}_{i_{p_{k}}}. The two views are essentially equivalent.

执行程序的过程总结于算法 1。The procedure for executing a program is summarized in Algorithm 1.

算法 1 执行程序Algorithm 1 Executing a program
1: Functions: f1,…,fKf_{1},\dots,f_{K} in topological order
2: Input: input s0∈S0{\bm{s}}_{0}\in\mathcal{S}_{0}
3: for k:=1,…,Kk\coloneqq 1,\ldots,K do
4:   Retrieve parent nodes (i1,…,ipk):=pa⁡(k)(i_{1},\dots,i_{p_{k}})\coloneqq{\operatorname{pa}}(k)
5:   Compute sk:=fk(spa⁡(k)):=fk(si1,…,sipk){\bm{s}}_{k}\coloneqq f_{k}({\bm{s}}_{{\operatorname{pa}}(k)})\coloneqq f_{k}({\bm{s}}_{i_{1}},\ldots,{\bm{s}}_{i_{p_{k}}})
6: Output: f(s0):=sKf({\bm{s}}_{0})\coloneqq{\bm{s}}_{K}

处理程序的多个输入或输出Dealing with multiple program inputs or outputs

当一个程序有多个输入时,我们总能把它们归入 s0∈S0{\bm{s}}_{0}\in\mathcal{S}_{0},作为 s0=(s0,1,…,s0,N0){\bm{s}}_{0}=({\bm{s}}_{0,1},\dots,{\bm{s}}_{0,N_{0}}) 并带有 S0=(S0,1×⋯×S0,N0)\mathcal{S}_{0}=(\mathcal{S}_{0,1}\times\dots\times\mathcal{S}_{0,N_{0}}),因为后续函数总能筛选出 s0{\bm{s}}_{0} 中它们所需的元素。同样,如果一个中间函数 fkf_{k} 有多个输出,我们总能把它们归组为单个输出 sk=(sk,1,…,sk,Nk){\bm{s}}_{k}=({\bm{s}}_{k,1},\dots,{\bm{s}}_{k,N_{k}}) 并带有 Sk=(Sk,1×⋯×Sk,Nk)\mathcal{S}_{k}=(\mathcal{S}_{k,1}\times\dots\times\mathcal{S}_{k,N_{k}}),因为后续函数可以筛选出 sk{\bm{s}}_{k} 中它们所需的元素。When a program has multiple inputs, we can always group them into s0∈S0{\bm{s}}_{0}\in\mathcal{S}_{0} as s0=(s0,1,…,s0,N0){\bm{s}}_{0}=({\bm{s}}_{0,1},\dots,{\bm{s}}_{0,N_{0}}) with S0=(S0,1×⋯×S0,N0)\mathcal{S}_{0}=(\mathcal{S}_{0,1}\times\dots\times\mathcal{S}_{0,N_{0}}), since later functions can always filter out what elements of s0{\bm{s}}_{0} they need. Likewise, if an intermediate function fkf_{k} has multiple outputs, we can always group them as a single output sk=(sk,1,…,sk,Nk){\bm{s}}_{k}=({\bm{s}}_{k,1},\dots,{\bm{s}}_{k,N_{k}}) with Sk=(Sk,1×⋯×Sk,Nk)\mathcal{S}_{k}=(\mathcal{S}_{k,1}\times\dots\times\mathcal{S}_{k,N_{k}}), since later functions can filter out the elements of sk{\bm{s}}_{k} that they need.

另一种表示方式:二部图Alternative representation: bipartite graphs

在我们的形式体系中,由于函数 fkf_{k} 始终只有一个输出 sk{\bm{s}}_{k},节点 kk 便可看作同时表示变量 sk{\bm{s}}_{k} 与函数 fkf_{k}。另一种做法如图 4.4 所示:将变量与函数表示为彼此分离的节点,即采用二部图。这种形式体系与概率建模中使用的因子图 [71, 121] 相近,只是其边为有向边。该形式体系的一个优点是能让函数显式地拥有多个输出。为简明起见,本书仍采用前一种形式体系。In our formalism, because a function fkf_{k} always has a single output sk{\bm{s}}_{k}, a node kk can be seen as representing both the variable sk{\bm{s}}_{k} and the function fkf_{k}. Alternatively, as shown in Fig. 4.4, we can represent variables and functions as separate nodes, that is, using a bipartite graph. This formalism is akin to factor graphs [71, 121] used in probabilistic modeling, but with directed edges. One advantage of this formalism is that it allows functions to explicitly have multiple outputs. We focus on our formalism for simplicity.

图 4.4:程序的两种可能表示方式。左:函数与输出变量由同一组节点表示。右:函数与变量由彼此不相交的两组节点表示。Figure 4.4: Two possible representations of a program. Left: Functions and output variables are represented by the same nodes. Right: functions and variables are represented by a disjoint set of nodes.

4.1.4 算术电路Arithmetic circuits

算术电路是计算图最简单的例子之一,源出计算复杂性理论。形式上,域 F\mathbb{F}(例如实数集 R\mathbb{R})上的算术电路是一个有向无环图(DAG),其根节点为 F\mathbb{F} 的元素,其函数 fkf_{k} 或为 ++,或为 ×\times。后者通常称为门。与一般计算图的情形不同,由于每个 fkf_{k} 或为 ++,或为 ×\times,因此必须允许图具有多个根节点。根节点既可以是变量,也可以是常数,且都应属于 F\mathbb{F}。Arithmetic circuits are one of the simplest examples of computation graph, originating from computational complexity theory. Formally, an arithmetic circuit over a field F\mathbb{F}, such as the reals R\mathbb{R}, is a directed acyclic graph (DAG) whose root nodes are elements of F\mathbb{F} and whose functions fkf_{k} are either ++ or ×\times. The latter are often called gates. Contrary to the general computation graph case, because each fkf_{k} is either ++ or ×\times, it is important to allow the graph to have several root nodes. Root nodes can be either variables or constants, and should belong to F\mathbb{F}.

算术电路可用于计算多项式。同一个多项式可能有多个算术电路来表示。于是便产生一个重要问题:如何为计算给定多项式找到最高效的算术电路。为比较表示同一多项式的不同算术电路,一个直观的复杂度概念是电路规模,其定义如下。Arithmetic circuits can be used to compute polynomials. There are potentially multiple arithmetic circuits for representing a given polynomial. One important question is then to find the most efficient arithmetic circuit for computing a given polynomial. To compare arithmetic circuits representing the same polynomial, an intuitive notion of complexity is the circuit size, as defined below.

定义 4.1.1(电路规模与多项式规模)。Definition 4.1.1 (Circuit and polynomial sizes).
电路 C\mathcal{C} 的规模 S(C)S(\mathcal{C}) 是表示 C\mathcal{C} 的有向无环图中边的数目。多项式 ff 的规模 S(f)S(f) 是所有表示 ff 的 C\mathcal{C} 中最小的 S(C)S(\mathcal{C})。The size S(C)S(\mathcal{C}) of a circuit C\mathcal{C} is the number of edges in the directed acyclic graph representing C\mathcal{C}. The size S(f)S(f) of a polynomial ff is the smallest S(C)S(\mathcal{C}) among all C\mathcal{C} representing ff.

关于算术电路的更多内容,读者可参阅 [44] 的专著。For more information on arithmetic circuits, we refer the reader to the monograph of [44].

4.2 前馈网络4.2 Feedforward networks

前馈网络可视为由参数化函数 fkf_{k} 构成的计算链,A feedforward network can be seen as a computation chain with parameterized functions fkf_{k},

s0\displaystyle{\bm{s}}_{0} :=x\displaystyle\coloneqq{\bm{x}}
s1\displaystyle{\bm{s}}_{1} :=f1(s0,w1)\displaystyle\coloneqq f_{1}({\bm{s}}_{0},{\bm{w}}_{1})
s2\displaystyle{\bm{s}}_{2} :=f2(s1,w2)\displaystyle\coloneqq f_{2}({\bm{s}}_{1},{\bm{w}}_{2})
sK\displaystyle{\bm{s}}_{K} :=fK(sK−1,wK),\displaystyle\coloneqq f_{K}({\bm{s}}_{K-1},{\bm{w}}_{K}),

其中给定输入 x∈X{\bm{x}}\in\mathcal{X} 与可学习参数 w1,…,wK∈W1×⋯×WK{\bm{w}}_{1},\ldots,{\bm{w}}_{K}\in\mathcal{W}_{1}\times\dots\times\mathcal{W}_{K}。每个函数 fkf_{k} 称为一层,每个 sk∈Sk{\bm{s}}_{k}\in\mathcal{S}_{k} 可视为输入 x{\bm{x}} 的中间表示。Sk\mathcal{S}_{k} 的维数称为第 kk 层的宽度(或隐藏单元数)。前馈网络定义了从 X×W\mathcal{X}\times\mathcal{W} 到 SK\mathcal{S}_{K} 的函数 sK=:f(x,w){\bm{s}}_{K}\eqqcolon f({\bm{x}},{\bm{w}}),其中 w:=(w1,…,wK)∈W:=W1×…×WK{\bm{w}}\coloneqq({\bm{w}}_{1},\dots,{\bm{w}}_{K})\in\mathcal{W}\coloneqq\mathcal{W}_{1}\times\ldots\times\mathcal{W}_{K}。for a given input x∈X{\bm{x}}\in\mathcal{X} and learnable parameters w1,…,wK∈W1×⋯×WK{\bm{w}}_{1},\ldots,{\bm{w}}_{K}\in\mathcal{W}_{1}\times\dots\times\mathcal{W}_{K}. Each function fkf_{k} is called a layer and each sk∈Sk{\bm{s}}_{k}\in\mathcal{S}_{k} can be seen as an intermediate representation of the input x{\bm{x}}. The dimensionality of Sk\mathcal{S}_{k} is known as the width (or number of hidden units) of layer kk. A feedforward network defines a function sK=:f(x,w){\bm{s}}_{K}\eqqcolon f({\bm{x}},{\bm{w}}) from X×W\mathcal{X}\times\mathcal{W} to SK\mathcal{S}_{K}, where w:=(w1,…,wK)∈W:=W1×…×WK{\bm{w}}\coloneqq({\bm{w}}_{1},\dots,{\bm{w}}_{K})\in\mathcal{W}\coloneqq\mathcal{W}_{1}\times\ldots\times\mathcal{W}_{K}.

给定这样一个参数化程序,我们便可调整 w{\bm{w}} 以拟合某些数据,从而学习其中的参数。例如,给定由 (xi,yi)({\bm{x}}_{i},{\bm{y}}_{i}) 对组成的数据集,我们可以关于 w{\bm{w}} 最小化在数据上平均的平方损失 ∥yi−f(xi,w)∥22\|{\bm{y}}_{i}-f({\bm{x}}_{i},{\bm{w}})\|_{2}^{2}。要最小化这样的损失,就需要获取其关于 w{\bm{w}} 的梯度。Given such a parameterized program, we can learn the parameters by adjusting w{\bm{w}} to fit some data. For instance, given a dataset of (xi,yi)({\bm{x}}_{i},{\bm{y}}_{i}) pairs, we may minimize the squared loss ∥yi−f(xi,w)∥22\|{\bm{y}}_{i}-f({\bm{x}}_{i},{\bm{w}})\|_{2}^{2} on average over the data, w.r.t. w{\bm{w}}. The minimization of such a loss requires accessing its gradients with respect to w{\bm{w}}.

4.3 多层感知机4.3 Multilayer perceptrons

4.3.1 组合仿射层与激活函数Combining affine layers and activations

上一节没有说明如何参数化前馈网络。一种典型的参数化方式称为多层感知机(MLP),它采用如下形式的全连接(又称稠密)层:In the previous section, we did not specify how to parametrize the feedforward network. A typical parametrization, called the multilayer perceptron (MLP), uses fully-connected (also called dense) layers of the form

sk=fk(sk−1,wk):=ak(Wksk−1+bk),{\bm{s}}_{k}=f_{k}({\bm{s}}_{k-1},{\bm{w}}_{k})\coloneqq a_{k}({\bm{W}}_{k}{\bm{s}}_{k-1}+{\bm{b}}_{k}),

其中我们定义了元组 wk:=(Wk,bk){\bm{w}}_{k}\coloneqq({\bm{W}}_{k},{\bm{b}}_{k}),并假定 Wk{\bm{W}}_{k} 与 bk{\bm{b}}_{k} 分别是尺寸适当的矩阵和向量。该层还可进一步分解为两个函数。函数 s↦Wks+bk{\bm{s}}\mapsto{\bm{W}}_{k}{\bm{s}}+{\bm{b}}_{k} 称为仿射层;函数 v↦ak(v){\bm{v}}\mapsto a_{k}({\bm{v}}) 是一个无参数的非线性函数,通常称为激活函数(见 4.4 节)。值 αk:=Wksk−1+bk{\bm{\alpha}}_{k}\coloneqq{\bm{W}}_{k}{\bm{s}}_{k-1}+{\bm{b}}_{k} 通常称为预激活值,值 ak(αk)a_{k}({\bm{\alpha}}_{k}) 称为激活值。where we defined the tuple wk:=(Wk,bk){\bm{w}}_{k}\coloneqq({\bm{W}}_{k},{\bm{b}}_{k}) and where we assumed that Wk{\bm{W}}_{k} and bk{\bm{b}}_{k} are a matrix and a vector of appropriate size. We can further decompose the layer into two functions. The function s↦Wks+bk{\bm{s}}\mapsto{\bm{W}}_{k}{\bm{s}}+{\bm{b}}_{k} is called an affine layer. The function v↦ak(v){\bm{v}}\mapsto a_{k}({\bm{v}}) is a parameter-free nonlinearity, often called an activation function (see Section 4.4). The value αk:=Wksk−1+bk{\bm{\alpha}}_{k}\coloneqq{\bm{W}}_{k}{\bm{s}}_{k-1}+{\bm{b}}_{k} is often called the pre-activation value and the value ak(αk)a_{k}({\bm{\alpha}}_{k}) is the activation value.

更一般地,我们可以用关于 sk−1{\bm{s}}_{k-1} 的任意参数化线性函数替代矩阵—向量乘积 Wksk−1{\bm{W}}_{k}{\bm{s}}_{k-1}。例如,卷积层将输入 sk−1{\bm{s}}_{k-1} 与若干滤波器 WkW_{k} 的卷积视为一个线性映射。More generally, we may replace the matrix-vector product Wksk−1{\bm{W}}_{k}{\bm{s}}_{k-1} by any parametrized linear function of sk−1{\bm{s}}_{k-1}. For example, convolutional layers use the convolution of an input sk−1{\bm{s}}_{k-1} with some filters WkW_{k}, seen as a linear map.

注 4.3.1(处理多个输入)。Remark 4.3.1 (Dealing with multiple inputs).
有时需要处理多输入网络。例如,假设我们要设计一个函数 g(x1,x2,wg)g({\bm{x}}_{1},{\bm{x}}_{2},{\bm{w}}_{g}),其中 x1∈X1{\bm{x}}_{1}\in\mathcal{X}_{1},x2∈X2{\bm{x}}_{2}\in\mathcal{X}_{2}。一种简单的做法是使用拼接 x:=x1⊕x2∈X1⊕X2{\bm{x}}\coloneqq{\bm{x}}_{1}\oplus{\bm{x}}_{2}\in\mathcal{X}_{1}\oplus\mathcal{X}_{2} 作为网络 f(x,wf)f({\bm{x}},{\bm{w}}_{f}) 的输入。另一种做法是,不在输入层拼接 x1{\bm{x}}_{1} 与 x2{\bm{x}}_{2},而是让它们经过一层或多层隐藏层之后再拼接。Sometimes, it is necessary to deal with networks of multiple inputs. For example, suppose we want to design a function g(x1,x2,wg)g({\bm{x}}_{1},{\bm{x}}_{2},{\bm{w}}_{g}), where x1∈X1{\bm{x}}_{1}\in\mathcal{X}_{1} and x2∈X2{\bm{x}}_{2}\in\mathcal{X}_{2}. A simple way to do so is to use the concatenation x:=x1⊕x2∈X1⊕X2{\bm{x}}\coloneqq{\bm{x}}_{1}\oplus{\bm{x}}_{2}\in\mathcal{X}_{1}\oplus\mathcal{X}_{2} as input to a network f(x,wf)f({\bm{x}},{\bm{w}}_{f}). Alternatively, instead of concatenating x1{\bm{x}}_{1} and x2{\bm{x}}_{2} at the input layer, they can be concatenated after having been through one or more hidden layers.

4.3.2 与广义线性模型的联系Link with generalized linear models

当深度为 K=1K=1(即只有一层)时,MLP 的输出为When the depth is K=1K=1 (only one layer), the output of an MLP is

s1=a1(W1x+b1).{\bm{s}}_{1}=a_{1}({\bm{W}}_{1}{\bm{x}}+{\bm{b}}_{1}).

这称为广义线性模型(GLM),见 3.4 节。因此,MLP 将 GLM 作为特例包含在内。特别地,当 a1a_{1} 取 softargmax(见 4.4 节)时,我们便得到(多分类)logistic 回归。对于一般的深度 KK,MLP 的输出为This is called a generalized linear model (GLM); see Section 3.4. Therefore, MLPs include GLMs as a special case. In particular, when a1a_{1} is the softargmax (see Section 4.4), we obtain (multiclass) logistic regression. For general depth KK, the output of an MLP is

sK=aK(WKsK−1+bK).{\bm{s}}_{K}=a_{K}({\bm{W}}_{K}{\bm{s}}_{K-1}+{\bm{b}}_{K}).

这可以看作是在输入 x{\bm{x}} 的学习表示 sK−1{\bm{s}}_{K-1} 之上应用一个 GLM。这正是 MLP 的主要吸引力所在:它同时学习特征表示与输出模型!后文将会看到,MLP 也可以作为子组件用于其他架构。This can be seen as a GLM on top of learned representation sK−1{\bm{s}}_{K-1} of the input x{\bm{x}}. This is the main appeal of MLPs: they learn the feature representation and the output model at the same time! We will see that MLPs can also be used as subcomponents in other architectures.

4.4 激活函数4.4 Activation functions

正如 4.3 节所述,前馈网络通常会在每一层使用激活函数 aka_{k}。本节介绍从标量到标量或从向量到标量的各种非线性函数,还会介绍可用作此类激活函数的概率映射。As we saw in Section 4.3, feedforward networks typically use an activation function aka_{k} at each layer. In this section, we present various nonlinearities from scalar to scalar or from vector to scalar. We also present probability mappings that can be used as such activations.

4.4.1 ReLU 与 softplusReLU and softplus

许多激活函数是标量到标量的函数,但也可以按逐元素方式应用于向量。ReLU(修正线性单元)是一种常用的非线性函数,定义为输入的非负部分Many activations are scalar-to-scalar functions, but they can also be applied to vectors in an element-wise fashion. The ReLU (rectified linear unit) is a popular nonlinearity defined as the non-negative part of its input

relu(u):=max⁡(u,0)={u,u≥00,u<0.\mathrm{relu}(u)\coloneqq\max(u,0)=\begin{cases}u,&u\geq 0\\ 0,&u<0\end{cases}.

它是分段线性函数,在 u=0u=0 处有一个折角。采用 ReLU 激活函数的多层感知机称为整流神经网络,其各层具有如下形式:It is a piecewise linear function and includes a kink at u=0u=0. A multilayer perceptron with ReLU activations is called a rectifier neural network. The layers take the form

sk=relu(Aksk−1+bk),{\bm{s}}_{k}=\mathrm{relu}({\bm{A}}_{k}{\bm{s}}_{k-1}+{\bm{b}}_{k}),

其中 ReLU 按逐元素方式应用。ReLU 可替换为一种光滑近似(即不含折角),称为 softpluswhere the ReLU is applied element-wise. The ReLU can be replaced with a smooth approximation (i.e., without kinks), called the softplus

softplus(u):=log⁡(1+eu).\mathrm{softplus}(u)\coloneqq\log(1+e^{u}).

与 ReLU 不同,它始终严格为正。ReLU 还可有其他平滑变体,见 13.4 节。Unlike the ReLU, it is always strictly positive. Other smoothed variants of the ReLU are possible, see Section 13.4.

4.4.2 最大池化与 log-sum-expMax pooling and log-sum-exp

许多激活函数是向量到标量的函数:它们把向量归约为一个标量值。该标量值可视为一种统计量,用以“概括”该向量。Many activations are vector-to-scalar functions: they reduce vectors to a scalar value. This scalar value can be seen as a statistic, “summarizing” the vector.

最大池化Max pooling

向量到标量归约的一个例子是最大值,亦称最大池化。给定向量 u∈RM{\bm{u}}\in\mathbb{R}^{M},其定义为An example of vector-to-scalar reduction is the maximum value, also known as max pooling. Given a vector u∈RM{\bm{u}}\in\mathbb{R}^{M}, it is defined as

max⁡(u):=max⁡j∈[M]uj.\max({\bm{u}})\coloneqq\max_{j\in[M]}u_{j}.
图 4.5:最大值算子是一种分段线性函数。log-sum-exp(又称 softmax)则是一种平滑近似。Figure 4.5: The maximum operator is a piecewise linear function. The log-sum-exp (a.k.a. softmax) is a smoothed approximation.

将 log-sum-exp 视为软最大值Log-sum-exp as a soft maximum

向量到标量归约的另一个例子是 log-sum-exp,Another example of vector-to-scalar reduction is the log-sum-exp,

logsumexp(u):=softmax(u):=log⁡∑j=1Meuj.\mathrm{logsumexp}({\bm{u}})\coloneqq\mathrm{softmax}({\bm{u}})\coloneqq\log\sum_{j=1}^{M}e^{u_{j}}.

如图 4.5 所示,它已知具有软最大值的行为。log-sum-exp 可视为 softplus 的推广,因为对所有 u∈Ru\in\mathbb{R} 都有As illustrated in Fig. 4.5, it is known to behave like a soft maximum. The log-sum-exp can be seen as a generalization of the softplus, as we have for all u∈Ru\in\mathbb{R}

logsumexp((u,0))=softplus(u).\mathrm{logsumexp}((u,0))=\mathrm{softplus}(u).

log-sum-exp 的一种数值稳定实现如下:A numerically stable implementation of the log-sum-exp is given by

logsumexp(u)=logsumexp(u−c1⁡)+c,\mathrm{logsumexp}({\bm{u}})=\mathrm{logsumexp}({\bm{u}}-c\operatorname{\mathbf{1}})+c,

其中 c:=max⁡j∈[M]ujc\coloneqq\max_{j\in[M]}u_{j}。where c:=max⁡j∈[M]ujc\coloneqq\max_{j\in[M]}u_{j}.

更一般地,我们可以引入温度参数 γ>0\gamma>0More generally, we can introduce a temperature parameter γ>0\gamma>0

logsumexpγ(u)=γ⋅logsumexp(u/γ).\mathrm{logsumexp}_{\gamma}({\bm{u}})=\gamma\cdot\mathrm{logsumexp}({\bm{u}}/\gamma).

可以证明,对所有 u∈RM{\bm{u}}\in\mathbb{R}^{M},It can be shown that for all u∈RM{\bm{u}}\in\mathbb{R}^{M},

max⁡(u)≤logsumexpγ(u)≤max⁡(u)+γ⋅log⁡(M).\max({\bm{u}})\leq\mathrm{logsumexp}_{\gamma}({\bm{u}})\leq\max({\bm{u}})+\gamma\cdot\log(M).

因此,当 γ→0\gamma\to 0 时,logsumexpγ(u)→max⁡(u)\mathrm{logsumexp}_{\gamma}({\bm{u}})\to\max({\bm{u}})。软最大值也可有其他定义,见 13.5 节。Therefore, logsumexpγ(u)→max⁡(u)\mathrm{logsumexp}_{\gamma}({\bm{u}})\to\max({\bm{u}}) as γ→0\gamma\to 0. Other definitions of soft maximum are possible; see Section 13.5.

将 log-sum-exp 视为对数域求和Log-sum-exp as a log-domain sum

除了用作软最大值,log-sum-exp 还常出现于对数域中的求和计算。事实上,假设要计算 s:=∑i=1Muis\coloneqq\sum_{i=1}^{M}u_{i},其中 ui>0u_{i}>0。若定义 u~i:=log⁡ui\tilde{u}_{i}\coloneqq\log u_{i} 与 s~:=log⁡s\tilde{s}\coloneqq\log s,则有Besides its use as a soft maximum, the log-sum-exp often arises for computing sums in the log domain. Indeed, suppose we want to compute s:=∑i=1Muis\coloneqq\sum_{i=1}^{M}u_{i}, where ui>0u_{i}>0. If we define u~i:=log⁡ui\tilde{u}_{i}\coloneqq\log u_{i} and s~:=log⁡s\tilde{s}\coloneqq\log s, we then have

s~=log⁡∑i=1Mexp⁡(u~i).\tilde{s}=\log\sum_{i=1}^{M}\exp(\tilde{u}_{i}).

换一种写法,我们得到恒等式Written differently, we have the identity

log⁡(∑i=1Mui)=logsumexp(log⁡(u)).\log\left(\sum_{i=1}^{M}u_{i}\right)=\mathrm{logsumexp}(\log({\bm{u}})).

因此,可将 log-sum-exp 视为乘积恒等式的求和对应形式We can therefore see the log-sum-exp as the sum counterpart of the identity for products

log⁡(∏i=1Mui)=∑i=1Mlog⁡(ui).\log\left(\prod_{i=1}^{M}u_{i}\right)=\sum_{i=1}^{M}\log(u_{i}).

例如,我们在 10.7.1 节中利用 log-sum-exp 在对数域中执行前向—后向算法。As an example, we use the log-sum-exp to perform the forward-backward algorithm in the log-domain in Section 10.7.1.

4.4.3 S 形函数:二值阶跃函数与 logistic 函数Sigmoids: binary step and logistic functions

我们常常希望把实数值映射到 [0,1][0,1] 中的某个数,用以表示某一事件的概率。为此,通常使用 S 形函数。S 形函数是曲线呈特征性“S”形的函数。这类函数是标量到标量的概率映射:用于把实数值压缩到 [0,1][0,1]。Oftentimes, we want to map a real value to a number in [0,1][0,1], that can represent the probability of an event. For that purpose, we generally use sigmoids. A sigmoid is a function with a characteristic “S”-shaped curve. These functions are scalar-to-scalar probability mappings: they are used to squash real values to [0,1][0,1].

二值阶跃函数Binary step function

一个例子是二值阶跃函数,又称 Heaviside 阶跃函数,An example is the binary step function, also known as Heaviside step function,

step(u):={1,u≥00,u<0.\mathrm{step}(u)\coloneqq\begin{cases}1,&u\geq 0\\ 0,&u<0\end{cases}.

它是从 R\mathbb{R} 到 {0,1}\{0,1\} 的映射。遗憾的是,它并不连续:其图像在 u=0u=0 处发生跳跃。此外,由于该函数在其余各点均为常数,因而在这些点处导数为零,这使其难以作为以反向传播训练的神经网络的一部分使用。It is a mapping from R\mathbb{R} to {0,1}\{0,1\}. Unfortunately, it has a discontinuity: a jump in its graph at u=0u=0. Moreover, because the function is constant at all other points, it has zero derivative at these points, which makes it difficult to use as part of a neural network trained with backpropagation.

logistic 函数Logistic function

一种更好的 S 形函数是 logistic 函数,它是从 R\mathbb{R} 到 (0,1)(0,1) 的映射,定义为A better sigmoid is the logistic function, which is a mapping from R\mathbb{R} to (0,1)(0,1) and is defined as

logistic(u)\displaystyle\mathrm{logistic}(u) :=11+e−u\displaystyle\coloneqq\frac{1}{1+e^{-u}}
=eu1+eu\displaystyle=\frac{e^{u}}{1+e^{u}}
=12+12tanh⁡(u2).\displaystyle=\frac{1}{2}+\frac{1}{2}\tanh\left(\frac{u}{2}\right).

它将 (−∞,0)(-\infty,0) 映射到 (0,0.5)(0,0.5),将 [0,+∞)[0,+\infty) 映射到 [0.5,1)[0.5,1),并满足 logistic(0)=0.5\mathrm{logistic}(0)=0.5。因此,它可以看作是从实数值到概率值的映射。logistic 函数可以看作是不连续的二值阶跃函数 step(u)\mathrm{step}(u) 的可微近似。可以证明,logistic 函数是 softplus 的导数,即对所有 u∈Ru\in\mathbb{R}It maps (−∞,0)(-\infty,0) to (0,0.5)(0,0.5), [0,+∞)[0,+\infty) to [0.5,1)[0.5,1) and it satisfies logistic(0)=0.5\mathrm{logistic}(0)=0.5. It can therefore be seen as mapping from real values to probability values. The logistic can be seen as a differentiable approximation to the discontinuous binary step function step(u)\mathrm{step}(u). The logistic function can be shown to be the derivative of softplus, i.e., for all u∈Ru\in\mathbb{R}

softplus′(u)=logistic(u).\mathrm{softplus}^{\prime}(u)=\mathrm{logistic}(u).

logistic 函数的两个重要性质是:对所有 u∈Ru\in\mathbb{R}Two important properties of the logistic function are that for all u∈Ru\in\mathbb{R}

logistic(−u)=1−logistic(u)\mathrm{logistic}(-u)=1-\mathrm{logistic}(u)

以及and

logistic′(u)\displaystyle\mathrm{logistic}^{\prime}(u) =logistic(u)⋅logistic(−u)\displaystyle=\mathrm{logistic}(u)\cdot\mathrm{logistic}(-u)
=logistic(u)⋅(1−logistic(u)).\displaystyle=\mathrm{logistic}(u)\cdot(1-\mathrm{logistic}(u)).

也可以采用其他 S 形函数;参见 13.6 节。Other sigmoids are possible; see Section 13.6.

4.4.4 概率映射:argmax 与 softargmaxProbability mappings: argmax and softargmax

将实向量变换为概率向量往往很有用。这是一个从 RM\mathbb{R}^{M} 到概率单纯形的映射,定义为It is often useful to transform a real vector into a vector of probabilities. This is a mapping from RM\mathbb{R}^{M} to the probability simplex, defined by

△M:={π∈RM ⁣:∀j∈[M], πj≥0, ∑j=1Mπj=1}.\triangle^{M}\coloneqq\left\{{\bm{\pi}}\in\mathbb{R}^{M}\colon\forall j\in[M],\ \pi_{j}\geq 0,\ \sum_{j=1}^{M}\pi_{j}=1\right\}.

这类向量到向量的概率映射有两个例子:argmax 与 softargmax。Two examples of such vector-to-vector probability mappings are the argmax and the softargmax.

ArgmaxArgmax

argmax 算子定义为The argmax operator is defined by

argmax(u):=ϕ(arg max⁡j∈[M]uj)∈{e1,…,eM},\mathrm{argmax}({\bm{u}})\coloneqq\phi\left(\argmax_{j\in[M]}u_{j}\right)\in\{{\bm{e}}_{1},\dots,{\bm{e}}_{M}\},

其中 ϕ(j)\phi(j) 表示整数 j∈[M]j\in[M] 的 one-hot 编码,即where ϕ(j)\phi(j) denotes the one-hot encoding of an integer j∈[M]j\in[M], that is,

ϕ(j):=(0,…,0,1⏟j,0,…,0)=ej∈{0,1}M.\phi(j)\coloneqq(0,\ldots,0,\underbrace{1}_{j},0,\ldots,0)={\bm{e}}_{j}\in\{0,1\}^{M}.

该映射把全部概率质量放在单个坐标上(若有并列,则任意选取一个坐标)。遗憾的是,该映射是不连续函数。This mapping puts all the probability mass onto a single coordinate (in case of ties, we pick a single coordinate arbitrarily). Unfortunately, this mapping is a discontinuous function.

SoftargmaxSoftargmax

作为一种处处可微的松弛,我们可以使用由下式定义的 softargmaxAs a differentiable everywhere relaxation, we can use the softargmax defined by

softargmax(u):=exp⁡(u)∑j=1Mexp⁡(uj)∈relint(△M).\mathrm{softargmax}({\bm{u}})\coloneqq\frac{\exp({\bm{u}})}{\sum_{j=1}^{M}\exp(u_{j})}\in\mathrm{relint}(\triangle^{M}).

该算子在文献中通常称为 softmax,但这是一个误称:该算子实际上定义的是 argmax 的可微松弛。softargmax 的输出属于概率单纯形 relint(△M)={π∈△M ⁣:π>0}\mathrm{relint}(\triangle^{M})=\{{\bm{\pi}}\in\triangle^{M}\colon{\bm{\pi}}>{\mathbf{0}}\} 的相对内部,这意味着它永远无法到达单纯形的边界。若记 π=softargmax(u){\bm{\pi}}=\mathrm{softargmax}({\bm{u}}),则这意味着 πj∈(0,1)\pi_{j}\in(0,1);也就是说,πj\pi_{j} 永远不可能恰好等于 00 或 11。softargmax\mathrm{softargmax} 是 log-sum-exp 的梯度,This operator is commonly known in the literature as softmax but this is a misnomer: this operator really defines a differentiable relaxation of the argmax. The output of the softargmax belongs to the relative interior of the probability simplex relint(△M)={π∈△M ⁣:π>0}\mathrm{relint}(\triangle^{M})=\{{\bm{\pi}}\in\triangle^{M}\colon{\bm{\pi}}>{\mathbf{0}}\}, meaning that it can never reach the borders of the simplex. If we denote π=softargmax(u){\bm{\pi}}=\mathrm{softargmax}({\bm{u}}), this means that πj∈(0,1)\pi_{j}\in(0,1), that is, πj\pi_{j} can never be exactly 00 or 11. The softargmax\mathrm{softargmax} is the gradient of log-sum-exp,

∇logsumexp(u)=softargmax(u).\nabla\mathrm{logsumexp}({\bm{u}})=\mathrm{softargmax}({\bm{u}}).

softargmax\mathrm{softargmax} 可以看作 logistic 函数的推广,因为对所有 u∈Ru\in\mathbb{R} 都有The softargmax\mathrm{softargmax} can be seen as a generalization of the logistic function, as we have for all u∈Ru\in\mathbb{R}

[softargmax((u,0))]1=logistic(u).[\mathrm{softargmax}((u,0))]_{1}=\mathrm{logistic}(u).
注 4.4.1(softargmax 的自由度与可逆性)。Remark 4.4.1 (Degrees of freedom and invertibility of softargmax).
softargmax 算子对全体 u∈RM{\bm{u}}\in\mathbb{R}^{M} 与 c∈Rc\in\mathbb{R} 满足如下性质The softargmax operator satisfies the property for all u∈RM{\bm{u}}\in\mathbb{R}^{M} and c∈Rc\in\mathbb{R} π:=softargmax(u)=softargmax(u+c1⁡).{\bm{\pi}}\coloneqq\mathrm{softargmax}({\bm{u}})=\mathrm{softargmax}({\bm{u}}+c\operatorname{\mathbf{1}}). 这意味着 softargmax 算子具有 M−1M-1 个自由度,并且是一个不可逆函数。然而,由于上述性质,不失一般性,我们可以施加 u⊤1⁡=∑i=1Mui=0{\bm{u}}^{\top}\operatorname{\mathbf{1}}=\sum_{i=1}^{M}u_{i}=0(若情况并非如此,我们只需做 ui←ui−uˉu_{i}\leftarrow u_{i}-\bar{u},其中 uˉ:=1M∑j=1Muj\bar{u}\coloneqq\frac{1}{M}\sum_{j=1}^{M}u_{j})。将该约束与This means that the softargmax operator has M−1M-1 degrees of freedom and is a non-invertible function. However, due to the above property, without loss of generality, we can impose u⊤1⁡=∑i=1Mui=0{\bm{u}}^{\top}\operatorname{\mathbf{1}}=\sum_{i=1}^{M}u_{i}=0 (if this is not the case, we simply do ui←ui−uˉu_{i}\leftarrow u_{i}-\bar{u}, where uˉ:=1M∑j=1Muj\bar{u}\coloneqq\frac{1}{M}\sum_{j=1}^{M}u_{j}). Using this constraint together with log⁡πi=ui−log⁡∑j=1Mexp⁡(uj),\log\pi_{i}=u_{i}-\log\sum_{j=1}^{M}\exp(u_{j}), 结合,我们便得到we then obtain ∑i=1Mlog⁡πi=−Mlog⁡∑j=1Mexp⁡(uj)\sum_{i=1}^{M}\log\pi_{i}=-M\log\sum_{j=1}^{M}\exp(u_{j}) 从而so that ui=[softargmax−1(π)]i=log⁡πi−1M∑j=1Mlog⁡πj.u_{i}=[\mathrm{softargmax}^{-1}({\bm{\pi}})]_{i}=\log\pi_{i}-\frac{1}{M}\sum_{j=1}^{M}\log\pi_{j}.
图 4.6:argmax、softargmax 与 sparseargmax(参见 13.7 节)都是从 RM\mathbb{R}^{M} 到概率单纯形 △M:={π∈R+M ⁣:⟨π,1⁡⟩=1}\triangle^{M}\coloneqq\{{\bm{\pi}}\in\mathbb{R}^{M}_{+}\colon\langle{\bm{\pi}},\operatorname{\mathbf{1}}\rangle=1\} 的映射。更准确地说,argmax 映射到概率单纯形的顶点,即 one-hot 向量集合 {e1,…,eM}\{{\bm{e}}_{1},\dots,{\bm{e}}_{M}\};softargmax 映射到相对内部 relint(△M)={π∈△M ⁣:π>0}\mathrm{relint}(\triangle^{M})=\{{\bm{\pi}}\in\triangle^{M}\colon{\bm{\pi}}>{\mathbf{0}}\};而 sparseargmax 映射到整个概率单纯形 △M\triangle^{M},包括稀疏概率向量。逐元素应用的 S 形函数返回超立方体 [0,1]M[0,1]^{M} 中的向量,该超立方体的顶点是 {0,1}M\{0,1\}^{M} 中的 2M2^{M} 向量。Figure 4.6: The argmax, the softargmax and the sparseargmax (see Section 13.7) are mappings from RM\mathbb{R}^{M} to the probability simplex △M:={π∈R+M ⁣:⟨π,1⁡⟩=1}\triangle^{M}\coloneqq\{{\bm{\pi}}\in\mathbb{R}^{M}_{+}\colon\langle{\bm{\pi}},\operatorname{\mathbf{1}}\rangle=1\}. More precisely, the argmax maps to vertices of the probability simplex, the set of one-hot vectors {e1,…,eM}\{{\bm{e}}_{1},\dots,{\bm{e}}_{M}\}, the softargmax maps to the relative interior relint(△M)={π∈△M ⁣:π>0}\mathrm{relint}(\triangle^{M})=\{{\bm{\pi}}\in\triangle^{M}\colon{\bm{\pi}}>{\mathbf{0}}\} and the sparseargmax maps to the entire probability simplex △M\triangle^{M}, including sparse probability vectors. Sigmoids applied element-wise return vectors in the hypercube [0,1]M[0,1]^{M}, whose vertices are the 2M2^{M} vectors in {0,1}M\{0,1\}^{M}.

4.5 归一化层4.5 Normalization layers

神经网络中的中间状态(如激活值)常常会取到各种不同的值,这可能使梯度下降难以收敛。为解决这一问题,我们可以在网络的适当位置引入归一化层。本节介绍两种最常用的归一化层:批归一化与层归一化。Intermediate states in neural networks, such as activations, can often attain a wide range of different values, potentially making it difficult for gradient descent to converge. To remedy this issue, we can introduce normalization layers at suitable locations in the network. In this section, we present the two most popular ones: batch normalization and layer normalization.

4.5.1 批归一化Batch normalization

假设给定一批中间变量(如激活值或状态)s1,…,sB∈RD{\bm{s}}_{1},\dots,{\bm{s}}_{B}\in\mathbb{R}^{D},其中 si:=(si,1,…,si,D){\bm{s}}_{i}\coloneqq(s_{i,1},\dots,s_{i,D}),这些变量由某个函数作用于从训练集中抽取的 BB 个样本得到(为清晰起见,省略对层索引 kk 的依赖)。在批归一化 [99] 中,我们计算批内样本上的标准分数(又称 z 分数)来归一化这些值,Suppose we are given a batch of intermediate variables (such as activations or states) s1,…,sB∈RD{\bm{s}}_{1},\dots,{\bm{s}}_{B}\in\mathbb{R}^{D}, where si:=(si,1,…,si,D){\bm{s}}_{i}\coloneqq(s_{i,1},\dots,s_{i,D}), obtained by applying some function to BB samples drawn from the training set (we omit the dependency on the layer index kk for clarity). In batch normalization [99], we normalize the values by calculating the standard score (a.k.a. z-score) across batch samples,

μj\displaystyle\mu_{{\color{#000000}j}} :=1B∑i=1Bsi,j∀j∈[D]\displaystyle\coloneqq\frac{1}{B}\sum_{{\color{#000000}i=1}}^{{\color{#000000}B}}s_{i,j}\quad\forall j\in[D]
σj2\displaystyle\sigma_{{\color{#000000}j}}^{2} :=1B∑i=1B(si,j−μj)2∀j∈[D]\displaystyle\coloneqq\frac{1}{B}\sum_{{\color{#000000}i=1}}^{{\color{#000000}B}}(s_{i,j}-\mu_{j})^{2}\quad\forall j\in[D]
s^i,j\displaystyle\widehat{s}_{i,j} :=si,j−μjσji∈[B],j∈[D].\displaystyle\coloneqq\frac{s_{i,j}-\mu_{j}}{\sigma_{j}}\quad i\in[B],j\in[D].

其中,均值 μj\mu_{j} 与标准差 σj\sigma_{j} 是针对每个特征 j∈[D]j\in[D] 在批内样本 i∈[B]i\in[B] 上计算的。实践中,我们常给 σj\sigma_{j} 加上一个小量 ε>0\varepsilon>0,以避免除零或数值不稳定。此外,我们常按下式对数值重新缩放:Here, the means μj\mu_{j} and the standard deviations σj\sigma_{j} are computed for each feature j∈[D]j\in[D] across samples i∈[B]i\in[B] in the batch. In practice, we often add a small value ε>0\varepsilon>0 to σj\sigma_{j} to avoid division by zero or numerical instabilities. Moreover, we often rescale the values as

s~i,j:=βj+γjs^i,ji∈[B],j∈[D],\widetilde{s}_{i,j}\coloneqq\beta_{j}+\gamma_{j}\widehat{s}_{i,j}\quad i\in[B],j\in[D],

其中均值 β:=(β1,…,βD){\bm{\beta}}\coloneqq(\beta_{1},\dots,\beta_{D}) 与标准差 γ:=(γ1,…,γD){\bm{\gamma}}\coloneqq(\gamma_{1},\dots,\gamma_{D}) 是可学习参数。where the means β:=(β1,…,βD){\bm{\beta}}\coloneqq(\beta_{1},\dots,\beta_{D}) and standard deviations γ:=(γ1,…,γD){\bm{\gamma}}\coloneqq(\gamma_{1},\dots,\gamma_{D}) are learnable parameters.

批归一化的一个问题在于,推断时无法计算均值 μj\mu_{j} 与标准差 σj\sigma_{j},因为推断时不存在训练批次的概念(单个样本会使方差为 00)。为解决这一问题,我们可以在训练过程中估计整个训练集上的均值 μ^j\widehat{\mu}_{j} 与标准差 σ^j\widehat{\sigma}_{j},通常采用滑动平均。因此,实用的批归一化实现需要维护 DD 个均值与标准差统计量,以便在推断时使用。One issue with batch normalization is that the means μj\mu_{j} and standard deviations σj\sigma_{j} cannot be computed at inference time, as there is no notion of training batch (a single sample would lead to a variance of 00). To address this issue, we can estimate means μ^j\widehat{\mu}_{j} and standard deviations σ^j\widehat{\sigma}_{j} across the whole training set during the course of training, usually using a running average. A practical batch normalization implementation therefore needs to maintain DD mean and standard deviation statistics, so as to be able to use them at inference time.

4.5.2 层归一化Layer normalization

作为替代方案,层归一化 [6] 改为对特征求和来标准化数值,As an alternative, in layer normalization [6], we instead standardize the values by summing across features,

μi\displaystyle\mu_{{\color{#000000}i}} :=1D∑j=1Dsi,j∀i∈[B]\displaystyle\coloneqq\frac{1}{D}\sum_{{\color{#000000}j=1}}^{{\color{#000000}D}}s_{i,j}\quad\forall i\in[B]
σi2\displaystyle\sigma_{{\color{#000000}i}}^{2} :=1D∑j=1D(si,j−μi)2∀i∈[B]\displaystyle\coloneqq\frac{1}{D}\sum_{{\color{#000000}j=1}}^{{\color{#000000}D}}(s_{i,j}-\mu_{i})^{2}\quad\forall i\in[B]
s^i,j\displaystyle\widehat{s}_{i,j} :=si,j−μiσii∈[B],j∈[D].\displaystyle\coloneqq\frac{s_{i,j}-\mu_{i}}{\sigma_{i}}\quad i\in[B],j\in[D].

这一次,均值 μi\mu_{i} 与标准差 σi\sigma_{i} 是针对每个样本 i∈[B]i\in[B] 在特征 j∈[D]j\in[D] 上计算的(如前,我们常给 σi\sigma_{i} 加上一个小量 ε\varepsilon)。与批归一化类似,我们常按下式对数值重新缩放:This time, the means μi\mu_{i} and the standard deviations σi\sigma_{i} are computed for each sample i∈[B]i\in[B] across features j∈[D]j\in[D] (as before, we often add a small value ε\varepsilon to σi\sigma_{i}). Similarly to batch normalization, we often rescale the values as

s~i,j:=βj+γjs^i,ji∈[B],j∈[D],\widetilde{s}_{i,j}\coloneqq\beta_{j}+\gamma_{j}\widehat{s}_{i,j}\quad i\in[B],j\in[D],

其中均值 β:=(β1,…,βD){\bm{\beta}}\coloneqq(\beta_{1},\dots,\beta_{D}) 与标准差 γ:=(γ1,…,γD){\bm{\gamma}}\coloneqq(\gamma_{1},\dots,\gamma_{D}) 是可学习参数。与批归一化相比,层归一化的一个关键优势在于它在推断时是良定义的:它按样本逐一应用,不依赖训练批次的概念。因此,我们可以把层归一化视为一个函数,它对任意 si∈RD{\bm{s}}_{i}\in\mathbb{R}^{D}(无论是否属于某个批次)都对应where the means β:=(β1,…,βD){\bm{\beta}}\coloneqq(\beta_{1},\dots,\beta_{D}) and standard deviations γ:=(γ1,…,γD){\bm{\gamma}}\coloneqq(\gamma_{1},\dots,\gamma_{D}) are learnable parameters. A key advantage of layer normalization compared to batch normalization is that it is well defined at inference time, since it is applied on a per-sample basis and does not rely on the notion of a training batch. As a result, we can view layer normalization as a function that to any si∈RD{\bm{s}}_{i}\in\mathbb{R}^{D} (regardless of whether it is part of a batch or not) associates

si~:=LayerNorm(si).\widetilde{{\bm{s}}_{i}}\coloneqq\mathrm{LayerNorm}({\bm{s}}_{i}).

4.6 残差神经网络4.6 Residual neural networks

现在我们讨论另一种前馈网络参数化:残差神经网络。考虑一个具有 K+1K+1 层 f1f_{1}、…、fKf_{K}、fK+1f_{K+1} 的前馈网络。当然,只要 fK+1f_{K+1} 能够精确表示恒等函数,该前馈网络所能表示的函数集合就应当是 f1f_{1}、…、fKf_{K} 所能表示的函数集合的超集。换句话说,从理论上讲,深度不应损害前馈网络的表达能力。然而,每个 fkf_{k} 都能精确表示恒等函数这一假设在实践中未必成立。这意味着更深的网络有时会比更浅的网络更难训练,从而使准确率随深度增加而饱和或下降。We now discuss another feedforward network parametrization: residual neural networks. Consider a feedforward network with K+1K+1 layers f1f_{1}, …, fKf_{K}, fK+1f_{K+1}. Surely, as long as fK+1f_{K+1} can exactly represent the identity function, the set of functions that this feedforward network can express should be a superset of the functions that f1f_{1}, …, fKf_{K} can express. In other words, depth should in theory not hurt the expressive power of feedforward networks. Unfortunately, the assumption that each fkf_{k} can exactly represent the identity function may not hold in practice. This means that deeper networks can sometimes be more difficult to train than shallower ones, making the accuracy saturate or degrade as a function of depth.

残差神经网络 [91] 的核心思想是设计称为残差块的层 fkf_{k},使其更容易表示恒等函数。形式上,一个残差块具有如下形式The key idea of residual neural networks [91] is to design layers fkf_{k}, called residual blocks, that make it easier to represent the identity function. Formally, a residual block takes the form

sk=fk(sk−1,wk):=sk−1+hk(sk−1,wk).{\bm{s}}_{k}=f_{k}({\bm{s}}_{k-1},{\bm{w}}_{k})\coloneqq{\bm{s}}_{k-1}+h_{k}({\bm{s}}_{k-1},{\bm{w}}_{k}).

函数 hkh_{k} 称为残差,因为它建模的是差值 sk−sk−1{\bm{s}}_{k}-{\bm{s}}_{k-1}。与 sk−1{\bm{s}}_{k-1} 相加通常称为跳跃连接。只要能够容易地调整 wk{\bm{w}}_{k} 使 hk(sk−1,wk)=0h_{k}({\bm{s}}_{k-1},{\bm{w}}_{k})={\mathbf{0}} 成立,fkf_{k} 就能自由地变为恒等函数。例如,若采用The function hkh_{k} is called residual, since it models the difference sk−sk−1{\bm{s}}_{k}-{\bm{s}}_{k-1}. The addition with sk−1{\bm{s}}_{k-1} is often called a skip connection. As long as it is easy to adjust wk{\bm{w}}_{k} so that hk(sk−1,wk)=0h_{k}({\bm{s}}_{k-1},{\bm{w}}_{k})={\mathbf{0}}, fkf_{k} can freely become the identity function. For instance, if we use

hk(sk−1,wk):=Ckak(Wksk−1+bk)+dk,h_{k}({\bm{s}}_{k-1},{\bm{w}}_{k})\coloneqq{\bm{C}}_{k}a_{k}({\bm{W}}_{k}{\bm{s}}_{k-1}+{\bm{b}}_{k})+{\bm{d}}_{k},

其中 wk:=(Wk,bk,Ck,dk){\bm{w}}_{k}\coloneqq({\bm{W}}_{k},{\bm{b}}_{k},{\bm{C}}_{k},{\bm{d}}_{k}),则只需将 Ck{\bm{C}}_{k} 与 dk{\bm{d}}_{k} 分别设为零矩阵和零向量即可。已知残差块可以缓解所谓的梯度消失问题。where wk:=(Wk,bk,Ck,dk){\bm{w}}_{k}\coloneqq({\bm{W}}_{k},{\bm{b}}_{k},{\bm{C}}_{k},{\bm{d}}_{k}), it suffices to set Ck{\bm{C}}_{k} and dk{\bm{d}}_{k} to a zero matrix and vector. Residual blocks are known to remedy the so-called vanishing gradient problem.

许多论文和软件包会加入一个额外的激活函数,并改为将残差块定义为Many papers and software packages include an additional activation and instead define the residual block as

sk=fk(sk−1,wk):=ak(sk−1+hk(sk−1,wk)),{\bm{s}}_{k}=f_{k}({\bm{s}}_{k-1},{\bm{w}}_{k})\coloneqq a_{k}({\bm{s}}_{k-1}+h_{k}({\bm{s}}_{k-1},{\bm{w}}_{k})),

其中 aka_{k} 通常取为 ReLU 激活函数。是否加入这个额外的激活函数本质上是一种建模选择。在实践中,残差块还可能包含批归一化和卷积层等额外操作。where aka_{k} is typically chosen to be the ReLU activation. Whether to include this additional activation or not is essentially a modelling choice. In practice, residual blocks may also include additional operations such as batch norm and convolutional layers.

4.7 循环神经网络4.7 Recurrent neural networks

循环神经网络(RNN)是一类对向量序列进行运算的神经网络,这些序列可以作为输入、输出或两者兼有。其具体参数化取决于具体设定,但核心思想是维护一个状态向量,该向量由递归函数逐步更新,而该递归函数在各步之间共享参数。将这一递归展开,会得到一个有效的计算图,我们将在第 8 章看到这一点。我们区分图 4.7 所示的以下几种设定:Recurrent neural networks (RNNs) are a class of neural networks that operate on sequences of vectors, either as input, output or both. Their actual parametrization depends on the setup but the core idea is to maintain a state vector that is updated from step to step by a recursive function that uses shared parameters across steps. Unrolling this recursion defines a valid computational graph, as we will see in Chapter 8. We distinguish between the following setups illustrated in Fig. 4.7:

  • •

    向量到序列(一对多):fd ⁣:RD×RP→RL×Mf^{d}\colon\mathbb{R}^{D}\times\mathbb{R}^{P}\to\mathbb{R}^{L\times M}Vector to sequence (one to many):
    fd ⁣:RD×RP→RL×Mf^{d}\colon\mathbb{R}^{D}\times\mathbb{R}^{P}\to\mathbb{R}^{L\times M}

  • •

    序列到向量(多对一):fe ⁣:RL×D×RP→RMf^{e}\colon\mathbb{R}^{L\times D}\times\mathbb{R}^{P}\to\mathbb{R}^{M}Sequence to vector (many to one):
    fe ⁣:RL×D×RP→RMf^{e}\colon\mathbb{R}^{L\times D}\times\mathbb{R}^{P}\to\mathbb{R}^{M}

  • •

    序列到序列(多对多,对齐):fa ⁣:RL×D×RP→RL×Mf^{a}\colon\mathbb{R}^{L\times D}\times\mathbb{R}^{P}\to\mathbb{R}^{L\times M}Sequence to sequence (many to many, aligned):
    fa ⁣:RL×D×RP→RL×Mf^{a}\colon\mathbb{R}^{L\times D}\times\mathbb{R}^{P}\to\mathbb{R}^{L\times M}

  • •

    序列到序列(多对多,未对齐):fu ⁣:RL×D×RP→RL′×Mf^{u}\colon\mathbb{R}^{L\times D}\times\mathbb{R}^{P}\to\mathbb{R}^{L^{\prime}\times M}Sequence to sequence (many to many, unaligned):
    fu ⁣:RL×D×RP→RL′×Mf^{u}\colon\mathbb{R}^{L\times D}\times\mathbb{R}^{P}\to\mathbb{R}^{L^{\prime}\times M}

其中 LL 表示长度。注意,为记号方便,我们对每种设定都使用相同数量的参数 PP,当然实际情况未必如此。本节中,我们用记号 p1:L:=(p1,…,pL){\bm{p}}_{1:L}\coloneqq({\bm{p}}_{1},\dots,{\bm{p}}_{L}) 表示由 LL 个向量构成的序列。where LL stands for length. Note that we use the same number of parameters PP for each setup for notational convenience, but this of course does not need to be the case. Throughout this section, we use the notation p1:L:=(p1,…,pL){\bm{p}}_{1:L}\coloneqq({\bm{p}}_{1},\dots,{\bm{p}}_{L}) for a sequence of LL vectors.

(a)一对多(解码器)(a) One to many (decoder)
(b)多对一(编码器)(b) Many to one (encoder)
(c)序列到序列对齐(c) Sequence to sequence aligned
(d)序列到序列,未对齐(d) Sequence to sequence unaligned
图 4.7:循环神经网络架构Figure 4.7: Recurrent neural network architectures

4.7.1 向量到序列Vector to sequence

在此设定下,我们定义解码器函数 p1:L=fd(x,w){\bm{p}}_{1:L}=f^{d}({\bm{x}},{\bm{w}}),它从输入向量 x∈RD{\bm{x}}\in\mathbb{R}^{D} 和参数 w∈RP{\bm{w}}\in\mathbb{R}^{P} 映射到输出序列 p1:L∈RL×M{\bm{p}}_{1:L}\in\mathbb{R}^{L\times M}。例如,这对于图像描述生成很有用,即从一张图像(像素向量)生成一个句子(词嵌入序列)。形式上,我们可以通过递归定义 p1:L:=fd(x,w){\bm{p}}_{1:L}\coloneqq f^{d}({\bm{x}},{\bm{w}})In this setting, we define a decoder function p1:L=fd(x,w){\bm{p}}_{1:L}=f^{d}({\bm{x}},{\bm{w}}) from an input vector x∈RD{\bm{x}}\in\mathbb{R}^{D} and parameters w∈RP{\bm{w}}\in\mathbb{R}^{P} to an output sequence p1:L∈RL×M{\bm{p}}_{1:L}\in\mathbb{R}^{L\times M}. This is for instance useful for image caption generation, where a sentence (a sequence of word embeddings) is generated from an image (a vector of pixels). Formally, we may define p1:L:=fd(x,w){\bm{p}}_{1:L}\coloneqq f^{d}({\bm{x}},{\bm{w}}) through the recursion

zl\displaystyle{\bm{z}}_{l} :=g(x,zl−1,wg)l∈[L]\displaystyle\coloneqq g({\bm{x}},{\bm{z}}_{l-1},{\bm{w}}_{g})\quad l\in[L]
pl\displaystyle{\bm{p}}_{l} :=h(zl,wh)l∈[L].\displaystyle\coloneqq h({\bm{z}}_{l},{\bm{w}}_{h})\quad l\in[L].

其中 w:=(wg,wh,z0){\bm{w}}\coloneqq({\bm{w}}_{g},{\bm{w}}_{h},{\bm{z}}_{0})。gg 的目标是在给定输入 x{\bm{x}} 和前一解码器状态 zl−1{\bm{z}}_{l-1} 的情况下,更新当前解码器状态 zl{\bm{z}}_{l}。hh 的目标是在给定当前解码器状态 zl{\bm{z}}_{l} 的情况下生成输出 pl{\bm{p}}_{l}。重要的是,gg 与 hh 的参数在各步之间共享。通常,gg 与 hh 使用单隐藏层 MLP 参数化。注意,gg 有多个输入;我们将在 4.3 节讨论如何处理这类情形。where w:=(wg,wh,z0){\bm{w}}\coloneqq({\bm{w}}_{g},{\bm{w}}_{h},{\bm{z}}_{0}). The goal of gg is to update the current decoder state zl{\bm{z}}_{l} given the input x{\bm{x}}, and the previous decoder state zl−1{\bm{z}}_{l-1}. The goal of hh is to generate the output pl{\bm{p}}_{l} given the current decoder state zl{\bm{z}}_{l}. Importantly, the parameters of gg and hh are shared across steps. Typically, gg and hh are parametrized using one-hidden-layer MLPs. Note that gg has multiple inputs; we discuss how to deal with such cases in Section 4.3.

4.7.2 序列到向量Sequence to vector

在此设定下,我们定义编码器函数 p=fe(x1:L,w){\bm{p}}=f^{e}({\bm{x}}_{1:L},{\bm{w}}),它从输入序列 x1:L∈RL×D{\bm{x}}_{1:L}\in\mathbb{R}^{L\times D} 和参数 w∈RP{\bm{w}}\in\mathbb{R}^{P} 映射到输出向量 p∈RM{\bm{p}}\in\mathbb{R}^{M}。例如,这对于序列分类(如情感分析)很有用。形式上,我们可以用递归定义 p:=fe(x1:L,w){\bm{p}}\coloneqq f^{e}({\bm{x}}_{1:L},{\bm{w}})In this setting, we define an encoder function p=fe(x1:L,w){\bm{p}}=f^{e}({\bm{x}}_{1:L},{\bm{w}}) from an input sequence x1:L∈RL×D{\bm{x}}_{1:L}\in\mathbb{R}^{L\times D} and parameters w∈RP{\bm{w}}\in\mathbb{R}^{P} to an output vector p∈RM{\bm{p}}\in\mathbb{R}^{M}. This is for instance useful for sequence classification, such as sentiment analysis. Formally, we may define p:=fe(x1:L,w){\bm{p}}\coloneqq f^{e}({\bm{x}}_{1:L},{\bm{w}}) using the recursion

sl\displaystyle{\bm{s}}_{l} :=γ(xl,sl−1,wγ)l∈[L]\displaystyle\coloneqq\gamma({\bm{x}}_{l},{\bm{s}}_{l-1},{\bm{w}}_{\gamma})\quad l\in[L]
p\displaystyle{\bm{p}} =pooling(s1:L)\displaystyle=\mathrm{pooling}({\bm{s}}_{1:L})

其中 w:=(wγ,s0){\bm{w}}\coloneqq({\bm{w}}_{\gamma},{\bm{s}}_{0})。γ\gamma 的目标与 gg 类似,区别在于它更新编码器状态,且不将先前的预测作为输入。池化函数通常不带参数。其目标是将序列归约为一个向量。示例包括使用最后一个状态、状态的均值以及状态的按坐标最大值。where w:=(wγ,s0){\bm{w}}\coloneqq({\bm{w}}_{\gamma},{\bm{s}}_{0}). The goal of γ\gamma is similar to gg, except that it updates encoder states and does not take previous predictions as input. The pooling function is typically parameter-less. Its goal is to reduce a sequence to a vector. Examples include using the last state, the average of states and the coordinate-wise maximum of states.

4.7.3 序列到序列(对齐)Sequence to sequence (aligned)

在此设定下,我们定义函数 p1:L=fa(x1:L,w){\bm{p}}_{1:L}=f^{a}({\bm{x}}_{1:L},{\bm{w}}):它从输入序列 x1:L∈RL×D{\bm{x}}_{1:L}\in\mathbb{R}^{L\times D} 与参数 w∈RP{\bm{w}}\in\mathbb{R}^{P} 出发,映射得到输出序列 p1:L∈RL×M{\bm{p}}_{1:L}\in\mathbb{R}^{L\times M},并假定两者长度相同。一个应用示例是词性标注,其目标是为每个词 xl{\bm{x}}_{l} 标注词性(名词、动词、形容词等)。形式上,我们可以将 p1:L=fa(x1:L,w){\bm{p}}_{1:L}=f^{a}({\bm{x}}_{1:L},{\bm{w}}) 定义为In this setting, we define a function p1:L=fa(x1:L,w){\bm{p}}_{1:L}=f^{a}({\bm{x}}_{1:L},{\bm{w}}) from an input sequence x1:L∈RL×D{\bm{x}}_{1:L}\in\mathbb{R}^{L\times D} and parameters w∈RP{\bm{w}}\in\mathbb{R}^{P} to an output sequence p1:L∈RL×M{\bm{p}}_{1:L}\in\mathbb{R}^{L\times M}, which we assume to be of the same length. An example of application is part-of-speech tagging, where the goal is to assign each word xl{\bm{x}}_{l} to a part-of-speech (noun, verb, adjective, etc). Formally, we may define p1:L=fa(x1:L,w){\bm{p}}_{1:L}=f^{a}({\bm{x}}_{1:L},{\bm{w}}) as

sl\displaystyle{\bm{s}}_{l} :=γ(xl,sl−1,wγ)l∈[L]\displaystyle\coloneqq\gamma({\bm{x}}_{l},{\bm{s}}_{l-1},{\bm{w}}_{\gamma})\quad l\in[L]
pl\displaystyle{\bm{p}}_{l} =h(sl,wh)l∈[L]\displaystyle=h({\bm{s}}_{l},{\bm{w}}_{h})\quad l\in[L]

其中 w:=(wγ,wh,s0){\bm{w}}\coloneqq({\bm{w}}_{\gamma},{\bm{w}}_{h},{\bm{s}}_{0})。函数 γ\gamma 与 hh 的含义与前述相同。where w:=(wγ,wh,s0){\bm{w}}\coloneqq({\bm{w}}_{\gamma},{\bm{w}}_{h},{\bm{s}}_{0}). The functions γ\gamma and hh are similar as before.

4.7.4 序列到序列(未对齐)Sequence to sequence (unaligned)

在此设定下,我们定义函数 p1:L′=fu(x1:L,w){\bm{p}}_{1:L^{\prime}}=f^{u}({\bm{x}}_{1:L},{\bm{w}}):它从输入序列 x1:L∈RL×D{\bm{x}}_{1:L}\in\mathbb{R}^{L\times D} 与参数 w∈RP{\bm{w}}\in\mathbb{R}^{P} 出发,映射得到输出序列 p1:L′∈RL′×M{\bm{p}}_{1:L^{\prime}}\in\mathbb{R}^{L^{\prime}\times M},而两者长度可以不同。一个应用示例是机器翻译,其中源语言与目标语言的句子未必等长。通常,p1:L′=fu(x1:L,w){\bm{p}}_{1:L^{\prime}}=f^{u}({\bm{x}}_{1:L},{\bm{w}}) 由以下两个步骤定义In this setting, we define a function p1:L′=fu(x1:L,w){\bm{p}}_{1:L^{\prime}}=f^{u}({\bm{x}}_{1:L},{\bm{w}}) from an input sequence x1:L∈RL×D{\bm{x}}_{1:L}\in\mathbb{R}^{L\times D} and parameters w∈RP{\bm{w}}\in\mathbb{R}^{P} to an output sequence p1:L′∈RL′×M{\bm{p}}_{1:L^{\prime}}\in\mathbb{R}^{L^{\prime}\times M}, which potentially has a different length. An example of application is machine translation, where the sentences in the source and target languages do not necessarily have the same length. Typically, p1:L′=fu(x1:L,w){\bm{p}}_{1:L^{\prime}}=f^{u}({\bm{x}}_{1:L},{\bm{w}}) is defined as the following two steps

c\displaystyle{\bm{c}} :=fe(x1:L,we)\displaystyle\coloneqq f^{e}({\bm{x}}_{1:L},{\bm{w}}_{e})
p1:L′\displaystyle{\bm{p}}_{1:L^{\prime}} :=fd(c,wd)\displaystyle\coloneqq f^{d}({\bm{c}},{\bm{w}}_{d})

其中 w:=(we,wd){\bm{w}}\coloneqq({\bm{w}}_{e},{\bm{w}}_{d}),并复用了先前定义的编码器 fef^{e} 与解码器 fdf^{d}。将两步合并,可得where w:=(we,wd){\bm{w}}\coloneqq({\bm{w}}_{e},{\bm{w}}_{d}), and where we reused the previously-defined encoder fef^{e} and decoder fdf^{d}. Putting the two steps together, we obtain

sl\displaystyle{\bm{s}}_{l} :=γ(xl,sl−1,wγ)l∈[L]\displaystyle\coloneqq\gamma({\bm{x}}_{l},{\bm{s}}_{l-1},{\bm{w}}_{\gamma})\quad l\in[L]
c\displaystyle{\bm{c}} =pooling(s1:L)\displaystyle=\mathrm{pooling}({\bm{s}}_{1:L})
zl\displaystyle{\bm{z}}_{l} :=g(c,pl−1,zl−1,wg)l∈[L′]\displaystyle\coloneqq g({\bm{c}},{\bm{p}}_{l-1},{\bm{z}}_{l-1},{\bm{w}}_{g})\quad l\in[L^{\prime}]
pl\displaystyle{\bm{p}}_{l} :=h(zl,wh)l∈[L′].\displaystyle\coloneqq h({\bm{z}}_{l},{\bm{w}}_{h})\quad l\in[L^{\prime}].

这一架构恰如其分地被称为编码器—解码器架构。注意,我们把目标序列的长度记为 L′L^{\prime}。然而在实践中,目标长度可能取决于输入,而且往往无法预先得知。为解决这一问题,通常会在词表(按本书记号,其大小为 DD)中额外加入一个“序列结束”(EOS)标记,从而在推断时便知道何时停止生成输出序列。不过,这种编码器—解码器架构有一个缺点:输入序列的全部信息都集中于上下文向量 c{\bm{c}} 之中,因此该向量可能成为瓶颈。This architecture is aptly named the encoder-decoder architecture. Note that we denoted the length of the target sequence as L′L^{\prime}. However, in practice, the target length can be input dependent and is often not known ahead of time. To deal with this issue, the vocabulary (of size DD in our notation) is typically augmented with an “end of sequence” (EOS) token so that, at inference time, we know when to stop generating the output sequence. One disadvantage of this encoder-decoder architecture, however, is that all the information about the input sequence is contained in the context vector c{\bm{c}}, which can therefore become a bottleneck.

4.8 transformer4.8 Transformers

transformer [199] 是近年来深度学习领域最成功的进展之一。本节将逐一剖析 transformer 的各个组件。Transformers [199] are one of the most successful recent developments in deep learning. In this section, we review Transformers, component by component.

4.8.1 注意力Attention

注意力层的目标是将输入序列 v1,…,vL∈RDv{\bm{v}}_{1},\dots,{\bm{v}}_{L}\in\mathbb{R}^{D_{v}} 映射为维度相同的输出序列 u1,…,uL∈RDv{\bm{u}}_{1},\dots,{\bm{u}}_{L}\in\mathbb{R}^{D_{v}}。一个自然的思路是:以输入元素的线性组合来定义每个输出元素 ui{\bm{u}}_{i},The goal of an attention layer is to map a sequence of inputs v1,…,vL∈RDv{\bm{v}}_{1},\dots,{\bm{v}}_{L}\in\mathbb{R}^{D_{v}} to a sequence of outputs u1,…,uL∈RDv{\bm{u}}_{1},\dots,{\bm{u}}_{L}\in\mathbb{R}^{D_{v}}, of same dimension. A natural idea is to define each output element ui{\bm{u}}_{i} using a linear combination of the input elements,

ui:=∑j=1Lai,jvj∈RDv.{\bm{u}}_{i}\coloneqq\sum_{j=1}^{L}a_{i,j}{\bm{v}}_{j}\in\mathbb{R}^{D_{v}}.

我们通常采用凸组合:假定组合权重满足 ai:=(ai,1,…,ai,L)∈△L{\bm{a}}_{i}\coloneqq(a_{i,1},\dots,a_{i,L})\in\triangle^{L}。这样便保证了,在增大某一系数 ai,ja_{i,j} 时,必然要以减小另一系数 ai,j′a_{i,j^{\prime}} 为代价,其中 j≠j′j\neq j^{\prime}。把 v1,…,vL{\bm{v}}_{1},\dots,{\bm{v}}_{L} 与 u1,…,uL{\bm{u}}_{1},\dots,{\bm{u}}_{L} 视为行向量并加以堆叠,我们便得到矩阵 V∈RL×Dv{\bm{V}}\in\mathbb{R}^{L\times D_{v}} 和 U∈RL×Dv{\bm{U}}\in\mathbb{R}^{L\times D_{v}}。我们还可构造注意力矩阵 A∈△L×L{\bm{A}}\in\triangle^{L\times L},用以汇集元素 ai,ja_{i,j};其中 △L×L\triangle^{L\times L} 表示按行随机的 L×LL\times L 矩阵之集。于是,注意力便可简洁地重写为We typically use a convex combination: we assume that the combination weights are such that ai:=(ai,1,…,ai,L)∈△L{\bm{a}}_{i}\coloneqq(a_{i,1},\dots,a_{i,L})\in\triangle^{L}. This ensures that increasing a coefficient ai,ja_{i,j} is made at the expense of decreasing another coefficient ai,j′a_{i,j^{\prime}}, for j≠j′j\neq j^{\prime}. Let us form the matrices V∈RL×Dv{\bm{V}}\in\mathbb{R}^{L\times D_{v}} and U∈RL×Dv{\bm{U}}\in\mathbb{R}^{L\times D_{v}} by stacking v1,…,vL{\bm{v}}_{1},\dots,{\bm{v}}_{L} and u1,…,uL{\bm{u}}_{1},\dots,{\bm{u}}_{L}, seen as row vectors. Let us also form the attention matrix A∈△L×L{\bm{A}}\in\triangle^{L\times L} gathering the entries ai,ja_{i,j}, where △L×L\triangle^{L\times L} denotes the set of row-wise stochastic L×LL\times L matrices. Then, we can rewrite attention succinctly as

U=AV∈RL×Dv.{\bm{U}}={\bm{A}}{\bm{V}}\in\mathbb{R}^{L\times D_{v}}.

参照 6.2 节,我们可以把注意力视为一种软字典查找。从这个视角看,矩阵 V∈RL×Dv{\bm{V}}\in\mathbb{R}^{L\times D_{v}} 扮演字典值的角色,而注意力矩阵可定义为Following Section 6.2, we can view attention as a soft dictionary lookup. From this perspective, the matrix V∈RL×Dv{\bm{V}}\in\mathbb{R}^{L\times D_{v}} plays the role of dictionary values, and the attention matrix can be defined as

A:=softargmax(QK⊤)∈△L×L,{\bm{A}}\coloneqq\mathrm{softargmax}({\bm{Q}}{\bm{K}}^{\top})\in\triangle^{L\times L},

其中 Q∈RL×Dk{\bm{Q}}\in\mathbb{R}^{L\times D_{k}} 与 K∈RL×Dk{\bm{K}}\in\mathbb{R}^{L\times D_{k}} 分别扮演查询与字典键的角色。直观而言,QK⊤∈RL×L{\bm{Q}}{\bm{K}}^{\top}\in\mathbb{R}^{L\times L} 可看作一个相似度矩阵,包含查询与字典键之间的相似度。将上述各部分合在一起,我们便可把注意力定义为where Q∈RL×Dk{\bm{Q}}\in\mathbb{R}^{L\times D_{k}} and K∈RL×Dk{\bm{K}}\in\mathbb{R}^{L\times D_{k}} play the roles of queries and dictionary keys, respectively. Intuitively, QK⊤∈RL×L{\bm{Q}}{\bm{K}}^{\top}\in\mathbb{R}^{L\times L} can be seen as a similarity matrix containing the similarities between queries and dictionary keys. Putting everything together, we can define attention as

Attention(Q,K,V):=softargmax(QK⊤)V∈RL×Dv.\mathrm{Attention}({\bm{Q}},{\bm{K}},{\bm{V}})\coloneqq\mathrm{softargmax}\left({\bm{Q}}{\bm{K}}^{\top}\right){\bm{V}}\in\mathbb{R}^{L\times D_{v}}.

在掩码注意力中,我们额外引入一个掩码 M∈RL×L{\bm{M}}\in\mathbb{R}^{L\times L},In masked attention, we additionally incorporate a mask M∈RL×L{\bm{M}}\in\mathbb{R}^{L\times L},

Attention(Q,K,V;M):=softargmax((QK⊤)∘M)V∈RL×Dv,\mathrm{Attention}({\bm{Q}},{\bm{K}},{\bm{V}};{\bm{M}})\coloneqq\mathrm{softargmax}\left(({\bm{Q}}{\bm{K}}^{\top})\circ{\bm{M}}\right){\bm{V}}\in\mathbb{R}^{L\times D_{v}},

其中 ∘\circ 表示 Hadamard 乘积(逐元素乘积)。通过把相应的掩码元素 mi,jm_{i,j} 设为 −∞-\infty,该掩码可强制某些注意力权重 ai,ja_{i,j} 为零。例如,在仅解码器架构(4.8.8 节)中,该掩码将有助于为自回归模型定义因果注意力。where ∘\circ denotes the Hadamard product (element-wise multiplication). The mask can be used to force some attention weights ai,ja_{i,j} to be zero, by setting the corresponding mask entry mi,jm_{i,j} to −∞-\infty. For instance, in decoder-only architectures (Section 4.8.8), the mask will prove useful to define causal attention for autoregressive models.

注 4.8.1(缩放注意力)。Remark 4.8.1 (Scaled attention).
实际实现常使用缩放注意力,即在 soft-argmax 内部使用一个因子 1Dk\frac{1}{\sqrt{D_{k}}},以减小方差 [199, 脚注 4]。为清晰起见,我们省略这一细节。Practical implementations often use scaled attention, where a factor of 1Dk\frac{1}{\sqrt{D_{k}}} is used within the soft-argmax, in order to reduce the variance [199, Footnote 4]. We omit this detail for clarity.

4.8.2 自注意力Self-attention

假设给定一个特征向量序列 x1,…,xL∈RD{\bm{x}}_{1},\dots,{\bm{x}}_{L}\in\mathbb{R}^{D},并将其汇集为矩阵 X∈RL×D{\bm{X}}\in\mathbb{R}^{L\times D}。为定义注意力权重 ai,ja_{i,j},一个自然的想法是考虑 xi{\bm{x}}_{i} 与 xj{\bm{x}}_{j} 之间的相似度,以内积 ⟨xi,xj⟩\langle{\bm{x}}_{i},{\bm{x}}_{j}\rangle 来衡量。为确保 ai:=(ai,1,…,ai,L)∈△L{\bm{a}}_{i}\coloneqq(a_{i,1},\dots,a_{i,L})\in\triangle^{L},我们便可定义Suppose we are given a sequence of feature vectors x1,…,xL∈RD{\bm{x}}_{1},\dots,{\bm{x}}_{L}\in\mathbb{R}^{D}, that we gather as a matrix X∈RL×D{\bm{X}}\in\mathbb{R}^{L\times D}. To define the attention weights ai,ja_{i,j}, a natural idea is to consider the similarity between xi{\bm{x}}_{i} and xj{\bm{x}}_{j}, as measured by the inner product ⟨xi,xj⟩\langle{\bm{x}}_{i},{\bm{x}}_{j}\rangle. To ensure that ai:=(ai,1,…,ai,L)∈△L{\bm{a}}_{i}\coloneqq(a_{i,1},\dots,a_{i,L})\in\triangle^{L}, we can then define

ai,j:=exp⁡(⟨xi,xj⟩)∑j′=1Lexp⁡(⟨xi,xj′⟩)∈(0,1).a_{i,j}\coloneqq\frac{\exp(\langle{\bm{x}}_{i},{\bm{x}}_{j}\rangle)}{\sum_{j^{\prime}=1}^{L}\exp(\langle{\bm{x}}_{i},{\bm{x}}_{j^{\prime}}\rangle)}\in(0,1).

用矩阵记号,这可写成In matrix notation, this can be written

A:=softargmax(XX⊤)∈△L×L,{\bm{A}}\coloneqq\mathrm{softargmax}({\bm{X}}{\bm{X}}^{\top})\in\triangle^{L\times L},

其中 softargmax\mathrm{softargmax} 按行逐一施加。矩阵 XX⊤∈RL×L{\bm{X}}{\bm{X}}^{\top}\in\mathbb{R}^{L\times L} 是与行向量 x1,…,xL{\bm{x}}_{1},\dots,{\bm{x}}_{L} 相关联的 Gram 矩阵。按上一节的记号,这相当于取 Attention(Q,K,V)\mathrm{Attention}({\bm{Q}},{\bm{K}},{\bm{V}}),其中 Q=K=V=X{\bm{Q}}={\bm{K}}={\bm{V}}={\bm{X}}。换言之,序列中的各元素彼此“关注”,这被称为自注意力。where softargmax\mathrm{softargmax} is applied in a row-wise fashion. The matrix XX⊤∈RL×L{\bm{X}}{\bm{X}}^{\top}\in\mathbb{R}^{L\times L} is the Gram matrix associated with the row vectors x1,…,xL{\bm{x}}_{1},\dots,{\bm{x}}_{L}. In the notation of the previous section, this corresponds to using Attention(Q,K,V)\mathrm{Attention}({\bm{Q}},{\bm{K}},{\bm{V}}) with Q=K=V=X{\bm{Q}}={\bm{K}}={\bm{V}}={\bm{X}}. In other words, the elements of the sequence “pay attention” to each other. This is called self-attention.

前文所述的表述方式不含参数。为增强自注意力层的表达能力,[199] 提出改为将 X{\bm{X}} 投影,以此定义 Q{\bm{Q}}、K{\bm{K}} 与 V{\bm{V}}:So far, the formulation we described is parameter-free. To give more expressive power to the self-attention layer, [199] proposed instead to define Q{\bm{Q}}, K{\bm{K}} and V{\bm{V}} by projecting X{\bm{X}} as

Q\displaystyle{\bm{Q}} :=XWQ∈RL×Dk\displaystyle\coloneqq{\bm{X}}{\bm{W}}^{Q}\in\mathbb{R}^{L\times D_{k}}
K\displaystyle{\bm{K}} :=XWK∈RL×Dk\displaystyle\coloneqq{\bm{X}}{\bm{W}}^{K}\in\mathbb{R}^{L\times D_{k}}
V\displaystyle{\bm{V}} :=XWV∈RL×Dv,\displaystyle\coloneqq{\bm{X}}{\bm{W}}^{V}\in\mathbb{R}^{L\times D_{v}},

使用学习到的权重矩阵using the learned weight matrices

WQ\displaystyle{\bm{W}}^{Q} ∈RD×Dk\displaystyle\in\mathbb{R}^{D\times D_{k}}
WK\displaystyle{\bm{W}}^{K} ∈RD×Dk\displaystyle\in\mathbb{R}^{D\times D_{k}}
WV\displaystyle{\bm{W}}^{V} ∈RD×Dv.\displaystyle\in\mathbb{R}^{D\times D_{v}}.

关键在于,权重矩阵的大小与序列长度 LL 无关。因此,自注意力可以处理任意长度的序列。Importantly, the size of the weight matrices is independent of the length LL of the sequences. This allows self-attention to work with sequences of arbitrary length.

4.8.3 多头注意力Multi-head attention

为了捕捉多种注意力模式,[199] 发现定义 HH 个注意力头会带来收益In order to be able to capture multiple patterns of attention, [199] found it beneficial to define HH attention heads

Yi:=Attention(Qi,Ki,Vi;M)∈RL×Dv,{\bm{Y}}_{i}\coloneqq\mathrm{Attention}({\bm{Q}}_{i},{\bm{K}}_{i},{\bm{V}}_{i};{\bm{M}})\in\mathbb{R}^{L\times D_{v}},

其中where

Qi\displaystyle{\bm{Q}}_{i} :=XWiQ∈RL×Dk\displaystyle\coloneqq{\bm{X}}{\bm{W}}^{Q}_{i}\in\mathbb{R}^{L\times D_{k}}
Ki\displaystyle{\bm{K}}_{i} :=XWiK∈RL×Dk\displaystyle\coloneqq{\bm{X}}{\bm{W}}^{K}_{i}\in\mathbb{R}^{L\times D_{k}}
Vi\displaystyle{\bm{V}}_{i} :=XWiV∈RL×Dv,\displaystyle\coloneqq{\bm{X}}{\bm{W}}^{V}_{i}\in\mathbb{R}^{L\times D_{v}},

使用已学习的权重矩阵using the learned weight matrices

WiQ\displaystyle{\bm{W}}^{Q}_{i} ∈RD×Dk\displaystyle\in\mathbb{R}^{D\times D_{k}}
WiK\displaystyle{\bm{W}}^{K}_{i} ∈RD×Dk\displaystyle\in\mathbb{R}^{D\times D_{k}}
WiV\displaystyle{\bm{W}}^{V}_{i} ∈RD×Dv.\displaystyle\in\mathbb{R}^{D\times D_{v}}.

将 HH 个注意力头拼接,记为Let us denote the concatenation of the HH attention heads by

Concat(Y1,…,YH)∈RL×HDv.\mathrm{Concat}({\bm{Y}}_{1},\dots,{\bm{Y}}_{H})\in\mathbb{R}^{L\times HD_{v}}.

随后,[199] 将多头注意力定义为[199] then define multi-head attention as

MultiheadAttention(X;M)\displaystyle\mathrm{MultiheadAttention}({\bm{X}};{\bm{M}}) :=Concat(Y1,…,YH)WO\displaystyle\coloneqq\mathrm{Concat}({\bm{Y}}_{1},\dots,{\bm{Y}}_{H}){\bm{W}}^{O}
=∑i=1HAttention(XWiQ,XWiK,XWiV)WiO\displaystyle=\sum_{i=1}^{H}\mathrm{Attention}({\bm{X}}{\bm{W}}^{Q}_{i},{\bm{X}}{\bm{W}}_{i}^{K},{\bm{X}}{\bm{W}}_{i}^{V}){\bm{W}}_{i}^{O}
∈RL×D\displaystyle\in\mathbb{R}^{L\times D}

其中 WO∈RHDv×D{\bm{W}}^{O}\in\mathbb{R}^{HD_{v}\times D} 为可学习矩阵。该过程总结于算法 2。为清晰起见,我们用 for 循环表述;而面向 GPU 的实现则改用单次矩阵乘法。where WO∈RHDv×D{\bm{W}}^{O}\in\mathbb{R}^{HD_{v}\times D} is a learned matrix. We summarize the procedure in Algorithm 2. We use a for loop for the sake of clarity; a GPU-friendly implementation would instead be based on a single matrix multiplication.

算法 2 含 HH 个注意力头的多头注意力Algorithm 2 Multi-head attention with HH attention heads
1: Input: X∈RL×D{\bm{X}}\in\mathbb{R}^{L\times D}, optional mask M∈RL×L{\bm{M}}\in\mathbb{R}^{L\times L}
2: Parameters: {WiQ}i=1H\{{\bm{W}}_{i}^{Q}\}_{i=1}^{H}, {WiK}i=1H\{{\bm{W}}_{i}^{K}\}_{i=1}^{H}, {WiV}i=1H\{{\bm{W}}_{i}^{V}\}_{i=1}^{H}, WO{\bm{W}}^{O}
3: for i:=1,…,Hi\coloneqq 1,\ldots,H do
4:   Qi:=XWiQ∈RL×Dk{\bm{Q}}_{i}\coloneqq{\bm{X}}{\bm{W}}^{Q}_{i}\in\mathbb{R}^{L\times D_{k}}
5:   Ki:=XWiK∈RL×Dk{\bm{K}}_{i}\coloneqq{\bm{X}}{\bm{W}}^{K}_{i}\in\mathbb{R}^{L\times D_{k}}
6:   Vi:=XWiV∈RL×Dv{\bm{V}}_{i}\coloneqq{\bm{X}}{\bm{W}}^{V}_{i}\in\mathbb{R}^{L\times D_{v}}
7:   Yi:=Attention(Qi,Ki,Vi;M)∈RL×Dv{\bm{Y}}_{i}\coloneqq\mathrm{Attention}({\bm{Q}}_{i},{\bm{K}}_{i},{\bm{V}}_{i};{\bm{M}})\in\mathbb{R}^{L\times D_{v}}
8: Y:=Concat(Y1,…,YH)WO{\bm{Y}}\coloneqq\mathrm{Concat}({\bm{Y}}_{1},\dots,{\bm{Y}}_{H}){\bm{W}}^{O}
9: Output: MultiheadAttention(X;M):=Y∈RL×D\mathrm{MultiheadAttention}({\bm{X}};{\bm{M}})\coloneqq{\bm{Y}}\in\mathbb{R}^{L\times D}

4.8.4 Transformer 层Transformer layer

为提高训练效率,可引入残差连接与第一层归一化(4.5.2 节),从而定义To improve training efficiency, we can introduce residual connections and a first layer normalization (Section 4.5.2), to define

Z:=LayerNorm1(MultiheadAttention(X;M)+X)∈RL×D.{\bm{Z}}\coloneqq\mathrm{LayerNorm}_{1}(\mathrm{MultiheadAttention}({\bm{X}};{\bm{M}})+{\bm{X}})\in\mathbb{R}^{L\times D}.

为增强表达能力,Transformer 层进一步使用一个 MLP 与第二个层归一化,To improve expressiveness, a Transformer layer further uses an MLP and a second layer normalization,

X←LayerNorm2(MLP(Z)+Z)∈RL×D.{\bm{X}}\leftarrow\mathrm{LayerNorm}_{2}(\mathrm{MLP}({\bm{Z}})+{\bm{Z}})\in\mathbb{R}^{L\times D}.

LayerNorm\mathrm{LayerNorm} 中的下标意在强调:这两层各自使用独立的参数。此外,归一化按逐元素(逐 token)方式进行。MLP 块通常采用带激活函数 σ\sigma 的单个隐藏层,例如 GELU(高斯误差线性单元),见算法 3。由于使用了残差连接,MLP 块的输入与输出维度必须相同。The subscripts in LayerNorm\mathrm{LayerNorm} are used to emphasize that the two layers use their own parameters. In addition, normalization is applied in an element-wise (token-wise) fashion. The MLP block typically uses a single hidden layer with an activation function σ\sigma, such as a GELU (Gaussian error linear unit); see Algorithm 3. Because of the use of residual connections, the input and output dimensions of the MLP block must be the same.

算法 3 Transformer 的 MLP 块Algorithm 3 Transformer’s MLP block
1: Input: Z∈RL×D{\bm{Z}}\in\mathbb{R}^{L\times D}
2: Parameters: W1∈RD×D1,W2∈RD1×D{\bm{W}}_{1}\in\mathbb{R}^{D\times D_{1}},{\bm{W}}_{2}\in\mathbb{R}^{D_{1}\times D}
3: Z←ZW1∈RL×D1{\bm{Z}}\leftarrow{\bm{Z}}{\bm{W}}_{1}\in\mathbb{R}^{L\times D_{1}}
4: Z←σ(Z)∈RL×D1{\bm{Z}}\leftarrow\sigma({\bm{Z}})\in\mathbb{R}^{L\times D_{1}}
5: Z←ZW2∈RL×D{\bm{Z}}\leftarrow{\bm{Z}}{\bm{W}}_{2}\in\mathbb{R}^{L\times D}
6: Output: Z∈RL×D{\bm{Z}}\in\mathbb{R}^{L\times D}
注 4.8.2(后归一化与预归一化)。Remark 4.8.2 (Post-normalization vs. pre-normalization).
我们对 Transformer 层的描述遵循原始表述 [199],其使用后归一化。有些实现则依赖前归一化,即Our description of the Transformer layer follows the original formulation [199], which uses post-normalization. Some implementations instead rely on pre-normalization, that is, Z\displaystyle{\bm{Z}} :=MultiheadAttention(LayerNorm1(X);M)+X∈RL×D\displaystyle\coloneqq\mathrm{MultiheadAttention}(\mathrm{LayerNorm}_{1}({\bm{X}});{\bm{M}})+{\bm{X}}\in\mathbb{R}^{L\times D} X\displaystyle{\bm{X}} ←MLP(LayerNorm2(Z))+Z∈RL×D.\displaystyle\leftarrow\mathrm{MLP}(\mathrm{LayerNorm}_{2}({\bm{Z}}))+{\bm{Z}}\in\mathbb{R}^{L\times D}.

4.8.5 Transformer 块Transformer block

将 Transformer 层迭代 KK 次(每次使用不同参数),即可定义深度为 KK 的 Transformer 块。若隐去对参数的依赖,则可将带可选掩码 M∈RL×L{\bm{M}}\in\mathbb{R}^{L\times L} 的 Transformer 视为一个函数,A Transformer layer can be iterated KK times (each time with different parameters) to define a Transformer block of depth KK. Keeping the dependency on parameters implicit, we can see a Transformer, with an optional mask M∈RL×L{\bm{M}}\in\mathbb{R}^{L\times L}, as a function

X↦Transformer(X;M)=Transformer(x1,…,xL;M){\bm{X}}\mapsto\mathrm{Transformer}({\bm{X}};{\bm{M}})=\mathrm{Transformer}({\bm{x}}_{1},\dots,{\bm{x}}_{L};{\bm{M}})

从 RL×D\mathbb{R}^{L\times D} 映射到 RL×D\mathbb{R}^{L\times D}。Transformer 接收序列 X∈RL×D{\bm{X}}\in\mathbb{R}^{L\times D},并利用序列元素之间的相互依赖关系生成该序列的表示。该过程总结于算法 4。MultiheadAttention\mathrm{MultiheadAttention}、LayerNorm\mathrm{LayerNorm} 与 MLP\mathrm{MLP} 各块均以 kk 为索引,以强调其参数在每次迭代中互不相同。from RL×D\mathbb{R}^{L\times D} to RL×D\mathbb{R}^{L\times D}. The Transformer takes a sequence X∈RL×D{\bm{X}}\in\mathbb{R}^{L\times D} and uses the inter-dependencies between sequence elements to produce a representation of that sequence. We summarize the procedure in Algorithm 4. The MultiheadAttention\mathrm{MultiheadAttention}, LayerNorm\mathrm{LayerNorm} and MLP\mathrm{MLP} blocks are indexed by kk to emphasize that their parameters are different for each iteration.

参数数量与计算复杂度Number of parameters and computational complexity

Transformer 层可视为从 RL×D\mathbb{R}^{L\times D} 到 RL×D\mathbb{R}^{L\times D} 的函数。若要让标准多层感知机具有相同的函数签名,则需要 O(L2D2)O(L^{2}D^{2}) 个参数,且其一次网络前向传播的时间复杂度同样为 O(L2D2)O(L^{2}D^{2})。相比之下,一个 Transformer 层只有 O(D2)O(D^{2}) 个参数。其中,自注意力的复杂度为 O(L2D)O(L^{2}D),最后的 MLP 层复杂度为 O(LD2)O(LD^{2})。The Transformer layer can be seen as a function from RL×D\mathbb{R}^{L\times D} to RL×D\mathbb{R}^{L\times D}. To offer the same function signature, a standard multi-layer perceptron would have needed O(L2D2)O(L^{2}D^{2}) parameters and a forward pass through the network would have had a time complexity of O(L2D2)O(L^{2}D^{2}) as well. In contrast, a Transformer layer has O(D2)O(D^{2}) parameters. Self-attention has a complexity of O(L2D)O(L^{2}D) and the final MLP layer has a complexity of O(LD2)O(LD^{2}).

算法 4 深度为 KK 的 Transformer 块Algorithm 4 Transformer block of depth KK
1: Input: X∈RL×D{\bm{X}}\in\mathbb{R}^{L\times D}, optional mask M∈RL×L{\bm{M}}\in\mathbb{R}^{L\times L}
2: Parameters: Multi-head attention parameters, MLP parameters and layer norm parameters (each depth kk uses different parameters)
3: for k:=1,…,Kk\coloneqq 1,\ldots,K do
4:   Y:=MultiheadAttentionk(X;M)∈RL×D{\bm{Y}}\coloneqq\mathrm{MultiheadAttention}_{k}({\bm{X}};{\bm{M}})\in\mathbb{R}^{L\times D}
5:   Z:=LayerNormk,1(Y+X)∈RL×D{\bm{Z}}\coloneqq\mathrm{LayerNorm}_{k,1}({\bm{Y}}+{\bm{X}})\in\mathbb{R}^{L\times D} ▹\triangleright Residual connection
6:   X←LayerNormk,2(MLPk(Z)+Z)∈RL×D{\bm{X}}\leftarrow\mathrm{LayerNorm}_{k,2}(\mathrm{MLP}_{k}({\bm{Z}})+{\bm{Z}})\in\mathbb{R}^{L\times D} ▹\triangleright MLP layer
7: Output: X∈RL×D{\bm{X}}\in\mathbb{R}^{L\times D}

4.8.6 token 编码Token encoding

文本可表示为由离散符号构成的序列 x1,…,xLx_{1},\dots,x_{L},这些符号通常称为 token。此处每个 token xi∈[M]x_{i}\in[M](其中 MM 为词表大小)可对应单词、子词,乃至单个字符,具体取决于分词方式。为得到连续向量序列 x1,…,xL{\bm{x}}_{1},\dots,{\bm{x}}_{L}(其中 xi∈RD{\bm{x}}_{i}\in\mathbb{R}^{D}),通常采用嵌入层。该层通过线性投影将 xi∈[M]x_{i}\in[M] 变换为 xi∈RD{\bm{x}}_{i}\in\mathbb{R}^{D},Text can be represented as a sequence x1,…,xLx_{1},\dots,x_{L} of discrete symbols, often called tokens. Here, each token xi∈[M]x_{i}\in[M], where MM is the vocabulary size, can correspond to words, subwords, or even individual characters, depending on the tokenization procedure. To obtain a sequence of continuous vectors x1,…,xL{\bm{x}}_{1},\dots,{\bm{x}}_{L}, where xi∈RD{\bm{x}}_{i}\in\mathbb{R}^{D}, it is common to use an embedding layer. This layer transforms xi∈[M]x_{i}\in[M] into xi∈RD{\bm{x}}_{i}\in\mathbb{R}^{D} using the linear projection

xi:=WEexi,{\bm{x}}_{i}\coloneqq{\bm{W}}^{E}{\bm{e}}_{x_{i}},

其中 ej∈RM{\bm{e}}_{j}\in\mathbb{R}^{M} 为 j∈[M]j\in[M] 的 one-hot 编码,WE∈RD×M{\bm{W}}^{E}\in\mathbb{R}^{D\times M} 为可学习的嵌入矩阵。列 W:,jE∈RD{\bm{W}}^{E}_{:,j}\in\mathbb{R}^{D} 可解释为 token j∈[V]j\in[V] 的连续表示。词表通常还包含特殊 token,如“BOS”(序列开始)、“EOS”(序列结束)与“PAD”(填充 token,用于保证序列长度为 LL)。where ej∈RM{\bm{e}}_{j}\in\mathbb{R}^{M} is the one-hot encoding of j∈[M]j\in[M] and WE∈RD×M{\bm{W}}^{E}\in\mathbb{R}^{D\times M} is a learnable embedding matrix. The column W:,jE∈RD{\bm{W}}^{E}_{:,j}\in\mathbb{R}^{D} can be interpreted as the continuous representation of token j∈[V]j\in[V]. Usually, the vocabulary includes special tokens such as “BOS” (beginning of sequence), “EOS” (end of sequence) and “PAD” (padding token, to ensure that the sequence is of length LL).

4.8.7 位置编码Positional encoding

受其参数化方式影响,Transformer 对置换具有等变性:先置换输入序列再施加 Transformer,与先施加 Transformer 再置换输出序列,二者等价。形式上,对任意大小为 L×LL\times L 的置换矩阵 P\mathcal{P},以及视为矩阵 X{\bm{X}} 的输入序列 x1,…,xL{\bm{x}}_{1},\dots,{\bm{x}}_{L},均有Due to their parameterization, Transformers are equivariant with respect to permutations: permuting the input sequence and applying the Transformer is equivalent to applying the Transformer and permuting the output sequence. Formally, for any permutation matrix P\mathcal{P} of size L×LL\times L and input sequence x1,…,xL{\bm{x}}_{1},\dots,{\bm{x}}_{L} seen as a matrix X{\bm{X}}, we have

Transformer(PX)=PTransformer(X).\mathrm{Transformer}(\mathcal{P}{\bm{X}})=\mathcal{P}\mathrm{Transformer}({\bm{X}}).

这意味着 Transformer 将有序序列视为多重集(多重集是对集合概念的修改,允许其中元素出现多个实例)。若要在 Transformer 中利用顺序信息,有若干可行途径 [60]:加入位置编码(绝对或相对)、修改注意力矩阵,或用 RNN 对输入序列作预处理。加入位置编码时,通常将表示位置 i∈[L]i\in[L] 的向量 pi∈RD{\bm{p}}_{i}\in\mathbb{R}^{D} 加到相应元素 xi∈RD{\bm{x}}_{i}\in\mathbb{R}^{D} 之上,This means that Transformers treat an ordered sequence as a multi-set (a modification of the concept of a set that allows for multiple instances of its elements). To leverage order information in a Transformer, several approaches are possible [60]: adding positional encoding (either absolute or relative), modifying the attention matrix and pre-processing the input sequence with an RNN. To add positional encoding, one typically adds a vector pi∈RD{\bm{p}}_{i}\in\mathbb{R}^{D} representing the position i∈[L]i\in[L] to the corresponding element xi∈RD{\bm{x}}_{i}\in\mathbb{R}^{D},

xi←xi+pi.{\bm{x}}_{i}\leftarrow{\bm{x}}_{i}+{\bm{p}}_{i}.

理想的位置编码应当适用于任意序列长度。An ideal positional encoding should work with any sequence length.

可学习的位置编码Learned positional encoding

与 token 编码类似,定义位置编码的一个简便方法是使用嵌入层。每个位置 i∈[L]i\in[L] 经由下式变换为位置向量 pi∈RD{\bm{p}}_{i}\in\mathbb{R}^{D}:Similarly to the token encoding, a simple way to define a positional encoding is to use an embedding layer. Each position i∈[L]i\in[L] is transformed into a position vector pi∈RD{\bm{p}}_{i}\in\mathbb{R}^{D} by

pi:=WPei{\bm{p}}_{i}\coloneqq{\bm{W}}^{P}{\bm{e}}_{i}

其中 ei∈RL{\bm{e}}_{i}\in\mathbb{R}^{L} 是 i∈[L]i\in[L] 的 one-hot 编码,WP∈RD×L{\bm{W}}^{P}\in\mathbb{R}^{D\times L} 是可学习的嵌入矩阵。列 W:,iP∈RD{\bm{W}}^{P}_{:,i}\in\mathbb{R}^{D} 可解释为位置 i∈[L]i\in[L] 的连续表示。where ei∈RL{\bm{e}}_{i}\in\mathbb{R}^{L} is the one-hot encoding of i∈[L]i\in[L] and WP∈RD×L{\bm{W}}^{P}\in\mathbb{R}^{D\times L} is a learnable embedding matrix. The column W:,iP∈RD{\bm{W}}^{P}_{:,i}\in\mathbb{R}^{D} can be interpreted as the continuous representation of position i∈[L]i\in[L].

正弦位置编码Sinusoidal positional encoding

我们不必学习位置编码,也可以用启发式方式定义它。例如,[199] 提出了正弦位置编码 pi:=(pi,1,…,pi,D){\bm{p}}_{i}\coloneqq(p_{i,1},\dots,{\bm{p}}_{i,D}),其定义为Instead of learning the positional encoding, we can define it in a heuristic manner. For instance, [199] proposed the sinusoidal positional encoding pi:=(pi,1,…,pi,D){\bm{p}}_{i}\coloneqq(p_{i,1},\dots,{\bm{p}}_{i,D}), defined by

pi,j:={sin⁡(ωj⋅i) if j is evencos⁡(ωj−1⋅i) if j is odd∈[−1,1],p_{i,j}\coloneqq\begin{cases}\sin(\omega_{j}\cdot i)&\text{ if }j\text{ is even}\\ \cos(\omega_{j-1}\cdot i)&\text{ if }j\text{ is odd}\end{cases}\in[-1,1],

其中where

ωj:=1NjD=N−jD\omega_{j}\coloneqq\frac{1}{N^{\frac{j}{D}}}=N^{-\frac{j}{D}}

并且其中 NN 是常数,作者将其设为 N:=10000N\coloneqq 10000。我们可以把所有取值汇总为一个位置编码矩阵 P∈RL×D\bm{P}\in\mathbb{R}^{L\times D},如图 4.8 所示。and where NN is a constant, set to N:=10000N\coloneqq 10000 by the authors. We can gather the values in a position encoding matrix P∈RL×D\bm{P}\in\mathbb{R}^{L\times D}, as depicted in Fig. 4.8.

Refer to caption
图 4.8:位置编码矩阵 P∈RL×D\bm{P}\in\mathbb{R}^{L\times D} 的热图,其中 L=100L=100、D=50D=50、N=30N=30。这些取值属于区间 [−1,1][-1,1]。Figure 4.8: Heatmap of a positional encoding matrix P∈RL×D\bm{P}\in\mathbb{R}^{L\times D}, with L=100L=100, D=50D=50, and N=30N=30. The values belong to the range [−1,1][-1,1].

乍看之下,正弦位置编码或许显得有些神秘。为获得一些直观理解,可以将其与整数的离散二进制编码进行比较,On first sight, sinusoidal positional encoding may seem a bit mysterious. To gain some intuition, it is useful to compare it to a discrete binary encoding of integers,

7\displaystyle 7 ↔111\displaystyle\leftrightarrow{{\color{#000000}1}}{{\color{#000000}1}}{{\color{#000000}1}}
6\displaystyle 6 ↔110\displaystyle\leftrightarrow{{\color{#000000}1}}{{\color{#000000}1}}{{\color{#000000}0}}
5\displaystyle 5 ↔101\displaystyle\leftrightarrow{{\color{#000000}1}}{{\color{#000000}0}}{{\color{#000000}1}}
4\displaystyle 4 ↔100\displaystyle\leftrightarrow{{\color{#000000}1}}{{\color{#000000}0}}{{\color{#000000}0}}
3\displaystyle 3 ↔011\displaystyle\leftrightarrow{{\color{#000000}0}}{{\color{#000000}1}}{{\color{#000000}1}}
2\displaystyle 2 ↔010\displaystyle\leftrightarrow{{\color{#000000}0}}{{\color{#000000}1}}{{\color{#000000}0}}
1\displaystyle 1 ↔001\displaystyle\leftrightarrow{{\color{#000000}0}}{{\color{#000000}0}}{{\color{#000000}1}}
0\displaystyle 0 ↔000.\displaystyle\leftrightarrow{{\color{#000000}0}}{{\color{#000000}0}}{{\color{#000000}0}}.

我们可以看到,从右向左移动时,比特在 0{{\color{#000000}0}} 与 1{{\color{#000000}1}} 之间的交替变得更加频繁。正弦位置编码实现了类似的行为,只不过它是连续的。实际上,每个坐标 j∈[D]j\in[D] 都对应一条正弦波(当 jj 为偶数时)或余弦波(当 jj 为奇数时)。与 jj 关联的波的波长或周期为 2πωj\frac{2\pi}{\omega_{j}},频率为 ωj2π\frac{\omega_{j}}{2\pi}。由于 ωj\omega_{j} 是关于 jj 的递减函数,可以看到,当 jj 较小时,波的振荡更为频繁。图 4.9 展示了这一行为。We see that the bits alternate more frequently between 0{{\color{#000000}0}} and 1{{\color{#000000}1}} as we go from right to left. The sinusoidal positional encoding achieves a similar behavior, but is continuous. Indeed, each coordinate j∈[D]j\in[D] is associated with a sine wave (when jj is even) or a cosine wave (when jj is odd). The wavelength or period of the wave associated with jj is 2πωj\frac{2\pi}{\omega_{j}} and its frequency is ωj2π\frac{\omega_{j}}{2\pi}. Since ωj\omega_{j} is a decreasing function of jj, we see that the waves oscillate more frequently when jj is small. This behavior is illustrated in Fig. 4.9.

将正弦波与余弦波堆叠起来,已被用于构造随机傅里叶特征 [165, 190]。这些方法使用随机频率的波,而正弦位置编码使用频率递增的波。因此,两者的主要区别在于波频率的选择方式。Stacking sine and cosine waves has been used for creating random Fourier features [165, 190]. These use waves of random frequencies, while sinusoidal positional encoding uses waves of increasing frequency. These approaches therefore mainly differ in the way we choose wave frequencies.

图 4.9:使用正弦位置编码时,每个坐标 j∈[D]j\in[D] 都对应一条正弦波或余弦波。与二进制编码类比:在二进制编码中,低位比特在 00 与 11 之间的交替比高位比特更频繁;而与 jj 关联的波在 jj 较小时振荡得更为频繁。Figure 4.9: Using a sinusoidal positional encoding, each coordinate j∈[D]j\in[D] is associated with a sine or cosine wave. In analogy with a binary encoding, in which lower bits alternate between 00 and 11 more frequently than higher bits, the wave associated with jj oscillates more frequently when jj is small.

恢复相对位置信息Recovering relative positional information

正弦位置编码的一个重要性质是:对于任意偏移量 δ\delta,pi+δ{\bm{p}}_{i+\delta} 都可以表示为 pi{\bm{p}}_{i} 的线性函数 [199, 214]。因此,模型应当能够轻松学会依据相对位置进行注意力计算。事实上,利用关于角和的三角恒等式An important property of the sinusoidal positional encoding is that pi+δ{\bm{p}}_{i+\delta} can be represented as a linear function of pi{\bm{p}}_{i}, for any offset δ\delta [199, 214]. The model should therefore be able to easily learn to attend by relative positions. Indeed, using the trigonometric identities for angle sums

cos⁡(α+β)\displaystyle\cos(\alpha+\beta) =cos⁡(α)cos⁡(β)−sin⁡(α)sin⁡(β)\displaystyle=\cos(\alpha)\cos(\beta)-\sin(\alpha)\sin(\beta)
sin⁡(α+β)\displaystyle\sin(\alpha+\beta) =sin⁡(α)cos⁡(β)+cos⁡(α)sin⁡(β),\displaystyle=\sin(\alpha)\cos(\beta)+\cos(\alpha)\sin(\beta),

对于偶数 jj,我们有we have for jj even

(pi+δ,j+1pi+δ,j)\displaystyle\begin{pmatrix}p_{i+\delta,j+1}\\ p_{i+\delta,j}\end{pmatrix} =(cos⁡(ωj(i+δ))sin⁡(ωj(i+δ)))\displaystyle=\begin{pmatrix}\cos(\omega_{j}(i+\delta))\\ \sin(\omega_{j}(i+\delta))\end{pmatrix}
=(cos⁡(ωj⋅i)cos⁡(ωj⋅δ)−sin⁡(ωj⋅i)sin⁡(ωj⋅δ)sin⁡(ωj⋅i)cos⁡(ωj⋅δ)+cos⁡(ωj⋅i)sin⁡(ωj⋅δ))\displaystyle=\begin{pmatrix}\cos(\omega_{j}\cdot i)\cos(\omega_{j}\cdot\delta)-\sin(\omega_{j}\cdot i)\sin(\omega_{j}\cdot\delta)\\ \sin(\omega_{j}\cdot i)\cos(\omega_{j}\cdot\delta)+\cos(\omega_{j}\cdot i)\sin(\omega_{j}\cdot\delta)\end{pmatrix}
=(cos⁡(ωj⋅δ)−sin⁡(ωj⋅δ)sin⁡(ωj⋅δ)cos⁡(ωj⋅δ))(cos⁡(ωj⋅i)sin⁡(ωj⋅i))\displaystyle=\begin{pmatrix}\cos(\omega_{j}\cdot\delta)&-\sin(\omega_{j}\cdot\delta)\\ \sin(\omega_{j}\cdot\delta)&\cos(\omega_{j}\cdot\delta)\end{pmatrix}\begin{pmatrix}\cos(\omega_{j}\cdot i)\\ \sin(\omega_{j}\cdot i)\end{pmatrix}
=(cos⁡(ωj⋅δ)−sin⁡(ωj⋅δ)sin⁡(ωj⋅δ)cos⁡(ωj⋅δ))(pi,j+1pi,j)\displaystyle=\begin{pmatrix}\cos(\omega_{j}\cdot\delta)&-\sin(\omega_{j}\cdot\delta)\\ \sin(\omega_{j}\cdot\delta)&\cos(\omega_{j}\cdot\delta)\end{pmatrix}\begin{pmatrix}p_{i,j+1}\\ p_{i,j}\end{pmatrix}

因此,通过施加一个旋转矩阵,(pi,j+1,pi,j)(p_{i,j+1},p_{i,j}) 可以被线性投影为 (pi+δ,j+1,pi+δ,j)(p_{i+\delta,j+1},p_{i+\delta,j})。这使得 Transformer 能够轻松学会依据相对位置进行注意力计算。Therefore, (pi,j+1,pi,j)(p_{i,j+1},p_{i,j}) can be linearly projected to (pi+δ,j+1,pi+δ,j)(p_{i+\delta,j+1},p_{i+\delta,j}), by applying a rotation matrix. This allows a Transformer to easily learn to attend by relative positions.

旋转位置编码(RoPE)Rotary positional encoding (RoPE)

在自注意力中考虑绝对位置信息的另一种流行方法是 RoPE [189],它代表旋转位置编码(rotary positional encoding)。为简单起见,我们以单个注意力头和 Dv=Dk=DD_{v}=D_{k}=D 为例简要说明其思想。假设我们有一个已经用 token 编码编好的序列 x1,…,xL∈RD{\bm{x}}_{1},\dots,{\bm{x}}_{L}\in\mathbb{R}^{D}。随后,我们将查询向量和键向量定义为Another popular approach for taking into account absolute positional information in self-attention is RoPE [189], which stands for rotary positional encoding. For simplicity, we briefly explain the idea with a single attention head and Dv=Dk=DD_{v}=D_{k}=D. Suppose we have a sequence x1,…,xL∈RD{\bm{x}}_{1},\dots,{\bm{x}}_{L}\in\mathbb{R}^{D} already encoded with token encoding. We then define the query and key vectors as

qm\displaystyle{\bm{q}}_{m} :=RD(θ,m)WQxmm∈[L]\displaystyle\coloneqq\bm{R}_{D}(\theta,m){\bm{W}}^{Q}{\bm{x}}_{m}\quad m\in[L]
kn\displaystyle\bm{k}_{n} :=RD(θ,n)WKxnn∈[L],\displaystyle\coloneqq\bm{R}_{D}(\theta,n){\bm{W}}^{K}{\bm{x}}_{n}\quad n\in[L],

其中 RD(θ,m)∈RD×D\bm{R}_{D}(\theta,m)\in\mathbb{R}^{D\times D} 是旋转矩阵。其核心直觉是,我们将这个 DD 维向量旋转一个角度,该角度是位置 mm 的倍数。与可学习位置编码和正弦位置编码不同,权重矩阵 WQ{\bm{W}}^{Q} 和 WK{\bm{W}}^{K} 是在施加 RoPE 之前应用的,而不是之后。where RD(θ,m)∈RD×D\bm{R}_{D}(\theta,m)\in\mathbb{R}^{D\times D} is a rotation matrix. The main intuition is that we are rotating the DD-dimensional vector by an angle which is a multiple of the position mm. In contrast to the learned and sinusoidal positional encodings, the weight matrices WQ{\bm{W}}^{Q} and WK{\bm{W}}^{K} are applied before applying RoPE, not after.

当 D=2D=2 时,RD(θ,m)=R2(θ,m)\bm{R}_{D}(\theta,m)=\bm{R}_{2}(\theta,m) 定义为旋转矩阵When D=2D=2, RD(θ,m)=R2(θ,m)\bm{R}_{D}(\theta,m)=\bm{R}_{2}(\theta,m) is defined as the rotation matrix

R2(θ,m):=(cos⁡(mθ)−sin⁡(mθ)sin⁡(mθ)cos⁡(mθ))\bm{R}_{2}(\theta,m)\coloneqq\begin{pmatrix}\cos(m\theta)&-\sin(m\theta)\\ \sin(m\theta)&\cos(m\theta)\end{pmatrix}

其中角度为 θ∈R\theta\in\mathbb{R}、位置为 m∈[L]m\in[L]。利用欧拉公式for some angle θ∈R\theta\in\mathbb{R} and position m∈[L]m\in[L]. Using Euler’s formula

eimθ=cos⁡(mθ)+isin⁡(mθ),e^{im\theta}=\cos(m\theta)+i\sin(m\theta),

我们注意到,对于 v=(v1,v2)∈R2{\bm{v}}=(v_{1},v_{2})\in\mathbb{R}^{2} 和 v′=(v1′,v2′)∈R2{\bm{v}}^{\prime}=(v^{\prime}_{1},v^{\prime}_{2})\in\mathbb{R}^{2},v′:=R2(θ,m)v{\bm{v}}^{\prime}\coloneqq\bm{R}_{2}(\theta,m){\bm{v}} 等价于对于 z:=v1+iv2∈Cz\coloneqq v_{1}+iv_{2}\in\mathbb{C} 和 z′=v1′+iv2′∈Cz^{\prime}=v^{\prime}_{1}+iv^{\prime}_{2}\in\mathbb{C} 的 z′:=zeimθz^{\prime}\coloneqq ze^{im\theta}。RoPE 公式的详细推导参见 [189]。we note that v′:=R2(θ,m)v{\bm{v}}^{\prime}\coloneqq\bm{R}_{2}(\theta,m){\bm{v}} for v=(v1,v2)∈R2{\bm{v}}=(v_{1},v_{2})\in\mathbb{R}^{2} and v′=(v1′,v2′)∈R2{\bm{v}}^{\prime}=(v^{\prime}_{1},v^{\prime}_{2})\in\mathbb{R}^{2} is equivalent to z′:=zeimθz^{\prime}\coloneqq ze^{im\theta} for z:=v1+iv2∈Cz\coloneqq v_{1}+iv_{2}\in\mathbb{C} and z′=v1′+iv2′∈Cz^{\prime}=v^{\prime}_{1}+iv^{\prime}_{2}\in\mathbb{C}. See [189] for a detailed derivation of RoPE’s formula.

当 D>2D>2 时,假设 DD 为偶数,RD(θ,m)\bm{R}_{D}(\theta,m) 定义为When D>2D>2, assuming DD is even, RD(θ,m)\bm{R}_{D}(\theta,m) is defined as

RD(θ,m):=(R2(θ1,m)R2(θ2,m)⋱R2(θD/2,m)),\bm{R}_{D}(\theta,m)\coloneqq\begin{pmatrix}\bm{R}_{2}(\theta_{1},m)&&&\\ &\bm{R}_{2}(\theta_{2},m)&&\\ &&\ddots&\\ &&&\bm{R}_{2}(\theta_{D/2},m)\end{pmatrix},

其中 θj:=10000−2(j−1)/D\theta_{j}\coloneqq 10000^{-2(j-1)/D}。在实践中,我们从不把 RD(θ,m)\bm{R}_{D}(\theta,m) 具体化为矩阵,因为它会非常稀疏;相反,我们将其视为作用在任意向量 v∈RD{\bm{v}}\in\mathbb{R}^{D} 上的线性映射,where θj:=10000−2(j−1)/D\theta_{j}\coloneqq 10000^{-2(j-1)/D}. In practice, we never materialize RD(θ,m)\bm{R}_{D}(\theta,m) as a matrix, since it would be very sparse, but rather view it as a linear map applied to an arbitrary vector v∈RD{\bm{v}}\in\mathbb{R}^{D},

RD(θ,m)v=(v1v2v3v4⋮vD−1vD)⊗(cos⁡(mθ1)cos⁡(mθ1)cos⁡(mθ2)cos⁡(mθ2)⋮cos⁡(mθD/2)cos⁡(mθD/2))+(−v2v1−v4v3⋮−vDvD−1)⊗(sin⁡(mθ1)sin⁡(mθ1)sin⁡(mθ2)sin⁡(mθ2)⋮sin⁡(mθD/2)sin⁡(mθD/2)).\bm{R}_{D}(\theta,m){\bm{v}}=\begin{pmatrix}v_{1}\\ v_{2}\\ v_{3}\\ v_{4}\\ \vdots\\ v_{D-1}\\ v_{D}\end{pmatrix}\otimes\begin{pmatrix}\cos(m\theta_{1})\\ \cos(m\theta_{1})\\ \cos(m\theta_{2})\\ \cos(m\theta_{2})\\ \vdots\\ \cos(m\theta_{D/2})\\ \cos(m\theta_{D/2})\end{pmatrix}+\begin{pmatrix}-v_{2}\\ v_{1}\\ -v_{4}\\ v_{3}\\ \vdots\\ -v_{D}\\ v_{D-1}\end{pmatrix}\otimes\begin{pmatrix}\sin(m\theta_{1})\\ \sin(m\theta_{1})\\ \sin(m\theta_{2})\\ \sin(m\theta_{2})\\ \vdots\\ \sin(m\theta_{D/2})\\ \sin(m\theta_{D/2})\end{pmatrix}.

一旦计算出 Q{\bm{Q}} 和 K{\bm{K}},我们就可以像往常一样使用 Attention(Q,K,V;M)\mathrm{Attention}({\bm{Q}},{\bm{K}},{\bm{V}};{\bm{M}})。对于多头注意力,我们只需对每个注意力头应用相同的方法。Once we computed Q{\bm{Q}} and K{\bm{K}}, we can use Attention(Q,K,V;M)\mathrm{Attention}({\bm{Q}},{\bm{K}},{\bm{V}};{\bm{M}}) as usual. For multi-head attention, we simply apply the same approach for each attention head.

正如 [189] 所分析的,RoPE 具备若干有价值的性质。特别是,它关于序列长度 LL 是灵活的;尽管它是一种绝对编码,却也能捕捉 token 之间的相对距离。因此,它兼具绝对位置编码与相对位置编码的优点。As analyzed by [189], RoPE satisfies several valuable properties. In particular, it is flexible w.r.t. the sequence length LL and despite being an absolute encoding, it manages to also capture relative distance between tokens. It therefore has the merits of both absolute and relative positional encodings.

4.8.8 仅解码器架构Decoder-only architectures

定义语言模型Defining a language model

Transformer 最初是为机器翻译构建编码器—解码器架构而提出的 [199]。然而,在语言建模的语境下,Transformer 如今通常采用仅解码器的自回归架构。假设给定一个离散符号序列 x1,…,xL∈[M]x_{1},\dots,x_{L}\in[M](若序列元素少于 LL 个,可以使用填充符号)。(无条件的)语言模型的目标是构造一个产生联合概率的函数,Transformers were originally developed to create encoder-decoder architectures for machine translation [199]. However, in the context of language modelling, Transformers are now routinely used for decoder-only autoregressive architectures. Suppose we are given a sequence of discrete symbols x1,…,xL∈[M]x_{1},\dots,x_{L}\in[M] (if a sequence has less than LL elements, we can use padding symbols). The goal of (unconditional) language models is to create a function producing the joint probability,

(x1,…,xL)↦P(X1=x1,…,XL=xL).(x_{1},\dots,x_{L})\mapsto\mathbb{P}(X_{1}=x_{1},\dots,X_{L}=x_{L}).

利用概率的链式法则(10.1 节),不失一般性,我们可以将其写成Using the chain rule of probability (Section 10.1), without loss of generality, we can write

P(X1=x1,…,XL=xL)=∏k=1LP(Xk=xk∣X1=x1,…,Xk−1=xk−1).\mathbb{P}\left(X_{1}=x_{1},\ldots,X_{L}=x_{L}\right)=\prod_{k=1}^{L}\mathbb{P}(X_{k}=x_{k}\mid X_{1}=x_{1},\dots,X_{k-1}=x_{k-1}).

如果最大长度 LL 非常大,更实用的做法是只考虑大小为 NN 的上下文窗口,If the maximum length LL is very large, it is more practical to only consider a context window of size NN,

P(X1=x1,…,XL=xL):=∏k=1LP(Xk=xk∣Xk−N=xk−N,…,Xk−1=xk−1).\mathbb{P}\left(X_{1}=x_{1},\ldots,X_{L}=x_{L}\right)\coloneqq\prod_{k=1}^{L}\mathbb{P}(X_{k}=x_{k}\mid X_{k-N}=x_{k-N},\dots,X_{k-1}=x_{k-1}).

这相当于定义一个高阶马尔可夫链(10.4.3 节)。采用这种方法,构建语言模型便归结为定义一个函数This amounts to defining a higher-order Markov chain (Section 10.4.3). Using this approach, creating a language model then boils down to defining a function

(xk−N,…,xk−1,xk)↦P(Xk=xk∣Xk−N=xk−N,…,Xk−1=xk−1).(x_{k-N},\dots,x_{k-1},x_{k})\mapsto\mathbb{P}(X_{k}=x_{k}\mid X_{k-N}=x_{k-N},\dots,X_{k-1}=x_{k-1}).

假设离散符号序列 x1,…,xL∈[M]x_{1},\dots,x_{L}\in[M] 已通过 token 编码(4.8.6 节)和位置编码(4.8.7 节)映射为连续向量序列 x1,…,xL∈RD{\bm{x}}_{1},\dots,{\bm{x}}_{L}\in\mathbb{R}^{D}。使用因果 Transformer 块,我们可以获得当前上下文的表示,Let us assume that the sequence of discrete symbols x1,…,xL∈[M]x_{1},\dots,x_{L}\in[M] has been mapped to a sequence of continuous vectors x1,…,xL∈RD{\bm{x}}_{1},\dots,{\bm{x}}_{L}\in\mathbb{R}^{D} using token encoding (Section 4.8.6) and positional encoding (Section 4.8.7). Using a causal Transformer block, we can obtain a representation of the current context,

(xk−N,…,xk−1)←Transformer(xk−N,…,xk−1;MN).({\bm{x}}_{k-N},\dots,{\bm{x}}_{k-1})\leftarrow\mathrm{Transformer}({\bm{x}}_{k-N},\dots,{\bm{x}}_{k-1};{\bm{M}}_{N}).

为确保 Transformer 仅依赖过去的 token 来预测当前 token,掩码矩阵 MN{\bm{M}}_{N} 被设为大小为 N×NN\times N 的矩阵,其下三角部分元素设为 11,上三角部分元素设为 −∞-\infty。为将其归约为 RM\mathbb{R}^{M} 中的 logit,我们通常使用上下文的最后一个元素 xk−1∈RD{\bm{x}}_{k-1}\in\mathbb{R}^{D} 并应用一个线性模型,得到To ensure that the Transformer only relies on past tokens to predict the current token, the mask matrix MN{\bm{M}}_{N} is set to a matrix of size N×NN\times N, with the elements of the lower part set to 11, and the elements of the upper part set to −∞-\infty. To reduce this to logits in RM\mathbb{R}^{M}, we usually use the last element of the context xk−1∈RD{\bm{x}}_{k-1}\in\mathbb{R}^{D} and apply a linear model, to obtain

θk:=WDxk−1∈RM,{\bm{\theta}}_{k}\coloneqq{\bm{W}}^{D}{\bm{x}}_{k-1}\in\mathbb{R}^{M},

其中 WD∈RM×D{\bm{W}}^{D}\in\mathbb{R}^{M\times D} 是一个可学习的“解嵌入”矩阵。为得到有效的概率分布,我们对 logit θk{\bm{\theta}}_{k} 应用 soft-argmax,where WD∈RM×D{\bm{W}}^{D}\in\mathbb{R}^{M\times D} is a learned “disembedding” matrix. To obtain a valid probability distribution, we apply a soft-argmax on the logits θk{\bm{\theta}}_{k},

πk:=softargmax(θk)∈△M.{\bm{\pi}}_{k}\coloneqq\mathrm{softargmax}({\bm{\theta}}_{k})\in\triangle^{M}.

最后,我们现在可以定义Finally, we can now define

P(Xk=xk∣Xk−N=xk−N,…,Xk−1=xk−1):=[πk]xk.\mathbb{P}(X_{k}=x_{k}\mid X_{k-N}=x_{k-N},\dots,X_{k-1}=x_{k-1})\coloneqq[{\bm{\pi}}_{k}]_{x_{k}}.
注 4.8.3(权重绑定)。Remark 4.8.3 (Weight tying).
与学习一个单独的去嵌入矩阵 WD∈RM×D{\bm{W}}^{D}\in\mathbb{R}^{M\times D} 相比,一种常用技术是令 WD:=(WE)⊤{\bm{W}}^{D}\coloneqq({\bm{W}}^{E})^{\top},其中 WE∈RD×M{\bm{W}}^{E}\in\mathbb{R}^{D\times M} 是第 4.8.6 节中的嵌入矩阵。这种权重绑定减少了需要学习的参数数量,并已被证明在实践中效果良好 [161]。Instead of learning a separate disembedding matrix WD∈RM×D{\bm{W}}^{D}\in\mathbb{R}^{M\times D}, a frequently used technique is to set WD:=(WE)⊤{\bm{W}}^{D}\coloneqq({\bm{W}}^{E})^{\top}, where WE∈RD×M{\bm{W}}^{E}\in\mathbb{R}^{D\times M} is the embedding matrix from Section 4.8.6. This weight tying reduces the number of parameters to learn and is shown to work well in practice [161].

训练Training

我们将 Transformer 的参数(多头注意力、MLP、层归一化)汇总记为 w∈RP{\bm{w}}\in\mathbb{R}^{P}。于是,上下文窗口大小为 NN 的仅解码器 Transformer 定义了一个参数化概率分布Let us gather the Transformer parameters (multi-head attention, MLP, layer norm) as w∈RP{\bm{w}}\in\mathbb{R}^{P}. The decoder-only Transformer with a context window of size NN then defines a parametric probability distribution

pw(x1,…,xL):=∏k=1Lpw(xk∣xk−N,…,xk−1).p_{\bm{w}}(x_{1},\ldots,x_{L})\coloneqq\prod_{k=1}^{L}p_{\bm{w}}(x_{k}\mid x_{k-N},\dots,x_{k-1}).

给定一个序列语料 D\mathcal{D},我们通常通过最大化对数似然来求参数 w∈RP{\bm{w}}\in\mathbb{R}^{P},Given a corpus of sequences D\mathcal{D}, we usually seek the parameters w∈RP{\bm{w}}\in\mathbb{R}^{P} by maximizing the log-likelihood,

Ex∼D[log⁡pw(x1,…,xL)]=Ex∼D[∑k=1Llog⁡pw(xk∣xk−N,…,xk−1)].\mathbb{E}_{x\sim\mathcal{D}}\left[\log p_{\bm{w}}(x_{1},\dots,x_{L})\right]=\mathbb{E}_{x\sim\mathcal{D}}\left[\sum_{k=1}^{L}\log p_{\bm{w}}(x_{k}\mid x_{k-N},\dots,x_{k-1})\right].

这相当于以逐 token 的方式使用 logistic(交叉熵)损失。重要的是,用于预测下一个 token xkx_{k} 的上下文 xk−N,…,xk−1x_{k-N},\dots,x_{k-1} 始终来自数据,而非模型生成的 token。这被称为教师强制,它使 Transformer 的训练高度可并行化。该目标通常使用随机梯度算法近似求解。为最大化 GPU 利用率,通常将长度可变的序列打包在一起以组成批次。This amounts to using a logistic (cross-entropy) loss in a token-wise fashion. Importantly, the context xk−N,…,xk−1x_{k-N},\dots,x_{k-1} used to predict the next token xkx_{k} always comes from the data, not from the tokens generated by the model. This is called teacher forcing and makes Transformer training highly parallelizable. The objective is usually solved approximately using stochastic gradient algorithms. To maximize GPU utilization, sequences of variable lengths are usually packed together in order to form batches.

采样Sampling

上下文窗口大小为 NN 的仅解码器 Transformer,可视为构成一条高阶马尔可夫链,而高阶马尔可夫链是贝叶斯网络的一种特例。因此,要从该模型中生成序列,我们可以采用祖先采样(10.5.3 节),A decoder-only Transformer with a context window of size NN can be seen as forming a higher-order Markov chain, which is a special case of Bayesian network. To generate a sequence from the model, we can therefore use ancestral sampling (Section 10.5.3),

X0\displaystyle X_{0} :=x0\displaystyle\coloneqq x_{0}
X1\displaystyle X_{1} ∼pw(⋅∣X0)\displaystyle\sim p_{\bm{w}}(\cdot\mid X_{0})
X2\displaystyle X_{2} ∼pw(⋅∣X0,X1)\displaystyle\sim p_{\bm{w}}(\cdot\mid X_{0},X_{1})
Xk\displaystyle X_{k} ∼pw(⋅∣Xk−N,…,Xk−1),\displaystyle\sim p_{\bm{w}}(\cdot\mid X_{k-N},\dots,X_{k-1}),

其中 x0x_{0} 表示序列开始(BOS)token。当生成序列结束(EOS)token,或达到最大长度时,采样即停止。所生成的序列是独立同分布的。where x0x_{0} denotes the beginning-of-sequence (BOS) token. The sampling stops when the end-of-sequence (EOS) token is generated or when a maximum length is reached. The generated sequences are i.i.d. .

由于采样一次只产生一个 token,因此这一过程高度串行。Transformer 块按如下方式依次调用:Because sampling happens one token at a time, it is highly sequential. The Transformer block is called sequentially as

Transformer(X0;M1)\displaystyle\mathrm{Transformer}(X_{0};{\bm{M}}_{1})
Transformer(X0,X1;M2)\displaystyle\mathrm{Transformer}(X_{0},X_{1};{\bm{M}}_{2})
…
Transformer(Xk−1,…Xk−N;MN).\displaystyle\mathrm{Transformer}(X_{k-1},\dots X_{k-N};{\bm{M}}_{N}).

为避免反复进行相同的计算,在假定使用因果掩码的前提下,多头注意力(4.8.3 节)中用到的过去的键矩阵与值矩阵通常存入所谓的 KV 缓存。To avoid repeating the same computations again and again, assuming that a causal mask is used, the past key and value matrices used in multi-head attention (Section 4.8.3) are usually stored in the so-called KV cache.

4.8.9 仅编码器架构Encoder-only architectures

仅编码器 Transformer 可用于学习序列的表示。最突出的例子是 BERT [56],其全称为来自 Transformer 的双向编码器表示。BERT 使用不带因果掩码的算法 4(缩写中的“双向”即由此而来)。离散序列元素经 token 编码、位置编码以及可能的段编码转换为向量。出于下文即将说明的原因,每个序列的第一个 token 始终是一个特殊的分类 token [CLS]。训练分为两个阶段:预训练与微调。Encoder-only Transformers can be used for learning to represent sequences. The most prominent example is BERT [56], which stands for bidirectional encoder representations from transformers. BERT uses Algorithm 4 without causal mask (hence “bidirectional” in the acronym). Discrete sequence elements are transformed to vectors using token encoding, positional encoding and potentially segment encoding. For reasons that will become clear below, the first token of every sequence is always a special classification token [CLS]. Training is broken down into two phases: pretraining and finetuning.

预训练Pretraining

由于预训练在无标签语料上进行,因此需要合成预测任务。Since pre-training is performed on an unlabeled corpus, it is necessary to synthetically generate prediction tasks.

在掩码预测中,按一定比例(通常为 15%)对输入 token 随机施加掩码。随后训练模型,依据未被掩码的 token 所提供的上下文,预测被掩码 token 的原始词表 ID。这迫使模型学习一种丰富的、双向的语言表示。掩码策略包括:In masked prediction, a percentage (typically 15%) of the input tokens are randomly masked. The model is then trained to predict the original vocabulary ID of the masked tokens, given the context provided by the unmasked tokens. This forces the model to learn a rich, bidirectional representation of the language. The masking strategy involves:

  • •

    80% 的情况下,将选中的 token 替换为 [MASK];80% of the time, replacing the chosen token with [MASK],

  • •

    10% 的情况下,将选中的 token 替换为词表中的随机 token;10% of the time, replacing the chosen token with a random token from the vocabulary,

  • •

    10% 的情况下,保持选中的 token 不变。10% of the time, keeping the chosen token unchanged.

在下一句预测中,模型被训练以理解两个句子之间的关系。对每个训练样本,BERT 会收到两个句子 AA 和 BB。50% 的情况下,B 是原始文档中紧接 A 之后的真实下一句(标记为 IsNext);另外 50% 的情况下,BB 是语料中的随机句子(标记为 NotNext)。输入序列开头会添加一个特殊的 [CLS] token,其最终隐藏状态用于预测句子 BB 是否紧接句子 A。[SEP] token 用于分隔这两个句子。In next sentence prediction, the model is trained to understand the relationship between two sentences. For each training example, BERT is given two sentences, AA and BB. 50% of the time, B is the actual next sentence that follows A in the original document (labeled IsNext). The other 50% of the time, BB is a random sentence from the corpus (labeled NotNext). A special [CLS] token is prepended to the input sequence, and its final hidden state is used to predict whether sentence BB follows sentence A. The [SEP] token separates the two sentences.

微调Finetuning

在大规模语料上完成预训练后,预训练的 BERT 模型可在预训练的 Transformer 编码器之上添加一个小型的、面向具体任务的输出层,从而针对各类下游 NLP 任务(如文本分类、问答、命名实体识别)进行微调。随后,整个模型(含预训练权重)会在该任务的标注数据上接受微调。分类任务使用与类别 token [CLS] 对应的最终隐藏状态;命名实体识别(NER)、词性标注(POS)等标注任务(token 级分类)使用每个 token 的最终隐藏状态;问答任务通常要在给定文本中找出一个片段(起始 token 与结束 token),则被处理为两个 token 级分类问题:一个针对起始 token,一个针对结束 token。After pre-training on a massive corpus, the pretrained BERT model can be finetuned for various downstream NLP tasks (e.g., text classification, question answering, named entity recognition) by adding a small, task-specific output layer on top of the pre-trained Transformer encoder. The entire model, including the pretrained weights, is then finetuned on the labeled data for the specific task. For classification tasks, the final hidden state corresponding to the class token [CLS] is used. For tagging tasks (token-level classification) such as named entity recognition (NER) or part-of-speech (POS) tagging, the final hidden state of each token is used. For question answering tasks, which usually involve finding a span (start and end token) within a given text, this is treated as two token-level classification problems: one for the start token and one for the end token.

4.8.10 编码器—解码器架构Encoder-decoder architectures

编码器—解码器架构最早见于 Transformer 的奠基性论文 [199],可用于机器翻译、摘要、问答等序列到序列任务。记输入序列为 X{\bm{X}},输出序列为 Y{\bm{Y}}。The encoder-decoder architecture was the original architecture proposed in the seminal Transformer paper [199]. It can be used for sequence-to-sequence tasks, such as machine translation, summarization and question answering. We denote the input sequence by X{\bm{X}} and the output sequence by Y{\bm{Y}}.

编码器Encoder

编码器负责生成输入序列 X{\bm{X}} 的丰富表示 Henc{\bm{H}}_{\mathrm{enc}},以此为后续解码阶段提供上下文。与仅编码器架构相同,这一表示由不带因果掩码的算法 4 得到。多头自注意力层使编码器能够衡量输入序列中不同 token 彼此之间的重要性;对于输入中的每个 token,它都会计算出一个融入了同一序列中其余所有 token 信息的表示。编码器块为各子组件(多头注意力、层归一化、MLP)分别使用各自的参数,其中多头注意力所用的参数为 {WiQ}i=1H\{{\bm{W}}_{i}^{Q}\}_{i=1}^{H}、{WiK}i=1H\{{\bm{W}}_{i}^{K}\}_{i=1}^{H}、{WiV}i=1H\{{\bm{W}}_{i}^{V}\}_{i=1}^{H} 和 WO{\bm{W}}^{O}。The role of the encoder is to produce a rich representation Henc{\bm{H}}_{\mathrm{enc}} of the input sequence X{\bm{X}}, which serves as a context for the subsequent decoding phase. As in encoder-only architectures, this is achieved by using Algorithm 4 without causal mask. The multi-head self-attention layer allows the encoder to weigh the importance of different tokens in the input sequence relative to each other. For each token in the input, it computes a representation that incorporates information from all other tokens in the same sequence. The encoder block uses its own parameters for each sub-component (multi-head attention, layer norm, MLP). In particular, multi-head attention uses parameters {WiQ}i=1H\{{\bm{W}}_{i}^{Q}\}_{i=1}^{H}, {WiK}i=1H\{{\bm{W}}_{i}^{K}\}_{i=1}^{H}, {WiV}i=1H\{{\bm{W}}_{i}^{V}\}_{i=1}^{H} and WO{\bm{W}}^{O}.

解码器Decoder

解码器负责根据编码器给出的编码表示 Henc{\bm{H}}_{\mathrm{enc}} 以及先前生成的 token Y1:t−1{\bm{Y}}_{1:t-1},逐个 token 地生成输出序列 Y{\bm{Y}}。它与编码器的差别在于注意力的施加方式。首先,施加因果多头自注意力,得到与先前生成的 token Y1:t−1{\bm{Y}}_{1:t-1} 相对应的表示 Hdec{\bm{H}}_{\mathrm{dec}}。其次,施加多头交叉注意力。它与多头自注意力的关键区别在于,键、查询和值矩阵定义为The role of the decoder is to generate the output sequence Y{\bm{Y}} one token at a time, based on the encoded representation Henc{\bm{H}}_{\mathrm{enc}} from the encoder and the previously generated tokens Y1:t−1{\bm{Y}}_{1:t-1}. The decoder differs in the way attention is applied. First, we apply causal multi-head self-attention to obtain a representation Hdec{\bm{H}}_{\mathrm{dec}} corresponding to the previously generated tokens Y1:t−1{\bm{Y}}_{1:t-1}. Second, we apply multi-head cross-attention. The key difference with multi-head self-attention is that the key, query and value matrices are defined as

Qidec\displaystyle{\bm{Q}}^{\mathrm{dec}}_{i} :=HdecW′iQ\displaystyle\coloneqq{\bm{H}}_{\mathrm{dec}}{{\bm{W}}^{\prime}}_{i}^{Q}
Kienc\displaystyle{\bm{K}}^{\mathrm{enc}}_{i} :=HencW′iK\displaystyle\coloneqq{\bm{H}}_{\mathrm{enc}}{{\bm{W}}^{\prime}}_{i}^{K}
Vienc\displaystyle{\bm{V}}^{\mathrm{enc}}_{i} :=HencW′iV,\displaystyle\coloneqq{\bm{H}}_{\mathrm{enc}}{{\bm{W}}^{\prime}}_{i}^{V},

其中 {W′iQ}i=1H\{{{\bm{W}}^{\prime}}_{i}^{Q}\}_{i=1}^{H}、{W′iK}i=1H\{{{\bm{W}}^{\prime}}_{i}^{K}\}_{i=1}^{H} 和 {W′iV}i=1H\{{{\bm{W}}^{\prime}}_{i}^{V}\}_{i=1}^{H} 是解码器所用的权重矩阵。此后,与前文类似,再施加 MLP 与层归一化层。where {W′iQ}i=1H\{{{\bm{W}}^{\prime}}_{i}^{Q}\}_{i=1}^{H}, {W′iK}i=1H\{{{\bm{W}}^{\prime}}_{i}^{K}\}_{i=1}^{H} and {W′iV}i=1H\{{{\bm{W}}^{\prime}}_{i}^{V}\}_{i=1}^{H} are the weight matrices used for the decoder. Subsequently, MLP and layer norm layers are applied, similarly as before.

与仅解码器架构的区别Differences with decoder-only architectures

编码器—解码器架构为理解输入和生成输出各设一个专门的组件,能够对输入作双向理解,因此最适合输入序列与输出序列可能分属不同领域或模态的序列到序列(seq2seq)任务。An encoder-decoder architecture provides a dedicated component for understanding the input and another for generating the output. It allows for a bidirectional understanding of the input. It is therefore best suited for sequence-to-sequence (seq2seq) tasks where the input and output sequences may have different domains or modalities.

另一方面,仅解码器模型借助单一而强大的自回归机制,不断预测下一个 token,从而以精简的方式生成文本。话虽如此,正因其结构简单,如今越来越多的序列到序列任务也开始采用仅解码器架构,做法是把输入(提示)置于上下文之前。这意味着输入会受到因果掩码的作用,但模型性能依然十分出色。Decoder-only models, on the other hand, are streamlined for generating text by continuously predicting the next token, leveraging a single, powerful autoregressive mechanism. That being said, due to their simplicity, decoder-only architectures are now increasingly being used even for seq2seq tasks, by prepending the input (prompt) to the context. This means that the input is subject to the causal mask, but the performance remains remarkably strong.

4.9 小结4.9 Summary

  • •

    程序可以用有向无环图进行数学表示。Programs can be mathematically represented as a directed acyclic graph.

  • •

    神经网络是参数化程序。Neural networks are parameterized programs.

  • •

    前馈网络是参数化的计算链。Feedforward networks are parameterized computation chains.

  • •

    多层感知机(MLP)、残差神经网络(ResNet)与卷积神经网络(CNN)都是前馈网络的具体参数化形式。Multilayer perceptrons (MLPs), residual neural networks (ResNets) and convolutional neural networks (CNNs) are all particular parametrizations of feedforward networks.

  • •

    Transformer 块专为处理可变长度序列而设计,但它们对置换具有等变性,因而需要位置编码来利用位置信息。Transformer blocks are designed to process sequences of variable-length, but they are equivariant to permutations and therefore require positional encoding, in order to leverage positional information.