Generative Models Explained生成式模型讲解
#generative-ai#生成式AI17 chapters17 章

Generative Models Explained生成式模型讲解

The most familiar use of a generative model is to type a prompt, such as “a tilted ellipse”, and receive a picture that never existed before. This guide starts from that familiar scene and turns it, step by step, into a problem that can actually be worked on: what exactly the model has to learn, how to tell whether it has learned well, and what answers the main families of models give.

说到生成式模型,最熟悉的用法是输入一句提示词,比如“一个倾斜的椭圆”,几秒后得到一张从未存在过的图片。本文从这个熟悉的场景出发,一步步把它变成一个可以动手解决的问题:模型到底要学什么,怎样判断它学得好不好,以及几类主要模型分别给出了怎样的答案。

Seen from the outside, the scene has three layers:

  • Input and output: a prompt goes in and a picture that fits it comes out.
  • Randomness: the same prompt can produce many different pictures, so besides the prompt the model also takes a random input, usually a set of random numbers. Dropping the prompt and keeping only the random numbers, the model simply produces some plausible picture; this is called unconditional generation. The prompt is a condition added on top, so this guide studies unconditional generation first and brings the prompt back in the diffusion chapter.
  • Learning: the model is not a set of rules written by hand but is learned from a large collection of training images.

从外部看,这个场景可以分成三层:

  • 输入与输出:输入一句提示词,输出一张符合描述的图片。
  • 随机性:同一句提示词可以得到许多张不同的图片,说明模型除了提示词,还有一份随机输入,通常是一组随机数。去掉提示词、只保留随机数,模型就随意生成一张像样的图片,这称为无条件生成。提示词只是在此基础上加的条件,所以本文先研究无条件生成,到 Diffusion 一章再把提示词加回来。
  • 学习:模型不是人写好的规则,而是从大量训练图片中学出来的。
From the familiar “prompt in, picture out” to the problem this guide studies. Press Next to peel off one layer at a time.从熟悉的“输入提示词、输出图片”,到本文要研究的问题。按“下一步”逐层剥开。

The problem therefore becomes: given a large pile of training images, how can we build a machine that, each time it runs, produces a new image that looks as if it belonged with the training images? The next chapter makes “looks as if it belonged” precise.

于是问题变成:给定一大堆训练图片,怎样造出一台机器,每运行一次就产出一张新图片,而且看起来与训练图片属于同一类?下一章先把“看起来属于同一类”说得更精确。

Part I第一部分
Foundations: distributions, density and likelihood基础:分布、密度与似然
Data as samples

Data are samples from a distribution数据是分布的样本

The new image we want is not just any image. A 28×28 image has 784 pixels, and filling them in at random almost always gives noise. What we want is an image that looks as if it belonged with the training images, for example another handwritten digit.

Imagine every possible image sitting in a huge lottery box, each with a different share: images that look like real handwritten digits have large shares, and noise has almost none. The ten thousand training images are draws from this box, and generating a new image means drawing one more. Mathematically the box is a probability distribution, written $p_{\text{data}}(x)$, and an image's share is its probability. The difficulty is that the box itself cannot be seen; only the draws are at hand. A generative model therefore builds, from the draws, a box $p_\theta(x)$ that resembles the real one as closely as possible, and then draws from it. This problem is called density estimation. It belongs to unsupervised learning, because the training data consist only of the samples themselves, with no answers labelled by people. The appendix at the end reviews the probability ideas used throughout this guide.

For continuous values, such as pixel brightness, the probability of drawing any single exact value is zero, so another quantity is needed to describe how crowded the draws are near a point: the probability density. A density becomes a probability only after it is integrated over an interval, so the density itself can exceed 1, while the total area under the curve is always 1.

我们想要的“新图片”并不是任意一张图片。28×28 的图片有 784 个像素,随手给每个像素填一个值,几乎总是一片噪声;我们想要的是看起来与训练图片属于同一类的图片,比如又一个手写数字。

可以把所有可能的图片想象成装在一个巨大的抽奖箱里,每张图片占的份量不同:像真实手写数字的图片份量大,噪声图片的份量几乎为 0。训练集里的一万张图片,就是从这个箱子里抽出来的;生成一张新图片,就是再从箱子里抽一张。在数学上,这个箱子就是一个概率分布,记作 $p_{\text{data}}(x)$,每张图片的份量就是它的概率。困难在于箱子本身看不见,手里只有抽出来的样本。生成模型要做的,就是根据这些样本造一个尽量相像的箱子 $p_\theta(x)$,再从中抽取。这类问题称为 density estimation(密度估计)。它属于无监督学习,因为训练数据只有样本本身,没有人工标注的答案。全文用到的概率知识,在文末附录中有单独的介绍。

对于连续取值的量,例如像素的亮度,抽中某一个精确值的概率是 0,因此需要另一个量来描述“这个值附近的样本有多密集”,即概率密度。密度只有在一段区间上积分之后才成为概率,所以它本身可以大于 1,而曲线下的总面积始终等于 1。

A one-dimensional Gaussian $\mathcal N(0,\sigma^2)$. As σ shrinks, the distribution narrows and the peak density rises above 1; yet the probability of the yellow interval, and the total area under the curve, never exceed 1.一维高斯分布 $\mathcal N(0,\sigma^2)$。把 σ 调小,分布变窄,峰值密度会超过 1;但黄色区间对应的概率、以及曲线下的总面积,始终不超过 1。
Maximum Likelihood

Maximum likelihood: making the training data most probable最大似然:使训练数据最有可能发生

The previous chapter described generation as building a lottery box $p_\theta(x)$ that resembles the real one and drawing from it. Building it well requires a way to judge the resemblance, and a natural test is this: real training images, looked up in the model's box, should turn out to be common rather than rare. To run this test, the most direct approach is to write down a formula for $p_\theta(x)$, so that the share of any image can be computed. For one-dimensional data, for instance, one may assume a Gaussian, whose parameters θ are its mean μ and standard deviation σ; each choice of θ gives a different $p_\theta(x)$. The standard way to choose θ is maximum likelihood estimation, which makes the training data as probable as possible under the model. The formula uses the notation argmax, which differs from max:

  • $\max_\theta f(\theta)$: the largest value the function reaches, an output.
  • $\arg\max_\theta f(\theta)$: the θ at which that largest value is reached, an input. Read it as “the θ that makes $f(\theta)$ largest”.

For example, $f(\theta)=-(\theta-2)^2$ is largest at θ = 2, where it equals 0, so $\max_\theta f(\theta)=0$ while $\arg\max_\theta f(\theta)=2$. Training needs the parameters themselves, not the best score, so the formula uses argmax:

上一章把生成描述为:造一个尽量像真实箱子的 $p_\theta(x)$,再从中抽取。要把箱子造好,先得有办法判断它像不像。一个自然的标准是:把真实的训练图片放到模型的箱子里查一查,它们应该是常见的,而不是罕见的。为了做这个检查,最直接的做法是写出 $p_\theta(x)$ 的具体公式,这样任何一张图片的份量都能算出来。例如对一维数据,可以假设它服从高斯分布,参数 θ 就是均值 μ 和标准差 σ;不同的 θ 给出不同的 $p_\theta(x)$。挑选 θ 的标准做法是 maximum likelihood estimation(最大似然估计),即让训练数据在模型下出现的概率尽可能大。式中用到记号 argmax,它与 max 不同:

  • $\max_\theta f(\theta)$:函数能达到的最大值,是一个输出。
  • $\arg\max_\theta f(\theta)$:取得这个最大值时的 θ,是一个输入,读作“使 $f(\theta)$ 最大的 θ”。

例如 $f(\theta)=-(\theta-2)^2$ 在 θ = 2 时最大,最大值为 0,于是 $\max_\theta f(\theta)=0$,而 $\arg\max_\theta f(\theta)=2$。训练要的是参数本身,而不是最好的分数,所以公式里写的是 argmax:

Step by step逐项拆解
$$\htmlClass{fp fp1}{\theta^*}=\htmlClass{fp fp2}{\arg\max_\theta}\,\htmlClass{fp fp3}{\sum_i}\,\htmlClass{fp fp4}{\log}\,\htmlClass{fp fp5}{p_\theta\big(x^{(i)}\big)}$$

Taking the logarithm does not move the maximum, but it turns a product of per-sample probabilities into a sum and is numerically more stable. In the figure below, the height of each vertical line is one sample's $p_\theta(x^{(i)})$, and the log-likelihood is the sum of the logarithms of these heights. The method has one precondition: $p_\theta(x)$ must be written down and computed. For one-dimensional data a Gaussian takes a single line; for 784-dimensional images it is far harder, as the next chapter discusses.

