The goal: maximum likelihood目标:最大似然
We want a probabilistic model $p_\theta(x)$ that approximates the data distribution:
我们要学一个概率模型 $p_\theta(x)$,让它逼近数据分布:
$$p_\theta(x) \approx p_{\text{data}}(x)$$
Modelling $p(x)$ directly is hard, because real data such as images, speech and text are high-dimensional and highly structured. A latent variable $z$ splits generation into two steps: draw $z$, then generate $x$ from $z$.
直接建模 $p(x)$ 很难,图像、语音、文本这类数据维度高、结构复杂。引入隐变量 $z$ 后,生成拆成两步:先采 $z$,再根据 $z$ 生成 $x$。
$$z \sim p(z), \qquad x \sim p_\theta(x \mid z)$$
The prior is a standard Gaussian, $z \sim \mathcal{N}(0, I)$, which is easy to sample. This defines a joint generative process:
先验取标准高斯 $z \sim \mathcal{N}(0, I)$,便于采样。这样得到一个联合的生成过程:
$$p_\theta(x, z) = p(z)\, p_\theta(x \mid z)$$
Only $x$ is observed, so what we care about is the marginal distribution of $x$:
我们只观测得到 $x$,所以关心的是 $x$ 的边缘分布:
$$p_\theta(x) = \int p(z)\, p_\theta(x \mid z)\, dz$$
The integral runs over every possible $z$, takes the probability that this $z$ generates $x$, and weights it by $p(z)$. It marginalizes $z$ out and leaves a distribution over $x$ alone.
这个积分遍历所有可能的 $z$,取这个 $z$ 生成 $x$ 的概率,按 $p(z)$ 加权求和,也就是把 $z$ 边缘化掉,只留下 $x$ 的分布。
Given $n$ i.i.d. data points, maximum likelihood looks for the parameters under which the data are most probable. Taking the log turns the product into a sum:
有 $n$ 条独立同分布的数据,最大似然要找让这些数据概率最大的参数。取对数,乘积变成求和:
$$\max_\theta \prod_{i=1}^n p_\theta(x^{(i)}) \quad\Longleftrightarrow\quad \max_\theta\sum_{i=1}^n \log p_\theta(x^{(i)})$$
Expanding $p_\theta(x)$, the objective for a single data point is
展开 $p_\theta(x)$,单个样本的目标是
$$\max_\theta\; \log \int p(z)\, p_\theta(x \mid z)\, dz$$
The full objective only adds a sum over data points. What remains is whether this log of an integral can be computed.
全部样本只是再加一个求和。剩下的问题是这个对数积分能不能算。
Why it is intractable积分和后验都算不了
The integral runs over the whole space of $z$. With $z$ high-dimensional and continuous, it has no closed form. A Monte Carlo estimate $\mathbb{E}_{z \sim p(z)}[p_\theta(x \mid z)]$ has a huge variance: almost every $z$ drawn from the prior cannot generate the current $x$ and contributes nearly zero. The difficulty is this sparsity of the integrand in a high-dimensional space; the log on the outside only adds that $\log \mathbb{E}$ cannot be swapped into $\mathbb{E} \log$.
这个积分要遍历 $z$ 的整个空间。$z$ 是高维连续变量,积分没有闭式解。蒙特卡洛估计 $\mathbb{E}_{z \sim p(z)}[p_\theta(x \mid z)]$ 的方差又极大:从先验采到的 $z$ 绝大多数生成不了当前的 $x$,贡献几乎为 0。难点在于被积函数在高维空间里很稀疏;外面那层 $\log$ 只是让 $\log \mathbb{E}$ 没法直接换成 $\mathbb{E} \log$。
We do not need every $z$, only those that matter for the current $x$. That is what the posterior $p_\theta(z \mid x)$ describes. By Bayes' rule:
我们不需要遍历所有 $z$,只需要找到对当前 $x$ 重要的那些 $z$,这正是后验 $p_\theta(z \mid x)$ 描述的东西。用 Bayes 公式写出后验:
$$p_\theta(z \mid x) = \frac{p(z)\, p_\theta(x \mid z)}{p_\theta(x)} = \frac{p(z)\, p_\theta(x \mid z)}{\int p(z)\, p_\theta(x \mid z)\, dz}$$
The numerator $p(z)\, p_\theta(x \mid z)$ is the contribution of one particular $z$ to $x$. It can be computed: the prior and the decoder are both ours to define. The denominator $\int p(z)\, p_\theta(x \mid z)\, dz$ sums the contributions of all $z$ and is the normalizing constant. It is $p_\theta(x)$ again, the same integral we could not compute, so the true posterior is intractable too.
分子 $p(z)\, p_\theta(x \mid z)$ 是某个具体的 $z$ 对 $x$ 的贡献,它能算,先验和 decoder 都是我们自己定义的。分母 $\int p(z)\, p_\theta(x \mid z)\, dz$ 是所有 $z$ 贡献的总和,也就是归一化常数。它又是 $p_\theta(x)$,回到了那个算不了的积分,所以真实后验同样算不了。
This is a loop. The generative model itself needs only the prior $p(z)$ and the decoder $p_\theta(x \mid z)$, going from $z$ to $x$; there is no encoder in it. Training, however, has only $x$, with no paired $(x, z)$: we do not know which $z$ generated each $x^{(i)}$, so we have to infer it through the posterior. Optimizing $\log p_\theta(x)$ needs the posterior, and the posterior's denominator is $p_\theta(x)$. Flow models such as NICE[2] and continuous normalizing flows[3] optimize $\log p_\theta(x)$ exactly and avoid the loop by having no latent integral; the VAE keeps $z$ for its expressiveness and has to break the loop another way.
这里是一个循环。生成模型本身只需要先验 $p(z)$ 和 decoder $p_\theta(x \mid z)$,路线是 $z \to x$,里面没有 encoder。但训练数据里只有 $x$,没有配对的 $(x, z)$,我们不知道每个 $x^{(i)}$ 是从哪个 $z$ 生成的,只能用后验去推。想优化 $\log p_\theta(x)$ 需要后验,后验的分母又是 $p_\theta(x)$。NICE[2]、continuous normalizing flow[3] 这类 flow 模型精确地优化 $\log p_\theta(x)$,它们没有对隐变量的积分,也就没有这个循环;VAE 为了表达力保留 $z$,要用别的办法打破循环。
An encoder for the posterior用 encoder 近似后验
Since the true posterior $p_\theta(z \mid x)$ cannot be computed, a neural network approximates it:
真实后验 $p_\theta(z \mid x)$ 算不了,就用一个神经网络去近似它:
$$q_\phi(z \mid x) \approx p_\theta(z \mid x)$$
This is the encoder. It takes $x$ and outputs the parameters of a distribution over $z$, usually the mean $\mu$ and standard deviation $\sigma$ of a Gaussian. The model now has the shape of an autoencoder: the encoder $q_\phi(z \mid x)$ starts from $x$ and finds the $z$ that matter, approximating the posterior; the decoder $p_\theta(x \mid z)$ turns $z$ into $x$, the original generative path. Kingma and Welling call $q_\phi$ the recognition model, or probabilistic encoder[1].
这就是 encoder:输入 $x$,输出 $z$ 的分布参数,实践中通常是高斯的均值 $\mu$ 和标准差 $\sigma$。引入它之后,结构变成 autoencoder:encoder $q_\phi(z \mid x)$ 从 $x$ 出发找哪些 $z$ 重要,也就是近似后验;decoder $p_\theta(x \mid z)$ 把 $z$ 变成 $x$,是原来的生成路径。Kingma 和 Welling 把 $q_\phi$ 叫作 recognition model,也叫 probabilistic encoder[1]。
The encoder is an auxiliary distribution introduced to optimize the objective. It is not part of the generative process:
encoder 是为了优化目标函数引入的辅助分布,不是生成过程的一部分:
| Distribution分布 | Role角色 | Needed after training训练完还要不要 | Network对应网络 |
|---|---|---|---|
| $p(z)$ | Prior, part of the generative model先验,生成模型的一部分 | Yes, the starting point of sampling要,采样的起点 | No parameters, fixed to $\mathcal{N}(0, I)$无参数,固定为 $\mathcal{N}(0, I)$ |
| $p_\theta(x \mid z)$ | Decoder, the core of the generative modeldecoder,生成模型的核心 | Yes, it maps $z$ to $x$要,把 $z$ 映射到 $x$ | Neural network with parameters $\theta$神经网络,参数 $\theta$ |
| $q_\phi(z \mid x)$ | Encoder, the inference modelencoder,即 inference model | No, dropped for sampling不要,生成时丢掉 | Neural network with parameters $\phi$神经网络,参数 $\phi$ |
The question becomes how to make $q_\phi(z \mid x)$ close to $p_\theta(z \mid x)$. The natural measure is the KL divergence. The two derivations below both arrive at the ELBO.
问题变成怎么让 $q_\phi(z \mid x)$ 尽量接近 $p_\theta(z \mid x)$。自然的度量是 KL 散度。下面两种推导都得到 ELBO。
Derivation 1: from the KL divergence推导一:从 KL 散度出发
Write the KL divergence between the encoder and the true posterior:
直接写 encoder 和真实后验之间的 KL:
$$D_{\mathrm{KL}}\big(q_\phi(z \mid x) \,\Vert\, p_\theta(z \mid x)\big) = \mathbb{E}_{q_\phi(z \mid x)}\left[\log \frac{q_\phi(z \mid x)}{p_\theta(z \mid x)}\right]$$
It measures, on the $z$ the encoder samples, how far $q_\phi$ sits above or below the true posterior. We want it as small as possible. Replace the true posterior in the denominator using Bayes' rule,
它在 encoder 采到的 $z$ 上,看 $q_\phi$ 比真实后验高多少、低多少。我们希望它越小越好。把分母里的真实后验用 Bayes 公式替换:
$$p_\theta(z \mid x) = \frac{p(z)\, p_\theta(x \mid z)}{p_\theta(x)}$$
and substitute it back:
代回 KL:
$$D_{\mathrm{KL}}\big(q_\phi(z \mid x) \,\Vert\, p_\theta(z \mid x)\big) = \mathbb{E}_{q_\phi(z \mid x)}\left[\log \frac{q_\phi(z \mid x)\, p_\theta(x)}{p(z)\, p_\theta(x \mid z)}\right]$$
Expand the log:
展开 $\log$:
$$= \mathbb{E}_{q_\phi(z \mid x)}\big[\log q_\phi(z \mid x) - \log p(z) - \log p_\theta(x \mid z) + \log p_\theta(x)\big]$$
$\log p_\theta(x)$ does not depend on $z$, since $x$ is given, so it comes out of the expectation. The remaining terms group into a KL divergence to the prior and an expected log-likelihood:
$\log p_\theta(x)$ 与 $z$ 无关($x$ 是给定的),可以从期望里拿出来。剩下的项分成到先验的 KL 和一个对数似然的期望:
$$\begin{aligned} D_{\mathrm{KL}}\big(q_\phi(z \mid x) \,\Vert\, p_\theta(z \mid x)\big) &= \log p_\theta(x) + \underbrace{\mathbb{E}_{q_\phi(z \mid x)}\big[\log q_\phi(z \mid x) - \log p(z)\big]}_{D_{\mathrm{KL}}(q_\phi(z \mid x) \,\Vert\, p(z))} \\ &\quad - \mathbb{E}_{q_\phi(z \mid x)}\big[\log p_\theta(x \mid z)\big] \end{aligned}$$
Move terms to put $\log p_\theta(x)$ on its own:
移项,把 $\log p_\theta(x)$ 单独写出:
$$\log p_\theta(x) = \underbrace{\mathbb{E}_{q_\phi(z \mid x)}\big[\log p_\theta(x \mid z)\big]}_{\text{(A)}} - \underbrace{D_{\mathrm{KL}}\big(q_\phi(z \mid x) \,\Vert\, p(z)\big)}_{\text{(B)}} + \underbrace{D_{\mathrm{KL}}\big(q_\phi(z \mid x) \,\Vert\, p_\theta(z \mid x)\big)}_{\ge\, 0}$$
(A) is the reconstruction term and (B) the KL term to the prior. The third term is the KL divergence between $q_\phi$ and the true posterior, the quantity we set out to minimize. It is always nonnegative, but it contains the true posterior and cannot be computed. Dropping it leaves a lower bound on $\log p_\theta(x)$, the evidence lower bound (ELBO):
(A) 是重建项,(B) 是到先验的 KL 项。第三项是 $q_\phi$ 和真实后验的 KL,也就是我们一开始想压小的量;它永远 $\ge 0$,但含有真实后验,算不了。丢掉它,前两项就是 $\log p_\theta(x)$ 的下界,即 evidence lower bound(ELBO):
$$\boxed{\;\mathcal{L}_{\text{ELBO}}(\theta, \phi; x) = \mathbb{E}_{q_\phi(z \mid x)}\big[\log p_\theta(x \mid z)\big] - D_{\mathrm{KL}}\big(q_\phi(z \mid x) \,\Vert\, p(z)\big)\;}$$
This is equation (3) of the VAE paper, and the decomposition before it is its equation (1)[1]. For fixed $\theta$ and $x$ it reads
这就是 VAE 论文的式 (3),上面的分解是它的式 (1)[1]。给定 $\theta$ 和 $x$ 时:
$$\log p_\theta(x) = \mathcal{L}_{\text{ELBO}}(\theta, \phi; x) + D_{\mathrm{KL}}\big(q_\phi(z \mid x) \,\Vert\, p_\theta(z \mid x)\big)$$
The left side depends only on $\theta$ and $x$, not on $\phi$. So with respect to the encoder, raising the ELBO is the same as lowering the KL divergence to the true posterior: the better the encoder, the tighter the bound. When $q_\phi(z \mid x) = p_\theta(z \mid x)$, the ELBO equals $\log p_\theta(x)$. With respect to $\theta$ both terms change; raising the ELBO raises a lower bound on $\log p_\theta(x)$, and $\log p_\theta(x)$ never falls below it.
左边只依赖 $\theta$ 和 $x$,和 $\phi$ 无关。所以对 encoder 而言,提高 ELBO 就等于降低到真实后验的 KL:encoder 越好,下界越紧;$q_\phi(z \mid x) = p_\theta(z \mid x)$ 时,ELBO 等于 $\log p_\theta(x)$。对 $\theta$ 而言两项都会变,提高 ELBO 是在抬高 $\log p_\theta(x)$ 的下界,$\log p_\theta(x)$ 不会低于它。
The figure shows this for fixed $\theta$.
下图画的是 $\theta$ 固定时的情形。
The VAE updates $\theta$ and $\phi$ together by gradient ascent on this one objective. The paper notes that the true posterior is intractable, so the EM algorithm cannot be used[1]; the E-step of EM needs exactly that posterior. Instead of computing a posterior for every data point, one shared encoder outputs it for any $x$, which is called amortized inference.
VAE 用梯度上升同时更新 $\theta$ 和 $\phi$,两者优化同一个目标。论文指出真实后验算不了,所以不能用 EM[1];EM 的 E 步需要的正是真实后验。VAE 也不为每个数据点单独求一个后验,而是用一个共享的 encoder 对任意 $x$ 输出后验,这叫 amortized inference。
Derivation 2: Jensen's inequality推导二:Jensen 不等式
The second route starts from $\log p_\theta(x)$ itself and does not go through the posterior:
第二条路直接从 $\log p_\theta(x)$ 出发,不经过后验:
$$\log p_\theta(x) = \log \int p(z)\, p_\theta(x \mid z)\, dz$$
Multiply the integrand by $1 = q_\phi(z \mid x) / q_\phi(z \mid x)$, which brings $q_\phi$ in:
给被积函数乘上 $1 = q_\phi(z \mid x) / q_\phi(z \mid x)$,把 $q_\phi$ 引进来:
$$\log p_\theta(x) = \log \int q_\phi(z \mid x)\, \frac{p(z)\, p_\theta(x \mid z)}{q_\phi(z \mid x)}\, dz$$
By the definition of expectation,
按期望的定义,
$$\mathbb{E}_{q_\phi(z \mid x)}[f(z)] = \int q_\phi(z \mid x)\, f(z)\, dz$$
so the integral is an expectation under $q_\phi$:
所以上式是 $q_\phi$ 下的期望:
$$\log p_\theta(x) = \log \mathbb{E}_{q_\phi(z \mid x)}\left[\frac{p(z)\, p_\theta(x \mid z)}{q_\phi(z \mid x)}\right]$$
This step is importance sampling. The original integral is an expectation under $p(z)$, and samples from $p(z)$ almost never land on a $z$ that contributes to $x$. Multiplying by $q_\phi / q_\phi$ changes the proposal to $q_\phi$, whose samples concentrate on the $z$ that matter. The ratio inside is an unbiased estimate of $p_\theta(x)$ from samples of $q_\phi$. If $q_\phi$ equals the true posterior, the ratio is $p(z)\, p_\theta(x \mid z) / p_\theta(z \mid x) = p_\theta(x)$ for every $z$, a constant.
这一步就是 importance sampling。原来的积分是 $p(z)$ 下的期望,从 $p(z)$ 采几乎采不到对 $x$ 有贡献的 $z$;乘上 $q_\phi / q_\phi$ 等于把 proposal 换成 $q_\phi$,从它采出的样本集中在对 $x$ 重要的 $z$ 上。括号里的比值是用 $q_\phi$ 的样本对 $p_\theta(x)$ 的无偏估计。如果 $q_\phi$ 等于真实后验,这个比值对每个 $z$ 都是 $p(z)\, p_\theta(x \mid z) / p_\theta(z \mid x) = p_\theta(x)$,是常数。
In the figure below, the gray ellipse is where $p_\theta(x \mid z)$ is large for one $x$. Most samples from the prior fall outside it; samples from $q_\phi(z \mid x)$ concentrate on it.
下图中,灰色椭圆是对某个 $x$ 而言 $p_\theta(x \mid z)$ 较大的 $z$。从先验采的点大多落在它外面,从 $q_\phi(z \mid x)$ 采的点集中在它上面。
Since $\log$ is concave, Jensen's inequality gives $\log \mathbb{E}[A] \ge \mathbb{E}[\log A]$, and the log moves inside the expectation:
$\log$ 是凹函数,由 Jensen 不等式 $\log \mathbb{E}[A] \ge \mathbb{E}[\log A]$,把 $\log$ 移进期望:
$$\log p_\theta(x) \ge \mathbb{E}_{q_\phi(z \mid x)}\left[\log \frac{p(z)\, p_\theta(x \mid z)}{q_\phi(z \mid x)}\right]$$
This is equation (2) of the paper. Expand the log:
这是论文的式 (2)。展开 $\log$:
$$= \mathbb{E}_{q_\phi(z \mid x)}\big[\log p(z) + \log p_\theta(x \mid z) - \log q_\phi(z \mid x)\big]$$
Group $\log p(z) - \log q_\phi(z \mid x)$ into a KL divergence. Its sign has to be flipped to match $D_{\mathrm{KL}}(q_\phi \,\Vert\, p) = \mathbb{E}_{q_\phi}[\log q_\phi - \log p]$:
把 $\log p(z) - \log q_\phi(z \mid x)$ 合成 KL。要把符号翻过来,才能配上 $D_{\mathrm{KL}}(q_\phi \,\Vert\, p) = \mathbb{E}_{q_\phi}[\log q_\phi - \log p]$:
$$= \underbrace{\mathbb{E}_{q_\phi(z \mid x)}\big[\log p_\theta(x \mid z)\big]}_{\text{(A)}} - \underbrace{D_{\mathrm{KL}}\big(q_\phi(z \mid x) \,\Vert\, p(z)\big)}_{\text{(B)}}$$
The direction of this KL divergence matters. We want to change the encoder $q_\phi$, not the prior $p(z)$, so the expectation is taken under $q_\phi$, and $q_\phi$ is the first argument of the KL.
注意这个 KL 的方向。我们要改变的是 encoder $q_\phi$,不是先验 $p(z)$,所以期望在 $q_\phi$ 下取,$q_\phi$ 是 KL 的第一个参数。
The result is the same ELBO as in the first derivation. What Jensen's inequality loosened is the KL divergence to the true posterior, and a third route shows it directly. Since $\log p_\theta(x)$ does not depend on $z$, taking its expectation under $q_\phi$ changes nothing; then write $p_\theta(x) = p_\theta(x, z) / p_\theta(z \mid x)$ and multiply inside the log by $q_\phi / q_\phi$:
结果和推导一的 ELBO 完全相同。Jensen 不等式松掉的那部分,就是到真实后验的 KL,第三种写法可以直接看出来。$\log p_\theta(x)$ 与 $z$ 无关,对它取 $q_\phi$ 下的期望不改变它;再把 $p_\theta(x)$ 写成 $p_\theta(x, z) / p_\theta(z \mid x)$,在 $\log$ 里乘上 $q_\phi / q_\phi$:
$$\log p_\theta(x) = \mathbb{E}_{q_\phi(z \mid x)}\big[\log p_\theta(x)\big] = \mathbb{E}_{q_\phi(z \mid x)}\left[\log \frac{p_\theta(x, z)}{p_\theta(z \mid x)}\right]$$
$$= \mathbb{E}_{q_\phi(z \mid x)}\left[\log \frac{p_\theta(x, z)}{q_\phi(z \mid x)}\right] + \mathbb{E}_{q_\phi(z \mid x)}\left[\log \frac{q_\phi(z \mid x)}{p_\theta(z \mid x)}\right]$$
$$= \mathcal{L}_{\text{ELBO}}(\theta, \phi; x) + D_{\mathrm{KL}}\big(q_\phi(z \mid x) \,\Vert\, p_\theta(z \mid x)\big)$$
With $p_\theta(x, z) = p(z)\, p_\theta(x \mid z)$, the first expectation is the right side of the Jensen step, and the second is the third term of the first derivation. The two derivations differ only in where they start. The KL route starts from minimizing the divergence between $q_\phi$ and the true posterior and finds $\log p_\theta(x)$ in it. The Jensen route starts from maximizing $\log p_\theta(x)$ and relaxes it to a lower bound.
因为 $p_\theta(x, z) = p(z)\, p_\theta(x \mid z)$,第一个期望就是 Jensen 那一步的右边,第二个期望就是推导一里的第三项。两种推导只是出发点不同:KL 法从压小 $q_\phi$ 与真实后验的 KL 出发,化简时出现 $\log p_\theta(x)$;Jensen 法从最大化 $\log p_\theta(x)$ 出发,松弛成一个下界。
The two termsELBO 的两项
$$\mathcal{L}_{\text{ELBO}} = \underbrace{\mathbb{E}_{q_\phi(z \mid x)}\big[\log p_\theta(x \mid z)\big]}_{\text{(A)}} - \underbrace{D_{\mathrm{KL}}\big(q_\phi(z \mid x) \,\Vert\, p(z)\big)}_{\text{(B)}}$$
| Term项 | Involves涉及 | Meaning含义 | In training训练时的形式 |
|---|---|---|---|
| (A) reconstruction(A) 重建项 | encoder $q_\phi$ and decoder $p_\theta$encoder $q_\phi$ 和 decoder $p_\theta$ | How well $x$ is recovered after encoding it to $z$ and decoding $z$把 $x$ 编码成 $z$,再从 $z$ 解码,能多大程度还原 $x$ | Bernoulli decoder: cross-entropy; Gaussian decoder with fixed variance: squared error伯努利 decoder 对应交叉熵;固定方差的高斯 decoder 对应平方误差 |
| (B) KL term(B) KL 项 | encoder $q_\phi$ and prior $p(z)$encoder $q_\phi$ 和先验 $p(z)$ | Keeps the encoder's posterior from moving far from the prior不让 encoder 给出的后验偏离先验太远 | Closed form for Gaussian $q_\phi$ and $p(z) = \mathcal{N}(0, I)$高斯 $q_\phi$ 加 $p(z) = \mathcal{N}(0, I)$ 时有闭式解 |
The paper uses a Bernoulli decoder for binary data and a Gaussian decoder for real-valued data[1]. With decoder output $y$, the Bernoulli log-likelihood is the negative binary cross-entropy:
论文对二值数据用伯努利 decoder,对实值数据用高斯 decoder[1]。设 decoder 输出为 $y$,伯努利的对数似然是负的二元交叉熵:
$$\log p_\theta(x \mid z) = \sum_{i=1}^{D} \big[x_i \log y_i + (1 - x_i) \log (1 - y_i)\big]$$
A Gaussian decoder with mean $\mu_\theta(z)$ and a fixed variance $\sigma^2$ gives the squared error up to a scale and a constant:
均值为 $\mu_\theta(z)$、方差 $\sigma^2$ 固定的高斯 decoder,差一个系数和常数就是平方误差:
$$\log \mathcal{N}\big(x;\, \mu_\theta(z),\, \sigma^2 I\big) = -\frac{\lVert x - \mu_\theta(z) \rVert^2}{2\sigma^2} - \frac{D}{2}\log(2\pi\sigma^2)$$
The paper's Gaussian decoder also outputs $\log \sigma^2$; then the variance is learned and the term is no longer a plain squared error.
论文里的高斯 decoder 同时输出 $\log \sigma^2$,这时方差也在学,这一项就不再只是平方误差。
For the KL term, let $J$ be the dimension of $z$, and $\mu_j$, $\sigma_j$ the $j$-th entries of the encoder's output. Appendix B of the paper computes the two halves of the KL divergence separately:
KL 项:设 $z$ 的维度为 $J$,$\mu_j$、$\sigma_j$ 是 encoder 输出的第 $j$ 维。论文附录 B 把 KL 拆成两部分分别算:
$$\int q_\phi(z \mid x) \log p(z)\, dz = -\frac{J}{2}\log(2\pi) - \frac{1}{2}\sum_{j=1}^J \big(\mu_j^2 + \sigma_j^2\big)$$
$$\int q_\phi(z \mid x) \log q_\phi(z \mid x)\, dz = -\frac{J}{2}\log(2\pi) - \frac{1}{2}\sum_{j=1}^J \big(1 + \log \sigma_j^2\big)$$
Subtracting the second from the first gives
两式相减得到
$$-D_{\mathrm{KL}}\big(q_\phi(z \mid x) \,\Vert\, p(z)\big) = \frac{1}{2}\sum_{j=1}^J \big(1 + \log \sigma_j^2 - \mu_j^2 - \sigma_j^2\big)$$
Each term guards against a failure of the other. With only the reconstruction term, the encoder maps each $x$ to a point mass, a deterministic autoencoder. The latent space then has no structure, a $z$ sampled from $p(z)$ falls into the gaps between training points, and the decoder turns it into an output unlike any training data. With only the KL term, the encoder outputs the prior $\mathcal{N}(0, I)$ for every $x$, the KL term is zero, $z$ carries no information about $x$, and reconstruction fails. The same state can appear in real training, usually with a strong decoder that learns to ignore $z$, and is then called posterior collapse. Balancing the two terms gives a latent space that can reconstruct and is smooth, close to the prior, so sampling from $\mathcal{N}(0, I)$ generates data.
两项各自防着另一项的坏情况。只有重建项时,encoder 把每个 $x$ 编成一个点(确定性的 autoencoder),隐空间没有结构,从 $p(z)$ 采的 $z$ 落到训练点之间的空洞里,decoder 生成的结果不像任何训练数据。只有 KL 项时,encoder 对每个 $x$ 都输出先验 $\mathcal{N}(0, I)$,KL 为 0,$z$ 不带任何关于 $x$ 的信息,重建失败;真实训练中也会出现这种状态,通常是 decoder 很强、学会了忽略 $z$,这时叫 posterior collapse。两项平衡,隐空间既能重建,又光滑、接近先验,从 $\mathcal{N}(0, I)$ 采样就能生成。
The figure draws $q_\phi(z \mid x)$ for four data points in each of the three cases.
下图画出三种情形下四个数据点的 $q_\phi(z \mid x)$。
The ELBO contains only the prior, the encoder and the decoder, all of which we can compute. The intractable true posterior has moved into the gap between $\log p_\theta(x)$ and the bound.
ELBO 里只剩先验、encoder、decoder 三个能算的对象,算不了的真实后验被放进了 $\log p_\theta(x)$ 与下界之间的差距里。
The reparameterization trick重参数化
The reconstruction term $\mathbb{E}_{q_\phi(z \mid x)}[\log p_\theta(x \mid z)]$ is an expectation over samples from $q_\phi$, and we need its gradient with respect to $\phi$. Suppose the encoder outputs Gaussian parameters $\mu_\phi(x)$ and $\sigma_\phi(x)$, and $z$ is drawn directly:
重建项 $\mathbb{E}_{q_\phi(z \mid x)}[\log p_\theta(x \mid z)]$ 是对 $q_\phi$ 采样取的期望,而我们要对 $\phi$ 求梯度。设 encoder 输出高斯参数 $\mu_\phi(x)$、$\sigma_\phi(x)$,直接采:
$$z \sim \mathcal{N}\big(\mu_\phi(x),\, \sigma_\phi(x)^2\big)$$
Here $z$ is a random draw from a distribution that depends on $\phi$. The gradient $\partial z / \partial \phi$ is undefined, because the sampling step cuts the computation graph.
这时 $z$ 是从一个依赖 $\phi$ 的分布里采出的随机量,梯度 $\partial z / \partial \phi$ 没有定义,采样这一步把计算图切断了。
One fallback is the score function estimator, also known as REINFORCE:
一种退路是 score function estimator,也叫 REINFORCE:
$$\nabla_\phi\, \mathbb{E}_{q_\phi(z \mid x)}[f(z)] = \mathbb{E}_{q_\phi(z \mid x)}\big[f(z)\, \nabla_\phi \log q_\phi(z \mid x)\big]$$
It is unbiased, but the paper notes that it has very high variance and is impractical for this purpose[1].
它是无偏的,但论文指出它的方差非常大,在这里不实用[1]。
Reparameterization moves the randomness to a source that does not depend on $\phi$:
重参数化把随机性挪到一个与 $\phi$ 无关的来源上:
$$\boxed{\;z = \mu_\phi(x) + \sigma_\phi(x) \odot \epsilon, \qquad \epsilon \sim \mathcal{N}(0, I)\;}$$
All the randomness is in $\epsilon$, external noise that does not depend on $\phi$. Given $\epsilon$, $z$ is a deterministic function of $\mu_\phi$ and $\sigma_\phi$, with $\partial z / \partial \mu_\phi = 1$ and $\partial z / \partial \sigma_\phi = \epsilon$ elementwise, so gradients pass through. $\mu_\phi(x)$ and $\sigma_\phi(x)$ are not model parameters but intermediate outputs of the encoder. The gradient first reaches $z$ from the decoder's loss, then the encoder outputs $\mu_\phi$ and $\sigma_\phi$, then through the encoder network to its parameters $\phi$.
随机性全在 $\epsilon$ 上,它是与 $\phi$ 无关的外部噪声。给定 $\epsilon$ 后,$z$ 是 $\mu_\phi$、$\sigma_\phi$ 的确定性函数,逐元素有 $\partial z / \partial \mu_\phi = 1$、$\partial z / \partial \sigma_\phi = \epsilon$,梯度能传过去。$\mu_\phi(x)$、$\sigma_\phi(x)$ 不是模型参数,而是 encoder 网络的中间输出。反传时梯度先从 decoder 的 loss 到 $z$,再到 encoder 的输出 $\mu_\phi$、$\sigma_\phi$,最后经 encoder 网络到参数 $\phi$。
The figure compares the two computation graphs. With direct sampling, the gradient of the reconstruction term reaches $z$ and stops at the sampling step. With reparameterization it passes through the addition and the multiplication to $\mu_\phi$ and $\sigma_\phi$, then into the encoder; $\epsilon$ is an outside input and has nothing to update. The KL term is computed in closed form from $\mu_\phi$ and $\sigma_\phi$, so in both graphs its gradient reaches the encoder without going through $z$.
下图对比两种计算图。直接采样时,重建项的梯度传到 $z$ 就停在采样这一步;重参数化后,它经过加法和乘法到 $\mu_\phi$、$\sigma_\phi$,再进 encoder;$\epsilon$ 是外部输入,没有要更新的参数。KL 项由 $\mu_\phi$、$\sigma_\phi$ 直接算出闭式解,两种计算图里它的梯度都不经过 $z$ 就到达 encoder。
This is a change of variables in the expectation:
这等于在期望里做了一次变量代换:
$$\mathbb{E}_{z \sim q_\phi(z \mid x)}\big[f(z)\big] = \mathbb{E}_{\epsilon \sim \mathcal{N}(0, I)}\big[f\big(\mu_\phi(x) + \sigma_\phi(x) \odot \epsilon\big)\big]$$
On the right, the distribution being sampled, $\mathcal{N}(0, I)$, no longer depends on $\phi$; $\phi$ appears only inside the integrand, so the gradient goes into the expectation, through $f$ and into the encoder. This pathwise gradient has much lower variance than REINFORCE. The trick does not make sampling possible, since sampling from $q_\phi$ was always possible. It makes the expectation after sampling differentiable with respect to $\phi$.
右边被采样的分布 $\mathcal{N}(0, I)$ 不再依赖 $\phi$,$\phi$ 只出现在被积函数里,所以梯度可以移进期望,穿过 $f$ 进到 encoder。这种 pathwise 梯度的方差比 REINFORCE 小得多。这个技巧不是为了让采样可行,从 $q_\phi$ 采样本来就能做;它是为了让采样之后的期望对 $\phi$ 可导。
With the closed-form KL term and reparameterized samples, the paper's estimator for one data point is its equation (10):
KL 项用闭式解、重建项用重参数化的样本,论文对单个数据点的估计就是它的式 (10):
$$\begin{aligned} \mathcal{L}(\theta, \phi; x^{(i)}) &\simeq \frac{1}{2}\sum_{j=1}^J \Big(1 + \log \big(\sigma_j^{(i)}\big)^2 - \big(\mu_j^{(i)}\big)^2 - \big(\sigma_j^{(i)}\big)^2\Big) \\ &\quad + \frac{1}{L}\sum_{l=1}^L \log p_\theta\big(x^{(i)} \mid z^{(i,l)}\big) \end{aligned}$$
$$z^{(i,l)} = \mu^{(i)} + \sigma^{(i)} \odot \epsilon^{(l)}, \qquad \epsilon^{(l)} \sim \mathcal{N}(0, I)$$
In the experiments one sample per data point ($L = 1$) was enough with minibatches of $M = 100$[1]. In practice the encoder outputs $\log \sigma^2$ instead of $\sigma$, as in the paper's Gaussian MLP: the output can be any real number while $\sigma$ stays positive, and it is numerically stable. The code below uses a Bernoulli decoder, so the decoder's last layer is a sigmoid.
论文实验里,minibatch 大小 $M = 100$ 时,每个数据点采一个样本($L = 1$)就够了[1]。实践中 encoder 输出 $\log \sigma^2$ 而不是 $\sigma$,论文的高斯 MLP 也这样做:输出可以取任意实数,同时保证 $\sigma$ 为正,数值也稳定。下面的代码用伯努利 decoder,decoder 最后一层是 sigmoid。
def encode(self, x):
h = self.encoder_net(x)
mu = self.fc_mu(h)
log_var = self.fc_log_var(h) # log sigma^2 instead of sigma
return mu, log_var
def reparameterize(self, mu, log_var):
std = torch.exp(0.5 * log_var)
eps = torch.randn_like(std) # eps ~ N(0, I), independent of phi
return mu + eps * std # z = mu + sigma * eps, differentiable
def forward(self, x):
mu, log_var = self.encode(x)
z = self.reparameterize(mu, log_var)
x_recon = self.decoder_net(z)
return x_recon, mu, log_var
def loss(self, x, x_recon, mu, log_var):
# reconstruction term: -log p(x|z) with one sample of z
recon = F.binary_cross_entropy(x_recon, x, reduction='sum')
# KL term: closed form of KL(q(z|x) || N(0, I))
kl = -0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp())
return recon + kl # negative ELBO
After training训练之后
Generation does not need the encoder. It goes back to the original definition of the generative process:
生成不需要 encoder,回到最初对生成过程的定义:
$$z \sim p(z), \qquad x \sim p_\theta(x \mid z)$$
Draw $z$ from the prior $\mathcal{N}(0, I)$ and pass it through the decoder to get $x$, or sample $x$ from the distribution whose parameters the decoder outputs. During training, $x$ passes through the encoder to $(\mu, \sigma)$, noise $\epsilon$ gives $z$, and the decoder gives $\hat{x}$, with the reconstruction term and the KL term as the loss. At sampling time, $z \sim \mathcal{N}(0, I)$ goes straight into the decoder.
从先验 $\mathcal{N}(0, I)$ 采一个 $z$,过 decoder 得到 $x$;或者 decoder 输出分布参数,再从中采样 $x$。训练时 $x$ 经 encoder 得到 $(\mu, \sigma)$,加噪声 $\epsilon$ 得到 $z$,再经 decoder 得到 $\hat{x}$,loss 是重建项加 KL 项;生成时 $z \sim \mathcal{N}(0, I)$ 直接进 decoder。
The encoder still has uses beyond sampling:
encoder 在生成之外还有用处:
- Reconstruction and editing: encode $x$ to $z$, change $z$, and decode it, as in latent interpolation and attribute editing. To interpolate between $x_1$ and $x_2$, encode them to $z_1$ and $z_2$ and decode $\alpha z_1 + (1 - \alpha) z_2$.重建和编辑:给定 $x$,编码到 $z$,改 $z$ 再 decode,如隐空间插值、属性编辑。在 $x_1$、$x_2$ 之间插值,就把它们编码成 $z_1$、$z_2$,对 $\alpha z_1 + (1 - \alpha) z_2$ 做 decode。
- Representation learning: $\mu_\phi(x)$ serves as an embedding of $x$ for downstream tasks.表示学习:把 $\mu_\phi(x)$ 当作 $x$ 的 embedding 给下游任务。
- Anomaly detection: the reconstruction error, or how far $q_\phi(z \mid x)$ deviates, serves as the anomaly score.异常检测:用重建误差或 $q_\phi(z \mid x)$ 的偏离程度作为异常分数。
References参考文献
- Diederik P. Kingma and Max Welling. Auto-Encoding Variational Bayes. ICLR, 2014. arXiv:1312.6114
- Laurent Dinh, David Krueger, and Yoshua Bengio. NICE: Non-linear Independent Components Estimation. ICLR Workshop, 2015. arXiv:1410.8516
- Ricky T. Q. Chen, Yulia Rubanova, Jesse Bettencourt, and David Duvenaud. Neural Ordinary Differential Equations. NeurIPS, 2018. arXiv:1806.07366