Lecture 7 · Latent Variable Models I: From Exact Likelihood to the VAE

Deep Unsupervised Learning · Lecture 07。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 4 · Thu 2/8/2024 · Latent Variable Models — Variational AutoEncoder (VAE), first part (slides 1–66): why latent variable models, the training objective, exact likelihood for few latent values, prior sampling and why it fails, importance sampling, the variational approach and amortized inference, IWAE, two derivations of the variational lower bound, likelihood-ratio vs pathwise (reparameterization) gradients on a toy problem, the VAE, and why it is called an autoencoder. Homework 2, Questions 1 and 2a. Basis: The slides derive several key formulas live on the board. These notes write the derivations out, then check each claim numerically on models whose answers are known: a 2-D mixture with an exact objective, noisy ShapeWorld (whose exact likelihood is a sum over all 921,600 latent configurations), and probabilistic PCA, whose likelihood and posterior are Gaussians in closed form. The homework’s VAEs run on 2-D Gaussians and on binary ShapeWorld, so that a VAE’s bits can be put next to the exact floor and to Lectures 3–6. Code: code/lecture07/ (5 scripts + lvm.py; PyTorch (CPU); seconds each, except the ShapeWorld VAEs of script 05: ~8 minutes on the first run, then cached) Reading time: 4 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Explain what latent variable models offer (compact representations, faster sampling by exploiting structure) and what they cost (the likelihood becomes an integral).
  2. Train a latent variable model exactly when zz takes few values, and explain why prior sampling fails when it takes many.
  3. Use importance sampling to estimate log⁡p(x)\log p(x), and explain why the ideal proposal is the posterior p(z∣x)p(z \mid x).
  4. Derive the variational lower bound (VLB / ELBO) by Jensen’s inequality and by the KL identity, and state its gap exactly: log⁡p(x)−ELBO=KL(q(z∣x) ∥ p(z∣x))\log p(x) - \text{ELBO} = \mathrm{KL}(q(z \mid x) \,\Vert\, p(z \mid x)).
  5. Explain amortized inference and the IWAE bound.
  6. Derive the likelihood-ratio and pathwise gradient estimators, compare their variance, and say when each applies.
  7. Assemble a VAE, read its loss as “reconstruction + KL”, and explain when its latent is used and when it is ignored.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lectures 5–6 (flows: change of variables, variational dequantization)latent variable models, prior / importance sampling, ELBO, IWAEricher priors, hierarchical VAEs (Lecture 8)
Lecture 2 (maximum likelihood = KL)amortized inference, likelihood-ratio and pathwise gradientsdiscrete latents, VQ-VAE (Lecture 8)
Lecture 1 (ShapeWorld’s latents: shapes, sizes, positions)the VAE, posterior collapse in its simplest formposterior collapse with powerful decoders, β-VAE (Lecture 8); bits-back coding (Lecture 21)

0.3 Map

§1  why latent variable models                                                ← (concepts)
§2  the objective; Scenario 1: exact sums                                     ← code 01 (Part 1)
§3  Scenario 2: prior sampling, importance sampling                          ← code 01 (Parts 2-3), 02 (Part 1)
§4  the variational lower bound, its gap, amortization, IWAE                  ← code 02
§5  gradients: likelihood ratio vs pathwise                                   ← code 03
§6  the VAE; why it is an autoencoder                                         ← code 04, 05
§7  summary   §8 pitfalls   §9 exercises   §10 further reading   §11 next lecture

0.4 Notation

SymbolMeaning
zzlatent (unobserved) variable; p(z)p(z) the prior
pθ(x∣z)p_\theta(x \mid z)decoder / likelihood
pθ(x)=∫p(z) pθ(x∣z) dzp_\theta(x) = \int p(z)\,p_\theta(x \mid z)\,dzthe marginal likelihood (“evidence”)
pθ(z∣x)p_\theta(z \mid x)the true posterior
q(z)q(z), qϕ(z∣x)q_\phi(z \mid x)a proposal / approximate posterior; with ϕ\phi shared across xx: an encoder (amortized)
ELBO, VLBEq[log⁡p(x,z)−log⁡q(z∣x)]≤log⁡p(x)E_{q}[\log p(x, z) - \log q(z \mid x)] \le \log p(x)
IWAEK_KE[log⁡1K∑kp(x,zk)/q(zk∣x)]E\big[\log \frac1K \sum_k p(x, z_k)/q(z_k \mid x)\big], zk∼qz_k \sim q

0.5 How the experiments are run

Continuous data are in nats per point, binary images in bits per image. Three test benches with exact answers: a 2-D mixture of 3 Gaussians; noisy ShapeWorld (Lecture 1’s world with every pixel flipped with probability 0.05: a latent variable model with 921,600 configurations, whose exact log⁡p(x)\log p(x) is a 960×960960 \times 960 matrix product); and probabilistic PCA (z∈R2z \in \mathbb{R}^2, x∈R8x \in \mathbb{R}^8), where p(x)p(x) and p(z∣x)p(z \mid x) are Gaussians in closed form. Every script fixes its seeds; reruns print identical numbers.


1. Why latent variable models?

