Lecture 8 · Latent Variable Models II: Better Priors, Discrete Latents and Posterior Collapse

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

课程源码 ZIP ↓

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

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 4 · Thu 2/8/2024 · Latent Variable Models — VAE, second part (slides 67–111): the parts of the VAE, the VAE as a generative model, latent interpolation, varieties of the prior p(z)p(z) (unit normal, autoregressive / hierarchical, residual normal), discrete latents and VQ-VAE (straight-through optimization, embedding and commitment losses, learning p(z)p(z) afterwards), VQ-VAE 2.0, VAEs as building blocks, mutual information and the “ignoring latent code” problem with powerful decoders (weakening models, changing training dynamics), AR + VAE (VLAE, PixelVAE), β-VAE, variational dequantization, and the extra slides on wake-sleep and the Helmholtz machine. Homework 2, Questions 2b and 3. Basis: The slides list ideas and show results from papers. These notes derive the residual-normal KL, the VQ-VAE’s ELBO view and its straight-through gradient, why a powerful decoder makes the latent useless, and what β does to the bound. Every claim is then measured on ShapeWorld, where bits can be compared with the exact floor (17.80) and where — unlike for photographs — the true generative factors are known, so disentanglement can be measured rather than judged by eye. Code: code/lecture08/ (4 scripts + vae_tools.py; PyTorch (CPU); models cached; first runs ~4–15 minutes each, later runs seconds to a minute) 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. Name the parts of a VAE (prior, encoder, decoder) and say which of them limit it on ShapeWorld.
  2. Explain what the unit-normal prior gives (analytic KL, interpolation) and what it costs (independent dimensions), and derive the KL of a residual-normal posterior in a hierarchical VAE.
  3. Describe a VQ-VAE: nearest-code quantization, the straight-through estimator, embedding and commitment losses, why its KL is a constant, and why the prior is learned afterwards — and connect its codes to Lecture 4’s tokens.
  4. Diagnose dead codes and fix them.
  5. Explain, with mutual information, why a powerful decoder makes the latent useless (posterior collapse), and evaluate the remedies: weaker decoders, KL warm-up, free bits.
  6. Write the β-VAE objective, say what β trades, and measure disentanglement with the mutual information gap when the true factors are known.
  7. Explain wake-sleep and the Helmholtz machine, and why they gave way to the reparameterized ELBO.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lecture 7 (ELBO, IWAE, reparameterization, the ShapeWorld VAE: 66 bits, blurry)hierarchical priors, residual normal, VQ-VAE, straight-through, dead codesVQGAN (Lecture 10), latent diffusion on autoencoder latents (Lecture 12)
Lectures 3–4 (PixelCNN, Transformers on tokens: 18.8–22.3 bits)posterior collapse and its cures, mutual informationbits-back coding with VAEs (Lecture 21)
Lecture 6 (variational dequantization)β-VAE, disentanglement metrics (MIG)representation learning without decoders (Lectures 13–15)

0.3 Map

§1  the parts of the VAE, and what limited Lecture 7's model
§2  varieties of p(z): unit normal, hierarchical, residual normal                          ← code 01
§3  discrete latents: VQ-VAE, the straight-through estimator, learning p(z) afterwards     ← code 02
§4  mutual information and posterior collapse                                              ← code 03
§5  beta-VAE and disentanglement, measured                                                ← code 04
§6  related ideas: variational dequantization, wake-sleep, the Helmholtz machine
§7  summary   §8 pitfalls   §9 exercises   §10 further reading   §11 next lecture

0.4 Notation

SymbolMeaning
z1,z2z_1, z_2latents of a two-level hierarchy; p(z1) p(z2∣z1)p(z_1)\,p(z_2 \mid z_1) the learned prior
ze(x)z_e(x), eke_k, zq(x)z_q(x)VQ-VAE encoder output, codebook vector kk, quantized output (nearest eke_k)
sg[⋅]\mathrm{sg}[\cdot]stop-gradient: identity in the forward pass, zero gradient
I(x;z)I(x; z)mutual information between data and latent
β\betathe weight of the KL term (β = 1: the ELBO)
MIGmutual information gap (Chen et al., 2018)

0.5 How the experiments are run

All image models are trained on Lecture 1’s 10,000 / 2,000 binary ShapeWorld images (12 × 24) with Bernoulli decoders, so every number is in bits per image and comparable with the exact floor 17.80, Lecture 7’s flat VAE (66.2 bits ELBO, 61.0 IWAE), the flows of Lecture 6 (94.7, a bound) and the autoregressive models of Lectures 3–4 (22.3 / 18.8, exact). The β-VAE uses single 12 × 12 panels (exact entropy 9.29 bits) because its factors — shape (8 kinds), size (4), horizontal and vertical position — are then one of each. Models are cached in code/lecture08/checkpoints/ (Lecture 7’s VAEs are reused from its own folder); reruns print identical numbers.


1. The parts of the VAE

A VAE has three parts, each a design choice (the slides’ “parts of the VAE”):

  • Training: x→x \to encoder q(z∣x)q(z \mid x) →z→\to z \to decoder p(x∣z)p(x \mid z) →x′\to x', scored by reconstruction − KL.
  • Sampling: z∼p(z)→z \sim p(z) \to decoder →x′\to x'. A trained VAE is a generative model, and its latent space supports interpolation: decode points on the path between the codes of two images (the slides show faces morphing smoothly).

Lecture 7’s ShapeWorld VAE showed what can go wrong with each part: the prior N(0,I)N(0, I) treats all dimensions as independent; the posterior is a diagonal Gaussian; the decoder is factorized, so every detail must go through a smooth Gaussian code — samples were blobs, interpolations cross-faded. This lecture changes one part at a time: the prior (§2), the latent space itself (§3), the decoder (§4), and the weight of the KL term (§5).


2. Varieties of the prior