取对数不改变最大值的位置,却把各样本概率的连乘变成求和,数值上也更稳定。下图中每条竖线的高度就是一个样本的 $p_\theta(x^{(i)})$,对数似然是这些高度取对数后的总和。这个方法有一个前提:必须能写出 $p_\theta(x)$ 并算出它的值。对一维数据,高斯分布的公式一行就能写完;换成 784 维的图片就难得多,下一章讨论这一点。

Data and model p(x)数据与模型 p(x)
Likelihood landscape · μ across, σ up似然地形 · 横轴 μ,纵轴 σ
Fitting a Gaussian to one-dimensional data. Move the sliders, or click a point on the likelihood landscape on the right, and watch the line heights and the log-likelihood change; gradient ascent climbs the slope to the top of the landscape on its own.用高斯分布拟合一维数据。拖动滑块,或在右侧的似然地形上点选参数,观察竖线高度与对数似然的变化;“梯度上升”会沿坡度自动爬到地形的最高点。
Explicit vs. Implicit

Explicit and implicit: write down p(x), or only learn to sampleExplicit 与 Implicit:写出 p(x),还是只学会采样

Putting the two previous chapters together: to generate, we draw from $p_\theta(x)$; to train, we check how probable the training images are under $p_\theta(x)$ and adjust the parameters by maximum likelihood. Both rely on “writing down $p_\theta(x)$”, which means giving a function that takes any $x$ and returns how probable it is. For one-dimensional data the Gaussian formula is such a function. For images it would be a function that takes an image and returns the probability of that image.

The difficulty is a requirement every probability must meet: over all possible images, the probabilities add up to exactly 1. Getting a neural network to give an image a score is easy, but a score is not yet a probability. To turn scores into probabilities, each score must be divided by the total score of all images, just as a candidate's votes give a share only once the total number of votes is known. There are far too many possible images to add them all up, as the experiment below shows.

把前两章合起来看:生成时,从 $p_\theta(x)$ 中抽取;训练时,检查训练图片在 $p_\theta(x)$ 下有多常见,再用最大似然调整参数。两者都依赖“写出 $p_\theta(x)$”,也就是给出一个函数,输入任意一个 $x$,输出它出现的概率。对一维数据,高斯分布的公式就是这样的函数。换成图片,就需要一个函数:输入一张图片,输出这张图片出现的概率。

难点在于概率必须满足一个要求:所有可能的图片,概率加起来恰好等于 1。让神经网络给一张图片打一个分数并不难,但分数还不是概率。要把分数换算成概率,必须除以所有图片分数的总和,就像只知道某位候选人的票数还算不出得票率,还要知道总票数。而可能的图片多到根本加不完,下面的小实验演示这一点。

Turning scores into probabilities for black-and-white images. With a side length of 2 there are only 16 possible images, so all of them can be listed: each gets a score from the network (gray bar), and its probability is its score divided by the total. Drag the slider to enlarge the images: the number of possible images grows so fast that by 28×28 the total can never be added up.把黑白图片的分数换算成概率。边长为 2 时只有 16 种可能的图片,可以全部列出:网络给每张图片一个分数(灰色柱),概率等于它的分数除以全部分数的总和。拖动滑块增大图片边长,可能的图片数量增长极快,到 28×28 时总和已经不可能算出来。

Two routes grew out of this difficulty, and the first split of the taxonomy follows them:

  • Explicit density: keep the plan above. The model can compute the probability of any image, and a special structure makes the probabilities add up to 1 automatically, so the total never has to be computed. Training uses maximum likelihood; generation draws images according to these probabilities. The price is that the special structure limits how the model can be built; later chapters show two such structures.
  • Implicit density: skip computing probabilities and build the generating machine directly. It takes a set of random numbers and outputs an image, so each run is one draw from the box, without the box ever being written down. This sidesteps the total entirely, and the network can be built any way we like. The price is that the model cannot say how probable an image is and cannot use maximum likelihood, so training needs some other way to judge whether its images look real.

The figure below compares how the two routes train and generate.

由这个难点分出了两条路线,分类图的第一层正是按此划分的:

  • Explicit density(显式密度):坚持上面的方案。模型能算出任意一张图片的概率,并通过一种特殊的结构,使所有概率自动加起来等于 1,因而不必真的去求总和。训练时用最大似然,生成时按这些概率抽取图片。代价是特殊结构限制了模型的设计方式,后面的章节会介绍两种这样的结构。
  • Implicit density(隐式密度):跳过“算概率”这一步,直接造那台生成机器:输入一组随机数,输出一张图片,每运行一次就相当于从箱子里抽一张,而箱子本身从未被写出来。这样完全绕开了求总和的问题,网络也可以随意设计;代价是模型无法回答某张图片出现的可能性有多大,也不能用最大似然训练,需要另找办法判断生成的图片像不像真的。

下图对比两条路线怎样训练、怎样生成。

How the two routes train and generate. Both end by producing a new image; the explicit route gets there through probabilities, the implicit route goes straight from random numbers to an image.两条路线怎样训练、怎样生成。两者最终都产出新图片:explicit 路线绕道“算概率”,implicit 路线直接从随机数得到图片。

The two models below have learned the same two-dimensional distribution. The explicit model on the left can report the density at any point; the implicit model on the right can only keep sampling, and to learn the density it has to approximate it with a histogram of its samples.

下面两个模型学到的是同一个二维分布。左侧的 explicit 模型能回答任意一点的密度;右侧的 implicit 模型只能不断采样,若想知道密度,只能用样本的直方图去逼近。

Explicit · writes down p(x)Explicit · 写出了 p(x)
Implicit · can only sampleImplicit · 只会采样
Two representations of the same distribution. Click either canvas to ask for $p(x)$ at that point: the left side gives the exact value and the right side cannot answer. Only after many samples does the histogram on the right approach the heat map on the left, and the error reading falls accordingly.同一分布的两种表示。点击任一画布查询该点的 $p(x)$:左侧给出精确值,右侧无法回答。多次采样之后,右侧的直方图估计才慢慢接近左侧的热图,误差读数随之下降。

Following these two routes, and the specific techniques within each, the common generative models can be arranged into the map below1. The next three parts go through it in order.

按照这两条路线,以及每条路线内部的具体做法,常见的生成模型可以整理成下面这张分类图1。后面三部分将依次介绍。

Can compute p(x) 能计算 p(x) Cannot compute p(x), but can sample from it 不能计算 p(x), 但能从中采样 Exact Lower bound One step Many steps 精确计算 近似(下界) 一步采样 多步迭代采样
A map of generative models. The first split asks whether the model can compute $p(x)$; the second asks how it computes it, or how it samples. Click any node to see what that family can and cannot do.生成模型的分类。第一层按“能否计算 $p(x)$”划分,第二层按计算方式或采样方式划分。点击任一节点,查看这一类模型能做什么、不能做什么。
Encoder · Decoder

Inputs and outputs: what encoders and decoders do输入与输出:encoder 与 decoder 在做什么

Both routes are built from neural networks. For the purposes of this guide, a neural network can be treated as a function with adjustable parameters: numbers go in, other numbers come out, and the parameters θ decide how one becomes the other. A 28×28 grayscale image is simply 784 numbers, and training means adjusting θ again and again until the outputs come closer to what is wanted. Two kinds of network appear throughout generative models. An encoder compresses an image into a few numbers, called a latent vector; a decoder does the reverse and expands a few numbers into an image. The encoder's output is smaller than its input and the decoder's is larger, so the diagrams draw them as trapezoids that narrow or widen from left to right.

Generative models are built by combining networks like these. Each later chapter that introduces a model includes a structure diagram showing which networks it uses, what each takes in and puts out, and how training differs from generation. The boxes in these diagrams are colored by what they hold:

  • Data (blue): real images from the training set.
  • Networks (purple): the parts with parameters that training adjusts.
  • Latent vectors and noise (gray): a few numbers, or random numbers drawn from a standard normal distribution.
  • Loss (red): a single number measuring how far an output is from what is wanted; training makes it smaller.
  • Generated output (green): what the model produces.

两条路线都由神经网络搭建而成。在本文中,神经网络可以先看作一个带可调参数的函数:输入一组数,输出另一组数,参数 θ 决定输入怎样变成输出。一张 28×28 的灰度图片就是 784 个数;训练就是反复调整 θ,让输出更接近要求。生成模型里反复出现两类网络。Encoder(编码器)把一张图片压缩成少数几个数,称为 latent 向量;decoder(解码器)反过来,把少数几个数展开成一张图片。前者的输出比输入小,后者的输出比输入大,所以图中分别画成从左到右收窄和展开的梯形。