Autoregressive models and flows treat all random variables as observed. Latent variable models (LVMs) add variables we never get to observe. Why would we want more unknowns?

  • Simpler, lower-dimensional representations. The slides’ example: a photo is described by “corgi, red and white, at (x, y); background: wood bench in a park” — a handful of high-level variables, not a million pixel values. An LVM promises to identify such hidden variables automatically.
  • Faster sampling. Autoregressive models are slow because every pixel depends on every previous one. If pixels are (approximately) independent given a latent zz, then sampling is: draw zz, then all pixels at once.
  • Sometimes we know the causal story. ShapeWorld is literally an LVM: zz = (shapes, sizes, positions) → rendering → xx. In general we don’t know the latents, and the most popular models assume little about them (a standard normal vector); how best to specify latent variables is still open.

An LVM must support the four operations of the slides: sample (z∼p(z)z \sim p(z), x∼p(x∣z)x \sim p(x \mid z) — easy), evaluate p(x)=∑zp(z)p(x∣z)p(x) = \sum_z p(z)p(x\mid z) (hard), train (needs log⁡p(x)\log p(x) or a surrogate), and represent (x↦x \mapsto “its” zz — needs the posterior p(z∣x)p(z\mid x), also hard).


2. The objective, and Scenario 1: sum it exactly

The training objective is maximum likelihood with the latent summed (or integrated) out:

max⁡θ∑ilog⁡pθ(x(i))=max⁡θ∑ilog⁡∑zpZ(z) pθ(x(i)∣z).\max_\theta \sum_i \log p_\theta(x^{(i)}) = \max_\theta \sum_i \log \sum_z p_Z(z)\, p_\theta(x^{(i)} \mid z).

Scenario 1: zz takes a small number of values → the sum is tractable, and the objective is exact. The slides’ example is a mixture of 3 Gaussians with a uniform prior over components: log⁡p(x)=log⁡∑k=13πkN(x;μk,Σk)\log p(x) = \log \sum_{k=1}^{3} \pi_k N(x; \mu_k, \Sigma_k) — a log-sum-exp, differentiable, trainable by SGD. (One could also optimize the prior pZ(z)p_Z(z) — “learning the prior” — as Lecture 8 does.)

Script 01, Part 1 trains mixtures with K=1,2,3,5K = 1, 2, 3, 5 components on 3,000 points of a true 3-component mixture (truth on the test points 2.0610 nats):

KKtrain NLLtest NLL− truth
13.47493.4933+1.432
22.59082.5689+0.508
32.07492.0623+0.001
52.07222.0644+0.003

and the posterior p(z∣x)∝πzN(x;μz,Σz)p(z \mid x) \propto \pi_z N(x; \mu_z, \Sigma_z) is a soft cluster assignment (e.g. 0.968 / 0.032 for a point between two clusters).

Mixture posterior

Left: data and the fitted mixture. Right: the posterior responsibilities as colours (01_exact_and_sampled_likelihood.py).

Scenario 2: zz can take an impractical number of values — a continuous vector, or 100 binary properties (21002^{100} configurations), or ShapeWorld’s 921,600 configurations — and we must approximate.


3. Scenario 2: sampling the latent

3.1 Prior sampling, and why it fails

The first idea: if zz takes many values, sample it,

log⁡p(x)=log⁡Ez∼pZ[p(x∣z)]≈log⁡1S∑s=1Sp(x∣z(s)),z(s)∼pZ,\log p(x) = \log E_{z \sim p_Z}[p(x \mid z)] \approx \log \frac{1}{S}\sum_{s=1}^S p(x \mid z^{(s)}), \qquad z^{(s)} \sim p_Z,

and run SGD on that. The challenge (slides): with data in NN clusters, a uniformly sampled zz makes only 1/N1/N of the terms useful; with 100 binary high-level properties, the probability that a sampled zz matches a given xx is 0.5100≈8×10−310.5^{100} \approx 8 \times 10^{-31}. “When going to higher dimensional data, it becomes near impossible to be lucky enough that a sampled zz is a good match for a data point.”

Script 01, Part 2 makes this concrete on noisy ShapeWorld: zz = the clean image’s latents, xx = the clean image with each pixel flipped with probability 0.05. The exact −log⁡2p(x)-\log_2 p(x) of 200 noisy test images, summed over all 921,600 panel pairs, is 99.88 bits on average. The right latent has prior probability ~2−17.82^{-17.8} — a prior sample equals it about once in 228,000 draws — and every wrong one costs log⁡2(1/0.05)=4.3\log_2(1/0.05) = 4.3 bits per mismatched pixel:

prior samples SSestimated −log⁡2p(x)-\log_2 p(x)mean errorworst errorimages within 1 bit
10334.37−234.5−352.80%
1,000191.92−92.0−197.02%
100,000122.02−22.1−81.840%

Even 100,000 prior samples underestimate log⁡p(x)\log p(x) by 22 bits on average. By Jensen’s inequality, E[log⁡p^]≤log⁡pE[\log \hat p] \le \log p: the prior-sampling estimate is biased downwards, worst exactly when the posterior is narrow relative to the prior — i.e. when the latent is informative, which is what we want.

3.2 Importance sampling

To compute Ez∼p[f(z)]E_{z \sim p}[f(z)] when samples from pp are uninformative, sample from a proposal qq and reweight:

Ez∼pZ[p(x∣z)]=Ez∼q[pZ(z)q(z) p(x∣z)]≈1S∑spZ(z(s)) p(x∣z(s))q(z(s)),z(s)∼q.E_{z \sim p_Z}[p(x \mid z)] = E_{z \sim q}\Big[\frac{p_Z(z)}{q(z)}\, p(x \mid z)\Big] \approx \frac1S \sum_s \frac{p_Z(z^{(s)})\,p(x \mid z^{(s)})}{q(z^{(s)})}, \qquad z^{(s)} \sim q.

