ES98E · Course contents

Part A · Lectures 5–8

8. Inference: sampling, approximation and the ELBO

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

p(z∣x)=h(z)p(x),h(z)=p(x∣z)p(z),p(x)=∫h(z) dz.p(z\mid x)=\frac{h(z)}{p(x)},\qquad h(z)=p(x\mid z)p(z),\qquad p(x)=\int h(z)\,dz.

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 z′∼T(⋅∣z)z'\sim T(\cdot\mid z) and accepts with probability

a(z,z′)=min⁡ ⁣(1,h(z′)T(z∣z′)h(z)T(z′∣z)).a(z,z')=\min\!\left(1,\frac{h(z')T(z\mid z')}{h(z)T(z'\mid z)}\right).

On rejection the chain stays at zz; 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

min⁡{h(z)T(z′∣z), h(z′)T(z∣z′)},\min\{h(z)T(z'\mid z),\ h(z')T(z\mid z')\},

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 a(z)a(z), under conditions ensuring a finite integrated autocorrelation time,

Var⁡ ⁣(1N∑ta(zt))≈Var⁡p(a)N(1+2∑k≥1ρk),Neff=N1+2∑k≥1ρk.\operatorname{Var}\!\left(\frac1N\sum_ta(z_t)\right) \approx\frac{\operatorname{Var}_p(a)}N\left(1+2\sum_{k\ge1}\rho_k\right), \qquad N_{\rm eff}=\frac N{1+2\sum_{k\ge1}\rho_k}.

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 MM, augments zz with momentum p∼N(0,M)p\sim\mathcal N(0,M) and evolves

z˙=M−1p,p˙=−∇V(z),V(z)=−log⁡h(z).\dot z=M^{-1}p,\qquad\dot p=-\nabla V(z),\qquad V(z)=-\log h(z).

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 gg be an unknown scalar, with independent measurements xi=g+εix_i=g+\varepsilon_i, εi∼N(0,σ2)\varepsilon_i\sim\mathcal N(0,\sigma^2), and prior g∼N(g0,s02)g\sim\mathcal N(g_0,s_0^2). Assume both variances are known and strictly positive. Completing the square in the log joint gives

v=(s0−2+nσ−2)−1,m=v(s0−2g0+σ−2∑ixi),g∣x∼N(m,v).v=\left(s_0^{-2}+n\sigma^{-2}\right)^{-1},\qquad m=v\left(s_0^{-2}g_0+\sigma^{-2}\sum_ix_i\right), \qquad g\mid x\sim\mathcal N(m,v).

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 N(0,1)\mathcal N(0,1) and one measurement x=2x=2 with noise variance one, the posterior is N(1,1/2)\mathcal N(1,1/2). Compare the prior, the likelihood's shape as a function of gg, and the posterior.

Data and prior contribute precision
Multiply densities, then normalisedensityg-3500.65dashed: prior · dotted: likelihoodsolid: posterior N(1, 1/2)
Analytic normal example: prior mean 0 and variance 1; observation 2 with noise variance 1; posterior mean 1 and variance 1/2. The likelihood is displayed rescaled to integrate to one over g for comparison; it is not generally a probability density for g. Every curve uses the same horizontal and vertical scales. ↗

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.

See evidence add precision

v = 1/(1 + β) · m = βy/(1 + β)

-3510latent gprobability densityprior · rescaled likelihood · posterior

posterior mean = 0.000posterior variance = 1.000

Start with a standard-normal prior and increase the precision β of one Gaussian observation. At β = 0 the prior is unchanged; at β = 1 and y = 2 the posterior is N(1, 1/2). Dashed ink is the prior, dotted amber is the likelihood rescaled as a density over the latent variable, and solid teal is the normalised posterior. Density heights and horizontal scales stay fixed. ↗

Replace an integral by a bound with a measurable gap

Choose a normalised variational density q(z)q(z) with appropriate support and finite expectations. Define

L(q)=Eq[log⁡p(x,z)−log⁡q(z)].\mathcal L(q)=\mathbb E_q[\log p(x,z)-\log q(z)].

Jensen's inequality applied to log⁡Eq[p(x,z)/q(z)]\log\mathbb E_q[p(x,z)/q(z)] gives L(q)≤log⁡p(x)\mathcal L(q)\le\log p(x) when qq covers the joint's relevant support. More generally the same lower bound follows from nonnegative KL divergence, when qq is absolutely continuous with respect to the posterior and the quantities are finite:

DKL(q∥p(z∣x))=Eq[log⁡q(z)−log⁡p(x,z)+log⁡p(x)]=log⁡p(x)−L(q).\begin{aligned} D_{\rm KL}(q\|p(z\mid x)) &=\mathbb E_q[\log q(z)-\log p(x,z)+\log p(x)]\\ &=\log p(x)-\mathcal L(q). \end{aligned}

This is the evidence lower bound, or ELBO. Equality holds precisely when qq equals the posterior almost everywhere. It can also be written

L(q)=Eq[log⁡p(x∣z)]−DKL(q∥p(z))=Eq[log⁡p(x,z)]+H[q].\mathcal L(q)=\mathbb E_q[\log p(x\mid z)]-D_{\rm KL}(q\|p(z)) =\mathbb E_q[\log p(x,z)]+H[q].

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

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 qq 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 q(g)=N(a,b2)q(g)=\mathcal N(a,b^2) with b=eℓ>0b=e^\ell>0. Its entropy is ℓ+12log⁡(2πe)\ell+\tfrac12\log(2\pi e). Gaussian expectations give an exact ELBO:

L(a,b)=C−(a−g0)2+b22s02−12σ2∑i[(xi−a)2+b2]+log⁡b,\mathcal L(a,b)=C-\frac{(a-g_0)^2+b^2}{2s_0^2} -\frac1{2\sigma^2}\sum_i[(x_i-a)^2+b^2]+\log b,

where CC is independent of a,ba,b. Differentiating yields

∂L∂a=−a−g0s02+∑i(xi−a)σ2,∂L∂ℓ=1−b2(s0−2+nσ−2).\frac{\partial\mathcal L}{\partial a} =-\frac{a-g_0}{s_0^2}+\frac{\sum_i(x_i-a)}{\sigma^2},\qquad \frac{\partial\mathcal L}{\partial\ell}=1-b^2(s_0^{-2}+n\sigma^{-2}).

The optimum is exactly a=ma=m, b2=vb^2=v. 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

log⁡p(x)−L=12[b2+(a−m)2v−1+log⁡vb2].\log p(x)-\mathcal L =\frac12\left[\frac{b^2+(a-m)^2}{v}-1+\log\frac{v}{b^2}\right].

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.

Close the gap between a bound and the evidence

log p(x) = ELBO(q) + KL(q ‖ posterior)

-5510latent gdensity q and exact posteriorlog evidence (fixed)ELBO

KL gap = 5.616954q mean = -1.200; variance = 1.960

Optimise a Gaussian approximation to the exact posterior N(1, 1/2). The model and its evidence stay fixed. The moving density changes mean and log standard deviation; the lower gap is the exact Gaussian KL, not a Monte Carlo estimate. Smooth motion connects discrete ascent steps. The family contains the posterior, so the optimum can make the bound tight. ↗

When expectations are unavailable analytically, draw ϵs∼N(0,1)\epsilon_s\sim\mathcal N(0,1) and write gs=a+eℓϵsg_s=a+e^\ell\epsilon_s. Then

L^=1S∑slog⁡p(x,gs)+ℓ+12log⁡(2πe)\widehat{\mathcal L}=\frac1S\sum_s\log p(x,g_s)+\ell+\tfrac12\log(2\pi e)

is a Monte Carlo ELBO estimate. The reparameterisation trick moves randomness to a distribution independent of (a,ℓ)(a,\ell), 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 pθ(x∣z)p_\theta(x\mid z) and an encoder qφ(z∣x)q_\varphi(z\mid x), often a diagonal Gaussian with learned mean and log variance. Its per-observation objective is

L(θ,φ;x)=Eqφ(z∣x)[log⁡pθ(x∣z)]−DKL(qφ(z∣x)∥p(z)).\mathcal L(\theta,\varphi;x) =\mathbb E_{q_\varphi(z\mid x)}[\log p_\theta(x\mid z)] -D_{\rm KL}(q_\varphi(z\mid x)\|p(z)).

For q=N(μ,diag⁡(sj2))q=\mathcal N(\mu,\operatorname{diag}(s_j^2)) and standard-normal prior, the KL is 12∑j(μj2+sj2−1−log⁡sj2)\tfrac12\sum_j(\mu_j^2+s_j^2-1-\log s_j^2). 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 z∼p(z)z\sim p(z), then x∼pθ(x∣z)x\sim p_\theta(x\mid z). 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 zz, with q(z∣x)≈p(z)q(z\mid x)\approx p(z): 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 qq 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.