生成模型就是由这样的网络组合而成的。后面各章介绍具体模型时,都附有一张结构图,说明它由哪些网络组成、每个网络输入什么、输出什么,以及训练时和生成时的路线有何不同。结构图中方框的颜色表示其中的内容:

  • 数据(蓝色):训练集中的真实图片。
  • 网络(紫色):带参数、由训练调整的部分。
  • latent 向量与噪声(灰色):少数几个数,或从标准正态分布抽出的随机数。
  • 损失(红色):衡量输出离要求有多远的一个数,训练让它变小。
  • 生成结果(绿色):模型产出的内容。
What an encoder and a decoder take in and put out. Press Next to see each in turn.Encoder 与 decoder 的输入和输出。按“下一步”分别查看。
Part II第二部分
Explicit density: writing down p(x)Explicit density:写出 p(x)
Autoregressive · Tractable density

Autoregressive models: a joint distribution as a chain of conditionalsAutoregressive:把联合分布拆成一串条件分布

An image has hundreds of pixels, and writing down their joint distribution directly is very hard. An autoregressive model takes another angle: it lays the pixels out in a sequence and predicts each pixel from the ones before it. The figure below shows its structure.

一张图片有几百个像素,直接写出它们的联合分布十分困难。Autoregressive 模型换了一个角度:把像素排成一个序列,每次根据前面的像素预测下一个像素。下图是它的结构。

The structure of an autoregressive model. During training every position is predicted at once; during generation the network runs once per pixel, feeding each new pixel back in.Autoregressive 模型的结构。训练时所有位置一次算完;生成时每个像素运行一次网络,并把新像素接回输入。

The approach rests on the chain rule of probability, which guarantees that any joint distribution can be factored into a product of conditional distributions:

这种做法的依据是概率论的链式法则:任何联合分布都可以拆成一串条件分布的乘积:

Step by step逐项拆解
$$\htmlClass{fp fp1}{p(x)}=\htmlClass{fp fp2}{\prod_{t=1}^{T}}\htmlClass{fp fp3}{p(x_t}\htmlClass{fp fp4}{\mid x_1,\ldots,x_{t-1})}$$

Generating an image then becomes predicting pixels one at a time. Each step only has to answer “given the pixels so far, how likely is each value of the next one?”, which is exactly what an RNN or a masked Transformer does well3. Every factor can be computed exactly, so their product $p(x)$ can be too, and these models therefore have a tractable density. The price is that generation must proceed in order, so T pixels take T steps; and an image is two-dimensional, so forcing it into a single line is unnatural.

于是生成一张图片变成逐个预测像素,每一步只需回答“已知前面的像素,下一个像素取各个值的概率是多少”,这正是 RNN 或带掩码的 Transformer 擅长的事3。每个因子都能精确算出,它们的乘积 $p(x)$ 也就能精确算出,这类模型因而属于 tractable density(可精确计算的密度)。代价是生成必须按顺序进行,T 个像素就需要 T 步;而且图像本身是二维的,硬排成一行并不自然。

Six patterns in the training data (plus a little noise)训练数据中的六类图案(另加少量噪声)
An autoregressive model of 5×5 binary images, generated left to right and top to bottom. In Pixel by pixel, hatched cells are pixels not yet generated, which the model cannot see. In Draw and score, click a cell to flip it; each number is that pixel's conditional probability, and red outlines mark the pixels that surprise the model.一个 5×5 二值图像的 autoregressive 模型,按从左到右、从上到下的顺序生成。“逐像素生成”中,斜线格是尚未生成、模型看不到的像素;“手绘打分”中,点击格子可以翻转像素,每格的数字是该像素的条件概率,红框标出让模型感到意外的像素。
Latent space

Latent space: describing an image with a few numbersLatent space:用少数几个数描述一张图

A 28×28 image has 784 pixel values, but a random point in this 784-dimensional space is almost always noise. Real images occupy a tiny part of it, and they usually differ from one another along only a few factors, such as shape, stroke width and slant. A latent space is a low-dimensional coordinate system for these factors: each image corresponds to a point $z$ in it, and a decoder network turns $z$ back into pixels.

In the example below the latent space has only two dimensions: the horizontal axis controls shape and the vertical axis controls aspect ratio. The axes learned by a real model rarely have such tidy meanings, but the principle is the same. Nearby points in latent space decode to similar images, and moving along a straight line produces a smooth change in the image.

28×28 的图片有 784 个像素值,但在这 784 维空间里随手取一个点,几乎总是一片噪声;真实图片只占据其中极小的一部分,而且彼此的差别往往只体现在少数几个因素上,比如形状、粗细和倾斜。Latent space(潜空间)就是为这些因素建立的低维坐标系:每张图片对应其中的一个点 $z$,再由一个 decoder 网络把 $z$ 还原成像素。

下面的例子中 latent space 只有两维,横轴控制形状,纵轴控制横纵比。真实模型学到的坐标轴通常没有这样整齐的含义,但道理相同:latent space 中相距很近的点解码出相似的图片,沿一条直线移动对应图片的平滑变化。

Latent space · z ∈ ℝ²
Decoder output · x ∈ ℝ⁷⁸⁴Decoder 输出 · x ∈ ℝ⁷⁸⁴
Drag the purple point in the latent space on the left; the right side shows the 28×28 image the decoder produces, so two numbers determine 784 pixels. Turn on Show decoded grid to see the image belonging to every location on the plane.拖动左侧 latent space 中的紫色点,右侧显示 decoder 输出的 28×28 图片:两个数决定了 784 个像素。打开“铺满解码结果”,可以看到平面上每个位置各自对应的图片。

The benefit of this structure is clearest in interpolation. Averaging two images in pixel space gives only a double exposure of two translucent shapes, which is not an image the dataset would contain. Taking points along the line between two latent codes and decoding them gives genuine intermediate shapes.

这种结构的好处在插值时最为明显。在像素空间里直接对两张图片取平均,得到的只是两个半透明形状的叠影,并不是数据集里会出现的图片;在 latent space 里取两点连线上的中间点再解码,得到的则是一个真正的中间形状。

Pixel space像素空间
插值
Latent spaceLatent space
插值
Two interpolations between the same pair of endpoints. The top row blends linearly in pixel space, so the middle frames are double exposures; the bottom row interpolates in latent space and then decodes, so every frame is a complete shape.同一对端点的两种插值。上排在像素空间中线性混合,中间几格是两个形状的叠影;下排在 latent space 中线性插值后再解码,每一格都是完整的形状。
Autoencoder

Autoencoder: squeezing an image into a few numbers and backAutoencoder:把图片压成几个数,再还原回来

The previous chapter assumed a decoder that turns a point in latent space back into an image. An autoencoder is the most direct way to obtain one: an encoder compresses the image into a few numbers $z$, a decoder expands $z$ back into an image, and training asks only that the result be as close to the original as possible. The figure below shows its structure.

上一章假定已经有一个 decoder,能把 latent space 中的点还原成图片。Autoencoder(自编码器)是得到这样一个 decoder 最直接的办法:encoder 把图片压缩成少数几个数 $z$,decoder 再把 $z$ 还原成图片,训练只要求还原出的图片与原图尽量接近。下图是它的结构。

The structure of an autoencoder. During training the encoder and decoder learn together to reconstruct the input; at generation time only the decoder can be used, and there is no rule for choosing its starting point z.Autoencoder 的结构。训练时 encoder 与 decoder 一起学习重建输入;生成时只能使用 decoder,而它的起点 z 无从选择。

A trained encoder assigns each training image one fixed point, so the same image lands in the same place however many times it is encoded. The training objective cares only whether these points decode back to their images, not about the regions between them, so the codes end up scattered across the plane with large gaps the decoder has never seen. This is where generation runs into trouble: a $z$ picked at random usually falls into a gap and decodes to something that looks like nothing.

训练好的 encoder 给每张训练图片分配一个固定的点,同一张图片无论编码多少次,都落在同一个位置。训练目标只关心这些点能否还原成原图,并不关心点与点之间的区域,于是编码散落在平面各处,中间留着大片 decoder 从未见过的空白。用它生成新图片时,问题就出在这里:随手取一个 $z$,多半落在空白处,解码出来什么也不像。

Autoencoder · latent spaceAutoencoder · latent space
An autoencoder encoding the same image again and again (schematic, with a hand-built decoder). Choose a training image at the top. Each purple dot is one encoding, and the image below the plane decodes the latest point; however many times the image is encoded, the result is the same point. Pick a random z to place a green point on the plane: it usually lands in a gap between the codes, and the decoder can only output a meaningless pattern.Autoencoder 反复编码同一张图片(示意,decoder 为手工构造)。在上方选择一张训练图片;每个紫色点是一次编码结果,平面下方是最新一个点的解码,无论编码多少次,结果都是同一个点。“随手取一个 z”在平面上放一个绿色点:它多半落在编码之间的空白处,decoder 只能输出一团无意义的图案。