What is a good proposal for data point x(i)x^{(i)}? We want samples compatible with x(i)x^{(i)} — the posterior q(z)=pθ(z∣x(i))q(z) = p_\theta(z \mid x^{(i)}). With it every importance weight equals

p(z) p(x∣z)p(z∣x)=p(x),\frac{p(z)\,p(x \mid z)}{p(z \mid x)} = p(x),

so one sample gives the exact answer, with zero variance. Script 01, Part 3 uses proposals q∝p(z∣x)τq \propto p(z \mid x)^\tau on noisy ShapeWorld (S=10S = 10, 20 repetitions per image):

τ\taumean error of log⁡2p^\log_2\hat p (bits)std of one estimate
1 (the posterior)−0.0000.000
0.5+0.0000.022
0.25−0.0170.121
0.1−3.3405.150

and script 02, Part 1 on probabilistic PCA (mean error in nats over 500 test points):

samples SSprior sampling: mean errorstdposterior proposal: errorstd
1−118.39102.9+8e-162e-15
10−7.297.51+8e-167e-16
100−0.400.76+9e-163e-16
1,000−0.0260.170+8e-162e-16
10,000−0.0020.050+8e-162e-16

The issue (slides): it is not clear how to sample from p(z∣x)p(z \mid x) — that is the hard problem itself.

3.3 The variational approach

The general principle of variational methods: we cannot use the pp we want, so we propose a parameterized distribution qq we know how to work with (here: sample from, and evaluate), and find the parameter setting that makes it as good as possible — e.g. as close as possible to p(z∣x)p(z \mid x) in KL divergence. All quantities in the resulting objective are computable (§4).

3.4 Amortized inference

For every x(i)x^{(i)} we would solve its own optimization for its own q(i)q^{(i)} — not scalable to large datasets, and expensive for every new data point. Amortization: if the same inference problem is solved many times, train a neural network to solve it — an encoder qϕ(z∣x)q_\phi(z \mid x), e.g. N(μϕ(x),diag σϕ2(x))N(\mu_\phi(x), \mathrm{diag}\,\sigma^2_\phi(x)), shared by all xx. The slides’ trade-off: faster and a form of regularization, but not as precise (the “amortization gap”, §4.3).


4. The variational lower bound

4.1 Derivation 1: Jensen

For any distribution q(z∣x)q(z \mid x) with the right support,

log⁡p(x)=log⁡Ez∼q[p(x,z)q(z∣x)]  ≥  Ez∼q[log⁡p(x,z)−log⁡q(z∣x)]=:ELBO(x;q).\log p(x) = \log E_{z \sim q}\Big[\frac{p(x, z)}{q(z \mid x)}\Big] \;\ge\; E_{z \sim q}\big[\log p(x, z) - \log q(z \mid x)\big] =: \mathrm{ELBO}(x; q).

The inequality is Jensen’s (log⁡\log is concave). This is the variational lower bound (VLB), or evidence lower bound (ELBO). It is an objective amenable to stochastic optimization: an expectation under qq, which we can sample.

4.2 Derivation 2: KL — now we know the gap

Start from the KL divergence between qq and the true posterior:

KL(q(z∣x) ∥ p(z∣x))=Eq[log⁡q(z∣x)−log⁡p(x,z)p(x)]=log⁡p(x)−ELBO(x;q).\mathrm{KL}(q(z\mid x) \,\Vert\, p(z \mid x)) = E_q\Big[\log q(z\mid x) - \log \frac{p(x, z)}{p(x)}\Big] = \log p(x) - \mathrm{ELBO}(x; q).

So

log⁡p(x)=ELBO(x;q)+KL(q(z∣x) ∥ p(z∣x)),\log p(x) = \mathrm{ELBO}(x; q) + \mathrm{KL}\big(q(z \mid x) \,\Vert\, p(z \mid x)\big),

the same bound as Jensen’s, but now we know the gap: it is exactly the KL from qq to the true posterior. Two consequences (slides): the optimal qq is p(z∣x)p(z \mid x), at which point the bound is tight; and maximizing the ELBO over qq is the same as making qq close to the posterior, while maximizing it over θ\theta pushes up log⁡p(x)\log p(x) (minus whatever gap remains). Training a generative model by maximizing Ex∼pdata[ELBO]E_{x \sim p_{\text{data}}}[\mathrm{ELBO}] is therefore VLB maximization over both.

Script 02, Part 2 checks the identity on probabilistic PCA, where everything is in closed form:

proposal q(z∣x)q(z \mid x)ELBOlog⁡p(x)−\log p(x) - ELBOKL(q∥p(z∣x))(q \Vert p(z\mid x))
exact posterior−4.80120.00000.0000
best diagonal Gaussian (mean-field, per xx)−4.97230.17110.1711
amortized linear encoder (trained by SGD)−4.98430.18320.1832
posterior mean, prior covariance II−61.499756.698556.6985
the prior N(0,I)N(0, I) itself−119.0939114.2927114.2927

(log⁡p(x)=−4.8012\log p(x) = -4.8012.) The identity holds to the last digit. The posterior here is correlated with standard deviations 0.111 and 0.456 (the prior’s is 1): a diagonal qq cannot represent the correlation and pays 0.17 nats; the right mean with the prior’s width pays 57; the prior itself pays 114 — the single-sample prior-sampling error of §3.2.

4.3 Amortization and IWAE