2.1 The unit normal

p(z)=N(0,I)p(z) = N(0, I) has a nice analytic form (closed-form KL to a Gaussian posterior), and one can interpolate linearly between codes because the Gaussian is approximately closed under convex combinations. But all dimensions are independent — a limiting assumption: whatever structure the data have must be absorbed by the encoder and decoder.

2.2 A learned, hierarchical prior

Make the prior autoregressive over groups of latents, p(z)=∏ip(zi∣z<i)p(z) = \prod_i p(z_i \mid z_{<i}), with posteriors q(zi∣z<i,x)q(z_i \mid z_{<i}, x) — sample zz autoregressively, learn both pp and qq. NVAE (Vahdat & Kautz, 2020) builds deep hierarchies this way. The question the slides ask: how to handle the KL between two learned distributions? For a two-level model (z1∼N(0,I)z_1 \sim N(0, I), z2∣z1∼p(z2∣z1)z_2 \mid z_1 \sim p(z_2 \mid z_1), decoder p(x∣z2)p(x \mid z_2)):

KL(q(z1,z2∣x) ∥ p(z1,z2))=KL(q(z1∣x) ∥ p(z1))+Eq(z1∣x)[KL(q(z2∣z1,x) ∥ p(z2∣z1))].\mathrm{KL}\big(q(z_1, z_2 \mid x) \,\Vert\, p(z_1, z_2)\big) = \mathrm{KL}\big(q(z_1 \mid x) \,\Vert\, p(z_1)\big) + E_{q(z_1 \mid x)}\Big[\mathrm{KL}\big(q(z_2 \mid z_1, x) \,\Vert\, p(z_2 \mid z_1)\big)\Big].

2.3 The residual normal

NVAE’s insight: define the posterior as a residual over the prior. If p(z2∣z1)=N(μp(z1),σp2(z1))p(z_2 \mid z_1) = N(\mu_p(z_1), \sigma_p^2(z_1)), let

q(z2∣z1,x)=N(μp(z1)+Δμ(z1,x),  σp2(z1)⋅Δσ2(z1,x)).q(z_2 \mid z_1, x) = N\big(\mu_p(z_1) + \Delta\mu(z_1, x),\; \sigma_p^2(z_1)\cdot \Delta\sigma^2(z_1, x)\big).

Then, per dimension (Exercise 2),

KL(q ∥ p)=12(Δμ2σp2+Δσ2−1−log⁡Δσ2),\mathrm{KL}\big(q \,\Vert\, p\big) = \frac12\Big(\frac{\Delta\mu^2}{\sigma_p^2} + \Delta\sigma^2 - 1 - \log \Delta\sigma^2\Big),

analytic again, and “the posterior adds nothing” is simply Δμ=0\Delta\mu = 0, Δσ=1\Delta\sigma = 1. Homework 2 Q2b fixes σp=1\sigma_p = 1 for stability, so the KL becomes −log⁡Δσ−12+12(Δσ2+Δμ2)-\log\Delta\sigma - \tfrac12 + \tfrac12(\Delta\sigma^2 + \Delta\mu^2) — the formula in vae_tools.HierarchicalVAE.

2.4 Experiment

Script 01 trains homework 2 Q2b’s model — z1∈R16z_1 \in \mathbb{R}^{16} with prior N(0,I)N(0, I), z2∈R16z_2 \in \mathbb{R}^{16} with learned prior N(μp(z1),I)N(\mu_p(z_1), I), residual-normal q(z2∣z1,x)q(z_2 \mid z_1, x), decoder from z2z_2 only — with the same convolutional encoder trunk and decoder as Lecture 7’s flat VAE, for the same 4,000 steps:

model−ELBOreconKLKL of z1z_1 + z2∣z1z_2 \mid z_1IWAE (K=100K = 100)valid samples
two-level, residual normal68.4538.0330.422.68 + 27.7464.120%
(Lecture 7) flat VAE, 16 dims66.2329.2337.00–61.740%
(Lecture 7) flat VAE, 64 dims66.4130.2036.21–60.770%

(bits per image; training curve of the two-level model, test −ELBO: 109.4 → 85.4 → 75.8 → 70.3 → 69.3.)

Plan vs reality: the learned prior was expected to help; it is about 2 bits worse. The information sits almost entirely in z2z_2: the top level carries 2.7 bits. Holding z1z_1 fixed and redrawing z2∣z1z_2 \mid z_1 gives unrelated images (script 01, Part 2), so the “learned prior” is little more than a learned mean for a flat Gaussian code — and the model pays for a second KL term and a harder optimization problem. Hierarchies pay off in NVAE with many levels, spatial latent maps, careful normalization and long training; on a tiny dataset with a two-level vector hierarchy they do not. The lesson for the rest of the lecture: a better prior over a smooth Gaussian code does not fix the blur; changing what the code is (§3) and what the decoder can do (§4) matters more.


3. Discrete latents: VQ-VAE

3.1 Why discrete?

The slides: with a discrete zz, (1) the channel capacity is bounded — a code with KK values carries at most log⁡2K\log_2 K bits — and (2) it is simple to define expressive categorical priors p(z)p(z): autoregressive models over tokens are exactly what Lectures 3–4 built.

3.2 The VQ-VAE

VQ-VAE (van den Oord, Vinyals & Kavukcuoglu, 2017): the encoder outputs a grid of vectors ze(x)z_e(x); each is replaced by its nearest codebook vector,

zq(x)=ek,k=arg⁡min⁡j∥ze(x)−ej∥,z_q(x) = e_k, \qquad k = \arg\min_j \lVert z_e(x) - e_j \rVert,

and the decoder reconstructs from zq(x)z_q(x). In ELBO terms (the slides’ “parts of the VAE” for VQ-VAE): q(z∣x)q(z \mid x) is a deterministic distribution — a point mass on the nearest tokens; with a uniform prior over KK codes per position, KL(q∥p)=log⁡K\mathrm{KL}(q \Vert p) = \log K per position, a constant that can be dropped from training. The ELBO reduces to the reconstruction term.

