Skip to content

Module 18

Anurag Prasad edited this page Nov 9, 2026 · 9 revisions

Module 18 — Variational Autoencoders and Probabilistic Generative Models

⬅️ 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


Overview and learning goals

A variational autoencoder (VAE) is a probabilistic generative model: it assumes data $\mathbf{x}$ are generated from latent variables $\mathbf{z}$ with a simple prior, and learns both a decoder $p_\theta(\mathbf{x}\mid\mathbf{z})$ and an approximate posterior $q_\phi(\mathbf{z}\mid\mathbf{x})$ by maximising the evidence lower bound (ELBO). Unlike plain autoencoders, sampling $\mathbf{z}\sim p(\mathbf{z})$ yields new data, and the latent space is smooth.

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).

Beginner: the big picture

An ordinary autoencoder maps $\mathbf{x}$ to one point $\mathbf{z}$. A VAE maps $\mathbf{x}$ to a distribution over $\mathbf{z}$ (a mean and a variance) and adds a penalty keeping these distributions close to a standard Gaussian. That penalty fills the latent space with overlapping blobs, so that points between training codes also decode to plausible data, and we can generate by sampling from the Gaussian.

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
Loading

Figure 18.1 — VAE computation graph. Randomness enters only through $\mathbf{\varepsilon}$, so gradients flow through $\mu$ and $\sigma$ (reparameterisation). Original diagram.

Core concepts and derivations

Latent-variable models and the intractable posterior

The model: $p(\mathbf{z})=\mathcal{N}(0,I)$, $p_\theta(\mathbf{x}\mid\mathbf{z})$ given by a neural decoder. Marginal likelihood $p_\theta(\mathbf{x})=\int p_\theta(\mathbf{x}\mid\mathbf{z})p(\mathbf{z})\,d\mathbf{z}$ and the true posterior $p_\theta(\mathbf{z}\mid\mathbf{x})=p_\theta(\mathbf{x}\mid\mathbf{z})p(\mathbf{z})/p_\theta(\mathbf{x})$ are intractable, so we introduce an inference network $q_\phi(\mathbf{z}\mid\mathbf{x})$ (amortised variational inference).

ELBO derivation

For any $q_\phi$:

$$\ln p_\theta(\mathbf{x})=\mathbb{E}_{q_\phi}\!\left[\ln\frac{p_\theta(\mathbf{x},\mathbf{z})}{q_\phi(\mathbf{z}\mid\mathbf{x})}\right]+D_{KL}\bigl(q_\phi(\mathbf{z}\mid\mathbf{x})\,\Vert\,p_\theta(\mathbf{z}\mid\mathbf{x})\bigr)\ \ge\ \underbrace{\mathbb{E}_{q_\phi}[\ln p_\theta(\mathbf{x}\mid\mathbf{z})]}_{\text{reconstruction}}-\underbrace{D_{KL}\bigl(q_\phi(\mathbf{z}\mid\mathbf{x})\Vert p(\mathbf{z})\bigr)}_{\text{regulariser}}=\mathcal{L}(\theta,\phi;\mathbf{x}).$$

Derivation: $\ln p(\mathbf{x})=\mathbb{E}_q[\ln p(\mathbf{x})]$ and $p(\mathbf{x})=p(\mathbf{x},\mathbf{z})/p(\mathbf{z}\mid\mathbf{x})$; insert $q$ inside the logarithm; the leftover term is the KL to the true posterior, which is $\ge0$ (Module 03). Maximising $\mathcal{L}$ over $\theta$ improves the model; over $\phi$ tightens the bound. The reconstruction term rewards decodable codes; the KL term penalises codes that deviate from the prior. With a Gaussian decoder of fixed variance the first term is MSE; with Bernoulli outputs, binary cross-entropy.

Reparameterisation trick

Sampling $\mathbf{z}\sim\mathcal{N}(\mathbf{\mu},\mathrm{diag}\mathbf{\sigma}^2)$ is not differentiable w.r.t. $\mathbf{\mu},\mathbf{\sigma}$. Write $\mathbf{z}=\mathbf{\mu}+\mathbf{\sigma}\odot\mathbf{\varepsilon}$, $\mathbf{\varepsilon}\sim\mathcal{N}(0,I)$, moving randomness into a parameter-free noise source: $\nabla_\phi\mathbb{E}_{q_\phi}[f(\mathbf{z})]=\mathbb{E}_{\mathbf{\varepsilon}}[\nabla_\phi f(\mathbf{\mu}_\phi+\mathbf{\sigma}_\phi\odot\mathbf{\varepsilon})]$. This pathwise estimator has much lower variance than the score-function (REINFORCE) estimator $\mathbb{E}[f\nabla\ln q]$ (Kingma & Welling 2014; Rezende et al. 2014).

Gaussian KL in closed form