The amortization gap is the difference between the best qq per data point and the best qq an encoder can produce: here the linear encoder lands 0.012 nats behind the per-example mean-field optimum (the posterior mean is linear in xx in this model, so amortizing costs little; with nonlinear models and small encoders the gap can be large).

The importance-weighted autoencoder (IWAE; Burda et al., 2015) uses KK samples inside the log:

LK(x)=Ez1..zK∼q[log⁡1K∑k=1Kp(x,zk)q(zk∣x)],L1=ELBO≤LK≤LK+1≤log⁡p(x),\mathcal{L}_K(x) = E_{z_1..z_K \sim q}\Big[\log \frac1K \sum_{k=1}^K \frac{p(x, z_k)}{q(z_k \mid x)}\Big], \qquad \mathcal{L}_1 = \mathrm{ELBO} \le \mathcal{L}_K \le \mathcal{L}_{K+1} \le \log p(x),

and LK→log⁡p(x)\mathcal{L}_K \to \log p(x) as K→∞K \to \infty. It is importance sampling (§3.2) with a learned proposal, read as a bound. Script 02, Part 3 (gap log⁡p(x)−LK\log p(x) - \mathcal{L}_K in nats):

proposalK=1K = 15505005,000
best diagonal Gaussian0.1810.0610.0110.00260.0007
the prior115.916.70.8890.0600.003

IWAE

More samples help; a good proposal helps far more.


5. Gradients through an expectation

The ELBO is Ez∼qϕ[f(z)]E_{z \sim q_\phi}[f(z)] with ϕ\phi in the distribution we sample from. Differentiating with respect to θ\theta (inside ff) is easy; with respect to ϕ\phi it is not. Two estimators.

5.1 Likelihood ratio (score function, REINFORCE)

∇ϕEqϕ[f(z)]=∫f(z) ∇ϕqϕ(z) dz=∫f(z) qϕ(z) ∇ϕlog⁡qϕ(z) dz=Eqϕ[f(z) ∇ϕlog⁡qϕ(z)].\nabla_\phi E_{q_\phi}[f(z)] = \int f(z)\,\nabla_\phi q_\phi(z)\,dz = \int f(z)\,q_\phi(z)\,\nabla_\phi \log q_\phi(z)\,dz = E_{q_\phi}\big[f(z)\,\nabla_\phi \log q_\phi(z)\big].

It needs only values of ff — ff may be non-differentiable, zz may be discrete — and subtracting any constant baseline bb keeps it unbiased (Eq[∇log⁡q]=0E_q[\nabla \log q] = 0). Its issue: high variance; many samples of zz are needed for a good estimate. (This is the estimator of policy gradients in reinforcement learning, where no assumption on ff is made.)

5.2 Pathwise derivative (reparameterization trick)

Write the sample as a differentiable function of fixed noise, z=gϕ(ε)z = g_\phi(\varepsilon) — for a Gaussian z=μ+σ⊙εz = \mu + \sigma \odot \varepsilon, ε∼N(0,I)\varepsilon \sim N(0, I); any flow from Lectures 5–6 would do — then

∇ϕEz∼qϕ[f(z)]=∇ϕEε[f(gϕ(ε))]=Eε[∇zf(gϕ(ε)) ∇ϕgϕ(ε)].\nabla_\phi E_{z \sim q_\phi}[f(z)] = \nabla_\phi E_{\varepsilon}[f(g_\phi(\varepsilon))] = E_\varepsilon\big[\nabla_z f(g_\phi(\varepsilon))\,\nabla_\phi g_\phi(\varepsilon)\big].

It requires zz continuous and ff differentiable, and “can work with only 1–2 samples”.

5.3 The toy problem

The slides’ toy problem: move q=N(μ,σ2I)q = N(\mu, \sigma^2 I) in 2-D so that its samples reach a green point g=(2,1)g = (2, 1), i.e. minimize Eq∥z−g∥2E_q\lVert z - g\rVert^2 (we learn μ\mu from (−2,−2)(-2, -2), σ=0.5\sigma = 0.5 fixed; exact gradient (−8,−6)(-8, -6)). Script 03, Part 1 (2,000 estimates each):

samples nnestimatormeanstd per component
1likelihood ratio(−7.51, −5.55)(54.4, 51.7)
1likelihood ratio + baseline E[f]E[f](−8.51, −5.83)(13.4, 11.7)
1pathwise(−7.98, −5.99)(1.03, 0.98)
100likelihood ratio(−8.04, −6.28)(5.38, 5.27)
100pathwise(−8.00, −6.00)(0.10, 0.10)

Both are unbiased; the likelihood ratio’s single-sample noise is ~50× the pathwise one (and still 1–13× the gradient after a baseline). SGD with one sample per step, learning rate 0.02 (Part 2, median distance to gg over 20 runs):

estimatorstep 02550100300
likelihood ratio5.002.060.570.290.24 (1 of 20 runs diverged)
likelihood ratio, lr 0.0025.004.704.413.501.77
likelihood ratio + running baseline5.001.830.710.160.12
pathwise5.001.790.650.130.08

Gradient estimator trajectories

(Plan vs reality: the first version also learned σ\sigma; with the likelihood-ratio gradient, log⁡σ\log\sigma received huge noisy updates and the runs diverged to NaN. Keeping σ\sigma fixed isolates the comparison.)

And the other side of the trade-off (Part 3): with a 0/1 cost — “is zz inside the disk of radius 0.5 around gg?” — the pathwise gradient is zero almost everywhere and μ\mu never moves (1.00 → 1.00), while the likelihood ratio, which only needs values, moves into the disk (1.00 → 0.03) — as long as some samples land in it (started 5 units away, no sample ever does and neither estimator moves). Discrete latents (Lecture 8’s VQ-VAE) need yet another trick, the straight-through estimator.


