Variational Inference
Turning inference into optimization: the ELBO and the reparameterization trick.
Variational inference replaces an impossible integral with an optimization problem: find the member of a simple family that is closest to the posterior in KL divergence. That trade buys speed and scale, from topic models over millions of documents to deep generative models of images, at the price of a bias this lesson makes precise. You will derive the coordinate-ascent updates, see exactly how mean-field VI underestimates uncertainty, compute the gradients that make VI work at scale, and learn how to tell whether a variational fit can be trusted.
What you’ll learn
- Derive the ELBO decomposition and its equivalent forms, and connect variational inference to EM and to the convex-duality view of exponential families.
- Derive the coordinate-ascent (CAVI) update for mean-field VI, and compute the mean-field approximation of a correlated Gaussian exactly.
- Contrast the reverse and forward KL divergences, and explain expectation propagation as local moment matching.
- Derive the score-function and reparameterization gradient estimators, compare their variances, and explain stochastic VI, variational autoencoders and importance-weighted bounds.
- Diagnose a variational fit with Pareto-smoothed importance sampling, and state what is known about the asymptotics of variational posteriors.
The ELBO, three ways
Let be the data and everything unobserved (latent variables and parameters). Variational inference chooses a family of distributions over and solves . The divergence contains the unknown evidence, but the identity proved in Why EM Works splits it off:
| Form | Expression | Reading |
|---|---|---|
| Energy plus entropy | put mass where the joint is high, but stay spread out | |
| Fit minus complexity | explain the data, but do not stray far from the prior | |
| Evidence minus gap | a lower bound on the log evidence, tight only at the posterior |
If contains every distribution, the optimum is the exact posterior and the bound is tight: that is EM's E-step. Restricting trades exactness for tractability. When the latent variables are local (one per data point) and the parameters global, alternating a variational E-step with a maximization over parameters is variational EM, as in LDA (Topic Models & Latent Dirichlet Allocation).
Wainwright & Jordan (2008) give the general picture through convex duality. For an exponential family with sufficient statistics , the log-partition function has the variational representation , where is the set of realizable mean parameters (the marginal polytope, for discrete graphical models) and is the entropy of the maximum-entropy distribution with those means. Mean-field methods optimize over the means realizable by product distributions, an inner subset of , so they produce lower bounds; belief propagation relaxes both the set and the entropy, and its Bethe approximation is in general not a bound at all.
You fit two variational approximations to the same posterior; reaches ELBO and reaches . What can you conclude?
- is closer to the posterior in , by exactly 2.5 nats
- has better-calibrated credible intervals
- Nothing: ELBOs of different approximations cannot be compared
Show the answer
A. is closer to the posterior in , by exactly 2.5 nats
Both are bounds on the same , so the ELBO difference equals the difference of their KL gaps. That says is closer in reverse KL; it does not say how close either is, nor that its intervals are calibrated.
Mean field and coordinate ascent
The mean-field family factorizes completely, (or over blocks of variables). Optimizing one factor at a time has a closed-form answer.
Hold every factor except fixed and write for the expectation over the others. Collect the terms of the ELBO that involve :
Define the normalized density . The two terms combine into a negative KL divergence plus a constant:
The KL is minimized, at zero, by . Cycling through is coordinate ascent variational inference (CAVI): each update cannot decrease the ELBO, which is generally non-convex, so CAVI converges to a local optimum.
In conditionally conjugate models, where each complete conditional is in an exponential family, stays in that family and its natural parameter is the expected natural parameter of the complete conditional. That is why the LDA updates involve digamma functions: they are expectations of under a Dirichlet. A fully worked case shows both the strength and the weakness of mean field.
Let the target be in two dimensions, with precision matrix . As a function of , is quadratic, so is Gaussian:
So with , and symmetrically for . The fixed point has the exact means, , but variances :
For unit variances and correlation , , so the mean-field variance is . CAVI's iterates satisfy : each sweep shrinks the error by , the same rate as the Gibbs sampler on this target.
The posterior is a bivariate Gaussian with unit marginal standard deviations and correlation 0.9. What standard deviation does the mean-field approximation assign to each coordinate?
Show the answer
0.44
. The means are exact, but every marginal credible interval is less than half as wide as it should be. A factorized cannot tilt, so it shrinks to fit inside the narrow diagonal ridge: the conditional spread, not the marginal one.
Which KL? Mode seeking versus mass covering
The direction of the divergence decides the character of the approximation.
- Reverse KL, , the one VI minimizes, is infinite if puts mass where has none (zero-forcing). The optimal hides inside the posterior: it locks onto one mode of a multimodal posterior and is too narrow within a mode, as the Gaussian example showed.
- Forward KL, , is infinite if misses mass that has (zero-avoiding). The optimal spreads to cover all of , bridging modes and overestimating spread in the directions it cannot tilt.
Let . Only the cross-entropy term of depends on :
This is convex in , and . Setting the gradient to zero matches the expected sufficient statistics: for a Gaussian , the mean and covariance of ; for a factorized family, 's marginals.
Matching moments needs expectations under , which is the hard part, so forward KL cannot be minimized globally. Expectation propagation (Minka, 2001) applies it locally. Write the posterior as a product of factors, , and the approximation as with each in an exponential family. Repeatedly remove one approximate factor, multiply in the exact , project the result back onto the family by moment matching, and update accordingly. EP unifies assumed-density filtering and loopy belief propagation; it is often very accurate (Gaussian-process classification is a classic use) but has no convergence guarantee and gives no bound on .
| Property | Reverse KL (VI) | Forward KL (EP, moment matching) |
|---|---|---|
| Penalizes | mass where is small | missing mass where is large |
| On a multimodal | picks one mode | covers all modes, with mass in between |
| Correlated Gaussian, factorized | exact means; variances (too small) | exact means; the true marginal variances |
| Needs | expectations under only | expectations under (locally, in EP) |
| Bound on | yes, the ELBO | no |
Gradients of an expectation: scaling up
Outside conditionally conjugate models, CAVI's expectations have no closed form. Modern VI instead takes stochastic gradients of the ELBO with respect to the variational parameters . The ELBO is an expectation under of , and there are two ways to differentiate through the sampling.
Score function (the REINFORCE or likelihood-ratio estimator; Williams, 1992; used for black-box VI by Ranganath, Gerrish & Blei, 2014). Differentiate the density, using ; the term from 's own dependence on vanishes because . It needs only samples from and , so it works for discrete latent variables too:
Reparameterization (Kingma & Welling, 2013; Rezende, Mohamed & Wierstra, 2014). Write with parameter-free noise, such as , . The expectation is now over a fixed distribution, so the gradient moves inside. It needs continuous and a differentiable model, and uses the model's gradient:
A variance comparison. Take and , so the true gradient in is . The reparameterization estimator is , with variance 4 for every . The score-function estimator is ; expanding and using , , :
At , how many times larger is the score-function estimator's variance than the reparameterization estimator's?
Show the answer
21.75
, against 4: a factor of about 22, and it grows like . Score-function gradients need variance reduction (control variates, Rao–Blackwellization) to be practical; reparameterization gradients often work with a single sample.
Stochastic variational inference (Hoffman, Blei, Wang & Paisley, 2013) adds data subsampling. In conditionally conjugate models, the natural gradient of the ELBO with respect to the global variational parameters is simple, so each step computes the local optimum for a minibatch, forms the global parameter that the minibatch would imply if replicated to the full data size, and moves to with Robbins–Monro step sizes. Their experiments fit topic models to millions of documents.
Variational autoencoders amortize inference: instead of separate variational parameters for every data point, an encoder network outputs , and a decoder defines with prior ; both are trained on the ELBO with reparameterization gradients.
import torch
def negative_elbo(x, encoder, decoder):
"""One-sample estimate of -ELBO for a VAE; encoder and decoder are user-defined modules."""
mu, logvar = encoder(x) # q(z | x) = N(mu, diag(exp(logvar)))
z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu) # reparameterization
log_px = decoder.log_likelihood(x, z) # log p(x | z), one value per example
kl = 0.5 * (mu.pow(2) + logvar.exp() - 1.0 - logvar).sum(dim=-1) # KL(q(z|x) || N(0, I))
return (kl - log_px).mean() # minimize with any SGD optimizerThe KL term between two Gaussians is closed-form, ; only the reconstruction term is estimated by sampling. With a very expressive decoder, the KL term can collapse to zero and the latent code is ignored (observed for text by Bowman et al., 2016).
Did it work? Diagnostics and theory
The ELBO cannot certify a fit, because the gap is unknown. Yao, Vehtari, Simpson & Gelman (2018) proposed using as an importance-sampling proposal. Draw , compute the ratios , fit a generalized Pareto distribution to the largest ones, and read its shape , which measures how heavy the ratios' tail is. Ratios with have infinite variance (the divergence from to is infinite), and means even is infinite. Their recommendation:
- : is close to the posterior, and Pareto-smoothed importance sampling can refine its estimates further.
- : is not perfect but still useful, again with importance-sampling correction.
- : the approximation is unreliable; change the family, the divergence or the method.
They also proposed variational simulation-based calibration, which checks point estimates by refitting on data simulated from the prior.
Combine the theorem with the Gaussian calculation above: the exact posterior is approximately for Fisher information , and its mean-field projection has the right center but variances instead of . So mean-field VI gets point estimates right asymptotically and its uncertainty wrong whenever parameters are correlated a posteriori. Giordano, Broderick & Jordan (2018) recover better covariances from how the variational means respond to small perturbations of the model, a method that includes the Laplace approximation as a special case.
On the optimization side, the ELBO is non-convex in general, and convergence guarantees for black-box VI arrived only recently: Domke and coauthors (2023) proved convergence of proximal and projected stochastic gradient methods for dense Gaussian families with reparameterization gradients, for targets whose log-density is smooth and concave.
Key takeaways
- : maximizing the ELBO minimizes the reverse KL using only the joint density. With an unrestricted family it is EM's E-step; convex duality shows mean field as an inner approximation, hence a lower bound.
- CAVI sets . On a correlated Gaussian it recovers the means exactly but reports variances , for unit variances and correlation .
- Reverse KL is mode-seeking and overconfident; forward KL over an exponential family is moment matching, which expectation propagation applies locally, without a bound or a convergence guarantee.
- Score-function gradients are general but noisy; reparameterization gradients need continuous latents and are far lower in variance. Stochastic VI adds minibatches; VAEs amortize inference with an encoder; importance-weighted bounds tighten the ELBO toward .
- Check VI with the PSIS (below 0.5 good, above 0.7 unreliable). Variational posteriors are asymptotically normal with consistent means, but mean field understates uncertainty under posterior correlation.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In mean-field coordinate ascent, what is the optimal factor with all other factors held fixed?
- The exact posterior marginal
- The prior
Show the answer
B.
Collecting the ELBO's terms in gives with . The expectation is of the log joint, which is what makes conditionally conjugate models tractable.
A Bayesian logistic regression has two strongly correlated coefficients. Compared with MCMC, what will a mean-field variational fit typically report for them?
- Wider intervals, since VI is conservative
- Identical intervals once the ELBO has converged
- Shifted means but correct widths
- Roughly correct means but intervals that are too narrow
Show the answer
D. Roughly correct means but intervals that are too narrow
Reverse KL with a factorized family captures the conditional spread, , rather than the marginal spread, . For the Gaussian case the means are exact; asymptotically the variational mean is consistent (Wang & Blei), but the uncertainty is understated whenever posterior correlations are strong.
A model has discrete latent variables. Which gradient estimator can be used directly for black-box VI, and what is its main drawback?
- The score-function estimator; its variance is often high and needs control variates
- The reparameterization estimator; it is biased for discrete variables
- Either one, with identical variance
- Neither: discrete latent variables rule out variational inference
Show the answer
A. The score-function estimator; its variance is often high and needs control variates
The score-function estimator needs only samples and , so it handles discrete . Reparameterization needs to be a differentiable function of parameter-free noise, which discrete variables are not (relaxations exist, at the cost of bias).
After fitting VI, the Pareto-smoothed importance sampling diagnostic gives . What should you do?
- Trust the fit: below 1 means the KL divergence is finite
- Report the importance-weighted estimates, which fix any approximation
- Treat the approximation as unreliable, and change the variational family, the divergence or switch to MCMC
- Run the optimizer longer, which always lowers
Show the answer
C. Treat the approximation as unreliable, and change the variational family, the divergence or switch to MCMC
Above 0.7 the importance ratios are so heavy-tailed that even Pareto-smoothed importance sampling converges impractically slowly. The approximation misses posterior mass, so a richer family or a different method is needed.
Further reading
- M. I. Jordan, Z. Ghahramani, T. S. Jaakkola & L. K. Saul, "An introduction to variational methods for graphical models," Machine Learning 37(2), 183–233 (1999).
- M. J. Wainwright & M. I. Jordan, "Graphical models, exponential families, and variational inference," Foundations and Trends in Machine Learning 1(1–2), 1–305 (2008).
- D. M. Blei, A. Kucukelbir & J. D. McAuliffe, "Variational inference: A review for statisticians," Journal of the American Statistical Association 112(518), 859–877 (2017).
- D. P. Kingma & M. Welling, "Auto-encoding variational Bayes," arXiv:1312.6114 (2013).
- Y. Yao, A. Vehtari, D. Simpson & A. Gelman, "Yes, but did it work?: Evaluating variational inference," Proceedings of the 35th International Conference on Machine Learning, PMLR 80, 5581–5590 (2018).