A plain autoencoder is therefore good for compressing images and extracting features, but it cannot simply be used to generate. For a randomly picked $z$ to decode to a reasonable image as well, the codes have to fill a region agreed on in advance. That is what the VAE in the next chapter does.

因此普通 autoencoder 适合压缩图片、提取特征,却不能直接用来生成。要让随手取的 $z$ 也能解码成像样的图片,编码就必须铺满一块事先约定的区域,下一章的 VAE 正是这样做的。

Variational Autoencoder · Approximate density

VAE: encoding to a distributionVAE:编码成一个分布

A VAE (variational autoencoder) keeps the encoder and decoder of an autoencoder and makes two changes, both aimed at filling the gaps seen in the previous chapter4:

  • Encoder output: a distribution $\mathcal N(\mu,\sigma^2)$ instead of a point, and each encoding draws a fresh $z$ from it.
  • Training objective: besides accurate reconstruction, the distribution must also stay close to a prior agreed on in advance, $\mathcal N(0,I)$.

The figure below shows the structure of a VAE; Compare with Autoencoder sets the two models one above the other.

VAE(variational autoencoder,变分自编码器)保留了 autoencoder 的 encoder 与 decoder,只做两处改动,目的都是填满上一章看到的空白4:

  • Encoder 的输出:一个分布 $\mathcal N(\mu,\sigma^2)$,而不是一个点,每次编码都从中抽一个新的 $z$。
  • 训练目标:除了要求重建准确,还要求这个分布接近事先约定的先验 $\mathcal N(0,I)$。

下图是 VAE 的结构,“与 Autoencoder 对比”把两种模型上下并列。

The structure of a VAE. The encoder's output splits into μ and σ, noise ε is mixed in, and the loss gains a KL term; at generation time the encoder is not used at all. With Compare with Autoencoder on, the parts the VAE adds or changes are highlighted.VAE 的结构。Encoder 的输出分成 μ 与 σ,并混入噪声 ε,损失多出一项 KL;生成时完全不需要 encoder。打开“与 Autoencoder 对比”后,VAE 新增或改动的部分以强调色标出。

The first change means the decoder is trained not on a few isolated points but on a small region around each one. The second pulls all of these regions toward the origin until they join up. Together they leave no large gaps in the latent space, so a $z$ drawn at random from the prior still decodes to a reasonable image. The experiment below feeds the same image into both kinds of encoder again and again.

第一处改动使 decoder 在训练中见到的不是孤立的几个点,而是每个点周围的一小片区域;第二处改动把这些区域都拉向原点,直到彼此衔接。两者合起来,latent space 中就不再有大片空白,从先验中随手抽一个 $z$ 也能解码成像样的图片。下面的小实验把同一张图片反复送进两种 encoder。

Autoencoder · a pointAutoencoder · 一个点
VAE · a distributionVAE · 一个分布
The same image encoded repeatedly by the two kinds of encoder (schematic, with a hand-built decoder). Each purple dot is one encoding, and the image below each plane decodes the latest point. The autoencoder always returns the same point; the VAE returns a cloud around μ. Drawing a z from the prior shows the consequence: the autoencoder's decoder meets a point it has never seen, while the VAE's decodes it without trouble.两种 encoder 反复编码同一张图片(示意,decoder 为手工构造)。每个紫色点是一次编码结果,平面下方是最新一个点的解码。Autoencoder 每次都给出同一个点,VAE 则在 μ 周围给出一团点。“从先验抽一个 z”展示了这一差别的后果:autoencoder 的 decoder 遇到从未见过的点,VAE 的 decoder 则能正常解码。
AutoencoderVAE
Encoder outputOne point zParameters μ and σ of a distribution
Same image encoded twiceIdentical resultA different z each time
Training objectiveReconstruction errorReconstruction error + KL(q ‖ p(z))
Latent spaceScattered codes with gapsPacked around the origin, regions joined up
Generating new imagesNot directlyDraw z ~ N(0, I), then decode
Typical useCompression, feature extractionGeneration, smooth latent spaces
AutoencoderVAE
Encoder 输出一个点 z一个分布的参数 μ、σ
同一张图编码两次结果完全相同每次得到不同的 z
训练目标重建误差重建误差 + KL(q ‖ p(z))
Latent space编码散落,中间有空白集中在原点附近,彼此衔接
生成新图片不能直接生成抽 z ~ N(0, I) 再解码
常见用途压缩、提取特征生成、平滑的 latent space

Training with the ELBO用 ELBO 训练

The two requirements of the training objective, accurate reconstruction and closeness to the prior, can be derived from maximum likelihood. With a latent variable in the model, the probability of an image becomes $p_\theta(x)=\int p_\theta(x\mid z)\,p(z)\,dz$, an integral over every possible $z$, which cannot be computed exactly. The VAE therefore maximizes a lower bound on its logarithm, the ELBO (evidence lower bound):

训练目标的两项要求,即重建准确、分布接近先验,可以从最大似然推导出来。模型中有了 latent 变量之后,一张图片的概率变成 $p_\theta(x)=\int p_\theta(x\mid z)\,p(z)\,dz$,需要对所有可能的 $z$ 积分,无法精确计算。VAE 因此转而最大化它的对数的一个下界,即 ELBO(evidence lower bound,证据下界):

Step by step逐项拆解
$$\htmlClass{fp fp1}{\log p_\theta(x)}\ \htmlClass{fp fp2}{\ge}\ \htmlClass{fp fp3}{\mathbb E_{z\sim q_\phi(z\mid x)}}\big[\htmlClass{fp fp4}{\log p_\theta(x\mid z)}\big]\ \htmlClass{fp fp5}{-\ D_{\mathrm{KL}}\big(q_\phi(z\mid x)\,\|\,p(z)\big)}$$

Why is the right-hand side a lower bound? The exact relation is $\log p_\theta(x)=\text{ELBO}+D_{\mathrm{KL}}\big(q_\phi(z\mid x)\,\|\,p_\theta(z\mid x)\big)$. The last term measures how far the encoder's guess is from the true posterior $p_\theta(z\mid x)$, which cannot be computed; but a KL divergence is never negative, so the ELBO can never exceed $\log p_\theta(x)$. Raising the ELBO therefore either raises $\log p_\theta(x)$ itself or narrows the gap between the two.

右边为什么是下界?精确的关系是 $\log p_\theta(x)=\text{ELBO}+D_{\mathrm{KL}}\big(q_\phi(z\mid x)\,\|\,p_\theta(z\mid x)\big)$。最后一项衡量 encoder 的估计离真正的后验 $p_\theta(z\mid x)$ 有多远,这个后验算不出来;但 KL 散度永远不小于 0,所以 ELBO 永远不超过 $\log p_\theta(x)$。推高 ELBO,要么推高 $\log p_\theta(x)$ 本身,要么缩小两者之间的差距。

The ELBO and log p(x) on a number line, with schematic values. The red segment between them is the KL divergence between the encoder's distribution and the true posterior. Training the model moves both points to the right; a more accurate encoder shrinks the red gap.数轴上的 ELBO 与 log p(x)(示意数值)。两者之间的红色线段是 encoder 给出的分布与真实后验之间的 KL 散度。模型训练得越好,两点一起右移;encoder 估计得越准,红色差距越小。

The VAE is therefore an approximate density model. The second term is a KL divergence, and the two terms pull against each other:

  • The reconstruction term wants σ near 0 for every $x$ and the μ values well apart, which makes decoding easiest.
  • The prior term wants every μ near 0 and every σ near 1, squeezing all codes into a standard normal distribution.

The experiment below uses a weight β to set the balance between the two terms; β = 1 is the standard VAE10. At β = 0 the model reduces to a plain autoencoder, and the gaps between codes decode to noise. At moderate β the distributions join up, and every $z$ drawn from the prior decodes to a reasonable image. At large β all the distributions pile on top of one another, and the decoder can only output an average of the images, which looks blurry. This is also why VAE samples tend to be blurry.

VAE 因此属于 approximate density(近似密度)。式中第二项是 KL 散度,两项之间存在拉锯:

  • 重建项希望每个 $x$ 的 σ 趋于 0、μ 彼此分开,这样 decoder 最容易还原。
  • 先验项希望每个 μ 趋于 0、σ 趋于 1,让所有编码都挤成标准正态分布。