6. The variational autoencoder

6.1 Putting it together

With p(z)=N(0,I)p(z) = N(0, I) and qϕ(z∣x)=N(μϕ(x),diag σϕ2(x))q_\phi(z \mid x) = N(\mu_\phi(x), \mathrm{diag}\,\sigma_\phi^2(x)), the pathwise estimator applies to the ELBO directly:

ELBO(x)=Eε∼N(0,I)[log⁡pθ(x∣z)+log⁡p(z)−log⁡qϕ(z∣x)]z=μϕ(x)+σϕ(x)⊙ε,\mathrm{ELBO}(x) = E_{\varepsilon \sim N(0, I)}\big[\log p_\theta(x \mid z) + \log p(z) - \log q_\phi(z \mid x)\big]_{z = \mu_\phi(x) + \sigma_\phi(x) \odot \varepsilon},

and stochastic gradients with respect to both θ\theta and ϕ\phi are one backward pass away. That is the Variational AutoEncoder (Kingma & Welling, 2014; Rezende et al., 2014). The slides’ comparison: likelihood-ratio gradients for the same objective are possible but need many samples (and wake-sleep, an older alternative, optimizes a different objective — Lecture 8’s extra material).

6.2 Why is it called an autoencoder?

Regroup the ELBO:

ELBO(x)=Eqϕ(z∣x)[log⁡pθ(x∣z)]⏟reconstruction: encode x to z, decode back  −  KL(qϕ(z∣x) ∥ p(z))⏟a penalty on the code.\mathrm{ELBO}(x) = \underbrace{E_{q_\phi(z\mid x)}[\log p_\theta(x \mid z)]}_{\text{reconstruction: encode } x \text{ to } z\text{, decode back}} \;-\; \underbrace{\mathrm{KL}\big(q_\phi(z \mid x) \,\Vert\, p(z)\big)}_{\text{a penalty on the code}}.

The first term is an autoencoder: x→x \to (encoder) →z→\to z \to (decoder) →x\to x, scored by how well xx is reconstructed. The second charges for the information the code carries: with Gaussians it is analytic, 12∑j(σj2+μj2−1−log⁡σj2)\tfrac12\sum_j(\sigma_j^2 + \mu_j^2 - 1 - \log\sigma_j^2). In compression language (Lectures 1, 21), the ELBO is a code length: bits to describe zz (the KL) plus bits to describe xx given zz (the reconstruction).

6.3 Homework 2 Q1: when is the latent used?

The homework trains the same VAE — 2-D latent, diagonal Gaussian encoder, diagonal Gaussian decoder p(x∣z)=N(μ(z),diag σ2(z))p(x\mid z) = N(\mu(z), \mathrm{diag}\,\sigma^2(z)) — on (a) a Gaussian with a full covariance and (b) a Gaussian with a diagonal covariance. Script 04 uses standard deviations 2.0 and 0.2, rotated by 45° for (a):

(nats per point)(a) full covariance(b) diagonal covariance
−ELBO (10 draws of zz per point)1.92311.9145
reconstruction term−0.37981.9131
KL(q∥p(z))(q \Vert p(z))2.30280.0015
KL per latent dimension0.000 / 2.3030.000 / 0.001
IWAE, K=1,000K = 1{,}0001.91631.9146
truth (exact Gaussian, same points)1.91441.9144

Covariance of the decoder means μ(z)\mu(z), z∼p(z)z \sim p(z): in (a) [[1.98, 1.97], [1.97, 1.97]] — the data’s long axis (data: [[2.02, 1.98], [1.98, 2.02]]); in (b) essentially zero.

VAE on 2-D data

Rows (a), (b): test data, samples with decoder noise, decoder means without noise (04_vae_2d.py).

  • (b): the latent is ignored (KL ≈ 0, “posterior collapse”). The decoder’s own diagonal Gaussian is the data distribution; information in zz would cost KL and buy nothing. Decoder means sit at one point; all variation comes from decoder noise.
  • (a): the latent is used. A diagonal decoder cannot express the correlation, so the long axis of the data is routed through one latent dimension (2.3 nats); the second dimension is switched off. Decoder means trace the long axis; decoder noise supplies the thin direction.
  • In (a) the bound is 0.009 nats loose (the encoder’s diagonal Gaussian is not the exact posterior) and IWAE closes most of it; in (b) the bound is tight (unused zz: qq = prior = posterior).

The general lesson, taken up in Lecture 8: a VAE uses its latent only for what its decoder cannot model by itself.

6.4 A VAE on ShapeWorld

Homework 2 Q2a trains a convolutional VAE with a 16-dimensional latent on colour images. Script 05 trains the same architecture on binary ShapeWorld with a Bernoulli decoder, so the ELBO is a bound in bits, directly comparable with the 17.80-bit floor and with every model so far (4,000 steps of 64 images, latent sizes 4, 16, 64):

latent dim−ELBO (bits)reconstructionKLactive dimsIWAE K=10K = 10K=100K = 100K=1,000K = 1{,}000
4113.7298.5015.234 of 4112.75112.27112.02
1666.2329.2337.0016 of 1663.6861.7460.97
6466.4130.2036.2115 of 6462.5060.7759.95

