学习资料 理解深度学习 第 18 章 · 扩散模型
学 习 资 料 · 中 英 对 照

第 18 章 · 扩散模型

Understanding Deep Learning — Diffusion models

扩散模型
Diffusion models

Chapter 15 described generative adversarial models, which produce plausible-looking samples but do not define a probability distribution over the data. Chapter 16 discussed normalizing flows. These do define such a probability distribution but must place architectural constraints on the network; each layer must be invertible, and the determinant of its Jacobian must be easy to calculate. Chapter 17 introduced variational autoencoders, which also have a solid probabilistic foundation but where the computation of the likelihood is intractable and must be approximated by a lower bound.

This chapter introduces diffusion models. Like normalizing flows, these are probabilistic models that define a nonlinear mapping from latent variables to the observed data where both quantities have the same dimension. Like variational autoencoders, they approximate the data likelihood using a lower bound based on an encoder that maps to the latent variable. However, in diffusion models, this encoder is predetermined; the goal is to learn a decoder that is the inverse of this process and can be used to produce samples. Diffusion models are easy to train and can produce very high-quality samples that exceed the realism of those produced by GANs. The reader should be familiar with variational autoencoders (chapter 17) before reading this chapter.

第 15 章描述了生成对抗模型,它们能够生成看似合理的样本,但并未定义数据上的概率分布。第 16 章讨论了归一化流。它们确实定义了这样的概率分布,但必须对网络施加架构约束;每一层都必须是可逆的,并且其雅可比行列式必须易于计算。第 17 章介绍了变分自编码器,它们同样具有坚实的概率基础,但似然的计算不可处理,必须用下界来近似。

本章介绍扩散模型。与归一化流一样,这些概率模型定义了从隐变量到观测数据的非线性映射,并且这两个量具有相同的维度。与变分自编码器一样,它们使用基于编码器的下界来近似数据似然,该编码器映射到隐变量。然而,在扩散模型中,这个编码器是预先确定的;目标是学习一个解码器,它是该过程的逆过程,并可用于生成样本。扩散模型易于训练,并且能够产生非常高质量的样本,其真实感超过 GAN 生成的样本。读者在阅读本章之前应熟悉变分自编码器(第 17 章)。

18.1 概述
18.1 Overview

A diffusion model consists of an encoder and a decoder.

The encoder takes a data sample x and maps it through a series of intermediate latent variables z 1... z T. The decoder reverses this process; it starts with z T and maps back through z T −1,..., z 1 until it finally (re-)creates a data point x. In both encoder and decoder, the mappings are stochastic rather than deterministic.

一个扩散模型由一个编码器和一个解码器组成。编码器接收一个数据样本 x,并通过一系列中间隐变量 z 1... z T 对其进行映射。解码器逆转这一过程;它从 z T 开始,并反向映射经过 z T −1,..., z 1,直到最终(重新)生成一个数据点 x。在编码器和解码器中,映射都是随机而非确定性的。

The encoder is prespecified; it gradually blends the input with samples of white noise (figure 18.1). With enough steps, the conditional distribution q( z T | x ) and marginal distribution q( z T) of the final latent variable both become the standard normal distribution. Since this process is prespecified, all the learned parameters are in the decoder. In the decoder, a series of networks are trained to map backward between each

adjacent pair of latent variables z t and z t−1. The loss function encourages each network to invert the corresponding encoder step. The result is that noise is gradually removed from the representation until a realistic-looking data example remains. To generate a new data example x, we draw a sample from q( z T) and pass it through the decoder.

编码器是预先指定的;它逐渐将输入与白噪声样本混合(图 18.1)。经过足够多的步骤后,最终隐变量的条件分布 q (z T | x) 和边际分布 q (z T) 都会变成标准正态分布。由于此过程是预先指定的,所有学习到的参数都在解码器中。在解码器中,一系列网络被训练用于在每一之间进行反向映射

相邻隐变量对 z t 和 z t−1。损失函数促使每个网络反转相应的编码器步骤。结果是,表示中的噪声被逐渐去除,直到留下一个看起来真实的数据示例。为了生成新的数据示例 x,我们从 q (z T) 中抽取一个样本,并将其送入解码器。

图 18.1 扩散模型。编码器(前向过程,或扩散过程)将输入 x 映射到一系列隐变量 z 1... z T。该过程是预先指定的,并逐步将数据与噪声混合,直到只剩
图 18.1 扩散模型。编码器(前向过程,或扩散过程)将输入 x 映射到一系列隐变量 z 1... z T。该过程是预先指定的,并逐步将数据与噪声混合,直到只剩下噪声。解码器(反向过程)是学习得到的,并将数据沿隐变量反向传回,在每个阶段去除噪声。训练完成后,通过采样噪声向量 z T,并将其通过解码器来生成新样本。Figure 18.1 Diffusion models. The encoder (forward, or diffusion process) maps the input x through a series of latent variables z 1... z T. This process is prespecified and gradually mixes the data with noise until only noise remains. The decoder (reverse process) is learned and passes the data back through the latent variables, removing noise at each stage. After training, new examples are generated by sampling noise vectors z T and passing them through the decoder.

In section 18.2, we consider the encoder in detail. Its properties are non-obvious but are critical for the learning algorithm.

In section 18.3, we discuss the decoder. Section 18.4 derives the training algorithm, and section 18.5 reformulates it to be more practical.

Section 18.6 discusses implementation details, including how to make the generation conditional on text prompts.

在第 18.2 节中,我们详细讨论编码器。其性质并不显然,但对学习算法至关重要。在第 18.3 节中,我们讨论解码器。第 18.4 节推导训练算法,第 18.5 节对其进行重新表述,使其更实用。第 18.6 节讨论实现细节,包括如何使生成过程以上下文提示为条件。

18.2 编码器(前向过程)
18.2 Encoder (forward process)

The diffusion or forward process 1 (figure 18.2) maps a data example x through a series of intermediate variables z 1, z 2,..., z T with the same size as x according to:

扩散过程或前向过程 1 (图 18.2)将数据样本 x 映射到一系列

s 中间变量 z 1, z 2,..., z T,大小与 x 相同,根据:

where ϵt is noise drawn from a standard normal distribution. The first term attenuates the data plus any noise added so far, and the second adds more noise. The hyperparameters βt∈[0, 1] determine how quickly the noise is blended and are collectively known as the noise schedule. The forward process can equivalently be written as: This is a Markov chain because the probability of z t is determined entirely by the value of the immediately preceding variable z t−1. With sufficient steps T, all traces of the original data are removed, and q( z T | x ) = q( z T) becomes a standard normal distribution. 2

