Foundations to Frontier
Tests
H. Generative Models › H3 Variational Autoencoders

Latent variable models and the ELBO derivation

A latent variable model explains data x through unobserved causes z: draw z from a prior p(z), then x from p(x | z). The likelihood p(x) is an integral over z that is rarely tractable, and the posterior p(z | x) needs that same integral. The evidence lower bound (ELBO) sidesteps both: for any distribution q(z), log p(x) equals the ELBO plus KL(q(z) ‖ p(z | x)), so maximising the ELBO over q tightens the bound and over the model raises the likelihood. This page derives the ELBO three ways (Jensen's inequality, the KL identity and importance sampling), shows how EM and variational inference fall out of it, and introduces the importance-weighted (IWAE) bound. In the exercises you check log p(x) = ELBO + KL exactly in a linear-Gaussian model. You then measure how much a factorised (mean-field) q loses when the posterior is correlated. At posterior correlation −0.89 it lost 0.781 nats per point, and at −0.98 it lost 1.562, matching −½ ln(1 − ρ²) exactly. IWAE with 100 samples recovered about two-thirds of the gap in the first case but only 41% in the second. Naive sampling from the prior kept an effective 13 of 1000 samples.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Explaining data with hidden causes

A satellite image is shaped by things you never observe directly: cloud cover, sun angle, the crop in the field. A latent variable model writes this down: pick hidden causes z at random, then generate the data x from them. To learn such a model you need the probability of the data, which means averaging over every possible hidden cause. That average is usually impossible to compute. The trick behind VAEs is to guess which causes fit each data point (a distribution q) and optimise a lower bound on the probability instead. The bound is exact when the guess is perfect, and the shortfall is exactly how wrong the guess is. In the demo, move the guess q and watch the bound and the gap.

VAE lab
log p(x) = -1.872, ELBO = -2.381, gap = KL(q ‖ p(z | x)) = 0.509 nats. Set q to the exact posterior N(1.00, 0.333), std 0.58, and the gap vanishes.
Why engineers care

Latent variable models are how you fit, compress and impute sensor data with missing channels, detect anomalies by low likelihood, and build the encoders inside latent diffusion and world models.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A latent variable is…
  2. 2. The ELBO is…
  3. 3. The bound is tight when q equals…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Model: p(x, z) = p(z) p(x | z). Marginal likelihood (evidence) p(x) = ∫ p(z) p(x | z) dz. Posterior p(z | x) = p(x, z) / p(x).
  • Example (conjugate, 1-D): z ~ N(0, 1), x | z ~ N(z, s²). Then x ~ N(0, 1 + s²) and p(z | x) = N(x/(1 + s²), s²/(1 + s²)).
    • For x = 2, s² = 1: posterior N(1, 0.5), log p(x) = −½ ln(2π · 2) − 4/4 = −2.266.
  • Derivation 1 (Jensen): log p(x) = log E_q[p(x, z)/q(z)] ≥ E_q[log p(x, z) − log q(z)] = ELBO, because log is concave.
  • Derivation 2 (exact identity): log p(x) = ELBO(q) + KL(q(z) ‖ p(z | x)). Since KL ≥ 0 the ELBO is a bound, and the gap is exactly the KL to the posterior.
  • Two readings of the ELBO:
    • E_q[log p(x | z)] − KL(q(z) ‖ p(z)): reconstruction minus a penalty for moving away from the prior (the VAE form).
    • E_q[log p(x, z)] + H(q): expected log-joint plus entropy (the variational-inference form).
  • Gaussian KL to N(0, 1): ½(μ² + σ² − 1 − ln σ²). For μ = 1, σ = 0.5: 0.818 nats.
  • Mean-field price: if the true posterior is a bivariate Gaussian with correlation ρ, the best factorised q loses −½ ln(1 − ρ²): 0.144 nats at ρ = 0.5, 0.830 at ρ = 0.9.
  • IWAE bound (Burda et al., 2016): log (1/K) Σ_k p(x, z_k)/q(z_k) with z_k ~ q. K = 1 is the ELBO; it increases with K and tends to log p(x).
📝 Quick check (Level 1)
0/3 answered
  1. 1. log p(x) − ELBO equals…
  2. 2. KL(N(0, 1) ‖ N(0, 1)) is…
  3. 3. The IWAE bound with K = 1 is…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

The ELBO in code

Exercise 1.

  • The exact log-likelihood of a linear-Gaussian latent variable model (factor analysis / probabilistic PCA).
  • Its exact Gaussian posterior.
  • The ELBO of any Gaussian q in closed form, and a check that log p(x) − ELBO equals KL(q ‖ posterior).

Practice.

  • Compute log-likelihoods with logsumexp; never average raw probabilities.
  • Check a new ELBO implementation on a model with a known likelihood (linear-Gaussian or a small mixture) before trusting it on a deep model.
  • Report the ELBO and an IWAE estimate with K = 100–5000 samples when comparing likelihood models; the gap between them shows how loose the bound is.
  • Use reduction=‘sum’ over data dimensions and mean over the batch, or the KL and reconstruction terms are weighted inconsistently.
import torch, torch.distributions as td
def iwae_bound(x, enc, dec, K=100):
    q = enc(x)                                   # a td.Normal over z, batch shape (B, d)
    z = q.rsample((K,))                          # (K, B, d)
    log_w = (dec(z).log_prob(x).sum(-1)          # log p(x | z)
             + td.Normal(0., 1.).log_prob(z).sum(-1)
             - q.log_prob(z).sum(-1))
    return (torch.logsumexp(log_w, 0) - torch.log(torch.tensor(float(K)))).mean()
🐍 Exercise 1: exact likelihood, posterior and ELBO
Implement log p(x), the posterior and the ELBO of a linear-Gaussian latent variable model, and verify the KL identity.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Average log-weights with…
  2. 2. A good test of an ELBO implementation:
  3. 3. Tighter likelihood estimates come from…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Derivation 3 (importance sampling). p(x) = E_q[w] with w = p(x, z)/q(z). Any unbiased estimate of p(x) gives, through Jensen, a lower bound on log p(x) in expectation. One sample gives the ELBO; the mean of K samples gives the IWAE bound L_K. Burda et al. proved L_1 ≤ L_K ≤ L_(K+1) ≤ log p(x), and L_K → log p(x) when the weights are bounded. If log w is roughly Gaussian with variance σ², the single-sample gap is about σ²/2: the bound is loose whenever q is a poor importance proposal.

Proof of the identity. Write log p(x) = E_q[log p(x)] (it does not depend on z) = E_q[log p(x, z) − log p(z | x)] = E_q[log p(x, z) − log q(z)] + E_q[log q(z) − log p(z | x)] = ELBO + KL(q ‖ p(z | x)).

What maximising the ELBO does.

  • Over q with the model fixed: it minimises KL(q ‖ p(z | x)), the reverse KL, which is mode-seeking and tends to underestimate posterior variance.
  • Over the model with q fixed: it raises E_q[log p(x, z)], a lower bound on the likelihood.
  • EM alternates the two with q set to the exact posterior (E-step, gap zero), so each M-step cannot lower log p(x).
  • Variational EM / VI restricts q to a family (e.g. factorised Gaussians), so a gap remains: the approximation gap.
  • Amortised inference (VAEs) predicts q from x with an encoder network, adding an amortisation gap between the encoder’s q and the best q in the family (Cremer, Li and Duvenaud, 2018).

Why mean-field loses −½ ln(1 − ρ²). For a Gaussian posterior with precision Λ, the best factorised q keeps the posterior mean and uses variances 1/Λ_ii. The KL is ½ ln(det of the diagonal of Λ / det Λ), which in 2-D equals −½ ln(1 − ρ²). Overlapping decoder columns (two latents that explain the data in similar ways) produce strongly correlated posteriors.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The IWAE bound as K grows…
  2. 2. Minimising KL(q ‖ p) tends to…
  3. 3. The amortisation gap comes from…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How loose is the ELBO when the posterior is correlated, and how much do importance samples recover?

History.

  • A. Dempster, N. Laird and D. Rubin, “Maximum likelihood from incomplete data via the EM algorithm” (1977).
  • M. Jordan, Z. Ghahramani, T. Jaakkola and L. Saul, “An introduction to variational methods for graphical models” (1999).
  • D. P. Kingma and M. Welling, “Auto-encoding variational Bayes” (2014); Y. Burda, R. Grosse and R. Salakhutdinov, “Importance weighted autoencoders” (2016).
  • C. Cremer, X. Li and D. Duvenaud, “Inference suboptimality in variational autoencoders” (2018).

Exercise 2. A linear-Gaussian model where everything is exact.

  • Model: z ∈ ℝ² ~ N(0, I), x = W z + b + noise in ℝ⁶ with noise variance 0.05. The two columns of W have length 2 and cosine overlap 0, 0.9 or 0.99.
  • Data: 300 points sampled from the model; log p(x) computed exactly.
  • Bounds: the best mean-field (factorised Gaussian) ELBO, IWAE with that same q and K = 1, 10, 100, and naive Monte Carlo with 1000 samples from the prior (reported with its effective sample size, ESS).
  • All gaps are average nats per point below the exact log p(x).
overlap posterior correlation mean-field ELBO gap IWAE K = 10 IWAE K = 100 prior sampling (ESS of 1000)
0 0 0 0 0 0.144 (12.6)
0.9 −0.889 0.781 0.447 0.274 0.062 (26.4)
0.99 −0.978 1.562 1.160 0.929 0.014 (55.9)
  • The gap is exactly the mean-field price: −½ ln(1 − 0.889²) = 0.781 and −½ ln(1 − 0.978²) = 1.562, the analytic values (identical for seeds 1 and 2, since they depend only on the geometry).
  • IWAE helps but does not close it: with K = 100 it recovered 65% of the gap at overlap 0.9 but only 41% at 0.99, where the factorised proposal misses most of the posterior mass.
  • Prior sampling is a poor estimator: with a sharp posterior only about 13 of 1000 prior samples counted. It did better as overlap grew, because the posterior then stretches along one direction. In a 2-D latent space it still works; with tens of latents its ESS collapses to about 1.
  • Seeds 1 and 2: IWAE K = 100 gaps 0.254 / 0.266 (overlap 0.9) and 0.904 / 0.918 (0.99); prior-sampling gaps at overlap 0 were 0.143 and 0.463, showing how noisy that estimator is.
🐍 Exercise 2 (research): how loose is the ELBO when the posterior is correlated, and how much do importance samples recover?
Measure the mean-field ELBO gap, IWAE bounds and prior sampling against the exact log-likelihood of a linear-Gaussian model as the posterior correlation grows.

Latent variable models in AI, robotics and aerospace

  • Factor analysis and PPCA remain the first model to try for multichannel sensor data, with exact likelihoods for anomaly scores and missing-channel imputation.
  • Deep latent variable models (VAEs, world models such as Dreamer) fit perception and dynamics by maximising ELBOs.
  • Likelihood reporting: generative-model papers quote IWAE estimates with thousands of samples because the ELBO alone understates the likelihood.

References

  1. A. P. Dempster, N. M. Laird and D. B. Rubin (1977). “Maximum likelihood from incomplete data via the EM algorithm.” JRSS B.
  2. M. I. Jordan, Z. Ghahramani, T. S. Jaakkola and L. K. Saul (1999). “An introduction to variational methods for graphical models.” Machine Learning.
  3. M. E. Tipping and C. M. Bishop (1999). “Probabilistic principal component analysis.” JRSS B.
  4. D. P. Kingma and M. Welling (2014). “Auto-encoding variational Bayes.” ICLR.
  5. Y. Burda, R. Grosse and R. Salakhutdinov (2016). “Importance weighted autoencoders.” ICLR.
  6. C. Cremer, X. Li and D. Duvenaud (2018). “Inference suboptimality in variational autoencoders.” ICML.
  7. D. M. Blei, A. Kucukelbir and J. D. McAuliffe (2017). “Variational inference: a review for statisticians.” JASA.