(IWAE on 200 test images; “active” = average KL above 0.1 bits.)

  1. The ELBO is a code length with two parts. Four latent dimensions are too few: the code is cheap (15 bits) but reconstruction costs 98. With 16 dimensions, 37 bits of code buy a reconstruction of 29 bits. With 64 dimensions the total is the same, and 49 dimensions are switched off — their KL is zero because they buy no reconstruction. The KL term acts as an automatic dimension selector.
  2. The VAE sits between flows and autoregressive models. IWAE with K=1,000K = 1{,}000 lowers the bound by ~6 bits, to ~60–61 bits: far better than Lecture 6’s best flow (94.7, also a bound), far worse than the autoregressive models (18.8–22.3, exact).
  3. The autoencoder view. Reconstructions (decoder mean at z=μ(x)z = \mu(x), thresholded) are pixel-perfect for 23.3% of test images, with 5.4 wrong pixels per image on average: small and thin shapes are blurred away. Samples from the prior are shape-like blobs; none is a valid image (Bernoulli draws or thresholded means, T=1T = 1 or 0.70.7; 24–28 pixel flips from the nearest valid image). Interpolating between the codes of two test images cross-fades — one shape dissolves while the other appears — rather than moving or morphing a shape.

VAE on ShapeWorld

Test images, reconstructions, samples (thresholded means), and an interpolation (05_vae_shapeworld.py).

Why so blurry? The decoder is factorized: given zz, every pixel is an independent Bernoulli. So every detail — which of 8 shapes, which of 4 sizes, which position — must be carried by zz, and a Gaussian zz is a smooth code for crisp, discrete facts: between two training codes the decoder must produce something, and it produces an average. Lecture 8 attacks exactly this: richer (learned, hierarchical) priors, discrete codes, and autoregressive decoders — the last of which brings its own problem, posterior collapse.


7. Summary

  1. Latent variable models explain data through unobserved variables: compact representations, sampling by ancestral steps. The price: p(x)=∫p(z)p(x∣z) dzp(x) = \int p(z)p(x\mid z)\,dz.
  2. With few latent values, sum exactly (a 3-component mixture recovers the truth to 0.001 nats). With many, prior sampling is hopeless (22 bits too pessimistic with 100,000 samples on noisy ShapeWorld).
  3. Importance sampling with the posterior as proposal is exact from one sample; the art is to approximate the posterior — variationally, and amortized by an encoder.
  4. log⁡p(x)=ELBO+KL(q(z∣x)∥p(z∣x))\log p(x) = \mathrm{ELBO} + \mathrm{KL}(q(z\mid x) \Vert p(z \mid x)): the ELBO is tight iff qq is the posterior (checked to 4 decimals). IWAE tightens the bound with KK samples.
  5. Likelihood-ratio gradients need only values of ff but are noisy (~50× the pathwise noise here); pathwise gradients need differentiable ff and continuous zz, and work with one sample. The VAE uses the latter.
  6. The VAE = encoder + reparameterized sampling + decoder, trained on reconstruction − KL; it uses its latent only for what the decoder cannot do alone (homework 2 Q1: KL 2.3 nats vs 0.0015), and switches off latent dimensions it does not need (49 of 64 on ShapeWorld).
  7. On ShapeWorld a convolutional VAE reaches 66 bits (ELBO) / 61 bits (IWAE, K=1,000K = 1{,}000): better than flows (95), far worse than autoregressive models (18.8–22.3); reconstructions blur small shapes, samples are blobs, interpolations cross-fade.

8. Common pitfalls

  1. Reading a prior-sampling estimate as a likelihood. It is biased low, by many bits when the latent matters.
  2. Forgetting the normalizing constants of Gaussian decoders. They do not change gradients but change every reported number (script 02’s first version printed “−ELBO 7.2” for a true 4.9).
  3. Comparing an ELBO with an exact likelihood as if both were exact. The ELBO is a bound; report IWAE with large KK for a tighter (still lower) bound.
  4. Monte Carlo noise in the ELBO. A one-sample ELBO on a test set can be noisier than the effect being measured (script 04’s first version showed an “IWAE worse than the ELBO” by 0.0014 nats — two standard errors of a one-sample estimate).
  5. Likelihood-ratio gradients without a baseline. Unbiased but so noisy that SGD can diverge at learning rates where pathwise SGD converges.
  6. Interpreting KL ≈ 0 as a bug. It means the model found no use for zz; whether that is a problem depends on what the latent is for (Lecture 8).
  7. Sampling binary images by thresholding the decoder mean and calling it the model’s sample. The model’s distribution is the Bernoulli draw; thresholded means are a different (usually prettier) object.

9. Exercises

Exercise 1 (exact objective). For a mixture p(x)=∑kπkN(x;μk,σk2)p(x) = \sum_k \pi_k N(x; \mu_k, \sigma_k^2), show that ∇μklog⁡p(x)=p(z=k∣x) (x−μk)/σk2\nabla_{\mu_k}\log p(x) = p(z = k \mid x)\,(x - \mu_k)/\sigma_k^2. Interpret.

Answer

∇μklog⁡p(x)=πk∇μkN(x;μk,σk2)p(x)=πkN(x;μk,σk2)p(x)⋅x−μkσk2=p(z=k∣x)x−μkσk2\nabla_{\mu_k}\log p(x) = \frac{\pi_k \nabla_{\mu_k}N(x;\mu_k,\sigma_k^2)}{p(x)} = \frac{\pi_k N(x;\mu_k,\sigma_k^2)}{p(x)}\cdot\frac{x - \mu_k}{\sigma_k^2} = p(z = k\mid x)\frac{x-\mu_k}{\sigma_k^2}. Each component is pulled towards xx in proportion to its responsibility for xx: the gradient of the exact objective already contains the posterior (the same quantity EM uses).