3.3 How to optimize: straight-through, embedding and commitment

arg⁡min⁡\arg\min has no gradient. The straight-through estimator passes the decoder’s gradient with respect to zqz_q unchanged to zez_e, as if quantization were the identity: feed the decoder ze+sg[zq−ze]z_e + \mathrm{sg}[z_q - z_e] (forward: zqz_q; backward: identity). The codebook gets no gradient that way, so two extra terms are added:

L=−log⁡p(x∣zq(x))⏟reconstruction+∥sg[ze(x)]−e∥2⏟embedding loss: move codes to encoder outputs+β∥ze(x)−sg[e]∥2⏟commitment loss: keep encoder outputs near their codes,\mathcal{L} = \underbrace{-\log p(x \mid z_q(x))}_{\text{reconstruction}} + \underbrace{\lVert \mathrm{sg}[z_e(x)] - e \rVert^2}_{\text{embedding loss: move codes to encoder outputs}} + \beta\underbrace{\lVert z_e(x) - \mathrm{sg}[e] \rVert^2}_{\text{commitment loss: keep encoder outputs near their codes}},

with β=0.25\beta = 0.25 in the paper. (The embedding loss is often replaced by an exponential moving average of the assigned encoder outputs.)

3.4 Learning p(z)p(z)

During training the prior is uniform. Afterwards we want p(z)p(z) to match the distribution of the codes q(z∣x)q(z \mid x) of the training data — “we can use our favorite generative models here”: a PixelCNN in the paper, a Transformer these days (homework 2 Q3), or a diffusion model (Lectures 11–12). Since qq is deterministic, the two-part code length

−log⁡2p(z(x))−log⁡2p(x∣z(x))  ≥  −log⁡2p(x)-\log_2 p(z(x)) - \log_2 p(x \mid z(x)) \;\ge\; -\log_2 p(x)

is an upper bound in bits on the model’s own code length — directly comparable with everything else on ShapeWorld.

VQ-VAE 2 (Razavi et al., 2019) adds a hierarchy of code grids (a coarse top level, a fine bottom level) and autoregressive priors at both; the slides show it covering more of the data distribution than BigGAN-deep at similar quality. And VQ-style autoencoders became building blocks: VQGAN (Lecture 10), the autoencoder of Stable Diffusion (Lecture 12), the image tokenizer of CogView. Lecture 4 already used the idea: its tokenizers were hand-made “discrete autoencoders”; the VQ-VAE learns one.

3.5 Experiment

Script 02 trains homework 2 Q3’s VQ-VAE on ShapeWorld — K=128K = 128 codes of dimension 32, an encoder with two stride-2 convolutions and two residual blocks, so each image becomes a 3×63 \times 6 grid of 18 tokens (like Lecture 4’s 4×44 \times 4 patch tokens, but learned) — with three codebook treatments (3,000 steps each):

codebookcodes used during trainingcodes used (test)perplexityrecon bitspixel-perfect reconstructions
homework init U[−1/K,1/K]U[-1/K, 1/K]12 → 17 → 18 → 19 → 202011.411.2034.8%
init from encoder outputs46 → 75 → 97 → 97 → 9610257.21.6584.5%
homework init + dead-code restarts125 → 121 → 123 → 122 → 12212481.13.0671.4%

(“perplexity” = 2H2^{H} of the code usage, the effective number of codes.)

  1. Dead codes. With the tiny uniform initialization, encoder outputs land near a handful of codes; the others are never the nearest, receive no gradient, and stay dead: 20 of 128 codes in use. Initializing the codebook from encoder outputs (or restarting unused codes from current encoder outputs) brings ~100–124 into use and cuts the reconstruction cost from 11.2 to 1.7–3.1 bits.
  2. Discrete codes reconstruct far better than a Gaussian code: 84.5% of test images pixel-perfect from 18 tokens, against 23% for Lecture 7’s VAE.

Then the prior: Lecture 4’s TransformerAR (same configuration as there) on the 18-token sequences of the best VQ-VAE, 2,000 steps (test bits per sequence: 55.1 → 43.8 → 38.9 → 36.6 → 36.1):

model of the imagebits for the codesbits for xx given the codestotal (upper bound)
uniform prior over codes: 18log⁡212818 \log_2 128126.001.65127.65
Transformer prior p(z)p(z)35.991.6537.64
(Lecture 4) Transformer on lossless 4×4 dictionary tokens18.92018.92
exact entropy––17.80

and samples (tokens from the Transformer, decoded):

samplesvalidvalid and novelflips to valid
thresholded decoder means23.4%19.2%7.1
Bernoulli draws16.1%12.7%7.5

VQ-VAE samples

Test images (top) and samples of the VQ-VAE + Transformer prior (02_vq_vae.py).

  1. A learned prior over discrete codes is the step that matters. The Transformer turns 126 uniform code bits into 36: a total of 37.6 bits — well below the Gaussian VAE (61, IWAE) and the flows (95), and about a quarter of the samples are valid ShapeWorld images, most of them new. It is the first latent variable model of the course whose samples are often exactly right.
  2. But learned codes are not as good as a clean dictionary. Lecture 4’s Transformer on lossless 4×44 \times 4 dictionary tokens reached 18.9 bits and 90% valid samples. The VQ-VAE’s encoder has overlapping receptive fields, so the same shape at another position gets different codes, and several code sequences decode to nearly the same image — probability spent twice; 1.65 bits of reconstruction remain on top. (On photographs no lossless dictionary exists, which is why learned discrete autoencoders — VQ-VAE, VQGAN, FSQ — became the standard tokenizers.)

4. Mutual information and posterior collapse

4.1 Mutual information