下面的小实验用一个权重 β 调节两项的比例,β = 1 即标准 VAE10。β 为 0 时退化为普通 autoencoder,编码之间的空白处解码出噪声;β 适中时各分布彼此衔接,从先验中采样的 $z$ 都能解码成像样的图片;β 过大时所有分布挤在一起,decoder 只好输出各图片的平均,结果变得模糊。VAE 样本普遍偏模糊,原因也在于此。

Latent space · q(z|x) and the priorLatent space · q(z|x) 与先验
Decoded image解码结果
A schematic VAE in a two-dimensional latent space, with a hand-built decoder. Blue circles show each training image's $q_\phi(z\mid x)$ with radius σ; the gray dashed circles mark 1σ and 2σ of the prior $\mathcal N(0,I)$. Click or drag on the plane to decode any location, and sample from the prior to see what happens when new images are generated.二维 latent space 中的 VAE 示意,decoder 为手工构造。蓝色圆表示每张训练图片的 $q_\phi(z\mid x)$,半径为 σ;灰色虚线圆是先验 $\mathcal N(0,I)$ 的 1σ 与 2σ 范围。点击或拖动平面可查看任意位置的解码结果,“从先验采样”展示生成新图片时会发生什么。

Reparameterization trick重参数化技巧

Training meets one more technical obstacle. The reconstruction term needs a sample $z$ from $q_\phi(z\mid x)$, and sampling has no derivative, so gradients cannot flow back to the μ and σ produced by the encoder. The reparameterization trick moves the randomness into an independent noise variable ε:

训练时还有一个技术障碍。重建项需要从 $q_\phi(z\mid x)$ 中采样 $z$,而“采样”这个操作没有导数,梯度无法传回 encoder 输出的 μ 和 σ。重参数化技巧把随机性挪到一个独立的噪声 ε 上:

$$z=\mu+\sigma\epsilon,\qquad \epsilon\sim\mathcal N(0,1)$$

Now $z$ is an ordinary function of μ and σ, with $\partial z/\partial\mu=1$ and $\partial z/\partial\sigma=\epsilon$, so gradients pass through; ε is just an input that needs no gradient. Each forward pass draws a fresh ε, and the backward pass treats that ε as a constant.

这样 $z$ 成为 μ 和 σ 的普通函数,$\partial z/\partial\mu=1$,$\partial z/\partial\sigma=\epsilon$,梯度可以顺利回传;ε 只是一个不需要求导的输入。每次前向传播重新抽一个 ε,反向传播时把这次的 ε 当作常数即可。

Computation graphs for the two ways of sampling. Gray solid lines are the forward pass and blue dashed lines are gradients in the backward pass. With direct sampling the gradient stops at the sampling node; after reparameterization it bypasses ε and reaches μ and σ.两种采样写法的计算图。灰色实线为前向计算,蓝色虚线为反向传播的梯度。直接采样时梯度在采样节点处中断;重参数化之后,梯度绕过 ε 直达 μ 与 σ。
Part III第三部分
Implicit density: sampling onlyImplicit density:只会采样
Generative Adversarial Network · Direct

GAN: a discriminator in place of p(x)GAN:用一个判别器代替 p(x)

Once $p_\theta(x)$ is given up, maximum likelihood is no longer available, and another way is needed to judge whether the samples are good. A GAN trains a second network, the discriminator D, to act as a judge. The generator G turns random noise $z\sim p(z)$ into a sample $x=G(z)$, and D outputs $D(x)$, the probability that $x$ came from the real data5. The figure below shows its structure.

放弃写出 $p_\theta(x)$ 之后,最大似然无从谈起,需要另一种方式判断生成得好不好。GAN 的思路是再训练一个判别器 D 充当裁判:generator G 把随机噪声 $z\sim p(z)$ 变成样本 $x=G(z)$,D 输出 $D(x)$,即 $x$ 来自真实数据的概率5。下图是它的结构。

The structure of a GAN. During training the discriminator scores both real and generated images; at generation time only the generator is used.GAN 的结构。训练时判别器同时给真图和生成图片打分;生成时只用到 generator。

The objectives of the two networks are exactly opposed:

两个网络的目标正好相反:

Step by step逐项拆解
$$\htmlClass{fp fp1}{\min_G}\,\htmlClass{fp fp2}{\max_D}\ \htmlClass{fp fp3}{\mathbb E_{x\sim p_{\text{data}}}\big[\log D(x)\big]}+\htmlClass{fp fp4}{\mathbb E_{z\sim p(z)}\big[\log\big(1-D(G(z))\big)\big]}$$

D wants to label real samples 1 and generated samples 0; G wants D to label generated samples 1 as well. At the ideal equilibrium $p_G=p_{\text{data}}$, and D outputs 0.5 everywhere. G is a one-way map $z\to x$ with no matching encoder, so a GAN neither gives $p(x)$ nor maps an image back to $z$. What it gains in return is a sharp sample in a single step.

D 希望把真实样本判为 1、生成样本判为 0;G 希望 D 把生成样本也判为 1。理想的平衡点上 $p_G=p_{\text{data}}$,D 处处输出 0.5。G 是一个只能向前走的映射 $z\to x$,没有对应的 encoder,所以 GAN 既不给出 $p(x)$,也无法把一张图片映射回 $z$;它换来的是一步即可得到的清晰样本。

Generator · x = G(z)
Distributions and discriminator分布与判别器
Real distribution p_data真实分布 p_dataHistogram of generated samples生成样本直方图Discriminator D(x)判别器 D(x)
Start起点
A one-dimensional GAN trained live in the browser; G and D are small networks with 24 hidden units each. The left plot is the generator's learned map $G(z)$, with light blue bands marking where the real data lies. On the right, the green histogram can only be obtained by sampling again and again, which is exactly what implicit density means. Choose “D trains 300 steps first” and start again: G then stays on a single peak for a long time.在浏览器中实时训练的一维 GAN,G 与 D 都是含 24 个隐藏单元的小网络。左图是 generator 学到的映射 $G(z)$,浅蓝色横带标出真实数据所在的区间;右图中绿色直方图只能靠反复采样得到,这正是 implicit density 的含义。选择“D 先训练 300 步”再开始,G 会长时间只占据一个峰。

Training has no loss curve that shows progress, since the two networks gain and lose ground against each other. A common failure is mode collapse, in which G learns to produce only one of the peaks. When the discriminator is strong from the start, G is first pushed toward the nearest peak; from then on it can lower its loss simply by fooling D on that peak, so it never goes looking for the other one. Choosing “D trains 300 steps first” in the experiment above reproduces this.

A second problem lies in G's objective. Early in training the samples are poor, D sees through them easily, and $D(G(z))$ is close to 0. At exactly this end $\log(1-D)$ is almost flat, so G receives a gradient near 0 and learns almost nothing. In practice G minimizes $-\log D(G(z))$ instead. The two objectives share the same optimum, but the new one is steepest when $D(G(z))$ is near 0, providing the largest gradient exactly when it is most needed. The GAN experiment above uses this form.

训练过程没有一条能说明进展的损失曲线,两个网络此消彼长。常见的问题是 mode collapse(模式坍塌),即 G 只学会生成其中一个峰:判别器一开始就很强时,G 先被推向离它最近的那个峰,之后只要在这个峰上骗过 D 就能降低损失,便不再去探索另一个峰。在上面的实验中选择“D 先训练 300 步”即可复现这种情形。

另一个问题出在 G 的目标函数上。训练初期生成样本很差,D 很容易识破,$D(G(z))$ 接近 0;而 $\log(1-D)$ 恰好在这一端几乎是平的,G 得到的梯度接近 0,几乎学不到东西。实践中把 G 的目标换成最小化 $-\log D(G(z))$,两者的最优点相同,但新目标在 $D(G(z))$ 接近 0 时最陡,正好在最需要的时候提供最大的梯度。上面的 GAN 实验用的就是这一写法。

log(1 − D): original formlog(1 − D):原始写法−log D: non-saturating form−log D:non-saturating 写法
The two objectives for G, both to be minimized, as functions of $D(G(z))$. Drag the slider: the steepness of each tangent is the size of the gradient G receives. At the left end, where D easily spots the fakes, the original form gives almost no gradient.G 的两种目标函数(都要最小化)随 $D(G(z))$ 的变化。拖动滑块,切线的陡峭程度就是 G 收到的梯度大小:在左端,即 D 能轻松识破生成样本时,原始写法几乎没有梯度。
Diffusion · Rectified Flow · Indirect

Diffusion: splitting one big step into many small onesDiffusion:把一步生成拆成许多小步

A GAN asks the generator to turn noise into data in a single step, which is hard and makes training unstable. Diffusion models split this into many small steps: first fix a way to add noise to the data gradually, then train a network to remove only a little noise at a time6. The figure below shows its structure.

GAN 要求 generator 一步就把噪声变成数据,这件事很难,训练也不稳定。Diffusion 模型把它拆成许多小步:先规定如何逐渐给数据加噪,再训练网络每次只去掉一点噪声6。下图是它的结构。

The structure of a diffusion model. Training is a single regression step on a randomly noised image; generation applies the same network T times, starting from pure noise.Diffusion 模型的结构。训练只是对一张随机加噪的图片做一次回归;生成时从纯噪声出发,把同一个网络调用 T 次。

The idea has several mathematical formulations, of which rectified flow is the simplest7. It draws a straight line between the data $x$ and noise of the same shape $z\sim\mathcal N(0,I)$:

这一思路有多种数学表述,其中 rectified flow 最为简洁7。它在数据 $x$ 与同形状的噪声 $z\sim\mathcal N(0,I)$ 之间连一条直线:

Step by step逐项拆解
$$\begin{gathered}\htmlClass{fp fp1}{x_t}=\htmlClass{fp fp2}{(1-t)\,x}+\htmlClass{fp fp3}{t\,z},\qquad \htmlClass{fp fp4}{v=\frac{dx_t}{dt}=z-x},\qquad \htmlClass{fp fp5}{t\sim\mathrm{Uniform}[0,1]}\\ \htmlClass{fp fp6}{\mathcal L=\big\|f_\theta(x_t,t)-v\big\|_2^2}\end{gathered}$$

The network $f_\theta(x_t,t)$ learns to predict the velocity $v$, with loss $\|f_\theta(x_t,t)-v\|_2^2$. This is an ordinary regression problem, and far more stable than the adversarial training of a GAN.

网络 $f_\theta(x_t,t)$ 的任务是预测速度 $v$,损失为 $\|f_\theta(x_t,t)-v\|_2^2$,这是一个普通的回归问题,比 GAN 的对抗训练稳定得多。

The noising process. Each data point moves along a straight line toward its own noise point (thin gray lines). Drag t and watch $x_t$ turn from two crescents into a cloud of Gaussian noise.加噪过程。每个数据点沿直线走向各自的噪声点(灰色细线)。拖动 t,$x_t$ 从两道弯月逐渐变成一团高斯噪声。

The same $x_t$ can arise from many different pairs $(x,z)$, so the network can only learn the conditional expectation of the velocity, $\mathbb E[v\mid x_t,t]$. At $t=1$ pure noise carries no information about the data, so the velocity can only point toward the mean of all the data; a single step would send every sample to somewhere near that mean, the same source of blur as in a VAE. With more steps, each step re-estimates the direction from the current position, and the samples gradually separate and settle onto the data. Diffusion sampling is therefore indirect: there is no direct map $z\to x$, only repeated calls to $f_\theta$ starting from noise.

To control which class is generated, the condition $y$ can also be fed to the network, and during training $y$ is randomly replaced by an empty condition $\varnothing$, so that a single network learns both the conditional and the unconditional velocity. At sampling time, classifier-free guidance extrapolates between the two8:

同一个 $x_t$ 可能来自许多不同的 $(x,z)$ 组合,因此网络只能学到速度的条件期望 $\mathbb E[v\mid x_t,t]$。在 $t=1$ 处,纯噪声不含任何关于数据的信息,速度只能指向全体数据的平均位置;若只走一步,所有样本都会落在平均值附近,这与 VAE 的模糊同出一源。步数增加之后,每一步都根据当前位置重新估计方向,样本才逐渐分开、落到数据上。所以 diffusion 的采样是间接的:它没有一个直接的 $z\to x$ 映射,而是从噪声出发反复调用 $f_\theta$。

若要控制生成的类别,可以把条件 $y$ 一并输入网络,训练时随机把 $y$ 替换为空条件 $\varnothing$,使同一个网络同时学会有条件与无条件两种速度。采样时用 classifier-free guidance(无分类器引导)把二者外推8:

Step by step逐项拆解
$$\htmlClass{fp fp1}{v^{\text{cfg}}}=\htmlClass{fp fp2}{v^{\varnothing}}+\htmlClass{fp fp3}{(1+w)}\,\htmlClass{fp fp4}{\big(v^{y}-v^{\varnothing}\big)}$$

$1+w=0$ gives unconditional generation, $1+w=1$ ordinary conditional generation, and $1+w>1$ strengthens the condition further.

$1+w=0$ 为无条件生成,$1+w=1$ 为普通的条件生成,$1+w>1$ 则进一步强化条件。

Steps T步数 T
Condition y条件 y
The sampling process. Green particles start from noise and follow the velocity field (gray arrows) toward the data in T steps. The velocity field here is computed exactly from the training data, as if the network had been trained to perfection. Each step moves every particle along the arrow at its current position; Next advances one step and Back undoes one. The mean distance to the data measures how close the particles finally land, and the line below keeps the result of each T so that they can be compared. With a single step, every particle lands at the mean of the data. Choose a condition and raise the guidance, and the particles gather more tightly on that crescent but also crowd toward one end of it: guidance trades diversity for fidelity.采样过程。绿色粒子从噪声出发,沿速度场(灰色箭头)分 T 步走向数据。这里的速度场由训练数据精确算出,相当于一个训练到极致的网络。每一步,粒子沿着当前位置的箭头移动一段;“下一步”前进一步,“上一步”退回一步。与数据的平均距离衡量粒子最终离数据有多近,下面一行会记下各个 T 的结果,便于比较。把步数设为 1,所有粒子都落在数据的平均位置;选择一个条件并调大引导强度,粒子会更集中地落在对应的弯月上,但也挤向弯月的一端,这是引导以多样性换取贴合程度的代价。
Putting it together

Latent diffusion and the full pictureLatent Diffusion 与全景

Running diffusion directly in pixel space is expensive, because the noise must have the same shape as the image. A latent diffusion model combines the earlier families9. A VAE first trains an encoder and a decoder that compress images into a smaller latent space, with a GAN discriminator loss making the decoder's output sharper. The encoder is then frozen and a diffusion model is trained on the latents, with conditions such as text injected through cross-attention. To generate, the model denoises iteratively in latent space starting from noise, and the decoder turns the result back into an image.

直接在像素空间做 diffusion 的计算量很大,因为噪声必须与图片同形状。Latent diffusion model 把前面几类模型组合在一起9:先用 VAE 训练一对 encoder 与 decoder,把图片压缩到较小的 latent space,并借助 GAN 的判别器损失让 decoder 的输出更清晰;随后冻结 encoder,在 latent 上训练 diffusion 模型,文本等条件通过 cross-attention 注入。生成时在 latent space 中从噪声开始迭代去噪,最后交给 decoder 还原成图片。

The structure of a latent diffusion model. Training has two stages: first a VAE is trained, with a GAN discriminator helping the decoder produce sharp images, then its encoder is frozen and a diffusion model is trained on the latents, reading the text condition. Generation uses only the diffusion network and the VAE decoder. The images are schematic.Latent diffusion 的结构。训练分两个阶段:先训练 VAE(借助 GAN 的判别器让 decoder 输出清晰),再冻结 encoder,在 latent 上训练读取文本条件的 diffusion 模型;生成时只用到 diffusion 网络和 VAE 的 decoder。图中的图片为示意。

The table below compares the four families.下表把四类模型放在一起比较。

ModelFamilyp(x)Latent zSamplingMain drawback
AutoregressiveExplicit · tractableExactNoneOne element at a time, slowImages must be ordered into a sequence
VAEExplicit · approximateLower bound only (ELBO)Yes, with an encoderOne step, fastBlurry samples
GANImplicit · directNoOnly z→xOne step, fastUnstable training, mode collapse
Diffusion / FlowImplicit · indirectNo (in this taxonomy)Noise has the data's shapeMany iterations, slowSampling takes dozens of steps
模型分类p(x)Latent z采样主要问题
AutoregressiveExplicit · tractable精确可算无逐个元素,慢图像需人为排成序列
VAEExplicit · approximate只有下界 ELBO有,且有 encoder一步,快样本偏模糊
GANImplicit · direct不能只有 z→x一步,快训练不稳定,mode collapse
Diffusion / FlowImplicit · indirect不能(本分类下)噪声与数据同形多步迭代,慢采样需要几十步
The trade-offs of the four families can be summarized as follows. Autoregressive models keep an exact $p(x)$ at the cost of generating one element at a time; VAEs give up an exact $p(x)$ in exchange for a latent space that can be sampled; GANs also give up the map from $x$ back to $z$ in exchange for sharp samples in a single step; diffusion models give up single-step generation in exchange for stable training and high-quality samples.
四类模型的取舍可以这样概括:autoregressive 保留精确的 $p(x)$,代价是逐个生成;VAE 放弃精确的 $p(x)$,换来可以采样的 latent space;GAN 连 $x\to z$ 的映射也放弃,换来一步生成的清晰样本;diffusion 放弃一步生成,换来稳定的训练和高质量的样本。
Appendix附录
Probability essentials概率统计基础
Joint · Marginal · Conditional

