条件语句、循环等控制流是计算机编程不可或缺的组成部分,因为它们使我们能够表达复杂的程序。因此,一个自然的问题是:这些构造能否被纳入可微程序?这正是本章的研究内容。Control flows, such as conditionals or loops, are an essential part of computer programming, as they allow us to express complex programs. It is therefore natural to ask whether these constructs can be included in a differentiable program. This is what we study in this chapter.
控制流依赖于比较运算符,又称关系运算符。形式上,我们可以将比较运算符 定义为从 和 到 的函数。所得的二值(布尔)输出 随后可用于条件语句(见 5.6 节、5.7 节),以决定执行哪一个分支。我们定义以下运算符,如图 5.1 所示:Control flows rely on comparison operators, a.k.a. relational operators. Formally, we can define a comparison operator as a function from and to . The binary (Boolean) output can then be used within a conditional statement (see Section 5.6, Section 5.7) to decide whether to execute one branch or another. We define the following operators, illustrated in Fig. 5.1:
大于:greater than:
小于:less than:
等于:equal:
不等于:not equal:
其中 为 Heaviside 阶跃函数where is the Heaviside step function
Heaviside 阶跃函数是分段常值函数。在 处,该函数不连续;在 处,它连续且导数为零。由于上述比较运算符均以 函数表达,它们都连续且几乎处处可微,且导数恒为零。因此,尽管它们的导数几乎处处良定义,却不携带任何信息,反而会阻碍梯度反向传播。The Heaviside step function is piecewise constant. At , the function is discontinuous. At , it is continuous and has null derivative. Since the comparison operators we presented are all expressed in terms of the function, they are all continuous and differentiable almost everywhere, with null derivative. Therefore, while their derivatives are well-defined almost everywhere, they are uninformative and prevent gradient backpropagation.


为得到不等式运算符的连续松弛,我们可以启发式地将“大于”和“小于”表达式中的阶跃函数替换为 sigmoid 函数 ,其中 为缩放参数。该 sigmoid 函数应满足以下性质:To obtain a continuous relaxation of inequality operators, we can heuristically replace the step function in the expression of “greater than” and “less than” by a sigmoid function , where is a scaling parameter. Such a sigmoid function should satisfy the following properties:
,
,
,
.
满足上述性质的两个 sigmoid 函数例子是 logistic 函数(标准 logistic 分布的 CDF)Two examples of sigmoids satisfying the aforementioned properties are the logistic function (the CDF of the standard logistic distribution)
以及标准高斯分布的 CDF,其定义见式 3.1,and the standard Gaussian’s CDF, defined in Eq. 3.1,
于是,我们可以定义软“大于”We may then define the soft “greater than”
以及软“小于”运算符and the soft “less than”
在极限情形下,当 时,有 。可见,在极限情形下,若 与 相距无穷远,则 输出的值为 。除 logistic 函数与标准高斯分布的 CDF 之外,也可以采用其他 S 形函数,13.6 节对此已有讨论。特别地,对于稀疏 S 形函数,存在一个有限值 ,使得 。In the limit, we have that when . In the limit, therefore outputs a value of if and are infinitely apart. Besides the logistic function and the standard Gaussian’s CDF, other sigmoid functions are possible, as discussed in Section 13.6. In particular, with sparse sigmoids, there exists a finite value such that .
当用于替换阶跃函数的 S 形函数为 logistic 函数或标准高斯分布的 CDF 时,我们便能以更形式化的视角,重新审视前面关于 与 的启发式定义。事实上,对于实数值 与 ,我们可以为其关联随机变量When the sigmoid used to replace the step function is the logistic function or the standard Gaussian’s CDF, we can revisit the previous heuristic definition of and from a more formal perspective. Indeed, to real values and , we can associate random variables
从而构成一个随机过程(这里假定 与 固定)。也可以将其写成thereby forming a stochastic process (we assume that and are fixed). Alternatively, we can also write
其中,对两个分布 与 ,记 为它们的外积 。于是可定义where for two distributions and , we denote by their outer product . We can then define
其中 为随机变量 的累积分布函数(CDF),而 是 与 的函数。类似地可得where is the cumulative distribution function (CDF) of the random variable , and is a function of and . Similarly, we obtain
由此可见,软不等式运算符基于 与 之差的 CDF。We see that the soft inequality operators are based on the CDF of the difference between and .
对于位置—尺度族分布(12.4.1 节),从扰动的角度,我们也可以定义噪声变量 与 ,使得 与 (12.4.1 节)。于是有For location-scale family distributions (Section 12.4.1), from a perturbation perspective, we can also define noise variables and such that and (Section 12.4.1). We then have
当 与 时,有When and , we have
| (5.1) |
记 为标准高斯分布的 CDF,于是得到Denoting the standard Gaussian’s CDF, we then obtain
其中 。对于 与 ,相应的分布为高斯噪声。where . The corresponding distribution for and is Gaussian noise.
当 与 时,有When and , we have
| (5.2) |
于是得到(另见命题 14.5.3)We then obtain (see also Proposition 14.5.3)
对于 与 ,相应的分布为 Gumbel 噪声。The corresponding distribution for and is Gumbel noise.
通过下式即可轻松恢复“硬”不等式运算符We easily recover the “hard” inequality operator by
其中 ,且 为 delta 分布,它将概率 赋予 。where and where is the delta distribution that assigns a probability of to .
相等运算符 可视为数值之间一种极端的相似度函数,其输出只能是 或 。因此,若要定义软相等运算符,一个自然的思路便是用更一般的相似度函数取代相等运算符。相似度函数应在 处取得最大值,并随 与 相互远离而递减。核函数便是一类常见的相似度函数。简言之,核 可看作内积The equality operator can be seen as an extreme kind of similarity function between numbers, that can only output the values or . To define soft equality operators, a natural idea is therefore to replace the equality operator by a more general similarity function. A similarity function should achieve its maximum at and it should decrease as and move apart. A common family of similarity functions are kernels. Briefly, a kernel can be seen as the inner product
在某个(可能是无穷维的)空间 中, 与 的嵌入 与 之间的内积(确切地说,该空间是再生核希尔伯特空间);关于核的深入综述参见 [178, 185]。为得到 与 之间近似于相等运算符的相似度度量,我们可以做归一化处理,得到between the embeddings and of and in some (potentially infinite-dimensional) space , a reproducing kernel Hilbert space to be precise; see [178, 185] for an in-depth review of kernels. To obtain a similarity measure between and approximating the equality operator, we can normalize to obtain
其中 。这便是 与 之间的余弦相似度。where . This is the cosine similarity between and .
一类特殊的核是各向同性核,其形式为A particular kind of kernel is isotropic kernels of the form
其取值只取决于输入之间的差。当核带有尺度参数 时,我们将其记作 。据此,可将软相等运算符定义为that depend only on the difference between inputs. When the kernel has a scale parameter , we use the notation . We can then define a soft equality operator as
各向同性核有多种可选,例如高斯核Several isotropic kernels can be chosen such as the Gaussian kernel
或 logistic 核or the logistic kernel
其中我们定义了双曲正割where we defined the hyperbolic secant
正如其名称所示,这些核可从概率视角自然导出,下文将对此加以介绍。As their names suggest, these kernels arise naturally from a probabilistic perspective, that we present below.
图 5.2 给出了用这些核得到的软相等运算符。直观地说,我们将位于 处的一根竖条替换成了一个隆起函数。用 logistic 核得到的软相等运算符,与 [153] 以另一种方式得到的表达式(见其式 9)相吻合。The soft equality operators obtained with these kernels are illustrated in Fig. 5.2. Intuitively, we replaced a bar located at with a bump function. The soft equality operator obtained with the logistic kernel coincides with the expression [153] arrive at (see their Eq. 9), in a different manner.
我们再次采用随机过程视角,在此视角下将随机变量关联起来We again adopt the stochastic process perspective, in which we associate random variables
与实数值 和 相关联。然而,要处理相等运算符,我们不能简单地使用 的期望,因为to real values and . However, to handle the equality operator, we cannot simply use the expectation of since
设 与 为相互独立的连续变量。尽管我们不能直接使用 的概率,也不能等价地使用 的概率,但仍可考虑采用 的概率密度函数(PDF),并取其于 处的值。为确保该函数在 处取得最大值 ,可对该 PDF 加以归一化,从而定义 and being independent continuous variables. While we cannot use the probability of , or equivalently of , we can consider using the probability density function (PDF) of evaluated at . To ensure that the maximum is achieved at with value , we can normalize the PDF to define
其中 (此处假设 在 处取得最大值)。众所周知,两个随机变量之和的 PDF 即为二者各自 PDF 的卷积。由此可得where (we assume that attains its maximum at ). It is well-known that the PDF of the sum of two random variables is the convolution of their respective PDFs. We therefore have
特别地,当 时,若 为服从位置—尺度族分布的随机变量的 PDF,则可得In particular, with , if is the PDF of a location-scale family distributed random variable, we obtain
我们确实得到了一个内积,因而也就得到了一个核函数。We indeed recover an inner product and therefore a kernel.
虽然 ,但我们也可以改用 作为软相等的一种替代刻画。对任意随机变量 ,均有While , we can also consider using as an alternative notion of soft equality. For any random variable , we have
因此,Therefore,
据此,还可推出 的 PDF 为We can also derive the PDF of as
特别地and in particular
因此Therefore
这也进一步说明,取 的 PDF 在 处的值是合理的。当 服从正态分布时, 服从所谓的折叠正态分布。further justifying using the PDF of evaluated at . When follows a normal distribution, follows the so-called folded normal distribution.
当 、 时,由式 5.1 可得When and , we obtain from Eq. 5.1
从而so that
我们确实得到了 ,其中 为高斯核,。至于绝对差的 CDF,则可得We indeed recover , where is the Gaussian kernel with . For the CDF of the absolute difference, we obtain
当 、 时,回顾When and , recalling that
由式 5.2 可得we obtain from Eq. 5.2
从而so that
我们确实得到了 ,其中 为 logistic 核,。We indeed recover , where is the logistic kernel with .
前一种方法是将 和 映射为两个相互独立的随机变量 和 (这里假定 和 固定不变)。我们也可以换一种做法:将 和 映射为两个彼此相依的随机变量 和 ,其协方差取决于 与 之间的相似度。借助高斯过程[95],即可实现这一做法。The previous approach relied on mapping and to two independent random variables and (we assume that and are fixed). Instead, we can consider mapping and to two dependent random variables and , whose covariance depends on the similarity between and . We can do so by using a Gaussian process [95].
上的高斯过程,是以 为索引的随机过程 :对任意一组与 相对应的 个随机变量 ,它们都构成多元高斯随机变量。高斯过程由均值函数 与协方差函数 共同刻画。均值函数可直接取 ;协方差函数则须保证高斯过程中任意随机变量组合的方差非负,而核函数恰好满足这一性质。因此可以定义A Gaussian process on is a stochastic process indexed by such that any subset of random variables associated with is a multivariate Gaussian random variable. The Gaussian process is characterized by the mean function , and its covariance function . For the mean function, we may simply choose . For the covariance function, we need to ensure that the variance of any combination of random variables in the Gaussian process is non-negative. This property is satisfied by kernel functions. We can therefore define
其中 为某个核函数。有了这种从实数到随机变量的映射,还需给出随机变量之间相似度的度量,一个自然的选择是它们的相关性for some kernel . Equipped with such a mapping from real numbers to random variables, we need a measure of similarity between random variables. A natural choice is their correlation
于是得到We therefore obtain
这与前文所述的余弦相似度度量一致。特别地,当 且 时,便得到先前启发式定义的软相等运算符which coincides with the cosine similarity measure we saw before. In the particular case and when , we then recover the previous heuristically defined soft equality operator
逻辑运算符可用于实施布尔代数运算。形式上,可将其定义为从 到 的函数。例如,and(逻辑合取,又称逻辑积)、or(逻辑析取,又称逻辑和)与 not(逻辑否定,又称逻辑补)运算符的定义为Logical operators can be used to perform Boolean algebra. Formally, we can define them as functions from to . The and (logical conjunction a.k.a. logical product), or (logical disjunction a.k.a. logical addition) and not (logical negation a.k.a. logical complement) operators, for example, are defined by
这些运算符的经典性质包括Classical properties of these operators include
交换律:Commutativity:
结合律:Associativity:
and 对 or 的分配律:Distributivity of and over or:
单位元:Neutral element:
De Morgan 定律:De Morgan’s laws:
更一般地,对于二值向量 ,可将 all(全称量化,)与 any(存在量化,)运算符——即从 到 的函数——定义为More generally, for a binary vector , we can define all (universal quantification, ) and any (existential quantification, ) operators, which are functions from to , as
以及and
and、or 与 not 运算符还可等价地写作We can equivalently write the and, or and not operators as
以上定义都是此前那些定义的扩展:可将它们用作定义在 上的函数,如图 5.3 所示。这意味着,借助 5.2 节中定义的软比较运算符,便可得到 。同理,也可定义 all 与 any 的连续扩展,它们是定义在 上、取值于 的函数,即These are extensions of the previous definitions: we can use them as functions from , as illustrated in Fig. 5.3. This means that we can use the soft comparison operators defined in Section 5.2 to obtain . Likewise, we can define continuous extensions of all and any, which are functions from to , as
从概率的角度看,若令 与 为两个相互独立的随机变量,分别服从参数为 与 的 伯努利分布,则From a probabilistic perspective, if we let and be two independent random variables distributed according to Bernoulli distributions with parameters and , then
在概率论中,这三个式子分别对应两个独立变量的乘积法则、加法法则和补集法则。In probability theory, these correspond to the product rule of two independent variables, the addition rule, and the complement rule.
同理,若令 为服从参数为 的多元 伯努利分布的随机变量,则Likewise, if we let be a random variable distributed according to a multivariate Bernoulli distribution with parameters , then
以上两式分别是概率的链式法则,以及 个独立变量的概率加法法则。These are the chain rule of probability and the addition rule of probability for independent variables.
更一般地,模糊逻辑文献 [108, 102] 引入了三角范数与余范数的概念,分别用以给出 and 与 or 运算符的连续松弛。More generally, in the fuzzy logic literature [108, 102], the concepts of triangular norms and co-norms have been introduced to provide continuous relaxations of the and and or operators, respectively.
前文给出的 and 与 or 的概率式扩展,正是三角范数与余范数的示例,表 5.1 中还列出了更多例子。借助这些运算符的结合律性质,可将它们推广到向量 ,从而定义 all 与 any 运算符的连续扩展,如表 5.2 所示。更多示例与分析,例如可参见 [198,第 2 章和第 3 章]。The previously-defined probabilistic extensions of and and or are examples of triangular norms and conorms. More examples are given in Table 5.1. Thanks to the associative property of these operators, we can generalize them to vectors to define continuous extensions of the all and any operators, as shown in Table 5.2. For more examples and analysis, see for instance [198, Chapters 2 and 3].


