The latent-variable model generates observations by sampling a hidden cause and then an observation. Inference runs in the other direction: which hidden causes remain plausible after observing the data? Bayes' rule says
The numerator may be easy to evaluate even when its integral is not. Sampling and variational inference exploit this fact in different ways. We will compare them against an example with an exact answer, rather than infer accuracy from a plausible-looking density.
In this chapter: MCMC, normal inference, the ELBO, variational optimisation, VAEs.
Explore a distribution without its normalising constant
Metropolis–Hastings proposes and accepts with probability
On rejection the chain stays at ; the repeated state must be retained. The normalising constant cancels. A symmetric Gaussian random-walk proposal removes the proposal-density ratio, giving the simpler Metropolis rule in the source. The full expression is needed for asymmetric proposals.
The accepted flow between a pair of states is proportional to
which is symmetric under exchange. This detailed-balance argument establishes invariance of the target distribution. Convergence additionally needs appropriate irreducibility, aperiodicity and recurrence conditions. A proposal that cannot cross between modes can satisfy a local acceptance rule and still fail to explore the full posterior.
For a stationary chain and a scalar observable , under conditions ensuring a finite integrated autocorrelation time,
Effective sample size depends on the observable, and estimating it from a poorly mixing chain can be misleading. Warm-up can reduce initialisation effects and adapt proposals; discarding early states alone does not prove convergence. Use multiple dispersed chains, convergence diagnostics and Monte Carlo error estimates. Finite chains can be biased; “asymptotically exact” refers to valid limiting expectations under the required assumptions.
Random walks struggle along narrow, correlated or curved posteriors. Hamiltonian Monte Carlo chooses a positive-definite mass matrix , augments with momentum and evolves
A reversible, volume-preserving numerical integrator and an acceptance correction account for integration error. Gradients guide long proposals; they need not be cheap if the likelihood contains an expensive simulator. NUTS adapts trajectory construction and commonly tunes step size during warm-up. It does not guarantee movement between separated modes. Neal's HMC review explains the construction. The source's banana-posterior ESS comparison (about three versus one thousand) remains an unverified lecture report, not a general performance ratio.
Sampling is flexible and can represent non-Gaussian or multimodal structure when it mixes. Its cost, correlation and diagnostics motivate an alternative: fit a tractable distribution directly.
An exact posterior to keep us honest
Let be an unknown scalar, with independent measurements , , and prior . Assume both variances are known and strictly positive. Completing the square in the log joint gives
Independent information adds precision. The posterior mean is a precision-weighted compromise between prior mean and sample mean, not a simple average unless their precisions match. More observations reduce uncertainty under this fixed noise model; correlated measurements would contribute less independent information.
For an illustrative prior and one measurement with noise variance one, the posterior is . Compare the prior, the likelihood's shape as a function of , and the posterior.
Rather than jumping directly from prior to posterior, increase the observation precision continuously. The posterior narrows and shifts according to the same precision-weighted algebra. At unit precision, the animation recovers the worked example above.
v = 1/(1 + β) · m = βy/(1 + β)
posterior mean = 0.000posterior variance = 1.000
Replace an integral by a bound with a measurable gap
Choose a normalised variational density with appropriate support and finite expectations. Define
Jensen's inequality applied to gives when covers the joint's relevant support. More generally the same lower bound follows from nonnegative KL divergence, when is absolutely continuous with respect to the posterior and the quantities are finite:
This is the evidence lower bound, or ELBO. Equality holds precisely when equals the posterior almost everywhere. It can also be written
The first form balances expected reconstruction likelihood with divergence from the prior. The second displays variational entropy. Neither says that entropy always wins over concentration; a sharply concentrated true posterior may demand a narrow .
For a fixed generative model, maximising the ELBO minimises the reverse KL to its posterior. If model parameters also change, raising the bound need not separately raise the exact evidence and reduce the gap on every step. The source's claim that both objectives necessarily improve simultaneously is incorrect.
Reverse KL weights errors where places mass. A unimodal Gaussian approximation may ignore another posterior mode, or underestimate spread. Increasing samples used to estimate the ELBO reduces Monte Carlo error; it does not remove error caused by an inadequate variational family. MCMC also has finite-run and exploration errors, so neither method's accuracy follows from its label alone.
Variational inference with an answer we can derive
For the normal model above, choose with . Its entropy is . Gaussian expectations give an exact ELBO:
where is independent of . Differentiating yields
The optimum is exactly , . There is no variational family error here because the true posterior belongs to the family. Optimisation tolerance or noisy gradients can still prevent reaching that optimum. The analytic gap for any candidate is
This nonnegative quantity is a concrete implementation check: a wrong mean or variance gives a positive gap, and the exact posterior gives zero.
The analytic gap lets us watch variational optimisation without guessing whether a density looks close enough. Hold the model fixed and follow the approximation, the ELBO and their exact KL gap together. The evidence line stays still because the observation model is unchanged.
log p(x) = ELBO(q) + KL(q ‖ posterior)
KL gap = 5.616954q mean = -1.200; variance = 1.960
When expectations are unavailable analytically, draw and write . Then
is a Monte Carlo ELBO estimate. The reparameterisation trick moves randomness to a distribution independent of , so derivatives flow through the deterministic transformation. Interchanging derivative and expectation needs regularity and integrability. Gradient ascent, possibly with Adam, updates the variational parameters. In this conjugate example, analytic expectations are preferable; sampling is included to explain the method needed for nonlinear models.
Inference becomes a learned map
A variational autoencoder uses a decoder and an encoder , often a diagonal Gaussian with learned mean and log variance. Its per-observation objective is
For and standard-normal prior, the KL is . Reparameterised samples estimate the reconstruction term, and mini-batches train both networks. An encoder amortises inference across observations, potentially adding an amortisation gap beyond the chosen family's approximation error. Kingma and Welling introduce this stochastic training construction.
Generation uses the prior and decoder: sample , then . Encoding and reconstructing a training input is a different test. Evaluate held-out likelihood-related bounds, reconstruction, sample quality and latent use according to the application; they need not improve together. A flexible decoder may ignore , with : posterior collapse. This need not mean the decoder predicts only an unconditional mean; an expressive conditional likelihood can model a rich distribution without using the latent code.
Exact-posterior updates of recover the E-step viewpoint of EM; variational families relax it. ELBO optimisation is one method for nonlinear latent models, rather than the only possible training method. The course's progression is now visible: local approximations became fitted functions, fitted functions became probability models, and hidden representations required an explicit account of inference and approximation error.