Joint, marginal and conditional probability联合概率、边缘概率与条件概率

Autoregressive models write probabilities such as $p(x_t\mid x_{<t})$, and these rest on three basic ideas. A small example makes them concrete: over 100 days, record the weather and whether a passer-by carries an umbrella.

  • Joint probability $p(a,b)$: the probability that two things happen together, such as “rain and an umbrella”.
  • Marginal probability $p(a)$: the probability of one thing alone, found by adding up every case of the other; the probability of rain is that of “rain and umbrella” plus “rain and no umbrella”.
  • Conditional probability $p(b\mid a)=p(a,b)/p(a)$: the probability of b once a is known, which amounts to keeping only row a of the table and rescaling it to sum to 1.

Rearranging the last formula gives $p(a,b)=p(a)\,p(b\mid a)$, and applying it repeatedly yields the chain rule used by autoregressive models.

Autoregressive 模型中出现的 $p(x_t\mid x_{<t})$ 这类写法,建立在三个基本概念之上。用一个小例子说明:连续记录 100 天的天气,以及路人是否带伞。

  • 联合概率 $p(a,b)$:两件事同时发生的概率,例如“下雨且带伞”。
  • 边缘概率 $p(a)$:只关心其中一件事,把另一件事的各种情况加起来,例如“下雨”的概率等于“下雨且带伞”加上“下雨且没带伞”。
  • 条件概率 $p(b\mid a)=p(a,b)/p(a)$:已知 a 发生时 b 的概率,相当于只保留表格中 a 那一行,再重新缩放使其总和为 1。

把最后一个式子移项得到 $p(a,b)=p(a)\,p(b\mid a)$,反复使用它,就得到 autoregressive 模型所用的链式法则。

Joint probabilities of weather and umbrellas over 100 days; darker cells are more likely. Click a row or column header, or any cell, to condition on it: the highlighted row or column is rescaled into a conditional distribution, shown in the bars on the right.100 天中天气与带伞情况的联合概率,颜色越深概率越大。点击行、列标题或任一格子,即以该行(或列)为条件:高亮部分被重新缩放成条件分布,显示在右侧的条形中。
Bayes' rule

Prior, likelihood and posterior先验、似然与后验

Bayes' rule is most often met in the form $p(A\mid B)=p(B\mid A)\,p(A)/p(B)$, where the prior $p(A)$ is a single probability. Consider an example. An archer shoots at a line, aiming at a point θ that we do not know. Each arrow lands near θ but strays a little at random (the stray follows a normal distribution with standard deviation 1). After seeing where some arrows landed, we want to infer θ. Suppose at first there are only two possibilities, θ = −1 or θ = 1; for instance, two archers each have a fixed habit of aim, and the record does not say who shot. Three quantities are involved:

  • Prior $p(\theta=1)$: the probability, before looking at any arrows, that the aim point is 1, for example 0.5. It is a single number, and the prior of θ = −1 is the rest, 1 − 0.5.
  • Likelihood $p(D\mid\theta)$: if the aim point were θ, how probable the landing points actually seen, $D$, would be. The closer the arrows are to θ, the larger it is, and each candidate gets its own value.
  • Posterior $p(\theta=1\mid D)$: the probability, after looking at the arrows, that the aim point is 1. It is again a single number.

Now let there be nine candidates, θ = −2, −1.5, …, 2. Each candidate still has its own prior probability, and the nine numbers together, which add up to 1, describe how plausible every candidate is. If θ may be any real number, these numbers merge into a curve over θ. This is what is meant by “the prior is a distribution over θ”: not one number, but one number for every possible θ, of which the prior of any particular candidate is still a probability. (For a continuous θ the curve gives a density, which becomes a probability over an interval, as in chapter 1.) Throughout this guide θ stands for an unknown to be inferred from data; in the other chapters it is usually a model's parameters, and the same reasoning applies. The experiment below switches between 2 candidates, 9 candidates and a continuous θ.

Back to the two-candidate case, suppose three arrows land at 0.4, 1.3 and 0.8. The walkthrough below goes through Bayes' rule with these numbers.

贝叶斯公式最常见的写法是 $p(A\mid B)=p(B\mid A)\,p(A)/p(B)$,其中先验 $p(A)$ 是一个概率值。下面用一个例子说明。一位射手对着一条直线射箭,瞄准的位置 θ 未知;每一箭都落在 θ 附近,但会随机偏开一点(偏开的距离服从标准差为 1 的正态分布)。看到若干落点之后,想推断 θ 在哪里。先假设只有两种可能:θ = −1 或 θ = 1,例如两位射手各有固定的瞄准习惯,而记录上没写是谁射的。这里涉及三个量:

  • 先验 $p(\theta=1)$:还没看落点时,认为瞄准点是 1 的概率,例如 0.5。它是一个概率值,θ = −1 的先验就是剩下的 1 − 0.5。
  • 似然 $p(D\mid\theta)$:假如瞄准点是 θ,射出眼前这组落点 $D$ 的可能性有多大。落点离 θ 越近,似然越大;两个候选各算出一个值。
  • 后验 $p(\theta=1\mid D)$:看过落点之后,认为瞄准点是 1 的概率,同样是一个概率值。

现在把候选增加到九个:θ = −2、−1.5、……、2。每个候选仍然有自己的先验概率,九个数合起来、总和为 1,描述了每个候选各有多可信。如果 θ 可以是任意实数,这些数就连成一条 θ 上的曲线。所谓“先验是 θ 上的一个分布”,指的正是这条曲线:它不是一个数,而是给每个可能的 θ 都配一个数,其中任何一个具体候选的先验仍然是概率。(θ 连续时,曲线的高度是密度,要在一段区间上积分才是概率,与第 1 章所讲相同。)全文都用 θ 表示需要从数据中推断的未知量,在其他章节中它通常是模型的参数,道理完全相同。下面的小实验可以在 2 个候选、9 个候选和连续 θ 三种情形之间切换。

先回到两个候选的情形,假设射了三箭,分别落在 0.4、1.3 和 0.8,下面用这组数逐项拆解贝叶斯公式。

Step by step逐项拆解
$$\htmlClass{fp fp1}{p(\theta\mid D)}=\dfrac{\htmlClass{fp fp2}{p(D\mid\theta)}\;\htmlClass{fp fp3}{p(\theta)}}{\htmlClass{fp fp4}{p(D)}}$$

In the experiment below the centre of the target is at 0. Each prior is a normal distribution $\mathcal N(m_0,s_0^2)$: its centre $m_0$ says where the aim is believed to be, and its spread $s_0$ says how firmly. Three priors are offered, standing for different background knowledge held before any arrow is shot:

  • Flat: nothing is known about the aim, so $p(\theta)$ is the same everywhere.
  • Near 0: most archers aim at the centre of the target. The prior is $\mathcal N(0,0.5^2)$: the aim is believed to lie between −0.5 and 0.5 with probability of about 68%, and between −1 and 1 with about 95%.
  • Leans left: word has it that this archer tends to aim left. The prior is $\mathcal N(-1.5,0.7^2)$, with about 95% probability between −2.9 and −0.1. The belief may be wrong; setting the true aim point to the right shows what happens when the prior is mistaken.

A single best guess for θ can be obtained in two common ways:

  • Maximum likelihood estimation (MLE): the θ that makes the likelihood $p(D\mid\theta)$ largest. It uses the data only; here it is the average landing point $\bar x$.
  • Maximum a posteriori (MAP) estimation: the θ that makes the posterior $p(\theta\mid D)$ largest. It uses both the data and the prior.

Why the prior changes the MAP estimate, and by how much, can be derived step by step:

下面的小实验中,靶心位于 0。每种先验都是一个正态分布 $\mathcal N(m_0,s_0^2)$:中心 $m_0$ 表示认为瞄准点在哪里,宽度 $s_0$ 表示有多确定。实验提供三种先验,代表射箭之前掌握的不同背景知识:

  • 均匀:对瞄准点一无所知,$p(\theta)$ 处处相同。
  • 相信靠近 0:大多数射手都瞄准靶心。先验取 $\mathcal N(0,0.5^2)$,即认为瞄准点约有 68% 的可能在 −0.5 到 0.5 之间,约 95% 的可能在 −1 到 1 之间。
  • 相信偏左:事先听说这位射手习惯偏左瞄准。先验取 $\mathcal N(-1.5,0.7^2)$,即认为瞄准点约有 95% 的可能在 −2.9 到 −0.1 之间。这个看法不一定对,把真实瞄准点设在右侧,可以观察先验出错时会发生什么。