| t-范数(松弛后的 and)t-norm (relaxed and) | t-余范数(松弛后的 or)t-conorm (relaxed or) | |
|---|---|---|
| 概率的Probabilistic | ||
| 极值Extremum | ||
| ŁukasiewiczŁukasiewicz |
| All()All () | Any()Any () | |
|---|---|---|
| 概率性Probabilistic | ||
| 极值Extremum | ||
| ŁukasiewiczŁukasiewicz |
if-else 语句依据条件执行不同的代码。形式上,可将 函数定义为An if-else statement executes different code depending on a condition. Formally, we can define the function by
| (5.3) | ||
变量 称为谓词。它是一个二值(布尔)变量,因此当 时,函数 无定义。于是,该函数关于 既不连续也不可微。另一方面,分别对应假分支与真分支的 与 可以是连续变量。若 ,则函数关于 为线性,关于 为常值。反之,若 ,则函数关于 为线性,关于 为常值。下面讨论如何对 求导。The variable is called the predicate. It is a binary (Boolean) variable, making the function undefined if . The function is therefore discontinuous and nondifferentiable w.r.t. . On the other hand, and , which correspond to the false and true branches, can be continuous variables. If , the function is linear w.r.t. and constant w.r.t. . Conversely, if , the function is linear w.r.t. and constant w.r.t. . We now discuss how to differentiate through .
当 固定时, 是关于 与 的良定义函数,因而可作为计算图中的一个节点使用(8.3 节)。由于它关于 与 具有线性性,可得其关于 与 的雅可比矩阵分别为For fixed, is a valid function w.r.t. and , and can therefore be used as a node in a computational graph (Section 8.3). Due to the linearity w.r.t. and , we obtain that the Jacobians w.r.t. and are
与and
其中 为适当大小的单位矩阵。if-else 语句大多会与其他函数组合使用。设 与 为可微函数,并定义 与 ,其中 ,。于是,、 与 的组合即为由下式定义的函数 :where is the identity matrix of appropriate size. Most of the time, if-else statements are composed with other functions. Let and be differentiable functions. We then define and , where and . The composition of , and is then the function defined by
由此可得其雅可比矩阵为We obtain that the Jacobians are
与and
只要 与 是可微函数,我们便可毫无障碍地通过分支变量 与 求导。真正棘手的是谓词变量 ,下面就来讨论这一点。As long as and are differentiable functions, we can therefore differentiate through the branch variables and without any issue. More problematic is the predicate variable , as we now discuss.
谓词变量 是二值的,因而无法直接求导。不过, 可以是某个比较运算符的输出。例如,假设我们想表达由下式定义的函数 :The predicate variable is binary and therefore cannot be differentiated directly. However, can be the output of a comparison operator. For example, suppose we want to express the function defined by
采用我们的记号,上式可改写为Using our notation, this can be rewritten as
Heaviside 阶跃函数在 处不连续,但在所有 上连续且可微,导数为 。因此,函数 关于 的导数为零。The Heaviside step function has a discontinuity at , but it is continuous and differentiable with derivative for all . The function therefore has null derivative w.r.t. ,
换言之,虽然 关于 (对于 )有良定义的导数,但这些导数并不提供有用信息。作为另一个例子,现在我们考虑函数In other words, while has well-defined derivatives w.r.t. for , the derivatives are uninformative. As another example, let us now consider the function
其中 是某个可微函数。这一次, 同时影响谓词与真分支。于是,利用命题 2.3.12 可得for some differentiable function . This time, influences both the predicate and the true branch. Then, using Proposition 2.3.12, we obtain
换言之,谓词 的导数不会影响 的导数。In other words, the derivatives of the predicate do not influence the derivatives of .
幸运的是,我们还记得Fortunately, we recall that
该函数完全良定义,即使 取代了 。也就是说,该定义将式 5.3 从离散集合 扩展到连续的单位线段 。我们已经看到This function is perfectly well-defined, even if , instead of . That is, this definition is an extension of Eq. 5.3 from the discrete set to the continuous unit segment . We saw that
其中我们用 表示一个将 映射到 的可微 S 形函数。例如,我们可以使用 logistic 函数或标准高斯分布的 CDF。如果我们现在定义where we use to denote a differentiable S-shaped function mapping to . For instance, we can use the logistic function or the standard Gaussian’s CDF. If we now define
| (5.4) |
则雅可比矩阵变为the Jacobian becomes
若 或 ,则雅可比矩阵处处非零,从而使梯度能够通过计算图反向传播。这是第四部分所研究的平滑的一个例子。If or , the Jacobian is non-null everywhere, allowing gradients to backpropagate through the computational graph. This is an example of smoothing as studied in Part IV.
从概率视角看,我们可以把式 5.4 视为 的期望,其中 是一个服从参数为 的 伯努利分布的二值随机变量:From a probabilistic perspective, we can view Eq. 5.4 as the expectation of , where is a binary random variable distributed according to a Bernoulli distribution with parameter :
对两个可能分支取期望,使该函数关于 可微,因为 是可微的。当然,这样做的代价是需要对两个分支都求值,而不是只求值其中一个分支。概率视角还表明,如有需要,我们也可以按下式计算方差:Taking the expectation over the two possibles branches makes the function differentiable with respect to , since is differentiable. Of course, this comes at the cost of evaluating both branches, instead of a single one. The probabilistic perspective suggests that we can also compute the variance if needed as
概率视角还提示,可以采用不同的尺度来定义平滑,如图 5.6 所示。The probabilistic viewpoint also suggests different scales at which a smoothing can be defined as illustrated in Fig. 5.6.
另一种视角 [153] 基于 logistic 分布。事实上,若 是服从均值为 、尺度为 的 logistic 分布的随机变量,则如我们在注 3.3.1 中所见,其 CDF 为 ,因此Another perspective [153] is based on the logistic distribution. Indeed, if is a random variable following a logistic distribution with mean and scale , we saw in Remark 3.3.1 that the CDF is and therefore
上一节关注的是 if-else 语句,即只有两个分支的条件语句。现在我们将研究推广到包含 else-if 语句的条件语句,这类语句有 个分支。In the previous section, we focused on if-else statements: conditionals with only two branches. We now generalize our study to conditionals including else-if statements, that have branches.
对于只有 个分支的条件语句,我们用二值变量 来编码条件语句需要走的分支。对于有 个分支的条件语句,我们需要一种方式来编码条件语句需要走 个分支中的哪一个。为此,我们可以使用向量 ,其中 表示标准基向量(又称 one-hot 向量)For conditionals with only branches, we encoded the branch that the conditional needs to take using the binary variable . For conditionals with branches, we need a way to encode which of the branches the conditional needs to take. To do so, we can use a vector , where denotes the standard basis vector (a.k.a. one-hot vector)
即一个在第 个坐标处为 1、其余 个坐标为零的向量。向量 是 分类变量 的编码。a vector with a single one in the coordinate and zeros. The vector is the encoding of a categorical variable .
要构造这样的向量 ,我们可以组合前面定义的比较运算符和逻辑运算符来定义 。不过,必须确保只有一个 非零。例 5.7.1 给出了一个例子。To form such a vector , we can combine the previously-defined comparison and logical operators to define . However, we need to ensure that only one is non-zero. We give an example in Example 5.7.1.
构造 的另一条途径,是使用 argmax 和 argmin 算子Another way to form is to use the argmax and argmin operators
它们可以看作大于和小于运算符的自然推广。遇到并列情形时,我们任意打破平局。They can be seen as a natural generalization of the greater than and less than operators. In case of ties, we break them arbitrarily.
现在,我们可以把条件语句表示为函数 ,其定义为We can now express a conditional statement as the function
defined by
| (5.5) | ||
与 函数类似, 函数关于 不连续且不可微。不过,若对某个 固定 ,则该函数关于 是线性的,并在 时关于 为常值。下面用一个简单例子说明如何借助这一形式化来表达。Similarly to the function, the function is discontinuous and nondifferentiable w.r.t. . However, given fixed for some , the function is linear in and constant in for . We illustrate how to express a simple example, using this formalism.
当 固定时, 是关于 的有效函数,因而仍可作为计算图中的一个节点使用。由于关于 具有线性性,可得关于 的雅可比矩阵为For fixed, is a valid function w.r.t. , and can therefore again be used as a node in a computational graph. Due to the linearity w.r.t. , we obtain that the Jacobian w.r.t. is
设 为可微函数,且 。若定义复合Let be a differentiable function and . If we define the composition
则可得关于 的雅可比矩阵为we then obtain that the Jacobian w.r.t. is
只要各 函数可微,我们就能在 固定时通过分支变量 求导。As long as the functions are differentiable, we can therefore differentiate through the branch variables for fixed.
正如我们所见, 既可以由比较运算符和逻辑运算符组合得到,也可以由 argmax 和 argmin 算子得到。下面说明这些算子为何会带来问题。例如,假设我们希望表示函数As we saw, can be obtained by combining comparison and logical operators, or it can be obtained by argmax and argmin operators. We illustrate here why these operators are problematic. For example, suppose we want to express the function
采用我们的记号,这可以表示为In our notation, this can be expressed as
与 ifelse 情形一样,关于 的雅可比矩阵几乎处处为零,As for the ifelse case, the Jacobian w.r.t. is null almost everywhere,
与 Heaviside 阶跃函数类似,argmax 和 argmin 函数也是分段常值函数,并在出现平局时不连续。它们的雅可比矩阵几乎处处为零,在出现平局时则无定义。因此,尽管其雅可比矩阵几乎处处良定义,它们却不提供有用信息,还会阻碍梯度反向传播。我们可以用 softargmax 替换 argmaxSimilarly to the Heaviside step function, the argmax and argmin functions are piecewise constant, with discontinuities in case of ties. Their Jacobians are zero almost everywhere, and undefined in case of ties. Therefore, while their Jacobian is well-defined almost everywhere, they are uninformative and prevent gradient backpropagation. We can replace the argmax with a softargmax
类似地and similarly
argmax 的其他松弛方式同样可行,详见 13.7 节。关于扰动的视角,另见 14.5.3 节。Other relaxations of the argmax are possible, as discussed in Section 13.7. See also Section 14.5.3 for the perturbation perspective.
幸运的是,该定义Fortunately, the definition
若以 代替 ,该定义便完全成立,因此可视为式 5.5 的推广。此时若定义is perfectly valid if we use instead of , and can therefore be seen as an extension of Eq. 5.5. If we now define
| (5.6) |
雅可比矩阵变为the Jacobian becomes
它处处非零,因而梯度得以沿计算图反向传播。which is non-null everywhere, allowing gradients to backpropagate through the computational graph.
从概率视角看,式 5.6 可视为 的期望,其中 是服从以 为参数的 分类分布的 分类随机变量:From a probabilistic perspective, we can view Eq. 5.6 as the expectation of , where is a categorical random variable distributed according to a categorical distribution with parameter :
对 个可能分支取期望,可使函数关于 可微,代价则是需要计算所有分支,而非只计算单个分支。与 if-else 情形类似,如有需要,方差可按如下方式计算Taking the expectation over the possible branches makes the function differentiable with respect to , at the cost of evaluating all branches, instead of a single one. Similarly as for the if-else case, we can compute the variance if needed as
图 5.7 对此作了说明。This is illustrated in Fig. 5.7.
for 循环是一种控制流,用于依次调用固定数目 个函数,并复用上一次迭代的输出。就最一般的情形而言,for 循环可写为如下形式。For loops are a control flow for sequentially calling a fixed number of functions, reusing the output from the previous iteration. In full generality, a for loop can be written as follows.
如图 5.9 所示,这定义了一条计算链。若各函数 均可微,便定义了一个有效的计算图,因此我们可以借助自动微分,对 关于其输入 求导。4.2 节回顾的前馈网络可视为参数化的 for 循环,即As illustrated in Fig. 5.9, this defines a computation chain. Assuming the functions are all differentiable, this defines a valid computation graph, we can therefore use automatic differentiation to differentiate w.r.t. its input . Feedforward networks, reviewed in Section 4.2, can be seen as parameterized for loops, i.e.,
其中 为某个可微函数。for some differentiable function .
图 5.9:scan 函数的计算图。序列到序列 RNN 可视为参数化的 scan 函数。
Figure 5.9: Computation graph of the scan function.
Sequence-to-sequence RNNs can be seen as a parameterized scan function.
scan 是源自函数式编程的高阶函数(即函数的函数)。它可用于对各个元素 执行某种操作 ,并将该操作的结果 传递至下一次迭代。Scan is a higher-order function (meaning a function of a function) originating from functional programming. It is useful to perform an operation on individual elements while carrying the result of that operation to the next iteration.
如图 5.9 所示,这同样定义了一个有效的计算图;只要函数 可微,便可以用自动微分对其求导。4.7 节讨论的序列到序列 RNN 可以视为参数化的 scan。这一抽象的优越之处在于,并行 scan 算法在计算机科学中已有广泛研究 [25, 182]。As illustrated in Fig. 5.9, this again defines a valid computational graph and can be differentiated through using autodiff, assuming the function is differentiable. Sequence-to-sequence RNNs, reviewed in Section 4.7, can be seen as a parameterized scan. An advantage of this abstraction is that parallel scan algorithms have been studied extensively in computer science [25, 182].
while 循环是一种控制流:它重复执行某项操作,并复用上一次迭代的输出,直至某个条件得到满足。设 是判断应当停止()还是继续()的函数, 是执行操作的函数。于是,不失一般性,while 循环可以写成如下形式。A while loop is a control flow used to repeatedly perform an operation, reusing the output of the previous iteration, until a certain condition is met. Suppose is a function to determine whether to stop () or continue () and is a function for performing an operation. Then, without loss of generality, a while loop can be written as follows.
这个定义在某种程度上是循环的,因为我们使用了 while 关键字。不过,我们也可以等价地把该算法改写为递归形式。This definition is somewhat cyclic, as we used the while keyword. However, we can equivalently rewrite the algorithm recursively.
与 for 循环和 scan 不同,while 循环的迭代次数事先未知,甚至可能无限。就这一点而言,while 循环可以视为一个循环图,如图 5.10 所示。Unlike for loops and scan, the number of iterations of while loops is not known ahead of time, and may even be infinite. In this respect, a while loop can be seen as a cyclic graph, as illustrated in Fig. 5.10.
我们还可以用 5.6 节定义的 函数,把算法 4 实现为We can also implement Algorithm 4 in terms of the function defined in Section 5.6 as
然而,为避免无限递归,关键在于 必须支持惰性求值。也就是说,上面定义中的 当且仅当 时才应当被求值。换言之, 这一事实对于保证递归的良定义至关重要。However, to avoid an infinite recursion, it is crucial that supports lazy evaluation. That is, in the definition above should be evaluated if and only if . In other words, the fact that is crucial to ensure that the recursion is well-defined.
为避免无界 while 循环带来的问题,我们可以强制 while 循环在 次迭代后停止,即截断 while 循环。展开算法 4 可得(此处取 )To avoid the issues with unbounded while loops, we can enforce that a while loop stops after iterations, i.e., we can truncate the while loop. Unrolling Algorithm 4 gives (here with )
| elseelse | |
| else else | |
| else else | |
借助 函数,我们可以将其改写为Using the function, we can rewrite it as
而这本身又等价于which is itself equivalent to
更一般地,对于 ,公式为More generally, for , the formula is
其中我们定义了where we defined
另见 [153]。若进一步引入简记See also [153]. If we further define the shorthand notation
使得 是一个离散概率分布,包含在 次迭代中每一次停止的概率,那么我们就可以用条件语句改写截断 while 循环的输出,so that is a discrete probability distribution containing the probabilities to stop at each of the iterations, we can rewrite the output of a truncated while using a conditional,
如图 5.11 所示。This is illustrated in Fig. 5.11.
给定函数 与初始化 ,while 循环的取值只能落在由 所定义的离散取值集合 中。若 while 循环无界,则该集合可能是可数无限的;若 while 循环保证会停止,则该集合是有限的。循环是从状态 转移到状态 ,还是停留在 ,由停止准则 决定。因此,为了对 while 循环的状态建模,我们可以考虑一个离散空间为 的马尔可夫链(该空间总可以与 等同),其转移概率为Given the function and the initialization , a while loop can only go through a discrete set of values defined by . This set is potentially countably infinite if the while loop is unbounded, and finite if the while loop is guaranteed to stop. Whether the loop moves from the state to the state , or stays at , is determined by the stopping criterion . To model the state of the while loop, we can then consider a Markov chain with a discrete space , which we can always identify with , with transition probabilities
而初始状态为 。这里, 是循环在第 次迭代时的取值。注意,由于 ,这些 个取值是“退化”的概率。不过,这一框架让我们能够自然地推广到 while 循环的光滑版本。为说明该框架,若 while 循环在 处停止,则转移概率可以写成一个矩阵and initial state . Here, is the value at iteration of the loop. Note that since , the values are “degenerate” probabilities. However, this framework lets us generalize to a smooth version of the while loop naturally. To illustrate the framework, if the while loop stops at , the transition probabilities can be cast as a matrix
while 循环的输出 由状态停留在同一取值上的时刻决定The output of the while-loop is determined by the time at which the state stays at the same value
注意, 本身是一个随机变量,因为它由 这些变量定义。它被称为停时。于是该链的输出为Note that itself is a random variable, as it is defined by the variables. It is called a stopping time. The output of the chain is then
由于停时无法事先得知,对 的求和从 到 。然而,若我们在停止准则中强制 while 循环运行的迭代次数不超过 ,即令Because the stopping time is not known ahead of time, the sum over goes from to . However, if we enforce in the stopping criterion that the while loop runs no longer than iterations, by setting
我们便自然地重新得到此前通过展开 while 循环所得到的表达式,we then naturally recover the expression found by unrolling the while loop before,
例如,当 时,转移概率矩阵为For example, with , the transition probability matrix is
借助这一框架,只要我们平滑掉谓词,甚至可以通过 while 循环的停止准则进行反向传播。例如,我们看到例 5.10.1 中的停止准则为 ,因此With the help of this framework, we can backpropagate even through the while loop’s stopping criterion, provided that we smooth out the predicate. For example, we saw that the stopping criterion in Example 5.10.1 is and therefore
由于 函数的作用,while 循环关于 的导数恒为 ,这与 if-else 语句的情形相同。若把停止准则改为 ,则有(回想一下, 在 上是良定义的)Due to the function, the derivative of the while loop with respect to will always be , just like it was the case for if-else statements. If we change the stopping criterion to , we then have (recall that is well defined on )
取 时,我们得到更具信息量的导数。特别地,当 时,关于 的导数恒不为零。平滑后的输出仍如前述表示为期望With , we obtain more informative derivatives. In particular, with , the derivatives w.r.t. are always non-zero. The smoothed output is expressed as before as the expectation
其中where
我们也可以不强制迭代 次,而是在停止概率足够高时停止 [153],前提是停止概率收敛到 。Instead of enforcing a number of iterations, it is also possible to stop when the probability of stopping becomes high enough [153], assuming that the probability of stopping converges to .
对于条件语句,我们已经看到:在谓词固定的前提下,对分支变量求导并无问题。For conditionals, we saw that differentiating through the branch variables is not problematic given a fixed predicate.
然而对于谓词变量,我们看到必须引入可微松弛,才能避免导数为零。However, for the predicate variable, we saw that a differentiable relaxation is required to avoid null derivatives.
我们以原则性的方式引入了软比较运算符,所借助的是随机过程视角,以及逻辑运算符的连续扩展。We introduced soft comparison operators in a principled manner, using a stochastic process perspective, as well as the continuous extension of logical operators.
for 循环与 scan 定义的都是有效的计算图,因为它们的迭代次数事先已经确定。前馈网络与 RNN 则可分别视为参数化的 for 循环与 scan。For loops and scan define valid computational graphs, as their number of iterations is fixed ahead of time. Feedforward networks and RNNs can be seen as parameterized for loops and scan, respectively.
与 for 循环和 scan 不同,while 循环的迭代次数事先未知,甚至可能无穷。不过,展开的 while 循环定义的是有效的有向无环图。借助马尔可夫链视角,我们给出了一种有原则的方法,可以对 while 循环的停止准则进行求导。Unlike for loops and scan, the number of iterations of while loops is not known ahead of time and may even be infinite. However, unrolled while loops define valid directed acyclic graphs. We defined a principled way to differentiate through the stopping criterion of a while loop, thanks to a Markov chain perspective.