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 (unit normal, autoregressive / hierarchical, residual normal), discrete latents and VQ-VAE (straight-through optimization, embedding and commitment losses, learning 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:
- Name the parts of a VAE (prior, encoder, decoder) and say which of them limit it on ShapeWorld.
- 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.
- 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.
- Diagnose dead codes and fix them.
- 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.
- Write the β-VAE objective, say what β trades, and measure disentanglement with the mutual information gap when the true factors are known.
- Explain wake-sleep and the Helmholtz machine, and why they gave way to the reparameterized ELBO.
0.2 Prerequisites and scope
| Assumed | Introduced here | Developed later |
|---|---|---|
| Lecture 7 (ELBO, IWAE, reparameterization, the ShapeWorld VAE: 66 bits, blurry) | hierarchical priors, residual normal, VQ-VAE, straight-through, dead codes | VQGAN (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 information | bits-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
| Symbol | Meaning |
|---|---|
| latents of a two-level hierarchy; the learned prior | |
| , , | VQ-VAE encoder output, codebook vector , quantized output (nearest ) |
| stop-gradient: identity in the forward pass, zero gradient | |
| mutual information between data and latent | |
| the weight of the KL term (β = 1: the ELBO) | |
| MIG | mutual 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: encoder decoder , scored by reconstruction − KL.
- Sampling: decoder . 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 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
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, , with posteriors — sample autoregressively, learn both and . 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 (, , decoder ):
2.3 The residual normal
NVAE’s insight: define the posterior as a residual over the prior. If , let
Then, per dimension (Exercise 2),
analytic again, and “the posterior adds nothing” is simply , . Homework 2 Q2b fixes for stability, so the KL becomes — the formula in vae_tools.HierarchicalVAE.
2.4 Experiment
Script 01 trains homework 2 Q2b’s model — with prior , with learned prior , residual-normal , decoder from only — with the same convolutional encoder trunk and decoder as Lecture 7’s flat VAE, for the same 4,000 steps:
| model | −ELBO | recon | KL | KL of + | IWAE () | valid samples |
|---|---|---|---|---|---|---|
| two-level, residual normal | 68.45 | 38.03 | 30.42 | 2.68 + 27.74 | 64.12 | 0% |
| (Lecture 7) flat VAE, 16 dims | 66.23 | 29.23 | 37.00 | – | 61.74 | 0% |
| (Lecture 7) flat VAE, 64 dims | 66.41 | 30.20 | 36.21 | – | 60.77 | 0% |
(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 : the top level carries 2.7 bits. Holding fixed and redrawing 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 , (1) the channel capacity is bounded — a code with values carries at most bits — and (2) it is simple to define expressive categorical priors : 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 ; each is replaced by its nearest codebook vector,
and the decoder reconstructs from . In ELBO terms (the slides’ “parts of the VAE” for VQ-VAE): is a deterministic distribution — a point mass on the nearest tokens; with a uniform prior over codes per position, 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
has no gradient. The straight-through estimator passes the decoder’s gradient with respect to unchanged to , as if quantization were the identity: feed the decoder (forward: ; backward: identity). The codebook gets no gradient that way, so two extra terms are added:
with in the paper. (The embedding loss is often replaced by an exponential moving average of the assigned encoder outputs.)
3.4 Learning
During training the prior is uniform. Afterwards we want to match the distribution of the codes 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 is deterministic, the two-part code length
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 — codes of dimension 32, an encoder with two stride-2 convolutions and two residual blocks, so each image becomes a grid of 18 tokens (like Lecture 4’s patch tokens, but learned) — with three codebook treatments (3,000 steps each):
| codebook | codes used during training | codes used (test) | perplexity | recon bits | pixel-perfect reconstructions |
|---|---|---|---|---|---|
| homework init | 12 → 17 → 18 → 19 → 20 | 20 | 11.4 | 11.20 | 34.8% |
| init from encoder outputs | 46 → 75 → 97 → 97 → 96 | 102 | 57.2 | 1.65 | 84.5% |
| homework init + dead-code restarts | 125 → 121 → 123 → 122 → 122 | 124 | 81.1 | 3.06 | 71.4% |
(“perplexity” = of the code usage, the effective number of codes.)
- 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.
- 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 image | bits for the codes | bits for given the codes | total (upper bound) |
|---|---|---|---|
| uniform prior over codes: | 126.00 | 1.65 | 127.65 |
| Transformer prior | 35.99 | 1.65 | 37.64 |
| (Lecture 4) Transformer on lossless 4×4 dictionary tokens | 18.92 | 0 | 18.92 |
| exact entropy | – | – | 17.80 |
and samples (tokens from the Transformer, decoded):
| samples | valid | valid and novel | flips to valid |
|---|---|---|---|
| thresholded decoder means | 23.4% | 19.2% | 7.1 |
| Bernoulli draws | 16.1% | 12.7% | 7.5 |

Test images (top) and samples of the VQ-VAE + Transformer prior (02_vq_vae.py).
- 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.
- But learned codes are not as good as a clean dictionary. Lecture 4’s Transformer on lossless 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,
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:
where is the aggregate posterior. The average KL is an upper bound on the information the latent carries — the “bits in ” of the tables below.
4.2 Why a powerful decoder ignores
So far all decoders were simple (a factorized Bernoulli or Gaussian). Due to their lack of expressivity, all the entropy is pushed into , and 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, for every , then makes the KL zero and the ELBO equals — the best possible. Any information in 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 ); a constant or minimum KL rate (-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 , so the first 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 (Lecture 3’s masked convolutions; 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 | −ELBO | recon | KL = bits in | active dims | −ELBO / IWAE (same 200 images) | probe from | probe from |
|---|---|---|---|---|---|---|---|
| (Lecture 7) factorized Bernoulli decoder | 66.35 | 29.35 | 37.00 | 16 of 16 | 67.96 / 62.37 | 75.4% | 80.0% |
| strong PixelCNN decoder | 26.25 | 24.60 | 1.66 | 2 of 16 | 26.33 / 25.76 | 42.8% | 77.5% |
| strong + KL warm-up (0 → 1 over 1,500 steps) | 27.35 | 23.96 | 3.38 | 9 of 16 | 28.10 / 26.49 | 51.2% | 78.3% |
| strong + free bits (0.5 bit per dimension) | 29.07 | 21.32 | 7.75 | 16 of 16 | 29.71 / 26.79 | 61.3% | 78.5% |
| weak PixelCNN decoder (4 neighbours) | 86.22 | 81.97 | 4.25 | 3 of 16 | 89.27 / 87.96 | 57.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.)
- Collapse, in numbers. With the strong decoder the VAE reaches 26 bits — what the PixelCNN reached with no latent at all — and 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 keeps is global: a probe on recovers the shape 43% of the time.
- The remedies buy information, not likelihood. KL warm-up and free bits push 3.4 and 7.8 bits into (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 is a luxury the ELBO does not reward (Exercise 7). These tools are for getting a useful representation, not a better density model.
- Plan vs reality: the weak decoder did not force the latent on. With only 4 neighbours, global structure should have had to go through ; instead 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.
- Plan vs reality: the first probe was misleading. It read the encoder means and found ~78% accuracy for every model, including the collapsed one. The means do vary with — by tiny amounts that the posterior noise ( on inactive dimensions) hides from the decoder. Information in the latent must be measured where the decoder sees it: on samples (or via the KL).
5. β-VAE and disentanglement
5.1 The objective
The β-VAE (Higgins et al., 2017) reweights the KL term,
identical to the ELBO for . With the code is squeezed: each bit in costs β bits of reconstruction. The paper reports, on faces and chairs, latent dimensions that each control one interpretable factor (azimuth, smile, …): disentanglement. With the objective is no longer a bound on ; 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 and each latent coordinate (the encoder mean, binned), estimate ; the mutual information gap
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 ( = 3.00, 2.00, 2.68, 2.67 bits for shape, size, , ):
| β | recon | KL | −ELBO (β = 1 bound) | active dims | MIG shape | MIG size | MIG | MIG | mean MIG |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 11.90 | 19.11 | 31.01 | 10 | 0.02 () | 0.23 () | 0.05 () | 0.01 () | 0.077 |
| 2 | 21.20 | 12.24 | 33.44 | 8 | 0.01 () | 0.30 () | 0.14 () | 0.05 () | 0.124 |
| 4 | 37.59 | 7.33 | 44.92 | 5 | 0.04 () | 0.09 () | 0.20 () | 0.09 () | 0.106 |
| 8 | 66.43 | 2.85 | 69.29 | 3 | 0.18 () | 0.39 () | 0.35 () | 0.29 () | 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 , , ; horizontal position 0.82 in but also 0.69 in . At β = 8 only three coordinates are left:
| factor | |||
|---|---|---|---|
| shape | 0.48 | 1.12 | 0.51 |
| size | 0.22 | 1.13 | 0.25 |
| 0.27 | 0.48 | 1.41 | |
| 1.21 | 0.44 | 0.24 |
— one coordinate for each position, one that mixes shape and size.

β = 4: decoding while one active coordinate moves from −2 to +2 (04_beta_vae_disentanglement.py). moves the shape horizontally — a cleanly disentangled factor. goes from a large frame at the top to a small blob at the bottom (size, vertical position and shape at once); from a filled disk to a cross; from a large frame to a small diamond.
- β 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).
- 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.
- 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. Related ideas
6.1 Variational dequantization
Lecture 6’s variational dequantization is a latent variable model in disguise: the noise is a latent, the encoder, 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 and a generative model — was trained with the wake-sleep algorithm. The VLB was derived from , which is hard to optimize because is drawn from . Wake-sleep instead minimizes , which is also hard because we do not know — but there is a trick: we know if we generate the data ourselves. In the sleep phase, sample from the model and train to predict from ; in the wake phase, encode real with and train on the resulting pairs. The caveat: the sleep phase uses , not , 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
- 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).
- 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).
- 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).
- The average KL is an upper bound on . A powerful decoder makes nearly useless (posterior collapse: a PixelCNN decoder reached 26 bits with 1.7 bits in ). KL warm-up and free bits push information into at a cost in bits; a weak decoder alone did not. Measure information on samples of , not on encoder means.
- β-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.
- Wake-sleep trained Helmholtz machines with the reversed KL on model samples; the reparameterized ELBO replaced it.
8. Common pitfalls
- Assuming a learned prior helps automatically. A hierarchy adds KL terms and optimization difficulty; check the bits and how much information each level carries.
- 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.
- Reading a VQ-VAE’s reconstruction as its likelihood. The code bits must be added: with a uniform prior they are ; with a learned prior far fewer.
- 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.
- 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.
- 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).
- Comparing β-VAE objectives across β. Only the β = 1 ELBO is a bound on .
9. Exercises
Exercise 1 (the KL of a hierarchy). Show .
Answer
Write both joints with the chain rule and split the logarithm: . The first term is the first KL; in the second, take the inner expectation over given first: it is the conditional KL, averaged over .
Exercise 2 (the residual normal). For and in one dimension, derive . Why does this help optimization?
Answer
. With , , : . 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 , which the networks can start from.
Exercise 3 (the VQ-VAE’s ELBO). With a point mass on the nearest codes and a uniform prior over codes at each of positions, show . Then show that for any prior , .
Answer
: a constant, so it can be dropped from training. For the bound: since all terms are nonnegative; take . (It is the ELBO with a deterministic , whose entropy is 0.)
Exercise 4 (straight-through). With the decoder input , compute in the forward pass and in the backward pass. Why do the codebook vectors need the separate embedding loss?
Answer
Forward: . Backward: contributes no gradient, so — the decoder’s gradient with respect to its input is copied to the encoder output. The codebook enters only through , so the reconstruction loss gives it no gradient at all; the embedding loss 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 with , 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 far away, the nearest code is the one most aligned with ‘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 with and the mutual information under .
Answer
. The first term is , the second . So the average KL term pays for the information in plus any mismatch between the aggregate posterior and the prior (which a learned prior can remove).
Exercise 7 (why a perfect decoder ignores ). Suppose the decoder family contains for all . Show that the maximum of is attained with , and that any carrying information about with the same decoder has a lower ELBO.
Answer
For any model, (Gibbs’ inequality). With and : ELBO , so the maximum is attained. With the same decoder and an informative , the reconstruction term is unchanged ( does not depend on ) and the KL is positive: strictly worse. The optimum gives no information.
Exercise 8 (free bits). The free-bits objective replaces by , where is dimension ‘s KL averaged over a minibatch. Show that dimensions with receive no KL gradient. What is the minimum KL cost of the training objective, and is the result still an ELBO?
Answer
for : below the threshold, a dimension can gain information “for free” from the reconstruction gradient. The training objective never charges less than per dimension, 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 a lower bound on ? What does β > 1 do to the trade-off between reconstruction and code length, in bits?
Answer
. For it is : still a (looser) bound. For it can exceed : not a bound. With β > 1, each bit stored in 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 is uniform over 4 values ( bits). Coordinate determines up to a fair coin between two values; is independent of . Compute , and . What if were an exact copy of ?
Answer
bit; ; . If copies , 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, are sampled from the model and is trained to maximize . Which divergence does this minimize, and why is the result not guaranteed to maximize the ELBO on real data?
Answer
(up to a constant): the reverse direction of the ELBO’s , and averaged over model samples instead of data. If the model is far from the data, is trained on the wrong inputs; and the mass-covering KL() 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 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.