The mutual information between two random variables,

I(X;Y)=KL(p(x,y) ∥ p(x)p(y))=H(X)−H(X∣Y),I(X; Y) = \mathrm{KL}\big(p(x, y) \,\Vert\, p(x)p(y)\big) = H(X) - H(X \mid Y),

measures dependency in general — unlike covariance, it sees nonlinear relations and is zero only for independent variables. It is the quantity behind InfoGAN, contrastive predictive coding (Lecture 14) and exploration bonuses in reinforcement learning.

For a VAE, average the KL term over the data:

Epdata(x)[KL(q(z∣x) ∥ p(z))]=Iq(x;z)+KL(q(z) ∥ p(z))  ≥  Iq(x;z),E_{p_{\text{data}}(x)}\big[\mathrm{KL}(q(z \mid x) \,\Vert\, p(z))\big] = I_q(x; z) + \mathrm{KL}\big(q(z) \,\Vert\, p(z)\big) \;\ge\; I_q(x; z),

where q(z)=Ex[q(z∣x)]q(z) = E_x[q(z \mid x)] is the aggregate posterior. The average KL is an upper bound on the information the latent carries — the “bits in zz” of the tables below.

4.2 Why a powerful decoder ignores zz

So far all decoders were simple (a factorized Bernoulli or Gaussian). Due to their lack of expressivity, all the entropy is pushed into zz, and zz must convey a lot of information. Now take a powerful decoder — an autoregressive PixelCNN. What is the maximum ELBO? If the decoder can model the data alone, p(x∣z)=pdata(x)p(x \mid z) = p_{\text{data}}(x) for every zz, then q(z∣x)=p(z)q(z \mid x) = p(z) makes the KL zero and the ELBO equals log⁡pdata(x)\log p_{\text{data}}(x) — the best possible. Any information in zz incurs a KL penalty that is usually nonzero, and nothing forces the model to pay it. This “ignoring latent code” problem is well documented (Bowman et al., 2015; Chen et al., 2016; and many more).

4.3 Remedies

The slides list two families:

  • Weakening the decoder: dropout on the autoregressive conditioning (Bowman et al., 2015: word dropout in text VAEs); a PixelCNN with a limited receptive field (Chen et al., 2016: the Variational Lossy Autoencoder — local texture goes to the decoder, global structure must go through zz); a constant or minimum KL rate (δ\delta-VAE, Razavi et al., 2019).
  • Changing the training dynamics: KL warm-up (anneal the KL weight from 0 to 1, Bowman et al., 2015); free bits (Kingma et al., 2016: each latent dimension’s KL counts at least λ\lambda, so the first λ\lambda bits are free); more updates to the encoder (He et al., 2019: lagging inference networks).

PixelVAE (Gulrajani et al., 2016) and VLAE combine a VAE with an autoregressive decoder on purpose: the latent for global structure, the decoder for local detail.

4.4 Experiment

Script 03 replaces the VAE’s factorized decoder by a PixelCNN conditioned on zz (Lecture 3’s masked convolutions; zz enters every layer as a learned bias). Strong decoder: a 7×7 mask-A convolution and four 5×5 mask-B layers. Weak decoder: a single 3×3 mask-A layer — each pixel sees only its 4 causal neighbours. Latent: 16 dimensions; 2,000 steps each:

model−ELBOreconKL = bits in zzactive dims−ELBO / IWAE50_{50} (same 200 images)probe from z∼qz \sim qprobe from μ(x)\mu(x)
(Lecture 7) factorized Bernoulli decoder66.3529.3537.0016 of 1667.96 / 62.3775.4%80.0%
strong PixelCNN decoder26.2524.601.662 of 1626.33 / 25.7642.8%77.5%
strong + KL warm-up (0 → 1 over 1,500 steps)27.3523.963.389 of 1628.10 / 26.4951.2%78.3%
strong + free bits (0.5 bit per dimension)29.0721.327.7516 of 1629.71 / 26.7961.3%78.5%
weak PixelCNN decoder (4 neighbours)86.2281.974.253 of 1689.27 / 87.9657.7%77.7%

(bits per image; probe = a linear classifier predicting the left shape, chance 12.5%; Lecture 3’s PixelCNN without any latent: 25.0 bits. KL of the test set during training: strong 2.55 → 1.70; warm-up 18.3 → 3.4 as the weight reaches 1; free bits ~7.4–7.8 throughout; weak 4.8 → 4.3.)

  1. Collapse, in numbers. With the strong decoder the VAE reaches 26 bits — what the PixelCNN reached with no latent at all — and zz carries 1.7 bits in 2 of 16 dimensions, against 37 bits for the factorized decoder. The decoder does the work; the latent is nearly ignored. What little zz keeps is global: a probe on zz recovers the shape 43% of the time.
  2. The remedies buy information, not likelihood. KL warm-up and free bits push 3.4 and 7.8 bits into zz (probe 51% and 61%) — and the bound gets worse: by 1.1 and 2.8 bits in the ELBO, by 0.7 and 1.0 bits in the tighter IWAE estimate. That is the slides’ argument made quantitative: with a decoder this strong, information in zz is a luxury the ELBO does not reward (Exercise 7). These tools are for getting a useful representation, not a better density model.
  3. Plan vs reality: the weak decoder did not force the latent on. With only 4 neighbours, global structure should have had to go through zz; instead zz carries 4.3 bits in 3 dimensions and the model is far worse (86 bits). The latent was switched off early in training, before the decoder “knew” it needed it — collapse is also an optimization phenomenon, which is why VLAE-style weak decoders are combined with warm-up or free bits in practice.
  4. Plan vs reality: the first probe was misleading. It read the encoder means μ(x)\mu(x) and found ~78% accuracy for every model, including the collapsed one. The means do vary with xx — by tiny amounts that the posterior noise (σ≈1\sigma \approx 1 on inactive dimensions) hides from the decoder. Information in the latent must be measured where the decoder sees it: on samples z∼q(z∣x)z \sim q(z \mid x) (or via the KL).

