Repository navigation
Module 18
⬅️ Module 17 · 🗺️ Curriculum · 🏠 Home · Module 19 ➡️
Level: Advanced · Prerequisites: Modules 03, 16 · Time: about 9–10 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
A variational autoencoder (VAE) is a probabilistic generative model: it assumes data
After this module you should be able to:
- derive the ELBO and interpret its reconstruction and KL terms;
- derive the reparameterisation trick and the closed-form Gaussian KL;
- explain
$\beta$ -VAE, posterior collapse, IWAE and VQ-VAE; - evaluate a VAE and diagnose failure modes (blurry samples, collapse).
An ordinary autoencoder maps
flowchart LR
X["x"] --> ENC["Encoder q(z|x)"] --> MU["mu(x)"]
ENC --> SG["sigma(x)"]
MU --> Z["z = mu + sigma * eps"]
SG --> Z
EPS["eps ~ N(0, I)"] --> Z
Z --> DEC["Decoder p(x|z)"] --> XH["x_hat"]
MU -.-> KL["KL(q(z|x) || N(0,I))"]
SG -.-> KL
Figure 18.1 — VAE computation graph. Randomness enters only through $\mathbf{\varepsilon}$, so gradients flow through $\mu$ and $\sigma$ (reparameterisation). Original diagram.
The model:
For any
Derivation:
Sampling
For
Check: zero iff
Per-example loss
$\mathcal{L}_\beta=\mathbb{E}q[\ln p(\mathbf{x}\mid\mathbf{z})]-\beta D{KL}$. Larger
With a powerful autoregressive decoder, the model can ignore
IWAE (Burda et al. 2016) uses
1-D latent,
ELBO bookkeeping: if the reconstruction term is
import torch, torch.nn as nn, torch.nn.functional as F
class VAE(nn.Module):
def __init__(s, d=784, h=400, k=20):
super().__init__()
s.enc = nn.Linear(d, h); s.mu = nn.Linear(h, k); s.logvar = nn.Linear(h, k)
s.dec = nn.Sequential(nn.Linear(k, h), nn.ReLU(), nn.Linear(h, d))
def forward(s, x):
h = F.relu(s.enc(x)); mu, logvar = s.mu(h), s.logvar(h)
z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu) # reparameterisation
return s.dec(z), mu, logvar
def elbo_loss(x, logits, mu, logvar, beta=1.0):
rec = F.binary_cross_entropy_with_logits(logits, x, reduction='sum') / x.size(0)
kl = -0.5 * torch.sum(1 + logvar - mu ** 2 - logvar.exp()) / x.size(0) # = 0.5*sum(mu^2 + sigma^2 - log sigma^2 - 1)
return rec + beta * klParameterise model.dec(torch.randn(n, k)).
- Hierarchical VAEs (ladder VAE, NVAE, very deep VAE) and their connection to diffusion models (a diffusion model is a hierarchical VAE with a fixed encoder, Module 20).
-
Normalising-flow posteriors/priors for flexible
$q$ and$p$ ; learned priors; VampPrior. - Amortisation gap and approximation gap quantify inference suboptimality.
- Latent diffusion (Module 20) uses a VAE/VQ-GAN autoencoder as its perceptual compression stage.
- Evaluation: ELBO/bits-per-dim, IWAE bound, FID for samples; active units for collapse diagnosis.
- Discrete latents with Gumbel-softmax relaxations.
- Summing vs averaging reconstruction over pixels changes the effective
$\beta$ . - Treating blur as a bug in code: it is a likelihood-model artefact.
- Not monitoring KL per dimension (collapse) or training with KL weight 1 from step 0 with a strong decoder.
- Using MSE as a likelihood without a variance (implicit
$\beta$ ). - Sampling
$\mathbf{z}$ at test-time reconstruction when you want deterministic output (use$\mathbf{\mu}$ ).
Q1. Derive the ELBO.
$\ln p(\mathbf{x})=\mathbb{E}q\ln\frac{p(\mathbf{x},\mathbf{z})}{q(\mathbf{z}\mid\mathbf{x})}+D{KL}(q\Vert p(\mathbf{z}\mid\mathbf{x}))$. Dropping the non-negative KL gives the bound, which expands to reconstruction minus
Q2. Why is the reparameterisation trick needed?
Sampling blocks gradients to
Q3. What does each ELBO term encourage?
Reconstruction: codes that retain information to decode
Q4. What is posterior collapse and how is it mitigated?
The decoder ignores
Q5. Why are VAE samples blurry?
A factorised Gaussian/Bernoulli likelihood averages over uncertainty, and the information limit imposed by the KL term loses fine detail.
Q6. How does β-VAE differ from a VAE?
It scales the KL term by
Q7. How does IWAE tighten the bound?
By averaging
Q8. Compare the pathwise and score-function gradient estimators.
Pathwise (reparameterisation) differentiates through the sample and usually has far lower variance but needs a differentiable transform; score-function works for discrete variables but has high variance.
- Kingma, D. P., & Welling, M. (2014). Auto-encoding variational Bayes. ICLR. arXiv:1312.6114.
- Rezende, D. J., Mohamed, S., & Wierstra, D. (2014). Stochastic backpropagation and approximate inference in deep generative models. ICML.
- Doersch, C. (2016). Tutorial on variational autoencoders. arXiv:1606.05908.
- Blei, D. M., Kucukelbir, A., & McAuliffe, J. D. (2017). Variational inference: a review for statisticians. JASA, 112(518).
- Higgins, I., et al. (2017). β-VAE. ICLR.
- Burda, Y., Grosse, R., & Salakhutdinov, R. (2016). Importance weighted autoencoders. ICLR. arXiv:1509.00519.
- Bowman, S. R., et al. (2016). Generating sentences from a continuous space. CoNLL.
- van den Oord, A., Vinyals, O., & Kavukcuoglu, K. (2017). Neural discrete representation learning (VQ-VAE). NeurIPS. arXiv:1711.00937.
- Alemi, A., et al. (2018). Fixing a broken ELBO. ICML.
- Locatello, F., et al. (2019). Challenging common assumptions in the unsupervised learning of disentangled representations. ICML.
⬅️ Module 17 · 🗺️ Curriculum · 🏠 Home · Module 19 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24