要得到 θ 的一个具体估计值,常用的方法有两种:

  • 最大似然估计(MLE):取使似然 $p(D\mid\theta)$ 最大的 θ。它只用数据,在这个例子中就是落点的平均位置 $\bar x$。
  • 最大后验估计(MAP):取使后验 $p(\theta\mid D)$ 最大的 θ。它同时用到数据和先验。

先验为什么会影响最大后验估计、影响多大,可以一步步推出来:

Step by step逐项拆解
$$\begin{gathered}\htmlClass{fp fp1}{\theta_{\text{MAP}}}=\arg\max_\theta\Big[\htmlClass{fp fp2}{\log p(D\mid\theta)}+\htmlClass{fp fp3}{\log p(\theta)}\Big]\\ =\arg\max_\theta\Big[\htmlClass{fp fp4}{-\tfrac12\textstyle\sum_{i=1}^{n}(x_i-\theta)^2}\;\htmlClass{fp fp5}{-\;\tfrac{1}{2s_0^2}(\theta-m_0)^2}\Big]\\ \htmlClass{fp fp6}{=\dfrac{n\,\bar x+w\,m_0}{n+w},\qquad w=\dfrac{1}{s_0^2}}\end{gathered}$$
Prior先验Likelihood (rescaled)似然(已缩放)Posterior后验
Candidates候选 θ
Prior先验
Bayesian updating for the archer's aim point θ. Green triangles along the axis are where the arrows landed. With 2 or 9 candidates, each candidate has three bars: its prior probability (gray outline), its likelihood rescaled so the bars add up to 1 (blue) and its posterior probability (purple); the bars of each kind add up to 1. With a continuous θ the bars become curves, and vertical lines mark the maximum likelihood (blue) and maximum a posteriori (purple) estimates.对射手瞄准点 θ 的贝叶斯更新。横轴上的绿色三角是箭的落点。2 个或 9 个候选时,每个候选有三根柱:先验概率(灰色描边)、似然(缩放到总和为 1,蓝色)和后验概率(紫色),同一种柱加起来都等于 1。切换到连续 θ 后,柱子连成曲线,竖线标出最大似然估计(蓝)与最大后验估计(紫)。

Connection to machine learning与机器学习的联系

Training a neural network on log-likelihood is maximum likelihood estimation over its parameters. Common regularization such as weight decay corresponds to adding a prior that favours small parameters, which turns training into maximum a posteriori estimation. In a VAE, the encoder's $q_\phi(z\mid x)$ is an approximation to a posterior: given an image, which latent points could have produced it.

用对数似然训练神经网络,就是对网络参数做最大似然估计。常用的正则化(例如 weight decay)相当于加了一个偏好较小参数的先验,训练也就变成了最大后验估计。在 VAE 中,encoder 给出的 $q_\phi(z\mid x)$ 是对一个后验的近似:给定一张图片,哪些 latent 点可能产生了它。

Expectation · Monte Carlo

Expectation, and estimating it by sampling期望与采样估计

The ELBO, the GAN objective and the diffusion loss are all written as expectations $\mathbb E[\cdot]$. Two ideas are involved:

  • Expectation: a probability-weighted average, the value a quantity takes on average over many repeated draws. For a continuous variable it is defined by an integral.
  • Monte Carlo estimate: when $z$ is a high-dimensional vector the integral usually cannot be computed, so it is approximated by the average over random samples.

The formula below puts the two side by side:

ELBO、GAN 的目标函数和 diffusion 的损失都写成期望 $\mathbb E[\cdot]$ 的形式,这里涉及两个概念:

  • 期望:按概率加权的平均,也就是大量重复抽样时某个量的平均值。连续变量的期望用积分定义。
  • 蒙特卡洛估计:$z$ 是高维向量时,这个积分通常算不出,于是改用随机样本的平均值来近似。

下式把两者并列:

Step by step逐项拆解
$$\htmlClass{fp fp1}{\mathbb E_{z\sim p}\big[f(z)\big]}=\htmlClass{fp fp2}{\int f(z)\,p(z)\,dz}\;\approx\;\htmlClass{fp fp3}{\frac{1}{N}\sum_{i=1}^{N}f(z_i)}$$
z ~ N(0, 1) and f(z)z ~ N(0, 1) 与 f(z)
Running average vs. N样本平均随 N 的变化
Estimating $\mathbb E[f(z)]$ for $z\sim\mathcal N(0,1)$. Left: the distribution, the function f (purple) and the samples drawn so far (green). Right: the running average as samples accumulate, with the true value as a dashed line. The estimate wanders at first and settles as N grows.估计 $z\sim\mathcal N(0,1)$ 时的 $\mathbb E[f(z)]$。左图为分布、函数 f(紫色)与已抽出的样本(绿色);右图为样本平均随样本数的变化,虚线为真实值。估计值起初上下波动,N 增大后逐渐稳定。
KL divergence

KL divergence: how different two distributions areKL 散度:两个分布相差多少

The prior term of a VAE has to measure how far the encoder's distribution $q$ is from the prior $p$. The standard measure is the KL divergence:

VAE 的先验项需要衡量 encoder 给出的分布 $q$ 离先验 $p$ 有多远,常用的度量是 KL 散度:

Step by step逐项拆解
$$\htmlClass{fp fp1}{D_{\mathrm{KL}}(q\,\|\,p)}=\htmlClass{fp fp2}{\mathbb E_{z\sim q}}\Big[\htmlClass{fp fp3}{\log q(z)-\log p(z)}\Big]$$

Three of its properties matter most:

  • It is never negative.
  • It equals 0 only when the two distributions are identical.
  • It is not symmetric: $D_{\mathrm{KL}}(q\|p)$ and $D_{\mathrm{KL}}(p\|q)$ are generally different, so it is not a distance in the usual sense.

For two Gaussians the integral has a closed form, so a VAE can compute its prior term exactly, without sampling.

其中最重要的有三条性质:

  • 它永远不小于 0。
  • 只有两个分布完全相同时才等于 0。
  • 它不对称:$D_{\mathrm{KL}}(q\|p)$ 与 $D_{\mathrm{KL}}(p\|q)$ 一般不相等,所以它不是通常意义上的距离。

两个高斯分布之间的 KL 散度有闭式解,因此 VAE 可以不经采样,直接精确算出先验项。

p is the standard normal (gray) and q is N(μ, σ²) (purple). The shaded area is the integrand $q\log(q/p)$: red where q is larger than p, blue where it is smaller. The KL divergence is its total area. Move q away from p and compare the two directions of KL in the readout.p 为标准正态分布(灰色),q 为 N(μ, σ²)(紫色)。阴影是被积函数 $q\log(q/p)$:q 大于 p 处为红色,小于 p 处为蓝色,KL 散度就是它的总面积。把 q 移离 p,比较读数中两个方向的 KL。
Glossary

Glossary术语表

Every term with a dotted underline in the text can be clicked for a short definition; the full list is below.

部分术语在业内普遍直接使用英文,例如 latent space、encoder、decoder、VAE、GAN 与 diffusion,本文沿用这些英文写法,并在表中给出中文释义。正文中带虚线的词都可以点击查看释义,完整列表如下。

References参考文献

  1. I. Goodfellow. NIPS 2016 Tutorial: Generative Adversarial Networks. arXiv:1701.00160, 2017.
  2. Stanford CS231n: Deep Learning for Computer Vision. Lecture 13–14: Generative Models; Lecture 15: 3D Vision.
  3. A. van den Oord, N. Kalchbrenner, K. Kavukcuoglu. Pixel Recurrent Neural Networks. ICML 2016.
  4. D. P. Kingma, M. Welling. Auto-Encoding Variational Bayes. ICLR 2014.
  5. I. Goodfellow et al. Generative Adversarial Nets. NeurIPS 2014.
  6. J. Ho, A. Jain, P. Abbeel. Denoising Diffusion Probabilistic Models. NeurIPS 2020.
  7. X. Liu, C. Gong, Q. Liu. Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow. ICLR 2023.
  8. J. Ho, T. Salimans. Classifier-Free Diffusion Guidance. arXiv:2207.12598, 2022.
  9. R. Rombach et al. High-Resolution Image Synthesis with Latent Diffusion Models. CVPR 2022.
  10. I. Higgins et al. β-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework. ICLR 2017.