5. β-VAE and disentanglement

5.1 The objective

The β-VAE (Higgins et al., 2017) reweights the KL term,

Lβ(x)=Eq(z∣x)[log⁡p(x∣z)]−β KL(q(z∣x) ∥ p(z)),\mathcal{L}_\beta(x) = E_{q(z\mid x)}[\log p(x \mid z)] - \beta\,\mathrm{KL}\big(q(z \mid x) \,\Vert\, p(z)\big),

identical to the ELBO for β=1\beta = 1. With β>1\beta > 1 the code is squeezed: each bit in zz costs β bits of reconstruction. The paper reports, on faces and chairs, latent dimensions that each control one interpretable factor (azimuth, smile, …): disentanglement. With β≠1\beta \ne 1 the objective is no longer a bound on log⁡p(x)\log p(x); we report the β = 1 ELBO of each model alongside.

5.2 Measuring it

On photographs disentanglement is judged by looking at latent traversals. On ShapeWorld we know the true factors, so we can measure it. For each factor vkv_k and each latent coordinate zjz_j (the encoder mean, binned), estimate I(zj;vk)I(z_j; v_k); the mutual information gap

MIGk=I(z(1);vk)−I(z(2);vk)H(vk)\mathrm{MIG}_k = \frac{I(z_{(1)}; v_k) - I(z_{(2)}; v_k)}{H(v_k)}

compares the most and second-most informative coordinates: 1 means one coordinate carries the factor alone, 0 that it is spread or absent.

5.3 Experiment

Script 04 trains a convolutional VAE with 10 latent dimensions on single 12 × 12 panels (20,000 training panels, 3,000 steps) for β = 1, 2, 4, 8 and measures every latent coordinate against the four true factors (HH = 3.00, 2.00, 2.68, 2.67 bits for shape, size, cxc_x, cyc_y):

βreconKL−ELBO (β = 1 bound)active dimsMIG shapeMIG sizeMIG cxc_xMIG cyc_ymean MIG
111.9019.1131.01100.02 (z0z_0)0.23 (z6z_6)0.05 (z1z_1)0.01 (z9z_9)0.077
221.2012.2433.4480.01 (z4z_4)0.30 (z6z_6)0.14 (z1z_1)0.05 (z3z_3)0.124
437.597.3344.9250.04 (z6z_6)0.09 (z6z_6)0.20 (z1z_1)0.09 (z3z_3)0.106
866.432.8569.2930.18 (z4z_4)0.39 (z4z_4)0.35 (z9z_9)0.29 (z1z_1)0.303

(bits per panel; exact entropy 9.29. In parentheses: the coordinate sharing the most information with the factor.)

The mutual information tables tell the story behind the MIG numbers. At β = 1 every factor is spread: shape has 0.86, 0.80 and 0.80 bits in z0z_0, z4z_4, z8z_8; horizontal position 0.82 in z1z_1 but also 0.69 in z6z_6. At β = 8 only three coordinates are left:

factorz1z_1z4z_4z9z_9
shape0.481.120.51
size0.221.130.25
cxc_x0.270.481.41
cyc_y1.210.440.24

— one coordinate for each position, one that mixes shape and size.

Traversals

β = 4: decoding while one active coordinate moves from −2 to +2 (04_beta_vae_disentanglement.py). z1z_1 moves the shape horizontally — a cleanly disentangled factor. z3z_3 goes from a large frame at the top to a small blob at the bottom (size, vertical position and shape at once); z6z_6 from a filled disk to a cross; z9z_9 from a large frame to a small diamond.

  1. β trades the model for the code. From β = 1 to 8, KL falls 19 → 3 bits while reconstruction rises 12 → 66; the ELBO goes from 31 to 69 bits, against a 9.29-bit world. Even at β = 1 the bound is 3× the entropy: the Gaussian code is a poor fit for 8 discrete shapes (§1).
  2. MIG rises with β — mostly because the code shrinks. With three coordinates left, each carries a larger share of whatever it encodes. The positions separate cleanly (they are continuous, smooth factors); shape — a categorical factor with 8 values — never gets a coordinate of its own, and is mixed with size.
  3. Disentanglement is partial and bought with a much worse model, in line with Locatello et al. (2019): without inductive biases matched to the factors, unsupervised disentanglement is not guaranteed. On ShapeWorld we can see which factors come out (positions) and which do not (shape, size) — something traversals of face images cannot tell us.

6.1 Variational dequantization

Lecture 6’s variational dequantization is a latent variable model in disguise: the noise uu is a latent, q(u∣x)q(u \mid x) the encoder, p(x+u)p(x + u) the “decoder”, and its bound is an ELBO. That is why it appears in this lecture’s slides.

6.2 Wake-sleep and the Helmholtz machine (extra)

Before the reparameterization trick, the Helmholtz machine (Dayan, Hinton et al., 1995) — Bernoulli latents and observations, a recognition model qq and a generative model pp — was trained with the wake-sleep algorithm. The VLB was derived from min⁡KL(q∥p(z∣x))\min \mathrm{KL}(q \Vert p(z \mid x)), which is hard to optimize because zz is drawn from qq. Wake-sleep instead minimizes KL(p(z∣x)∥q)\mathrm{KL}(p(z \mid x) \Vert q), which is also hard because we do not know p(z∣x)p(z \mid x) — but there is a trick: we know zz if we generate the data ourselves. In the sleep phase, sample (z,x)(z, x) from the model and train qq to predict zz from xx; in the wake phase, encode real xx with qq and train pp on the resulting pairs. The caveat: the sleep phase uses x∼pmodelx \sim p_{\text{model}}, not pdatap_{\text{data}}, and the reversed KL; neither guarantees a tight bound on real data, which is why wake-sleep is not effective when the model is far from the data, and why it did not scale. The VAE replaced it by optimizing the VLB directly with pathwise gradients. (The same “amortized inference” idea underlies both: one network replaces a per-example optimization — not scalable to large datasets otherwise, and expensive for new data points.)