For $q=\mathcal{N}(\mathbf{\mu},\mathrm{diag}\mathbf{\sigma}^2)$ and $p=\mathcal{N}(0,I)$ (Module 03's formula per dimension):

$$D_{KL}(q\Vert p)=\frac12\sum_{j=1}^{k}\bigl(\mu_j^2+\sigma_j^2-\ln\sigma_j^2-1\bigr).$$

Check: zero iff $\mu_j=0,\sigma_j=1$; grows when the mean drifts or the variance collapses to 0 (the $-\ln\sigma^2$ term).

Training objective and generation

Per-example loss $=-\ln p_\theta(\mathbf{x}\mid\mathbf{z})+D_{KL}$ with one sample $\mathbf{z}$. Generation: draw $\mathbf{z}\sim\mathcal{N}(0,I)$ and decode. Interpolation/arithmetic in latent space produces smooth transitions. Typical VAE samples are blurry: a unimodal Gaussian decoder with MSE averages over plausible outputs, and the KL term limits information in $\mathbf{z}$.

$\beta$-VAE, disentanglement and the rate–distortion view

$\mathcal{L}_\beta=\mathbb{E}_q[\ln p(\mathbf{x}\mid\mathbf{z})]-\beta D_{KL}$. Larger $\beta$ pressures the code toward the factorised prior and can encourage axis-aligned factors (Higgins et al. 2017), at the cost of reconstruction. Interpreting reconstruction as distortion and KL as rate, $\beta$ moves along a rate–distortion curve (Alemi et al. 2018). Unsupervised disentanglement is not identifiable without inductive biases (Locatello et al. 2019).

Posterior collapse and remedies

With a powerful autoregressive decoder, the model can ignore $\mathbf{z}$: $q(\mathbf{z}\mid\mathbf{x})\approx p(\mathbf{z})$, KL $\approx0$, and the latent carries no information (Bowman et al. 2016). Remedies: KL annealing (increase $\beta$ from 0 to 1), free bits (no penalty below a threshold per dimension), weaker decoders, skip connections from $\mathbf{z}$, or discrete latents.

IWAE and VQ-VAE

IWAE (Burda et al. 2016) uses $K$ importance samples for a tighter bound $\mathcal{L}_K=\mathbb{E}\bigl[\ln\frac1K\sum_k\frac{p(\mathbf{x},\mathbf{z}_k)}{q(\mathbf{z}_k\mid\mathbf{x})}\bigr]\ge\mathcal{L}_1$. VQ-VAE (van den Oord et al. 2017) quantises encoder outputs to the nearest entry of a learned codebook, using a straight-through gradient; with an autoregressive prior over codes it generates sharp images/audio and its codes underlie later image tokenisers.

Worked example

1-D latent, $\mu=1$, $\sigma=0.5$: $D_{KL}=\frac12(1+0.25-\ln0.25-1)=\frac12(0.25+1.386)=0.818$ nats. Reparameterisation with $\varepsilon=0.4$: $z=1+0.5\cdot0.4=1.2$.

ELBO bookkeeping: if the reconstruction term is $-85.0$ nats and KL $=12.3$, then $\mathcal{L}=-97.3$ and $-\mathcal{L}$ upper-bounds the negative log-likelihood ($\ln p(\mathbf{x})\ge-97.3$). Dividing by dimensionality gives bits-per-dimension.

Implementation

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 * kl

Parameterise $\ln\sigma^2$ (not $\sigma$) for stability; sample new data with model.dec(torch.randn(n, k)).

Advanced topics

  • 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.

Pitfalls and best practices

  • 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}$).

Conceptual questions and answers

Q1. Derive the ELBO.

Show answer

$\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 $D_{KL}(q\Vert p(\mathbf{z}))$.

Q2. Why is the reparameterisation trick needed?

Show answer

Sampling blocks gradients to $\mu,\sigma$. Expressing $\mathbf{z}=\mu+\sigma\varepsilon$ makes $\mathbf{z}$ a differentiable function of parameters with parameter-free noise.

Q3. What does each ELBO term encourage?

Show answer

Reconstruction: codes that retain information to decode $\mathbf{x}$. KL: posteriors close to the prior, giving a smooth, samplable latent space.

Q4. What is posterior collapse and how is it mitigated?

Show answer

The decoder ignores $\mathbf{z}$ and the posterior equals the prior (KL ≈ 0). Use KL annealing, free bits, weaker decoders or discrete latents.

Q5. Why are VAE samples blurry?

Show answer

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?

Show answer

It scales the KL term by $\beta>1$, trading reconstruction quality for a more factorised, sometimes more disentangled, latent representation.

Q7. How does IWAE tighten the bound?

Show answer

By averaging $K$ importance weights inside the logarithm; the bound increases monotonically with $K$ and approaches $\ln p(\mathbf{x})$.

Q8. Compare the pathwise and score-function gradient estimators.

Show answer

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.

Sources and further reading

  • 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 ➡️

🎓 Deep Learning Hub

🏠 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

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally