The ELBO: variational inference, VAEs and importance-weighted bounds
Before this lesson: lesson 03 (Jensen's inequality, KL divergence, Gibbs' inequality), lesson 04 (cross-entropy as a loss), lesson 06 (differential entropy, the Gaussian KL, forward and reverse KL). Bayes' rule and posteriors from probability lesson 01; importance sampling from the probability track; gradient estimators from calculus lesson 12. Time: about 80 minutes, plus the notebook.
Why this matters #
Bayesian inference needs the posterior . The numerator is easy: prior times likelihood. The denominator is an integral over all latent values, and in most models it has no closed form. The ELBO turns this integral into an optimization problem.
The same bound appears in many places:
- VAEs are trained by maximizing the ELBO (Kingma and Welling, 2013).
- Diffusion models: the DDPM loss is a reweighted ELBO over many noising steps (generative models track).
- EM for mixture models climbs the ELBO (ML fundamentals track, in preparation).
- Variational Bayesian neural networks put a distribution on the weights and maximize the ELBO.
- Science: fast approximate posteriors for inverse problems, such as seismic tomography, and latent-variable models of single-cell gene expression.
Two facts matter most in practice: how far the bound is from , and in which direction is wrong when its family is too simple. This lesson answers both.
In this lesson is the natural logarithm, so all values are in nats; divide by to get bits. This is also what PyTorch and NumPy compute.
1. Predict first #
2. The picture #
The model. A latent-variable model is a joint distribution . The prior says which latent values are likely before we see data. The likelihood says how the observation is produced from . We observe one and keep it fixed.
- The evidence (or marginal likelihood) is , a sum for discrete .
- The posterior is , by Bayes' rule.
- A variational distribution is any distribution over that we choose. It is our approximation of the posterior.
The simplest case: has two values. Suppose the model gives, for our observed ,
Then , so . The posterior is . A distribution on is one number . Define
(with at and ). Four values of :
| 0 | 0.5 | 0.9 | 1 | |
|---|---|---|---|---|
| −3.912 | −2.120 | −1.609 | −1.715 | |
| gap | 2.303 | 0.511 | 0 | 0.105 |
Move and watch the magenta ELBO curve under the dashed ceiling . The aqua gap is 0 only at the blue posterior value . The side panel shows that the gap equals , computed separately. Try the other joints, and the end points and .
Three things to see:
- The ELBO is never above . It is a floor under a fixed ceiling: the ceiling does not depend on .
- It touches the ceiling at one only: , the posterior.
- At , is a point mass on the most probable latent (the MAP latent). The ELBO is then . That is below the maximum. The ELBO rewards for spreading over every that explains , not only the best one.
The weights picture. Write
the importance weight of (as in importance sampling). If wherever , then:
- . The arithmetic mean of the weights is the evidence.
- . So is the geometric mean of the weights.
A geometric mean is never larger than the arithmetic mean, and the two are equal only when all values are equal. If is the posterior, then for every : all weights are equal and the gap is 0. The more the weights spread, the larger the gap. At the weights are and . Their arithmetic mean is ; their geometric mean is .
In the two-value example, is uniform () and the ELBO is while . The gap nats equals which quantity?
. The KL to the prior is a different term: it appears in the "reconstruction − KL" form of the ELBO, not in the gap. The other direction gives , not the gap.
is discrete and puts all its mass on one value . What is the ELBO?
With , the expectation has one term: . The entropy of a point mass on a discrete set is , not . The best is the MAP latent, but even then whenever another also has .
3. Definitions and main results #
Notation. , with equality only when (Gibbs' inequality, lesson 03). is the entropy of ; for a continuous it is the differential entropy of lesson 06.
Definition. For a fixed observation and a distribution over , the evidence lower bound is
Physicists call the variational free energy.
Theorem 1 (the evidence decomposition) #
Let be a distribution with wherever . Then
Hence , with equality if and only if .
The condition is needed for a finite KL. If puts mass where the posterior has none, then there: the ELBO is and the KL is .
Proof.
- does not depend on , so .
- Bayes' rule: for every with . This includes every that can draw. So .
- Multiply and divide by inside the log: .
- Take of both terms. The first gives . The second gives .
- , with equality if and only if (Gibbs). So , with the same equality case.
Check with the toy. At the gap is , and (the first quiz above).
The Jensen route (lesson 03). If wherever , then . The log is concave, so Jensen's inequality gives
This route gives the bound in one line, but not the size of the gap. Theorem 1 says the gap is exactly a KL divergence.
A consequence for Monte Carlo. Step 2 says for every when is the posterior. So the Monte Carlo estimate of the ELBO has zero variance at the posterior, for any number of samples .
The two standard forms #
Split in two ways. Each split gives a form of the ELBO that is used in practice.
Form 1: energy + entropy.
The first term (the negative energy) pulls toward latents with a high joint density, as MAP does. The entropy term pays for being spread out. Without it, the best would be a point mass at the MAP latent. In the toy at : and . The sum is , as in the table.
Form 2: reconstruction − KL to the prior. Use :
The reconstruction term rewards latents that explain well. The KL to the prior keeps close to the prior: moving away from , so that can store information about this particular , costs nats. This is the VAE form. Lesson 10 reads it as a trade-off between distortion and rate.
The three expressions, , energy + entropy, and reconstruction − KL, are the same number. Use the one whose terms you can compute.
A continuous example. Let and , and observe . Section 4 computes everything by hand: and the posterior is . For both forms have closed forms.
Move the mean and the variance of and compare it with the posterior. The posterior lies between the prior (dashed grey, centred at 0) and the likelihood (thin dark line, centred at 2). The two number lines show the same ELBO in two ways: minus the gap, and the reconstruction term minus the KL to the prior. Notice that has the best reconstruction but pays a large KL to the prior.
What maximizing the ELBO does #
Over , with the model fixed. does not depend on . So by Theorem 1,
This is the reverse KL of lesson 06. It is the direction we can work with. It needs only expectations under (we can sample from ) and values of ; the unknown is a constant. The forward KL needs expectations under the posterior, which is the thing we cannot compute. Fitting in this way is called variational inference (VI).
The reverse KL is large when puts mass where the posterior is small. So avoids low-posterior regions. Two consequences:
- Mode seeking. For a posterior with well-separated modes, a single Gaussian locks onto one mode. Each mode gives a local maximum of the ELBO; the starting point decides which one you find.
- Variances that are too small. Let the posterior be and let be a factorized (mean-field) Gaussian . The reverse-KL optimum is and . This is the variance of given all other coordinates, and it is never larger than the marginal variance . With unit variances and correlation ,
so and instead of 1. (The forward KL would give .)
Over the model parameters . Write the model as . Theorem 1 gives
A step in that raises the ELBO raises the log-likelihood, or moves the model's posterior toward , or both. So it is approximate maximum likelihood with a bias: it prefers models whose posteriors are easy to fit with the chosen family. For a dataset, the sum of the per-example ELBOs is a lower bound on the log-likelihood of the data.
If we set to the exact posterior before each step, the gap is 0 at the current . This is EM (expectation–maximization): the E-step sets , the M-step maximizes the ELBO in . Then never decreases.
The model is fixed. You maximize the ELBO over a family of distributions . Which quantity are you minimizing?
, and does not depend on . So a larger ELBO means a smaller reverse KL, by exactly the same amount. itself does not change when only changes. The KL to the prior is only one part of the ELBO.
Amortized inference, two gaps, and posterior collapse #
A dataset has many observations , and each has its own posterior. Fitting a separate for each is slow. A VAE uses one network, the encoder, that outputs for every . This is amortized inference: the cost of learning to infer is shared by all .
Let be the best member of the family for this (for example, the best diagonal Gaussian). The gap splits in two (Cremer, Li and Duvenaud, 2018):
- The approximation gap is : the family is too simple.
- The amortization gap is the price of one shared encoder instead of a separate optimization for each .
A different failure is posterior collapse. The decoder models well without using . Then the best encoder outputs for every , and the KL term is 0. The ELBO can still be good, but carries no information about .
Posterior collapse can happen at the optimum, not only because of bad training (Lucas et al., 2019). The smallest example is a linear VAE. Data . Decoder with prior . Then the model gives . Keep fixed and learn : the best fit makes when it can. If the decoder noise is 1 or more, the noise alone already explains the data, and the best is 0.
Change the decoder noise and the decoder weight . The encoder is always the exact posterior, so the ELBO equals the average log-likelihood. It is the reconstruction term (dark line) minus the KL to the prior. The yellow line marks the best . Push to 1 or above: the best becomes 0, the KL term becomes 0, and the latent is unused.
In this example the decoder noise acts as a weight. A Gaussian decoder gives , so a large makes the reconstruction term cheap compared with the KL term. Common remedies for collapse in real VAEs are KL annealing (the weight of the KL term grows from 0 to 1 during training) and "free bits" (no KL penalty below a few nats per latent group); see Kingma and Welling (2019), §2.8.
The VAE loss #
A VAE has an encoder and a decoder , both neural networks, and a prior . It maximizes the average ELBO in Form 2 over both and . The generative-models track covers the architecture and training practice. Here are the three pieces of the loss.
1. Gaussian encoder. The encoder outputs a mean vector and a log-variance vector , both of length (the latent dimension): .
2. The KL term in closed form. For one dimension,
and for a diagonal Gaussian the KL is the sum of this over the dimensions.
Derivation of the Gaussian KL to
- and .
- Under : and .
- So and .
- Subtract: .
The KL is 0 only at , : the function is with its minimum at .
3. The reconstruction term with the reparameterization trick. The term has no closed form for a neural decoder, so we estimate it with one (or a few) samples of . But we also need its gradient with respect to , and is inside the distribution we sample from. The reparameterization trick writes the sample as a deterministic function of and a fixed noise:
Now does not depend on , and backpropagation goes through to and . This gradient estimator has much lower variance than the score-function (REINFORCE) estimator (calculus lesson 12).
What is. It depends on the decoder's output distribution:
- Bernoulli decoder (binary or pixels): the decoder outputs logits , and
where is the sigmoid. This is minus the binary cross-entropy (lesson 04).
- Gaussian decoder with a fixed variance : , where is the decoder output and the data dimension. Up to a constant, this is a scaled squared error.
In PyTorch the loss for a batch is a few lines (the encoder and decoder are any networks):
import torch
import torch.nn.functional as F
def vae_loss(x, encoder, decoder):
mu, logvar = encoder(x) # q(z | x) = N(mu, diag(exp(logvar)))
eps = torch.randn_like(mu)
z = mu + torch.exp(0.5 * logvar) * eps # reparameterization
logits = decoder(z) # Bernoulli decoder p(x | z)
rec = -F.binary_cross_entropy_with_logits(logits, x, reduction="none").sum(dim=1)
kl = 0.5 * (mu**2 + logvar.exp() - 1 - logvar).sum(dim=1)
elbo = rec - kl # one-sample ELBO estimate per example
return -elbo.mean() # loss = -ELBO, in nats per example
Two details matter. Sum over the data dimensions and the latent dimensions (not a mean), or the two terms get the wrong relative weight. And the loss is in nats per example; divide by to report bits per dimension, the usual unit for images.
The encoder outputs and for a 2-D latent. What is the KL term ?
Sum over the two dimensions: . A shifted mean costs nats even when the variance matches the prior.
Theorem 2 (the importance-weighted bound; Burda, Grosse and Salakhutdinov, 2015) #
The ELBO is the log of a geometric mean of weights. If we average several weights before taking the log, the average spreads less, and Jensen's inequality loses less. This is the IWAE (importance weighted autoencoder) bound.
Let wherever . Draw independently from , write , and let . Define
Then:
- ;
- for every ;
- if is bounded and the ELBO is finite, as .
(Burda et al. state part 3 with bounded only; the finite ELBO is the extra assumption that the short proof below uses.)
Toy check. In the two-value example with uniform , the weights are and , each with probability . For : both draws are with probability , both with probability , and one of each with probability . So
between and . The gap falls from 0.511 to 0.255.
Proof of Theorem 2
- Part 1. For , , and is the ELBO.
- Upper bound. Each weight has mean . So : is an unbiased estimate of . Jensen for the concave log: .
- Monotonicity, setup. Take samples. Let be a uniformly random subset of of size , independent of the samples. Each index is in with probability . So .
- Jensen over , with the samples fixed: .
- Average over the samples. For each fixed , is an average of independent weights, so its expected log is . Hence .
- Limit. By the strong law of large numbers, with probability 1. If , then (the left inequality is "geometric mean ≤ arithmetic mean"). The left side is an average of independent integrable variables when the ELBO is finite. This sandwich lets the limit move inside the expectation (uniform integrability), so .
Why the gap shrinks like . Both the ELBO and have the form . The Jensen gap of the log grows with the spread of the estimate. The average of weights has variance . For large , a second-order Taylor expansion of around (the delta method) gives
So the gap shrinks like , and it is small when makes the weights nearly equal.
Increase and watch two things. Top: the orange histogram of 1000 estimates becomes narrow, and its average (≈ ) moves up toward the dashed ceiling . Some single estimates land above the ceiling. Bottom: the gap against on log-log axes approaches the dashed line. Change the proposal : the gap is 0 for every when is the posterior .
The price.
- Compute. times the work per example.
- High dimensions. Importance weights degrade when has many dimensions: one weight tends to dominate the sum.
- Training signal. A tighter bound is not always better for training. Average independent estimates of the gradient of . The signal-to-noise ratio of the encoder's gradient is of order , while the decoder's is of order (Rainforth et al., 2018). So a large helps the decoder and hurts the encoder.
- Evaluation. For evaluation, a large is standard: Burda et al. report test log-likelihoods with .
Another view: IWAE is an ELBO with a richer approximation
Draw samples from and keep one of them with probability proportional to its weight. The kept sample has an implicit distribution , which is closer to the posterior than . One can show (Cremer, Morris and Duvenaud, 2017; Kingma and Welling, 2019, §2.6). So IWAE does not change the model; it fits a better approximate posterior that is built from samples of the simple one.
For a fixed you compute , and exactly (not by sampling). Which ordering is guaranteed?
Theorem 2: never decreases in and never exceeds , for every model and every with the right support. is the ELBO. These are statements about expectations; a single Monte Carlo estimate of can still land above , as the figure shows.
Answers to section 1. (1) The maximum over all is , reached only by the posterior , where the KL gap is 0 (Theorem 1). (2) Tighter, or equal: . And always, as an expectation (Theorem 2). A single estimate can land above by noise. (3) On one mode, with a variance that is too small for the whole posterior: the reverse KL is mode seeking. (If the modes overlap strongly, can sit between them.)
4. Worked example #
Model. , , observed . Everything is in closed form, so every claim can be checked.
(a) Exact answers. with independent unit-variance noise, so and
Posterior: . The exponent is a quadratic in with coefficient on , so the precision is . The linear coefficient is , so the mean is . Hence .
(b) The ELBO for , in the reconstruction − KL form:
- Reconstruction: , and (squared bias plus variance). So
- KL to the prior (the VAE formula above):
| reconstruction | KL to prior | ELBO | |||
|---|---|---|---|---|---|
| −1.9189 | 0.5000 | −2.4189 | 0.1534 | 0.1534 | |
| −1.1689 | 2.0966 | −3.2655 | 1.0000 | 1.0000 | |
| −1.6689 | 0.5966 | −2.2655 | 0 | 0 |
Read the rows step by step.
- explains the data best (the highest reconstruction term), but pays 2.10 nats to move away from the prior.
- has the right mean but is too wide.
- The last column is computed separately, with the Gaussian KL formula of lesson 06:
It equals the gap in every row, as Theorem 1 says. For : exactly.
- Check of Form 1 for : and . The sum is . ✓
(c) Maximize over . Write the ELBO as a function of and :
- : , so .
- : , so .
The optimum is exactly the posterior. The Gaussian family contains it, so the approximation gap is 0 and the bound is tight.
(d) IWAE for . Both and the posterior have variance , so the normalizing constants cancel and
Under , , so . So is Gaussian with mean and variance 2. The ELBO gap is , as in the table. Section 5 estimates the IWAE gaps by sampling:
| 1 | 10 | 100 | |
|---|---|---|---|
| 1.00 | 0.19 | 0.03 |
Compare with the large- formula. Here with , and (the mean of a log-normal variable), so
Here , as it must be, because . The formula gives at (close to 0.028) and at (too large: is not yet "large").
5. In code #
NumPy and SciPy check the numbers of section 4 by other routes: numerical integration for the ELBO, the law of the log-weights for IWAE, and a numerical optimizer for the mean-field example. The notebook has these cells and the exercises.
import numpy as np
from scipy.stats import norm
from scipy.special import logsumexp
from scipy.optimize import minimize
# Model: z ~ N(0, 1), x | z ~ N(z, 1). Observed x = 2, so x ~ N(0, 2) and p(z | x) = N(1, 1/2).
x = 2.0
log_px = norm(0, np.sqrt(2)).logpdf(x)
print(round(log_px, 4)) # -2.2655
def kl_gauss(m1, v1, m2, v2): # KL(N(m1, v1) || N(m2, v2)), 1-D
return 0.5 * (np.log(v2 / v1) + (v1 + (m1 - m2) ** 2) / v2 - 1)
# (a) ELBO by numerical integration on a grid; the gap equals KL(q || posterior).
z = np.linspace(-10, 12, 200_001)
log_joint = norm(0, 1).logpdf(z) + norm(z, 1).logpdf(x) # log p(z) + log p(x | z)
for m, s2 in [(1.0, 1.0), (2.0, 0.5), (1.0, 0.5)]:
q = norm(m, np.sqrt(s2))
elbo = np.trapezoid(q.pdf(z) * (log_joint - q.logpdf(z)), z)
print(m, s2, round(elbo, 4), round(log_px - elbo, 4), round(kl_gauss(m, s2, 1.0, 0.5), 4))
# 1.0 1.0 -2.4189 0.1534 0.1534
# 2.0 0.5 -3.2655 1.0 1.0
# 1.0 0.5 -2.2655 0.0 0.0
# (b) IWAE gap for q = N(2, 1/2): log w - log p(x) = 3 - 2z ~ N(-1, 2) under q.
# Never average the weights directly: use logsumexp(log w) - log K.
rng = np.random.default_rng(1)
for K, n in [(1, 1_000_000), (10, 200_000), (100, 40_000)]:
Y = rng.normal(-1.0, np.sqrt(2.0), size=(n, K))
print(K, round(-np.mean(logsumexp(Y, axis=1) - np.log(K)), 2))
# 1 1.0
# 10 0.19
# 100 0.03
# (c) Reverse KL with a factorized q underestimates the marginal variances.
rho = 0.9
S = np.array([[1.0, rho], [rho, 1.0]])
P = np.linalg.inv(S)
def reverse_kl(log_var): # KL(N(0, diag) || N(0, S))
D = np.diag(np.exp(log_var))
return 0.5 * (np.trace(P @ D) - 2 + np.log(np.linalg.det(S) / np.linalg.det(D)))
res = minimize(reverse_kl, x0=np.zeros(2), method="Nelder-Mead", options={"xatol": 1e-8, "fatol": 1e-12})
print(np.exp(res.x).round(3)) # [0.19 0.19] = 1 - rho^2; the true marginal variances are 1
The grid integral in (a) is a route that does not use the closed forms of section 4. In (b) the log of an average of weights must be computed in log space: the weights themselves overflow or underflow for real models.
6. Where it shows up #
- VAEs. The loss is with an encoder and a decoder , trained jointly by stochastic gradients with the reparameterization trick. The IWAE objective replaces by . The generative-models track covers architectures, β-VAEs and VQ-VAEs.
- Diffusion models. The DDPM loss is a reweighted ELBO in which the "encoder" is the fixed noising process (generative models track). The first stage of latent diffusion (Stable Diffusion) is an autoencoder trained with a reconstruction loss (plus perceptual and adversarial terms) and a very small KL-to-prior penalty: Form 2 with a strongly down-weighted KL term.
- EM and variational Bayes. EM is coordinate ascent on the ELBO with an exact E-step. Variational Bayesian neural networks ("Bayes by Backprop") put a Gaussian on the weights and maximize the ELBO; the KL to the prior acts as a regularizer.
- Topic models and probabilistic programming. Latent Dirichlet allocation was fitted with mean-field VI. Pyro and NumPyro fit user-written models by stochastic VI ("SVI") on the ELBO.
- ML for science: inverse problems. Variational inference gives approximate posteriors for seismic tomography at a fraction of the cost of Monte Carlo sampling (Zhang and Curtis, 2020). The mean-field result of section 3 is the warning: a factorized reports too little uncertainty when the parameters are correlated, as neighbouring velocity cells are.
- ML for science: single-cell biology. scVI (Lopez et al., 2018) is a VAE for single-cell RNA counts; its latent space is used for clustering, batch correction and differential expression.
- Simulation-based inference: the other KL. If you can simulate pairs from the model, you can train by maximizing (neural posterior estimation). This minimizes the forward KL from the posterior, averaged over , so tends to cover all modes.
7. Common mistakes #
- Reading the ELBO as . It is minus a gap. A model can win on the ELBO by having a smaller gap, not a higher likelihood. Compare models with for a large .
- The wrong KL direction. Maximizing the ELBO minimizes , not . This is why VI underestimates uncertainty.
- Confusing the two KL terms. The gap is the KL to the posterior. The term inside Form 2 is the KL to the prior. Making the KL to the prior small does not make the bound tight.
- Dropping the entropy term. Without (or the part of a Monte Carlo estimate), the optimum collapses to a point mass at the MAP latent.
- Mean instead of sum in the VAE loss. Averaging the reconstruction over pixels but summing the KL over latents changes the weight of the two terms (like a large β). The ELBO sums both.
- "Larger is always better." The bound is tighter, but the cost grows like and the encoder's gradient becomes noisier.
- Treating one estimate as a guaranteed bound. holds in expectation; a single Monte Carlo estimate can land above .
8. Check yourself #
- Two latent values with and , and uniform. Compute
, the ELBO, the gap and .
Answer
, so . The weights are , so ELBO . Gap . The posterior is , so . ✓ - Why does variational inference minimize and not
?
Answer
The reverse KL needs only expectations under (which we can sample) and values of . The unknown is a constant, so maximizing the ELBO minimizes the reverse KL. The forward KL needs expectations under the posterior, which we cannot compute or sample. - In the worked example, restrict to the family . What is the best , and what
is the remaining gap called?
Answer
: , so . ELBO , gap . It is the approximation gap of this family: no member does better. - The posterior is a 2-D Gaussian with unit variances and correlation . What variances
does a mean-field get from the reverse KL? From the forward KL?
Answer
Reverse KL: . Forward KL: the marginal variances, 1. - If is the exact posterior, what is for each , and what is the variance of its
Monte Carlo estimate?
Answer
Every weight equals , so for every draw. Hence for all , and the estimate has zero variance. - A VAE has a 3-D latent. For every input the encoder outputs and
. What is the KL term, and what does this tell you about the model?
Answer
The KL term is : . Since this holds for every , the encoder ignores the input and carries no information about . This is posterior collapse: the decoder models without .
Write the evidence decomposition for a latent-variable model.
, with .
Derive the ELBO with Jensen's inequality in one line.
, because the log is concave.
Write the ELBO as reconstruction minus a KL. Which KL is it?
: the KL to the prior (not to the posterior).
Write the ELBO as energy plus entropy.
. Without the entropy term the best is a point mass at the MAP latent.
Maximizing the ELBO over minimizes which divergence, and what follows?
The reverse KL . So is mode seeking and tends to have too small a variance.
Give .
nats; sum over dimensions for a diagonal Gaussian.
What is the reparameterization trick, and why is it used?
Write with . The noise no longer depends on , so gradients flow through , with lower variance than the score-function estimator.
Define the IWAE bound .
with drawn independently from .
How does the IWAE gap behave for large ?
It is about : it shrinks like , and never decreases in .
What are the approximation gap and the amortization gap?
Approximation gap: for the best in the family. Amortization gap: the extra loss because one shared encoder replaces the best for each .
9. Interview angle #
- "Derive the ELBO." — Two ways: insert into to get ELBO + KL (this also gives the gap); or Jensen on .
- "What does each term of the VAE loss do?" — The reconstruction term rewards latents that explain . The KL to the prior limits the information in and keeps close to the prior, so that samples from the prior decode to realistic data.
- "Why can't we just maximize ?" — It needs , which has no closed form for a neural decoder, and naive Monte Carlo with samples from the prior has a huge variance.
- "Why is VI mode seeking? Why does it underestimate variance?" — The reverse KL punishes for mass where the posterior is small. A mean-field Gaussian gets the conditional variances .
- "Why the reparameterization trick?" — To backpropagate through sampling: moves the randomness into , which does not depend on the parameters.
- "Why is IWAE tighter, and why not train with ?" — The average of weights spreads less, so the Jensen gap shrinks like . But the cost is times larger, and the encoder's gradient signal-to-noise ratio falls like .
- "What is posterior collapse? How do you detect and reduce it?" — The KL term goes to 0 and the encoder outputs the prior for every . Watch the KL per latent dimension; use KL annealing, free bits, or a weaker decoder.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
- The ELBO of the two-value example as a function of ; check that the gap equals the KL to the posterior.
- The closed-form ELBO of the linear-Gaussian model against a Monte Carlo estimate with reparameterized samples.
iwae_boundwithlogsumexp, for , and the behaviour of the gap.- Fit by gradient ascent on the ELBO with reparameterization gradients, and recover the exact posterior .
- A mean-field for a correlated 2-D Gaussian posterior: the variances of section 3.
11. Watch and read #
- Kingma and Welling, An Introduction to Variational Autoencoders (2019): §2.2 (the decomposition and its gap), §2.4 (reparameterization), §2.6 (importance sampling and IWAE), §2.8 (KL annealing, free bits).
- Kingma and Welling, Auto-Encoding Variational Bayes (2013), the original VAE paper.
- Burda, Grosse and Salakhutdinov, Importance Weighted Autoencoders (2015): §3 (the bound and Theorem 1), Appendix A (the proof).
- Blei, Kucukelbir and McAuliffe, Variational Inference: A Review for Statisticians (2017): §2.2 (the ELBO), §2.3 (mean-field; Figure 1 shows the too-small variances).
- Cremer, Li and Duvenaud, Inference Suboptimality in Variational Autoencoders (2018): the approximation and amortization gaps.
- Rainforth et al., Tighter Variational Bounds are Not Necessarily Better (2018): the signal-to-noise argument against large in training.
- Lucas, Tucker, Grosse and Norouzi, Don't Blame the ELBO! A Linear VAE Perspective on Posterior Collapse (2019): the linear VAE of the third figure.
- Kevin Murphy, Probabilistic Machine Learning: Advanced Topics, free PDF: chapter 10 (variational inference) and chapter 21 (VAEs).
- Pyro, SVI Part I: the "guide" () and the ELBO in a probabilistic programming language.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.