7. Summary

  1. A VAE’s limits on ShapeWorld come from its parts: a factorized prior, a Gaussian code for discrete facts, and a factorized decoder (Lecture 7: 66 bits, blurry, no valid samples).
  2. Hierarchical priors with a residual-normal posterior keep the KL analytic, but a small two-level model did not help here (68.5 vs 66.2 bits; the top level carried 2.7 bits).
  3. VQ-VAE: nearest-code quantization, straight-through gradients, embedding and commitment losses; KL is a constant, and the prior is learned afterwards. Dead codes are real (20 of 128 codes used with the homework’s initialization; 102 with data initialization). With a Transformer prior over its 18 tokens: 37.6 bits and 23% valid samples — the best latent variable model of the course so far, still behind lossless hand-made tokens (18.9).
  4. The average KL is an upper bound on I(x;z)I(x; z). A powerful decoder makes zz nearly useless (posterior collapse: a PixelCNN decoder reached 26 bits with 1.7 bits in zz). KL warm-up and free bits push information into zz at a cost in bits; a weak decoder alone did not. Measure information on samples of zz, not on encoder means.
  5. β-VAE trades reconstruction for code length; disentanglement measured against ShapeWorld’s true factors (MIG) rises from 0.08 to 0.30 as β goes 1 → 8, mostly because the code shrinks to 3 dimensions: positions separate, shape and size stay entangled, and the model gets much worse.
  6. Wake-sleep trained Helmholtz machines with the reversed KL on model samples; the reparameterized ELBO replaced it.

8. Common pitfalls

  1. Assuming a learned prior helps automatically. A hierarchy adds KL terms and optimization difficulty; check the bits and how much information each level carries.
  2. Dead codes. A VQ codebook initialized far from the encoder outputs gets only a few codes ever selected; the rest never receive gradients. Initialize from data or restart unused codes, and report codebook usage.
  3. Reading a VQ-VAE’s reconstruction as its likelihood. The code bits must be added: with a uniform prior they are 18log⁡2K18 \log_2 K; with a learned prior far fewer.
  4. Calling KL ≈ 0 a training failure. With a decoder that can model the data alone, it is the optimum of the ELBO; whether it matters depends on what the latent is for.
  5. Fixing collapse by forcing KL up. Free bits and warm-up raise the KL, but the extra bits must also be used: check what the latent encodes (a probe), and whether the total bound improves.
  6. Judging disentanglement by eye. Traversals show what moves, not how much information each coordinate carries; when factors are known, measure (MIG and the full mutual-information table).
  7. Comparing β-VAE objectives across β. Only the β = 1 ELBO is a bound on log⁡p(x)\log p(x).

9. Exercises

Exercise 1 (the KL of a hierarchy). Show KL(q(z1,z2∣x)∥p(z1,z2))=KL(q(z1∣x)∥p(z1))+Eq(z1∣x)[KL(q(z2∣z1,x)∥p(z2∣z1))]\mathrm{KL}(q(z_1, z_2 \mid x) \Vert p(z_1, z_2)) = \mathrm{KL}(q(z_1\mid x) \Vert p(z_1)) + E_{q(z_1\mid x)}[\mathrm{KL}(q(z_2 \mid z_1, x) \Vert p(z_2 \mid z_1))].

Answer

Write both joints with the chain rule and split the logarithm: Eq[log⁡q(z1∣x)−log⁡p(z1)]+Eq[log⁡q(z2∣z1,x)−log⁡p(z2∣z1)]E_q[\log q(z_1\mid x) - \log p(z_1)] + E_q[\log q(z_2\mid z_1, x) - \log p(z_2 \mid z_1)]. The first term is the first KL; in the second, take the inner expectation over z2z_2 given z1z_1 first: it is the conditional KL, averaged over z1∼q(z1∣x)z_1 \sim q(z_1 \mid x).

Exercise 2 (the residual normal). For p=N(μp,σp2)p = N(\mu_p, \sigma_p^2) and q=N(μp+Δμ,σp2Δσ2)q = N(\mu_p + \Delta\mu, \sigma_p^2\Delta\sigma^2) in one dimension, derive KL(q∥p)=12(Δμ2/σp2+Δσ2−1−log⁡Δσ2)\mathrm{KL}(q \Vert p) = \tfrac12(\Delta\mu^2/\sigma_p^2 + \Delta\sigma^2 - 1 - \log\Delta\sigma^2). Why does this help optimization?

Answer

KL(N(m1,s12)∥N(m2,s22))=log⁡s2s1+s12+(m1−m2)22s22−12\mathrm{KL}(N(m_1, s_1^2) \Vert N(m_2, s_2^2)) = \log\frac{s_2}{s_1} + \frac{s_1^2 + (m_1 - m_2)^2}{2s_2^2} - \frac12. With s12=σp2Δσ2s_1^2 = \sigma_p^2\Delta\sigma^2, s22=σp2s_2^2 = \sigma_p^2, m1−m2=Δμm_1 - m_2 = \Delta\mu: −12log⁡Δσ2+12Δσ2+Δμ22σp2−12-\tfrac12\log\Delta\sigma^2 + \tfrac12\Delta\sigma^2 + \tfrac{\Delta\mu^2}{2\sigma_p^2} - \tfrac12. The KL depends only on the residual parameters: when the prior moves, the posterior moves with it and the KL does not change, so prior and posterior are not fighting each other; and “no information” is the simple point Δμ=0,Δσ=1\Delta\mu = 0, \Delta\sigma = 1, which the networks can start from.

Exercise 3 (the VQ-VAE’s ELBO). With q(z∣x)q(z \mid x) a point mass on the nearest codes and a uniform prior over KK codes at each of MM positions, show KL(q∥p)=Mlog⁡K\mathrm{KL}(q \Vert p) = M \log K. Then show that for any prior p(z)p(z), −log⁡p(z(x))−log⁡p(x∣z(x))≥−log⁡p(x)-\log p(z(x)) - \log p(x \mid z(x)) \ge -\log p(x).

Answer

KL=Eq[log⁡q−log⁡p]=log⁡1−log⁡K−M=Mlog⁡K\mathrm{KL} = E_q[\log q - \log p] = \log 1 - \log K^{-M} = M\log K: a constant, so it can be dropped from training. For the bound: p(x)=∑zp(z)p(x∣z)≥p(z(x)) p(x∣z(x))p(x) = \sum_z p(z)p(x\mid z) \ge p(z(x))\,p(x \mid z(x)) since all terms are nonnegative; take −log⁡-\log. (It is the ELBO with a deterministic qq, whose entropy is 0.)

Exercise 4 (straight-through). With the decoder input z~=ze+sg[zq−ze]\tilde z = z_e + \mathrm{sg}[z_q - z_e], compute z~\tilde z in the forward pass and ∂z~/∂ze\partial\tilde z/\partial z_e in the backward pass. Why do the codebook vectors need the separate embedding loss?

Answer

Forward: z~=ze+zq−ze=zq\tilde z = z_e + z_q - z_e = z_q. Backward: sg\mathrm{sg} contributes no gradient, so ∂z~/∂ze=I\partial \tilde z/\partial z_e = I — the decoder’s gradient with respect to its input is copied to the encoder output. The codebook enters only through sg[zq]\mathrm{sg}[z_q], so the reconstruction loss gives it no gradient at all; the embedding loss ∥sg[ze]−e∥2\lVert\mathrm{sg}[z_e] - e\rVert^2 pulls each chosen code towards the encoder outputs assigned to it (a k-means step done by SGD).

Exercise 5 (dead codes). Codes are initialized in U[−1/K,1/K]DU[-1/K, 1/K]^D with K=128K = 128, while encoder outputs have norms of order 1. Explain why most codes are never selected, and why a never-selected code stays dead.

Answer

All codes start in a tiny cube around the origin; for an encoder output zez_e far away, the nearest code is the one most aligned with zez_e‘s direction, and a few such “extreme” codes win for almost all outputs. A code that is never the nearest gets no embedding-loss gradient (the loss only involves chosen codes) and no other gradient, so it never moves: dead. Initializing codes at actual encoder outputs, or re-initializing unused codes there, gives every code a region of the data to win.

Exercise 6 (KL = information + mismatch). Show Epdata(x)[KL(q(z∣x)∥p(z))]=Iq(x;z)+KL(q(z)∥p(z))E_{p_{\text{data}}(x)}[\mathrm{KL}(q(z\mid x) \Vert p(z))] = I_q(x; z) + \mathrm{KL}(q(z) \Vert p(z)) with q(z)=Ex[q(z∣x)]q(z) = E_x[q(z\mid x)] and IqI_q the mutual information under pdata(x)q(z∣x)p_{\text{data}}(x)q(z \mid x).

Answer

ExEq(z∣x)[log⁡q(z∣x)−log⁡p(z)]=ExEq(z∣x)[log⁡q(z∣x)−log⁡q(z)]+Eq(z)[log⁡q(z)−log⁡p(z)]E_x E_{q(z\mid x)}[\log q(z \mid x) - \log p(z)] = E_x E_{q(z \mid x)}[\log q(z\mid x) - \log q(z)] + E_{q(z)}[\log q(z) - \log p(z)]. The first term is Iq(x;z)I_q(x; z), the second KL(q(z)∥p(z))\mathrm{KL}(q(z)\Vert p(z)). So the average KL term pays for the information in zz plus any mismatch between the aggregate posterior and the prior (which a learned prior can remove).

Exercise 7 (why a perfect decoder ignores zz). Suppose the decoder family contains p(x∣z)=pdata(x)p(x \mid z) = p_{\text{data}}(x) for all zz. Show that the maximum of Epdata[ELBO]E_{p_{\text{data}}}[\mathrm{ELBO}] is attained with q(z∣x)=p(z)q(z \mid x) = p(z), and that any qq carrying information about xx with the same decoder has a lower ELBO.

Answer

For any model, Epdata[ELBO]≤Epdata[log⁡pθ(x)]≤Epdata[log⁡pdata(x)]E_{p_{\text{data}}}[\mathrm{ELBO}] \le E_{p_{\text{data}}}[\log p_\theta(x)] \le E_{p_{\text{data}}}[\log p_{\text{data}}(x)] (Gibbs’ inequality). With p(x∣z)=pdata(x)p(x\mid z) = p_{\text{data}}(x) and q=p(z)q = p(z): ELBO =log⁡pdata(x)−0= \log p_{\text{data}}(x) - 0, so the maximum is attained. With the same decoder and an informative qq, the reconstruction term is unchanged (p(x∣z)p(x\mid z) does not depend on zz) and the KL is positive: strictly worse. The optimum gives zz no information.

Exercise 8 (free bits). The free-bits objective replaces ∑jKLj\sum_j \mathrm{KL}_j by ∑jmax⁡(λ,KLˉj)\sum_j \max(\lambda, \bar{\mathrm{KL}}_j), where KLˉj\bar{\mathrm{KL}}_j is dimension jj‘s KL averaged over a minibatch. Show that dimensions with KLˉj<λ\bar{\mathrm{KL}}_j < \lambda receive no KL gradient. What is the minimum KL cost of the training objective, and is the result still an ELBO?

Answer

∂max⁡(λ,a)/∂a=0\partial \max(\lambda, a)/\partial a = 0 for a<λa < \lambda: below the threshold, a dimension can gain information “for free” from the reconstruction gradient. The training objective never charges less than λ\lambda per dimension, λ×(dims)\lambda \times (\text{dims}) in total. It is not the ELBO (it ignores part of the KL); the model must be evaluated with the true ELBO / IWAE afterwards, which is what script 03 reports.

Exercise 9 (β and the bound). For which values of β is Lβ=Eq[log⁡p(x∣z)]−β KL\mathcal{L}_\beta = E_q[\log p(x\mid z)] - \beta\,\mathrm{KL} a lower bound on log⁡p(x)\log p(x)? What does β > 1 do to the trade-off between reconstruction and code length, in bits?

Answer

Lβ=ELBO−(β−1)KL\mathcal{L}_\beta = \mathrm{ELBO} - (\beta - 1)\mathrm{KL}. For β≥1\beta \ge 1 it is ≤ELBO≤log⁡p(x)\le \mathrm{ELBO} \le \log p(x): still a (looser) bound. For β<1\beta < 1 it can exceed log⁡p(x)\log p(x): not a bound. With β > 1, each bit stored in zz must save more than β bits of reconstruction to be worth it — so the code keeps only its most “valuable” bits (script 04: 19 → 3 bits of KL from β = 1 to 8, with reconstruction exploding).

Exercise 10 (the MIG by hand). A factor vv is uniform over 4 values (H=2H = 2 bits). Coordinate z1z_1 determines vv up to a fair coin between two values; z2z_2 is independent of vv. Compute I(z1;v)I(z_1; v), I(z2;v)I(z_2; v) and MIGv\mathrm{MIG}_v. What if z2z_2 were an exact copy of z1z_1?

Answer

I(z1;v)=H(v)−H(v∣z1)=2−1=1I(z_1; v) = H(v) - H(v\mid z_1) = 2 - 1 = 1 bit; I(z2;v)=0I(z_2; v) = 0; MIG=(1−0)/2=0.5\mathrm{MIG} = (1 - 0)/2 = 0.5. If z2z_2 copies z1z_1, both carry 1 bit, the gap is 0, and MIG = 0: the metric penalizes a factor spread over (here duplicated in) several coordinates, even though each is informative.

Exercise 11 (wake-sleep). In the sleep phase, (z,x)(z, x) are sampled from the model and qq is trained to maximize log⁡q(z∣x)\log q(z\mid x). Which divergence does this minimize, and why is the result not guaranteed to maximize the ELBO on real data?

Answer

Epmodel(x)[KL(p(z∣x)∥q(z∣x))]E_{p_{\text{model}}(x)}[\mathrm{KL}(p(z\mid x) \Vert q(z \mid x))] (up to a constant): the reverse direction of the ELBO’s KL(q∥p(z∣x))\mathrm{KL}(q \Vert p(z\mid x)), and averaged over model samples instead of data. If the model is far from the data, qq is trained on the wrong inputs; and the mass-covering KL(p∥qp \Vert q) does not make the ELBO’s bound tight. Neither phase follows the gradient of a single objective.


10. Further reading

From the slides

  • A. Vahdat, J. Kautz. NVAE: A Deep Hierarchical Variational Autoencoder, NeurIPS 2020.
  • A. van den Oord, O. Vinyals, K. Kavukcuoglu. Neural Discrete Representation Learning (VQ-VAE), NeurIPS 2017; A. Razavi, A. van den Oord, O. Vinyals. Generating Diverse High-Fidelity Images with VQ-VAE-2, NeurIPS 2019.
  • X. Chen et al. Variational Lossy Autoencoder, ICLR 2017; I. Gulrajani et al. PixelVAE, ICLR 2017; D. P. Kingma et al. Improving Variational Inference with Inverse Autoregressive Flow (free bits), NeurIPS 2016.
  • S. Bowman et al. Generating Sentences from a Continuous Space, CoNLL 2016 (KL annealing, word dropout); A. Razavi et al. Preventing Posterior Collapse with delta-VAEs, ICLR 2019; J. He et al. Lagging Inference Networks and Posterior Collapse in Variational Autoencoders, ICLR 2019.
  • I. Higgins et al. beta-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework, ICLR 2017.
  • J. Ho et al. Flow++ (variational dequantization), ICML 2019.
  • G. E. Hinton, P. Dayan, B. J. Frey, R. M. Neal. The Wake-Sleep Algorithm for Unsupervised Neural Networks, Science 1995.

Added by these notes

  • R. T. Q. Chen, X. Li, R. Grosse, D. Duvenaud. Isolating Sources of Disentanglement in VAEs (β-TCVAE, MIG), NeurIPS 2018.
  • F. Locatello et al. Challenging Common Assumptions in the Unsupervised Learning of Disentangled Representations, ICML 2019 — disentanglement is not identifiable without inductive biases or supervision.
  • M. D. Hoffman, M. J. Johnson. ELBO Surgery, 2016 — the KL term = mutual information + KL(aggregate posterior ‖ prior).
  • P. Esser, R. Rombach, B. Ommer. Taming Transformers for High-Resolution Image Synthesis (VQGAN), CVPR 2021 — next stop (Lecture 10).

11. Next lecture

Every model so far was trained by (a bound on) maximum likelihood. Lecture 9 drops likelihood altogether: a generative adversarial network learns a sampler x=G(z)x = G(z) by fooling a discriminator. We will see what the generator minimizes when the discriminator is optimal (Jensen–Shannon), why that makes GANs mode-seeking (the reverse-KL behaviour met in Lecture 5’s distillation), why they drop modes and saturate, and how to evaluate a model that has no likelihood at all — Parzen windows, Inception Score, FID — with ShapeWorld’s exact validity as the ground truth those metrics try to approximate.

← 返回课程目录