其中 ϵt 是取自标准正态分布的噪声。第一项衰减数据以及迄今添加的任何噪声,第二项添加更多噪声。超参数 βt∈[0, 1] 决定噪声混合的速度,统称为噪声调度。前向过程可以等价地写为:

图 18.2 前向过程。 a) 我们考虑一维数据 x,其中 T= 100 个隐变量 z1,..., z100 和 β=0.03 存在于所有步骤中。 x 的三个值
图 18.2 前向过程。 a) 我们考虑一维数据 x,其中 T= 100 个隐变量 z1,..., z100 和 β=0.03 存在于所有步骤中。 x 的三个值(灰色、青色和橙色)被初始化(顶行)。这些值通过 z1,..., z100 进行传播。在每个步骤中,变量通过将其值衰减 √1 −β 并添加均值为零、方差为 β 的噪声来更新(公式 18.1)。因此,这三个示例带噪声地传播通过这些变量,并倾向于向零移动。 b) 条件概率 Pr (z1|x) 和 Pr (zt|zt−1) 是正态分布,其均值比当前点略靠近零,并具有固定方差 βt (公式 18.2)。Figure 18.2 Forward process. a) We consider one-dimensional data x with T= 100 latent variables z1,..., z100 and β=0.03 at all steps. (gray, cyan, and orange) are initialized (top row). At each step, the variable is updated by attenuating its value by √1 −β and adding noise with mean zero and variance β (equation 18.1). Accordingly, the three examples noisily propagate through the variables with a tendency to move toward zero. b) The conditional probabilities Pr(z1|x) and Pr(zt|zt−1) are normal distributions with a mean that is slightly closer to zero than the current point and a fixed variance βt (equation 18.2).
公式

The joint distribution of all of the latent variables z 1, z 2,..., z T given input x is:

图 18.3 扩散核。 a) 点 x∗= 2.0 利用公式 18.1 在隐变量中传播(灰色显示了五条路径)。扩散核  q (zt|x∗) 是在从 x∗ 出发的条
图 18.3 扩散核。 a) 点 x∗= 2.0 利用公式 18.1 在隐变量中传播(灰色显示了五条路径)。扩散核 q (zt|x∗) 是在从 x∗ 出发的条件下变量 zt 的概率分布。它可以闭式计算,是一个正态分布,其均值向零移动,方差随 t 的增大而增大。热力图显示了每个变量的 q (zt|x∗)。青色线条显示距均值 ±2 个标准差的位置。 b) 扩散核 q (zt|x∗) 在 t = 20, 40 , 80 时显式显示。实际上,扩散核允许我们对对应于给定 x∗ 的隐变量 zt 进行采样,而无需计算中间变量 z1,..., zt−1。当 t 变得非常大时,扩散核变为标准正态分布。Figure 18.3 Diffusion kernel. a) The point x∗= 2.0 is propagated through the latent variables using equation 18.1 (five paths shown in gray). kernel q(zt|x∗) is the probability distribution over variable zt given that we started from x∗. It can be computed in closed-form and is a normal distribution whose mean moves toward zero and whose variance increases as t increases. Heatmap shows q(zt|x∗) for each variable. Cyan lines show ±2 standard deviations from the mean. b) The diffusion kernel q(zt|x∗) is shown explicitly for t = 20, 40, 80. In practice, the diffusion kernel allows us to sample a latent variable zt corresponding to a given x∗ without computing the intermediate variables z1,..., zt−1. When t becomes very large, the diffusion kernel becomes a standard normal.
图 18.4 边缘分布。 a) 给定初始密度 Pr (x) (顶行),扩散过程在穿过隐变量 zt 时逐渐模糊该分布,并将其推向标准正态分布。热图中随后的每一水平
图 18.4 边缘分布。 a) 给定初始密度 Pr (x) (顶行),扩散过程在穿过隐变量 zt 时逐渐模糊该分布,并将其推向标准正态分布。热图中随后的每一水平线表示一个边缘分布 q (zt)。 b) 上方图显示初始分布 Pr (x)。另外两幅图分别显示边缘分布 q (z20) 和 q (z60)。Figure 18.4 Marginal distributions. a) Given an initial density Pr(x) (top row), the diffusion process gradually blurs the distribution as it passes through the latent variables zt and moves it toward a standard normal distribution. Each subsequent horizontal line of heatmap represents a marginal distribution q(zt). b) The top graph shows the initial distribution Pr(x). The other two graphs show the marginal distributions q(z20) and q(z60), respectively. The diffusion
18.2.1 扩散核 q( z t| x )
18.2.1 Diffusion kernel q( z t| x )

To train the decoder to invert this process, we use multiple samples z t at time t for the same example x. However, generating these sequentially using equation 18.1 is timeconsuming when t is large. Fortunately, there is a closed-form expression for q( z t| x ), which allows us to directly draw samples z t given initial data point x without computing the intermediate variables z 1... z t−1. This is known as the diffusionkernel (figure 18.3).

为了训练解码器以逆转这一过程,我们使用多个样本 z t,它们对应于时间 t 的同一示例 x。然而,当 t 较大时,使用方程 18.1 依次生成这些样本非常耗时。幸运的是,存在 q (z t| x) 的闭式表达式,这允许我们直接抽取样本 z t (给定初始数据点 x),而无需计算中间变量 z 1... z t−1。这被称为扩散核(图 18.3)。为了推导 q (z t| x) 的表达式,考虑前向过程的前两个步骤

To derive an expression for q( z t| x ), consider the first two steps of the forward process: The last two terms are independent samples from mean-zero normal distributions with variances 1 −β2 −(1 −β2)(1 −β1) and β2, respectively. The mean of this sum is zero,

:

公式
公式

and its variance is the sum of the component variances (see problem 18.2), so:

其方差是各分量方差之和(见问题 18.2),因此:

where ϵ is also a sample from a standard normal distribution.

If we continue this process by substituting this equation into the expression for z 3 and so on, we can show that: where αt=Qt

其中 ϵ 也是来自标准正态分布的样本。

如果继续这一过程,将此方程代入 z 3 的表达式,依此类推,我们可以证明:

For any starting data point x, variable z t is normally distributed with a known mean and variance. Consequently, if we don’t care about the history of the evolution through the intermediate variables z 1... z t−1, it is easy to generate samples from q( z t| x ).

对于任意起始数据点 x,变量 z t 服从已知均值和方差的正态分布。因此,如果我们不关心通过中间变量 z 1... z t−1 的演化历史,就容易从 q (z t| x) 生成样本。

18.2.2 边缘分布 q( z t)
18.2.2 Marginal distributions q( z t)

The marginal distribution q( z t) is the probability of observing a value of z t given the distribution of possible starting points x and the possible diffusion paths for each starting point (figure 18.4). It can be computed by considering the joint distribution q( x , z 1...t)

边缘分布 q (z t) 是在给定可能的起始点分布 x 以及可能的扩散路径的情况下,观察到 z t 某个值的概率,对于每个起始

点(图 18.4)。可以通过考虑联合分布 q (x , z 1...t) 来计算。

and marginalizing over all the variables except z t:

并且边缘化除 z t 以外的所有变量:

where q( z 1...t| x ) was defined in equation 18.3.

However, since we now have an expression for the diffusion kernel q( z t| x ) that “skips” the intervening variables, we can equivalently write: Hence, if we repeatedly sample from the data distribution Pr( x ) and superimpose the diffusion kernel q( z t| x ) on each sample, the result is the marginal distribution q( z t) (fig- ure 18.4). However, the marginal distribution cannot be written in closed form because

we don’t know the original data distribution Pr( x ).

18.2.3 条件分布 q( z t−1| z t)
18.2.3 Conditional distribution q( z t−1| z t)

We defined the conditional probability q( z t| z t−1) as the mixing process (equation 18.2).

我们将条件概率 q (z t| z t−1) 定义为混合过程(公式 18.2)。

To reverse this process, we apply Bayes’ rule:

为了逆转这一过程,我们应用贝叶斯法则:

This is intractable since we cannot compute the marginal distribution q( z t−1).

For this simple 1D example, it’s possible to evaluate q( z t−1| z t) numerically (figure 18.5). In general, their form is complex, but in many cases, they are well-approximated by a normal distribution. This is important because when we build the decoder, we will approximate the reverse process using a normal distribution.

由于我们无法计算边际分布 q (z t−1),因此这在计算上是不可行的。

对于这个简单的一维示例,可以对 q (z t−1| z t) 进行数值求值(图 18.5)。一般来说,它们的形式很复杂,但在许多情况下,可以用正态分布很好地近似。这很重要,因为当我们构建解码器时,我们将使用正态分布来近似反向过程。

18.2.4 条件扩散分布 q( z t−1| z t, x )
18.2.4 Conditional diffusion distribution q( z t−1| z t, x )

There is one final distribution related to the encoder to consider. We noted above that we could not find the conditional distribution q( z t−1| z t) because we do not know the marginal distribution q( z t−1). However, if we know the starting variable x, then we do know the distribution q( z t−1| x ) at the time before. This is just the diffusion kernel (figure 18.3), and it is normally distributed. Hence, it is possible to compute the conditional diffusion distribution q( z t−1| z t, x ) in closed form (figure 18.6). This distribution is used to train the decoder. It is the distribution over z t−1 when we know the current latent variable z t and the training

还有最后一个与编码器相关的分布需要考虑。我们上面指出,我们无法求得条件分布 q (z t−1| z t),因为我们不知道边际分布 q (z t−1)。然而,如果我们知道起始变量 x,那么我们就确实知道前一个时间步的分布 q (z t−1| x)。这正是扩散核(图 18.3),并且它服从正态分布。因此,可以以闭式形式计算条件扩散分布 q (z t−1| z t, x) (图 18.6)。该分布用于训练解码器。它是 z t−1 的分布,当我们知道当前隐变量 z t 和训练

图 18.5 条件分布 q(zt−1|zt)。a) 边际密度 q(zt),其中三个点 z∗t 被高亮显示。b) 概率 q(zt−1|z∗t) 由贝叶斯定理计算,
图 18.5 条件分布 q(zt−1|zt)。a) 边际密度 q(zt),其中三个点 z∗t 被高亮显示。b) 概率 q(zt−1|z∗t) 由贝叶斯定理计算,并与 q(z∗t|zt−1)q(zt−1) 成正比。一般而言它并不服从正态分布,尽管正态分布通常是良好的近似。第一个似然项关于 zt−1 服从正态分布(公式 18.2),其均值比 z∗t 略远离零。第二项是边际密度 q(zt−1)。Figure 18.5 Conditional distribution q(zt−1|zt). a) The marginal densities q(zt) with three points z∗ t highlighted. b) The probability q(zt−1|z∗ computed via Bayes’ rule and is proportional to q(z∗ is not normally distributed (top graph), although often the normal is a good approximation (bottom two graphs). The first likelihood term q(z∗ in zt−1 (equation 18.2) with a mean that is slightly further from zero than z∗ (brown curves). The second term is the marginal density q(zt−1) (gray curves).
公式
图 18.6 条件分布 q(zt−1|zt, x)。a) 扩散核,其中三个点被高亮显示。b) 该概率由贝叶斯定理计算,并与 q(z∗t|zt−1)q(zt−1|
图 18.6 条件分布 q(zt−1|zt, x)。a) 扩散核,其中三个点被高亮显示。b) 该概率由贝叶斯定理计算,并与 q(z∗t|zt−1)q(zt−1|x∗) 成正比。该分布是正态分布,并且可以闭式计算。第一个似然项关于 zt−1 服从正态分布(公式 18.2),其均值比 z∗t 略远离零。第二项是扩散核 q(zt−1|x∗)。Figure 18.6 Conditional distribution q(zt−1|zt, x). a) Diffusion kernel for x∗= −2.1 with three points z∗ t highlighted. b) The probability q(zt−1|z∗ puted via Bayes’ rule and is proportional to q(z∗ mally distributed and can be computed in closed form. term q(z∗ t|zt−1) is normal in zt (equation 18.2) with a mean that is slightly further from zero than z∗ t (brown curves). kernel q(zt−1|x∗) (gray curves). t) (cyan curves) is t|zt−1)q(zt−1). In general, it t|zt−1) is normal t, x∗) is comThe first likelihood The second term is the diffusion

data example x (which, of course, we do when training). To compute an expression for q( z t−1| z t, x ) we start with Bayes’ rule:

where between the first two lines, we have used the fact that q( z t| z t−1, x )=q( z t| z t−1) because the diffusion process is Markov, and all information about z t is captured by z t−1. Between lines three and four, we use the Gaussian change of variables identity: Norm v [ Aw , B ] ∝ Norm w

数据样本 x (当然,我们在训练时会这样做)。为了计算 q (z t−1| z t, x) 的表达式,我们从贝叶斯法则开始: Norm v [ Aw , B ] ∝ Norm w t 为了将第一个分布用 z t−1 表示,我们接着使用第二个高斯恒等式

to rewrite the first distribution in terms of z t−1. We then use a second Gaussian identity:

:

Note that the constants of proportionality in equations 18.12, 18.13, and 18.14 must cancel out since the final result is already a correctly normalized probability distribution.

请注意,式 18.12、 18.13 和 18.14 中的比例常数必须相互抵消,因为最终结果已经是正确归一化的概率分布。

18.3 解码器模型(反向过程)
18.3 Decoder model (reverse process)

When we learn a diffusion model, we learn the reverse process. In other words, we learn a series of probabilistic mappings back from latent variable z T to z T −1, from z T −1 to z T −2, and so on, until we reach the data x. The true reverse distributions q( z t−1| z t) of the diffusion process are complex multi-modal distributions (figure 18.5) that depend on the data distribution Pr( x ). We approximate these as normal distributions: where f t[ z t, ϕt] is a neural network that computes the mean of the normal distribution in the estimated mapping from z t to the preceding latent variable z t−1. The terms {σ2

当我们学习扩散模型时,我们学习反向过程。换句话说,我们学习一系列概率映射,从隐变量 z T 到 z T −1,从 z T −1 到 z T −2,依此类推,直到到达数据 x。扩散过程的真实反向分布 q( z t−1| z t) 是复杂的多模态分布(图 18.5),它们依赖于数据分布 Pr( x )。我们将这些分布近似为正态分布:其中, f t[ z t, ϕt] 是一个神经网络,用于计算从 z t 到前一个隐变量 z t−1 的估计映射中正态分布的均值。各项 {σ2

t} are predetermined. If the hyperparameters βt in the diffusion process are close to zero (and the number of time steps T is large), then this normal approximation will be reasonable.

We generate new examples from Pr( x ) using ancestral sampling.

We start by drawing z T from Pr( z T). Then we sample z T −1 from Pr( z T −1| z T, ϕT), sample z T −2 from Pr( z T −2| z T −1, ϕT −1) and so on until we finally generate x from Pr( x | z 1, ϕ1).

t} 是预先确定的。如果扩散过程中的超参数 βt 接近于零(并且时间步数 T 很大),那么这种正态近似将是合理的。

18.4 训练
18.4 Training

The joint distribution of the observed variable x and the latent variables{ z t} is:

观测变量 x 与隐变量 { z t} 的联合分布为:

变量:

variables:

为了训练模型,我们最大化训练数据 { x i} 关于参数 ϕ 的对数似然:

To train the model, we maximize the log-likelihood of the training data{ x i} with respect to the parameters ϕ:

We can’t maximize this directly because the marginalization in equation 18.18 is intractable. Hence, we use Jensen’s inequality to define a lower bound on the likelihood and optimize the parameters ϕ1...T with respect to this bound exactly as we did for the VAE (see section 17.3.1).

我们无法直接最大化它,因为公式 18.18 中的边际化操作难以计算。因此,我们使用詹森不等式来定义似然的下界,并完全按照我们在 VAE 中的做法(参见 17.3.1 节),关于该下界优化参数 ϕ1...T。

18.4.1 证据下界(ELBO)
18.4.1 Evidence lower bound (ELBO)

To derive the lower bound, we multiply and divide the log-likelihood by the encoder distribution q( z 1...T | x ) and apply Jensen’s inequality (see section 17.3.2):

为了推导下界,我们将对数似然乘以并除以编码器分布 q( z 1...T | x ),并应用詹森不等式(见 17.3.2 节):

This gives us the evidence lower bound (ELBO): ELBO

In the VAE, the encoder q( z | x ) approximates the posterior distribution over the latent variables to make the bound tight, and the decoder maximizes this bound (figure 17.10). In diffusion models, the decoder must do all the work since the encoder has no parameters. It makes the bound tighter by both (i) changing its parameters so that the static encoder does approximate the posterior Pr( z 1...T | x , ϕ1...T) and (ii) optimizing its own parameters with respect to that bound (see figure 17.6).

由此得到证据下界(ELBO): ELBO

在 VAE 中,编码器 q (z | x) 近似隐变量的后验分布以使证据下界更紧,而解码器最大化该证据下界(图 17.10)。在扩散模型中,由于编码器没有参数,解码器必须完成所有工作。它通过两种方式使证据下界更紧: (i) 改变其参数,使得静态编码器确实近似后验 Pr (z 1...T | x ϕ1...T),以及 (ii) 针对该证据下界优化其自身参数(见图 17.6)。

18.4.2 简化证据下界(ELBO)
18.4.2 Simplifying the ELBO

We now manipulate the log term from the ELBO into the final form that we will optimize. We first substitute in the definitions for the numerator and denominator from equations 18.17 and 18.3, respectively:

现在,我们将证据下界(ELBO)中的对数项改写为我们将要优化的最终形式。首先,分别代入式 18.17 和式 18.3 中分子与分母的定义:

Then we expand the denominator of the second term: where the first equality follows because all of the information about variable z t is encompassed in z t−1, so the extra conditioning on the data x is irrelevant. The second

然后,我们展开第二项的分母:

equality is a straightforward application of Bayes’ rule.

Substituting in this result gives:

该等式是贝叶斯法则的直接应用。

代入此结果可得:

where all but two of the terms in the product of the ratios q( z t−1| x )/q( z t| x ) cancel out between lines two and three leaving only q( z 1| x ) and q( z T | x ). The last term in the third line is approximately log[1] = 0 since the result of the forward process q( z T | x ) is a standard normal distribution, and so is equal to the prior Pr( z T).

The simplified ELBO is hence: ELBO

其中,比值乘积 q (z t−1| x) /q (z t| x) 中除两项外的所有项在第二行和第三行之间相互抵消,只剩下 q (z 1| x) 和 q (z T | x)。第三行的最后一项近似为 log[1] = 0,因为前向过程 q (z T | x) 的结果是标准正态分布,因此它等于先验 Pr (z T)。 ELBO

where we have marginalized over the irrelevant variables in q( z 1...T | x ) between lines two and three and used the definition of KL divergence (see problem 18.7).

其中,我们已在 q (z 1...T | x) 中对不相关变量进行了边缘化,位于第二行之间和三个,并使用了 KL 散度的定义(见习题 18.7)。

18.4.3 分析证据下界(ELBO)
18.4.3 Analyzing the ELBO

The first probability term in the ELBO was defined in equation 18.16:

证据下界(ELBO)中的第一个概率项在式 18.16 中定义:

and is equivalent to the reconstruction term in the VAE. The ELBO will be larger if the model prediction matches the observed data. As for the VAE, we will approximate the expectation over the log of this quantity using a Monte Carlo estimate (see equations 17.22–17.23), in which we estimate the expectation with a sample from q( z 1| x ).

The KL divergence terms in the ELBO measure the distance between Pr( z t−1| z t, ϕt) and q( z t−1| z t, x ), which were defined in equations 18.16 and 18.15, respectively: The KL divergence between two normal distributions has a closed-form expression. More- over, many of the terms in this expression do not depend on ϕ (see problem 18.8), and

并且它等价于 VAE 中的重构项。如果模型预测与观测数据匹配,证据下界(ELBO)会更大。对于 VAE,我们将使用蒙特卡洛估计来近似该量的对数的期望(见式 17.2217.23),其中用来自 q (z 1| x) 的一个样本来估计期望。两个正态分布之间的 KL 散度具有闭式表达式。更 -

the expression simplifies to the squared difference between the means plus a constant C:

公式
公式
图 18.7 拟合模型。 a) 单个样本可以通过从标准正态分布 Pr (zT) (底部一行)采样,到达到 x (显示五条路径)来生成。估计的边缘密度(热力图)由
图 18.7 拟合模型。 a) 单个样本可以通过从标准正态分布 Pr (zT) (底部一行)采样,到达到 x (显示五条路径)来生成。估计的边缘密度(热力图)由这些样本汇总得到,并且与真实边缘密度(图 18.4)相似。 b) 估计分布 Pr (zt−1|zt) (棕色曲线)是对图 18.5 中扩散模型的真实后验 q (zt−1|zt) (青色曲线)的合理近似。估计模型和真实模型的边缘分布 Pr (zt) 和 q (zt) (分别为深蓝色曲线和灰色曲线)也相似。Figure 18.7 Fitted Model. a) Individual samples can be generated by sampling from the standard normal distribution Pr(zT) (bottom row) and then samreach x (five paths shown). The estimated marginal densities (heatmap) are the aggregation of these samples and are similar to the true marginal densities (figure 18.4). b) The estimated distribution Pr(zt−1|zt) (brown curve) is a reasonable approximation to the true posterior of the diffusion model q(zt−1|zt) (cyan curve) from figure 18.5. The marginal distributions Pr(zt) and q(zt) of the estimated and true models (dark blue and gray curves, respectively) are also similar.
18.4.4 扩散损失函数
18.4.4 Diffusion loss function

To fit the model, we maximize the ELBO with respect to the parameters ϕ1...T. We recast this as a minimization by multiplying with minus one and approximating the expectations with samples to give the loss function: reconstruction term predicted z t−1 target, mean of q( z t−1| z t, x )

where x i is the ith data point, and z it is the associated latent variable at diffusion step t.

为了拟合模型,我们相对于参数 ϕ1...T 最大化证据下界(ELBO)。我们通过乘以负一并用样本近似期望,将其转化为最小化问题,从而得到损失函数: reconstruction term predicted z t−1 target, mean of q( z t−1| z t, x )

其中 x i 是 ith 数据点,而 z it 是扩散步骤 t 中对应的隐变量。

18.4.5 训练过程
18.4.5 Training procedure

This loss function can be used to train a network for each diffusion time step. It minimizes the difference between the estimate f t[ z t, ϕt] of the hidden variable at the previous time step and the most likely value that it took given the ground truth de-noised data x.

Figures 18.7 and 18.8 show the fitted reverse process for the simple 1D example. This model was trained by (i) taking a large dataset of examples x from the original density, (ii) using the diffusion kernel to predict many corresponding values for the latent variable z t at each time t, and then (iii) training the models f t[ z t, ϕt] to minimize the loss function in equation 18.29. These models were nonparametric (i.e., lookup tables relating 1D input to 1D output), but more typically, they would be deep neural networks.

该损失函数可用于为每个扩散时间步训练一个网络。它最小化了上一时间步隐变量的估计值 f t[ z t, ϕt] 与给定真值去噪数据 x 时该隐变量最可能取值之间的差异。图 18.7 和图 18.8 展示了简单一维示例的拟合反向过程。该模型通过以下方式进行训练: (i) 从原始密度中获取大量示例 x, (ii) 使用扩散核预测许多对应的值,用于该潜

图 18.8 拟合模型结果。青色和棕色曲线分别是原始密度和估计密度,分别对应图 18.4 和图 18.7 的顶部行。垂直条是模型的分箱样本,通过从 Pr(z_T
图 18.8 拟合模型结果。青色和棕色曲线分别是原始密度和估计密度,分别对应图 18.4 和图 18.7 的顶部行。垂直条是模型的分箱样本,通过从 Pr(z_T) 采样并沿变量 z_{T-1}, z_{T-2}, … 反向传播得到,如图 18.7 中五条路径所示。Figure 18.8 Fitted model results. Cyan and brown curves are original and estimated densities and correspond to the top rows of figures 18.4 and 18.7, respectively. Vertical bars are binned samples from the model, generated by sampling from Pr(zT ) and propagating back through the variables zT −1, zT −2, . . . as shown for the five paths in figure 18.7.
18.5 损失函数的重参数化
18.5 Reparameterization of loss function

Although the loss function in equation 18.29 can be used, diffusion models have been found to work better with a different parameterization; the loss function is modified so that the model aims to predict the noise that was mixed with the original data example to create the current variable. Section 18.5.1 discusses reparameterizing the target (first two terms in second line of equation 18.29), and section 18.5.2 discusses reparameterizing the network (last term in second line of equation 18.29).

尽管方程 18.29 中的损失函数可以使用,但人们发现扩散模型采用不同的参数化方式效果更好;损失函数经过修改,使模型旨在预测与原始数据样本混合以生成当前变量的噪声。第 18.5.1 节讨论对目标进行重参数化(方程 18.29 第二行的前两项),第 18.5.2 节讨论对网络进行重参数化(方程 18.29 第二行的最后一项)。

18.5.1 目标的重参数化
18.5.1 Reparameterization of target

The original diffusion update was given by:

原始扩散更新由下式给出:

minus the noise that was added to it:

Substituting this into the target terms from equation 18.29 gives: where we have used the fact that √αt/√αt−1=√1 −βt between the second and third

将其代入式 18.29 的目标项中,得到:其中我们利用了 √αt/√αt−1=√1 −βt 在第二个和第三个之间这一事实

lines. Simplifying further, we get:

行。进一步简化后,我们得到:

公式

where we have multiplied the numerator and denominator of the first term by √1 −βt between lines two and three, multiplied out the terms, and simplified the numerator in the first term between lines three and four.

其中,我们在第二行与第三行之间将第一项的分子和分母乘以 √1 −βt,展开各项,并简化了第三行与第四行之间第一项的分子。

Substituting this back into the loss function (equation 18.29), we have:

将其代回损失函数(公式 18.29),我们得到:

18.5.2 网络的重参数化
18.5.2 Reparameterization of network

Now we replace the model ˆ z t−1= f t[ z t, ϕt] with a new model ˆϵ= g t[ z t, ϕt], which predicts the noise ϵ that was mixed with x to create z t:

现在,我们将模型 ˆ z t−1= f t[ z t, ϕt] 替换为一个新模型 ˆϵ= g t[ z t, ϕt],该模型预测与 x 混合以生成 z t 的噪声 ϵ:

Substituting the new model into equation 18.34 produces the criterion: Substituting in the definitions of x and f 1[ z 1, ϕ1] from equations 18.31 and 18.35, re-

将新模型代入公式 18.34,得到如下准则:

将式 18.31 和式 18.35 中 x 和 f 1[ z 1 的定义代入 , ϕ1] 分别,第一项简化为:

spectively, the first term simplifies to:

where we have disregarded the additive constants Ci.

其中,我们忽略了加性常数 Ci。

In practice, the scaling factors (which might be different at each time step) are ignored, giving an even simpler formulation:

where we have rewritten z t using the diffusion kernel (equation 18.30) in the second line.

其中,我们在第二行中利用扩散核(公式 18.30)重写了 z t。

18.6 实现
18.6 Implementation

This leads to straightforward algorithms for both training the model (algorithm 18.1) and sampling (algorithm 18.2). The training algorithm has the advantages that it is (i) simple to implement and (ii) naturally augments the dataset; we can reuse every original data point x i as many times as we want at each time step with different noise instantiations ϵ. The sampling algorithm has the disadvantage that it requires serial

这可以得到用于模型训练(算法 18.1)和采样(算法 18.2)的简单算法。训练算法具有如下优点:(i)易于实现,并且(ii)自然地增广了数据集;我们可以复用每个

原始数据点 x i 在每个时间步以不同的噪声实例进行任意多次采样 ϵ。该采样算法的缺点是需要串行处理许多神经网络 g t[ z t, ϕt],因而耗时。算法 18.1:扩散模型训练输入:训练数据 x输出:模型参数 ϕ重复对于 i ∈B 执行累积批次损失并执行梯度步直到收敛算法 18.2:采样输入:模型, g t[•, ϕt]输出:样本, x

processing of many neural networks g t[ z t, ϕt] and is hence time-consuming. Algorithm 18.1: Diffusion model training Input: Training data x Output: Model parameters ϕt repeat for i ∈B do Accumulate losses for batch and take gradient step until converged Algorithm 18.2: Sampling Input: Model, g t[•, ϕt] Output: Sample, x

18.6.1 图像应用
18.6.1 Application to images

Diffusion models have been very successful in modeling image data. Here, we need to construct models that can take a noisy image and predict the noise that was added at each step. The obvious architectural choice for this image-to-image mapping is the UNet (figure 11.10). However, there may be a very large number of diffusion steps, and training and storing multiple U-Nets is inefficient. The solution is to train a single U-Net that also takes a predetermined vector representing the time step as input (figure 18.9). In practice, this is resized to match the number of channels at each stage of the U-Net and used to offset and/or scale the representation at each spatial position.

A large number of time steps are needed as the conditional probabilities q( z t−1| z t) become closer to normal when the hyperparameters βt are close to zero, matching the form of the decoder distributions Pr( z t−1| z t, ϕt). However, this makes sampling slow. We might have to run the U-Net model through T =1000 steps to generate good images.

扩散模型在图像数据建模方面非常成功。在此,我们需要构建能够接收含噪图像并预测每一步添加的噪声的模型。对于这种图像到图像的映射,显而易见的架构选择是 U-Net (图 11.10)。然而,扩散步数可能非常多,训练和存储多个 U-Net 效率低下。解决方案是训练一个 U-Net,使其同时接收一个表示时间步的预定向量作为输入(图 18.9)。在实践中,该向量会被调整尺寸以匹配 U-Net 每个阶段的通道数,并用于在每个空间位置上偏移和 / 或缩放表示。

当超参数 βt 接近零时,条件概率 q (z t−1| z t) 会变得更接近正态分布,与解码器分布 Pr (z t−1| z t, ϕt) 的形式相匹配,因此需要大量的时间步。然而,这会使采样变慢。我们可能需要让 U-Net 模型运行 T =1000 步才能生成高质量图像。

18.6.2 提高生成速度
18.6.2 Improving generation speed

The loss function (equation 18.40) requires the diffusion kernel to have the form q( z t| x ) = Norm[√αt x ,√1 −αt· I ]. The same loss function will be valid for any forward process

损失函数(公式 18.40)要求扩散核具有如下形式 q( z t| x )= Norm[√αt x √1 −αt· I ]。相同的损失函数对任意前向过程均有效

图 18.9 用于图像扩散模型的 U-Net。该网络旨在预测添加到图像中的噪声。它由编
图 18.9 用于图像扩散模型的 U-Net。该网络旨在预测添加到图像中的噪声。它由编Figure 18.9 U-Net as used in diffusion models for images. The network aims to predict the noise that was added to the image. It consists of an encoder which reduces the scale and increases the number of channels and a decoder which increases the scale and reduces the number of channels. The encoder representations are concatenated to their partner in the decoder. Connections between adjacent representations consist of residual blocks, and periodic global self-attention in which every spatial position interacts with every other spatial position. A single network is used for all time steps, by passing a sinusoidal time embedding (figure 12.5) through a shallow neural network and adding the result to the channels at every spatial position at every stage of the U-Net.

with this relation, and there is a family of such compatible processes. These are all optimized by the same loss function but have different rules for the forward process and different corresponding rules for how to use the estimated noise g[ z t, ϕt] to predict z t−1 from z t in the reverse process (figure 18.10).

Among this family are denoising diffusion implicit models, which are no longer stochastic after the first step from x to z 1, and acceleratedsampling models, where the forward process is defined only on a sub-sequence of time steps. This allows a reverse process that skips time steps and hence makes sampling much more efficient; good samples can be created with 50 time steps when the forward process is no longer stochastic. This is much faster than before but still slower than most other generative models.

满足这种关系,并且存在一族这样的兼容过程。它们都由相同的损失函数优化,但前向过程有不同的规则,并且在反向过程中如何使用估计噪声 g[ z t, ϕt] 由 z t 预测 z t−1,也有不同的相应规则(图 18.10)。这一族中包括去噪扩散隐式模型,它们在从 x 到 z 1, 的第一步之后不再是随机的;还有加速采样模型,其中前向过程仅在时间步的一个子序列上定义。这允许一个跳过时间步的反向过程,从而显著提高采样效率;良好的采样 -

18.6.3 条件生成
18.6.3 Conditional generation

If the data has associated labels c, these can be exploited to control the generation. Sometimes this can improve generation results in GANs, and we might expect this to be the case in diffusion models as well; it’s easier to denoise an image if you have some information about what that image contains. One approach to conditional synthesis in diffusion models is classifierguidance. This modifies the denoising update from z t to z t−1 to take into account class information c. In practice, this means adding an extra

如果数据具有相关标签 c,则可以利用这些标签来控制生成。有时这可以改善 GAN 中的生成结果,我们可能也期望在扩散模型中如此;如果你拥有关于图像内容的某些信息,那么对图像去噪会更容易。扩散模型中条件合成的一种方法是分类器引导。这将去噪更新从 z t 修改为 z t−1,以考虑类别信息 c。在实践中,这意味着添加一个额外的

term into the final update step in algorithm 18.2 to yield:

项到算法 18.2 的最终更新步骤中,从而得到:

图 18.10 与同一模型兼容的不同扩散过程。 a) 重参数化模型的五条采样轨迹叠加在真值边缘分布上。顶行表示 Pr (x),后续行表示 q (x t)。 b)
图 18.10 与同一模型兼容的不同扩散过程。 a) 重参数化模型的五条采样轨迹叠加在真值边缘分布上。顶行表示 Pr (x),后续行表示 q (x t)。 b) 重参数化模型生成样本的直方图,与真值密度曲线 Pr (x) 一同绘制。同一个训练好的模型与一族扩散模型(以及相反方向上的相应更新)兼容,其中包括去噪扩散隐式模型(DDIM),该模型是确定性的,并且不会在每一步添加噪声。 c) 来自 DDIM 的五条轨迹。 d) 来自 DDIM 的样本直方图。同一模型还与加速扩散模型兼容,这些模型跳过推理步骤以提高采样速度。 e) 来自加速模型的五条轨迹。 f) 来自加速模型的样本直方图。Figure 18.10 Different diffusion processes that are compatible with the same model. a) Five sampled trajectories of the reparameterized model superimposed on the ground truth marginal distributions. Top row represents Pr( x ) and subsequent rows represent q( x t). b) Histogram of samples generated from reparameterized model plotted alongside ground truth density curve Pr( x ). The same trained model is compatible with a family of diffusion models (and corresponding updates in the opposite direction), including the denoising diffusion implicit model (DDIM), which is deterministic and does not add noise at each step. c) Five trajectories from DDIM. d) Histogram of samples from DDIM. The same model is also compatible with accelerated diffusion models that skip inference steps for increased sampling speed. e) Five trajectories from accelerated model. f) Histogram of samples from accelerated model.

The new term depends on the gradient of a classifier Pr(c| z t) that is based on the latent variable z t. This maps features from the downsampling half of the U-Net to the class c. Like the U-Net, it is usually shared across all time steps and takes time as an input. The update from z t to z t−1 now makes the class c more likely. Classifier-freeguidance avoids learning a separate classifier Pr(c| z t) but instead incorporates class information into the main model g t[ z t, ϕt, c]. In practice, this usually takes the form of adding an embedding based on c to the layers of the U-Net in a similar way to how the time step is added (see figure 18.9). This model is jointly trained on conditional and unconditional objectives by randomly dropping the class information

during training. Hence, it can both generate unconditional or conditional data examples at test time or any weighted combination of the two. This brings a surprising advantage; if the conditioning information is over-weighted, the model tends to produce very high quality but slightly stereotypical examples. This is somewhat analogous to the use of truncation in GANs (figure 15.10).

新项依赖于分类器 Pr (c| z t) 的梯度,该分类器基于隐变量 z t。它将来自 U-Net 下采样半部分的特征映射到类别 c。与 U-Net 类似,它通常在所有时间步之间共享,并将时间作为输入。从 z t 到 z t−1 的更新现在使类别 c 更有可能。无分类器引导避免学习一个单独的分类器 Pr(c| z t) 而是将类别信息融入主模型 g t[ z t, ϕt, c]。在实践中,这通常表现为以与添加时间步相似的方式,将基于 c 的嵌入添加到 U-Net 的各层中(见图 18.9)。该模型通过随机丢弃类别信息,在条件目标和无条件目标上进行联合训练

如果条件信息的权重过高,模型倾向于生成质量很高但略显刻板化的样本。这在某种程度上类似于 GAN 中使用截断(图 15.10)。