Exercise 2 (prior sampling is biased low). Show that E[log⁡1S∑sp(x∣z(s))]≤log⁡p(x)E[\log \frac1S\sum_s p(x\mid z^{(s)})] \le \log p(x) for z(s)∼p(z)z^{(s)} \sim p(z), and that the estimate is consistent as S→∞S \to \infty. For the 100-binary-property example, how many prior samples are needed before one matches with probability 1/2?

Answer

p^=1S∑p(x∣z(s))\hat p = \frac1S\sum p(x\mid z^{(s)}) is unbiased for p(x)p(x), so by Jensen E[log⁡p^]≤log⁡E[p^]=log⁡p(x)E[\log\hat p] \le \log E[\hat p] = \log p(x); by the law of large numbers p^→p(x)\hat p \to p(x) and log⁡\log is continuous. A match has probability 2−1002^{-100}; P(at least one)=1−(1−2−100)S≈S 2−100P(\text{at least one}) = 1 - (1 - 2^{-100})^S \approx S\,2^{-100}, so S≈299≈6×1029S \approx 2^{99} \approx 6 \times 10^{29}.

Exercise 3 (the zero-variance proposal). Show that with q(z)=p(z∣x)q(z) = p(z\mid x) every importance weight p(x,z)/q(z)p(x, z)/q(z) equals p(x)p(x). Why can’t we use this in practice?

Answer

p(x,z)/p(z∣x)=p(x,z) p(x)/p(x,z)=p(x)p(x,z)/p(z\mid x) = p(x,z)\,p(x)/p(x,z) = p(x). Using it requires sampling from and evaluating p(z∣x)=p(x,z)/p(x)p(z \mid x) = p(x, z)/p(x), which needs p(x)p(x) — the quantity we are trying to compute.

Exercise 4 (the ELBO two ways). Derive the ELBO with Jensen’s inequality and with the KL identity, and show that maximizing it over qq for fixed θ\theta minimizes KL(q∥p(z∣x))\mathrm{KL}(q \Vert p(z\mid x)).

Answer

See §4.1–4.2. Since log⁡p(x)\log p(x) does not depend on qq, arg⁡max⁡qELBO=arg⁡min⁡q[log⁡p(x)−ELBO]=arg⁡min⁡qKL(q∥p(z∣x))\arg\max_q \mathrm{ELBO} = \arg\min_q [\log p(x) - \mathrm{ELBO}] = \arg\min_q \mathrm{KL}(q \Vert p(z \mid x)).

Exercise 5 (Gaussian KL). Derive KL(N(μ,diag σ2)∥N(0,I))=12∑j(σj2+μj2−1−log⁡σj2)\mathrm{KL}(N(\mu, \mathrm{diag}\,\sigma^2) \Vert N(0, I)) = \frac12\sum_j(\sigma_j^2 + \mu_j^2 - 1 - \log\sigma_j^2). Which values of μj,σj\mu_j, \sigma_j make dimension jj “free”?

Answer

Eq[log⁡q−log⁡p]=∑jE[−12log⁡(2πσj2)−(zj−μj)22σj2+12log⁡2π+zj22]=∑j[−12log⁡σj2−12+12(σj2+μj2)]E_q[\log q - \log p] = \sum_j E[-\tfrac12\log(2\pi\sigma_j^2) - \tfrac{(z_j-\mu_j)^2}{2\sigma_j^2} + \tfrac12\log 2\pi + \tfrac{z_j^2}{2}] = \sum_j[-\tfrac12\log\sigma_j^2 - \tfrac12 + \tfrac12(\sigma_j^2 + \mu_j^2)]. It is zero iff μj=0\mu_j = 0, σj=1\sigma_j = 1: the encoder returns the prior for that dimension, whatever xx is — the dimension carries no information (an “inactive” dimension).

Exercise 6 (IWAE monotonicity). Show L1≤LK≤log⁡p(x)\mathcal{L}_1 \le \mathcal{L}_K \le \log p(x).

Answer

Upper bound: 1K∑kwk\frac1K\sum_k w_k with wk=p(x,zk)/q(zk∣x)w_k = p(x,z_k)/q(z_k\mid x) is unbiased for p(x)p(x); Jensen gives E[log⁡1K∑wk]≤log⁡p(x)E[\log \frac1K\sum w_k] \le \log p(x). Lower bound: by concavity of log⁡\log, log⁡1K∑kwk≥1K∑klog⁡wk\log\frac1K\sum_k w_k \ge \frac1K\sum_k \log w_k, whose expectation is L1\mathcal{L}_1. (Monotonicity in KK — LK≤LK+1\mathcal{L}_K \le \mathcal{L}_{K+1} — follows by writing the (K+1)(K{+}1)-sample average as an average of KK-sample averages; Burda et al., Theorem 1.)

Exercise 7 (the score function has mean zero). Show Eqϕ[∇ϕlog⁡qϕ(z)]=0E_{q_\phi}[\nabla_\phi \log q_\phi(z)] = 0, and conclude that any constant baseline leaves the likelihood-ratio estimator unbiased. What is the variance-optimal constant baseline for a scalar parameter?

Answer

Eq[∇log⁡q]=∫q ∇qq dz=∇∫q dz=∇1=0E_q[\nabla\log q] = \int q\,\frac{\nabla q}{q}\,dz = \nabla\int q\,dz = \nabla 1 = 0, so E[(f−b)∇log⁡q]=E[f∇log⁡q]E[(f - b)\nabla\log q] = E[f\nabla\log q]. Variance of (f−b)s(f - b)s with s=∇log⁡qs = \nabla\log q: minimize E[(f−b)2s2]E[(f-b)^2 s^2] over bb: b∗=E[fs2]/E[s2]b^* = E[f s^2]/E[s^2] — roughly E[f]E[f] when ff and s2s^2 are weakly correlated.

Exercise 8 (pathwise for the toy problem). For f(z)=∥z−g∥2f(z) = \lVert z - g\rVert^2 and z=μ+σεz = \mu + \sigma\varepsilon in dd dimensions, compute the pathwise estimator with one sample and its variance. Compare with the likelihood-ratio estimator’s variance at μ\mu far from gg.

Answer

∇μf(μ+σε)=2(μ+σε−g)\nabla_\mu f(\mu + \sigma\varepsilon) = 2(\mu + \sigma\varepsilon - g): mean 2(μ−g)2(\mu - g), covariance 4σ2I4\sigma^2 I — std 2σ=12\sigma = 1 per component for σ=0.5\sigma = 0.5 (script 03: 1.03, 0.98), independent of the distance to gg. Likelihood ratio: f(z) ε/σf(z)\,\varepsilon/\sigma; far from gg, f≈∥μ−g∥2=25f \approx \lVert\mu - g\rVert^2 = 25, so std ≈25/σ=50\approx 25/\sigma = 50 per component (script 03: 54, 52) — it grows with the size of ff, not just its slope; a baseline removes the constant part.

Exercise 9 (homework 2 Q1 reflection). Explain in two sentences why the VAE ignores its latent on the diagonal-covariance data and uses it on the full-covariance data. Would the answer change with a full-covariance decoder?

Answer

With diagonal data, the decoder’s own diagonal Gaussian (with μ,σ\mu, \sigma constant in zz) already equals the data distribution, so any information in zz costs KL without improving the reconstruction term; with correlated data, a diagonal decoder cannot express the correlation and the cheapest way to model it is to put the long axis into zz. With a full-covariance decoder, both datasets would be modelled exactly by the decoder alone and the latent would be ignored in both.

Exercise 10 (the ELBO is a code length). Interpret −ELBO(x)-\mathrm{ELBO}(x) in bits as the length of a two-part code. Why does this code waste bits compared with −log⁡2p(x)-\log_2 p(x), and how does “bits-back coding” (Lecture 21) recover them?

Answer

−ELBO=Eq[−log⁡2p(z)−log⁡2p(x∣z)]−H(q(z∣x))-\mathrm{ELBO} = E_q[-\log_2 p(z) - \log_2 p(x\mid z)] - H(q(z\mid x)) in bits: send z∼qz \sim q using the prior (−log⁡2p(z)-\log_2 p(z)), then xx given zz; the −H(q)-H(q) term is the subtlety. A naive two-part code pays Eq[−log⁡2p(z)−log⁡2p(x∣z)]E_q[-\log_2 p(z) - \log_2 p(x\mid z)], i.e. H(q)H(q) more than −ELBO-\mathrm{ELBO}, because the choice of zz among the many plausible ones carries H(q)H(q) bits of arbitrary information. Bits-back coding uses those choice bits to transmit other data, getting them “back”, so the net cost is −ELBO≥−log⁡2p(x)-\mathrm{ELBO} \ge -\log_2 p(x); the remaining waste is the KL to the true posterior.


10. Further reading

From the slides

  • D. P. Kingma, M. Welling. Auto-Encoding Variational Bayes, ICLR 2014.
  • Y. Burda, R. Grosse, R. Salakhutdinov. Importance Weighted Autoencoders, ICLR 2016.
  • G. E. Hinton, P. Dayan, B. J. Frey, R. M. Neal. The Wake-Sleep Algorithm for Unsupervised Neural Networks, Science 1995; P. Dayan, G. E. Hinton et al. The Helmholtz Machine, Neural Computation 1995.

Added by these notes

  • D. J. Rezende, S. Mohamed, D. Wierstra. Stochastic Backpropagation and Approximate Inference in Deep Generative Models, ICML 2014 (the reparameterization trick, independently).
  • R. J. Williams. Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning, 1992 (REINFORCE).
  • C. Cremer, X. Li, D. Duvenaud. Inference Suboptimality in Variational Autoencoders, ICML 2018 (the amortization gap).
  • S. Mohamed, M. Rosca, M. Figurnov, A. Mnih. Monte Carlo Gradient Estimation in Machine Learning, JMLR 2020 (a survey of both estimators).
  • D. P. Kingma, M. Welling. An Introduction to Variational Autoencoders, Foundations and Trends in ML, 2019.

11. Next lecture

Lecture 8 (latent variable models II) asks what to put around the VAE’s Gaussian latent: richer priors (a learned hierarchical prior with a residual-normal posterior — homework 2 Q2b), discrete latents (VQ-VAE with a straight-through estimator and a Transformer prior over its codes — homework 2 Q3 — and the tokens of Lecture 4 seen as a VAE), posterior collapse when the decoder is powerful enough to ignore zz (a PixelCNN decoder) and its cures (weaker decoders, KL warm-up, free bits), and β-VAE, whose disentanglement can be measured on ShapeWorld because the true factors — shape, size, position — are known.

← 返回课程目录