图 18.11 基于文本提示的级联条件生成。 a) 使用由一系列 U-Net 组成的扩散模型生成一张 64 × 64 图像。 b) 该生成过程以语言模型计算出的
图 18.11 基于文本提示的级联条件生成。 a) 使用由一系列 U-Net 组成的扩散模型生成一张 64 × 64 图像。 b) 该生成过程以语言模型计算出的句子嵌入为条件。 c) 生成更高分辨率的 256 × 256 图像,并以较小的图像和文本编码为条件。 d) 重复该过程以生成一张 1024 × 1024 图像。 e) 最终图像序列。改编自 Saharia 等人 (2022b)。在训练过程中。因此,它在测试时既可以生成无条件或有条件的数据样本,也可以生成两者的任意加权组合。这带来了一个意想不到的优势;Figure 18.11 Cascaded conditional generation based on a text prompt. a) A diffusion model consisting of a series of U-Nets is used to generate a 64 × 64 image. b) This generation is conditioned on a sentence embedding computed by a language model. c) A higher resolution 256 × 256 image is generated and conditioned on the smaller image and the text encoding. d) This is repeated to create a 1024 × 1024 image. e) Final image sequence. Adapted from Saharia et al. (2022b).
18.6.4 提升生成质量
18.6.4 Improving generation quality

As for other generative models, the highest quality results result from applying a combination of tricks and extensions to the basic model. First, it’s been noted that it also helps to estimate the variances σ2 t of the reverse process as well as the mean (i.e., the widths

of the brown normal distributions in figure 18.7). This particularly improves the results when sampling with fewer steps. Second, it’s possible to modify the noise schedule in the forward process so that βt varies at each step, and this can also improve results.

与其他生成模型一样,最高质量的结果来自在基本模型上应用一系列技巧和扩展。首先,人们注意到,同时估计反向过程的方差 σ2 t 和均值(即宽度

图 18.7 中棕色正态分布的宽度)。这在以更少步数采样时尤其能改善结果。其次,可以修改前向过程中的噪声调度,使 βt 在每一步都发生变化,这也能改善结果。

Third, to generate high-resolution images, a cascade of diffusion models is used. The first creates a low-resolution image (possibly guided by class information). The subsequent diffusion models generate progressively higher-resolution images. They condition on the lower-resolution image by resizing this and appending it to the layers of the constituent U-Net, as well as any other class information (figure 18.11).

Combining all of these techniques allows the generation of very high-quality images. Figure 18.12 shows examples of images generated from a model conditioned on the ImageNet class. It is particularly impressive that the same model can learn to generate such diverse classes. Figure 18.13 shows images generated from a model that is trained to condition on text captions encoded by a language model like BERT, which are inserted into the model in the same way as the time step (figures 18.9 and 18.11). This results in very realistic images that agree with the caption. Since the diffusion model is stochastic by nature, it’s possible to generate multiple images that are conditioned on the same caption.

第三,为了生成高分辨率图像,使用一系列级联扩散模型。第一个扩散模型生成低分辨率图像(可能由类别信息引导)。后续的扩散模型生成分辨率逐渐更高的图像。它们将低分辨率图像作为条件,方法是先缩放该图像,再将其与任何其他类别信息一起附加到 U-Net 的各层(图 18.11)。

结合所有这些技术,可以生成非常高质量的图像。图 18.12 展示了由以 I mageNet 类别为条件的模型生成的图像示例。同一模型能够学会生成如此多样的类别,这一点尤其令人印象深刻。图 18.13 展示了由一个经过训练的模型生成的图像,该模型以由 BERT 等语言模型编码的文本说明为条件,这些编码文本以与时间步相同的方式插入模型(图 18.9 和 18.11)。这会产生与说明相符的非常逼真的图像。由于扩散模型本质上是随机的,因此可以生成以同一说明为条件的多张图像。

18.7 小结
18.7 Summary

Diffusion models map the data examples through a series of latent variables by repeatedly blending the current representation with random noise. After sufficient steps, the representation becomes indistinguishable from white noise. Since these steps are small, the reverse denoising process at each step can be approximated with a normal distribution and predicted by a deep learning model. The loss function is based on the evidence lower bound (ELBO) and ultimately results in a simple least-squares formulation.

For image generation, each denoising step is implemented using a U-Net, so sampling is slow compared to other generative models. To improve generation speed, it’s possible to change the diffusion model to a deterministic formulation, and here sampling with fewer steps works well. Several methods have been proposed to condition generation on class information, images, and text information. Combining these methods produces impressive text-to-image synthesis results.

扩散模型通过反复将当前表示与随机噪声混合,将数据样本经由一系列隐变量进行映射。经过足够多的步骤后,该表示变得与白噪声无法区分。由于这些步骤很小,每一步的反向去噪过程可以用正态分布近似,并由深度学习模型预测。损失函数基于证据下界(ELBO),最终得到简单的最小二乘公式。

在图像生成中,每个去噪步骤都使用 U-Net 实现,因此与其他生成模型相比,采样速度较慢。为了提高生成速度,可以将扩散模型改为确定性公式,在这种情况下,使用更少的步骤进行采样也能取得良好效果。已经提出了多种方法,使生成过程以类别信息、图像和文本信息为条件。将这些方法结合起来,可以产生令人印象深刻的文本到图像合成结果。

注释
Notes
图 18.12 使用分类器引导的条件生成。针对不同 ImageNet 类别的条件图像样本。同一模型能够生成高度多样化图像类别的高质量样本。改编自 Dhariwa
图 18.12 使用分类器引导的条件生成。针对不同 ImageNet 类别的条件图像样本。同一模型能够生成高度多样化图像类别的高质量样本。改编自 Dhariwal 和 Nichol (2021)。Figure 18.12 Conditional generation using classifier guidance. conditioned on different ImageNet classes. The same model produces high quality samples of highly varied image classes. Adapted from Dhariwal & Nichol (2021).

Applications for images:

图 18.13 使用文本提示的条件生成。来自级联生成框架的合成图像,以由大型语言模型编码的文本提示为条件。该随机模型能够生成许多与提示兼容的不同图像。模型能够计
图 18.13 使用文本提示的条件生成。来自级联生成框架的合成图像,以由大型语言模型编码的文本提示为条件。该随机模型能够生成许多与提示兼容的不同图像。模型能够计数物体并将文本融入图像。改编自 Saharia 等人 (2022b)。Figure 18.13 Conditional generation using text prompts. from a cascaded generation framework, conditioned on a text prompt encoded by a large language model. The stochastic model can produce many different images compatible with the prompt. The model can count objects and incorporate text into images. Adapted from Saharia et al. (2022b). Image samples Synthesized images

Different data types:

Alternatives to denoising:

Comparison to other generative models:

Improving quality:

Improving speed:

Conditional generation:

Text-to-image:

Connections to other models:

习题
Problems
公式
公式
公式