08 / 15 · Latent Variables and Approximate Inference
Variational inference
When the posterior has no closed form, find the closest distribution of a simple form instead: the evidence lower bound, the mean-field update, an example with a known exact answer, and what the approximation gets wrong.
EM and Bayesian PCA · Conjugate priors and the exponential family · KL divergence
On this page 8
Take the simplest model with two unknowns. Observations come from , with an unknown mean and an unknown precision , the inverse variance. Give them the priors most people would write first, independent of each other: a normal prior on and a gamma prior on .
Each unknown is easy given the other. With fixed, the posterior of is normal; with fixed, the posterior of is gamma. Yet the joint posterior belongs to no standard family, because the evidence has no closed form. Integrating out is a gamma integral and leaves the normal prior of times , the shape of a Student- density, and a normal density times a Student- density has no closed-form integral. The models used in practice are harder. The posterior of a Bayesian mixture of Gaussians has one term for each of the ways of assigning points to components: terms for three components and a hundred points.
The Laplace approximation fits a Gaussian at one point, the mode. The previous note replaced the posterior of the latent variables by the best member of a tractable family. Can we do that for every unknown, and find the best distribution of a simple form without ever computing ? That is variational inference: an integral we cannot compute is replaced by an optimization we can (Jordan et al., 1999).
The evidence lower bound and the reverse KL#
Let collect all unknowns and be any distribution over them. Start from the KL divergence from to the posterior and use :
Rearranging gives the decomposition that the whole note rests on:
The first term is the evidence lower bound (ELBO), . The same bound follows in one line from Jensen’s inequality applied to ; the decomposition says more, because it names the gap.
Read it two ways. The left side does not depend on , so making larger makes closer to the posterior: is an objective for approximating the posterior. And since a KL divergence is never negative, for every : is also a lower bound on the evidence, with equality only at the exact posterior. The gap is finite only if puts no mass where the posterior has none.
Splitting the joint as gives a third reading:
The first term rewards for putting mass on values that explain the data; the second keeps close to the prior. The variational autoencoder trains with exactly this form.
Why is computable when is not? The evidence integrates a product of factors over all unknowns at once. The bound averages the logarithm of that product, which is a sum of log-factors, and under a that factorizes, each term of the sum is an expectation over one or two variables, often a known moment.
The direction of the divergence matters. Only the reverse direction can be minimized with the joint alone: the bound averages over , and raising it lowers without that divergence ever being computed. The reverse divergence grows without limit where puts mass and the posterior has almost none, and it costs nothing where the posterior has mass that misses. So the optimal stays inside the region where the posterior is large: it is zero-forcing, and with several separated modes it typically settles on one, mode-seeking. The forward direction covers all the mass instead; expectation propagation works with it, through local moment matching, and the Generative Models course compares the two on a mixture of two Gaussians.
Which family?#
Variational inference makes one approximation: is restricted to a family . Everything else is exact. Enlarging the family can only bring the bound closer to , so a richer cannot over-fit; the family is limited only to keep the expectations computable (Bishop, 2006, Section 10.1).
There are two ways to choose it. A fixed-form family fixes the shape, for example a Gaussian with a mean and a covariance to optimize; the black-box methods at the end of the course optimize such families with stochastic gradients. A free-form family fixes only which variables are independent and lets the bound decide the shape of each factor. The rest of this note uses the free-form mean-field family.
Mean field and the general update#
The mean-field family splits the unknowns into blocks and makes them independent:
Fix every factor except and look at as a function of alone. Write for the expectation over all factors except . The expectation of the log joint over the product splits into an expectation over of , and the entropy of a product is the sum of the factors’ entropies:
Here is a normalized density, its normalizing constant, and “const” collects the terms without . The only term that depends on is a negative KL divergence, which is largest, zero, when . So the best factor given the others is
with the constant fixed by normalization.
Three facts make the formula usable.
Only the neighbourhood of matters. Terms of without fall into the constant, so the update can be written with the complete conditional, . In a graphical model this conditional involves only the Markov blanket of : its parents, children and the children’s other parents. The reason is the factorization of the joint: the only factors that contain are its own conditional given its parents and the conditionals of its children, which also involve the children’s other parents. The Gibbs sampler of the next note draws from the same conditional, at the current values of the neighbours instead of averaging over them.
Conditional conjugacy gives closed forms. Suppose the complete conditional is in an exponential family,
with natural parameter depending on and . Its logarithm is linear in the sufficient statistics , so the update is a member of the same family, with natural parameter (Blei, Kucukelbir and McAuliffe, 2017, Section 4). The model need not be conjugate as a whole; each block must be conjugate given the others. That is the case of the opening example.
Coordinate ascent climbs the bound. The updates depend on each other through the expectations, so we cycle through them: coordinate ascent variational inference (CAVI). Each update finds the global maximum along its own coordinate, because the only term with is and the update makes it zero. So never decreases, and a non-decreasing sequence bounded above by converges. The bound is not concave in all factors jointly, so the limit is a local optimum, which can depend on the start (Blei, Kucukelbir and McAuliffe, 2017, Sections 2.4–2.5). This gives a free test: compute after every update. A decrease means a bug in the derivation or the code.
Worked example: a Gaussian with unknown mean and precision#
To check the approximation we need a model whose exact posterior we know. Take the normal model with the normal–gamma prior of the conjugate priors note, in which the prior variance of is tied to :
The gamma density with shape and rate is , with mean . The exact posterior is normal–gamma, and , with
This posterior does not factorize: the conditional variance of is , so and are dependent, and a factorized has something to lose (Bishop, 2006, Section 10.1.3).
We use eight observations, , and the prior , , :
| Quantity | Value |
|---|---|
| and | and |
| , , , | , , , |
| posterior mean of , | |
| posterior standard deviation of (a Student ) | |
| log evidence |
Where the last two rows come from
The marginal of is the Student of the conjugate priors note. Its variance follows from the law of total variance, with for a gamma variable (the gamma integral, for ):
The evidence is the ratio of the normalizing constants of posterior and prior (conjugacy). The normal–gamma density has the constant , and the likelihood brings :
The log joint, up to a constant, is
The factor . We keep the terms with and average over , which only replaces by . Completing the square, the bracket is , so
The factor is , centred on the exact posterior mean , with precision .
The factor . We keep the terms with and average over :
This is the logarithm of a gamma density, , with
where we used : write and expand; the cross term has mean zero under . The shape has rather than the exact posterior’s because the prior of depends on and contributes its half. Bishop’s printed equation (10.29) has here; the derivation above agrees with Murphy (2023, chapter 10).
Iterating. Start from and a with mean . The first update of moves its mean to and sets its precision to . The first update of then gives and
The bound climbs with every update, as CAVI promises:
| After | |
|---|---|
| the start | |
| update 1, | |
| update 2, | |
| update 3, | |
| update 4, | |
| convergence |
The log evidence is , so the remaining gap, , is ; the Code section obtains the same number by integrating the divergence directly.
Coordinate ascent for q(μ) q(λ)
The fixed point in closed form. At convergence the mean of is exact and the variance of is not. Two identities follow from the definition of : and . With and ,
Then
The mean of the precision is exactly the posterior mean, . The variance of under is , against the exact :
So reports a standard deviation of for where the truth is . The exact marginal of is a Student : a mixture of Gaussians with variances over the uncertain , in which small values of widen the tails. The factorized uses one Gaussian with the average precision and loses that spread. As grows, grows, the ratio tends to 1, and both and the exact posterior collapse onto . The standard deviation of is also slightly too small, against .
What mean field gets wrong#
Correlated unknowns#
Let the posterior be a Gaussian in two blocks, with precision matrix . The general update averages the quadratic form over :
The second line drops the term , which has no ; the third averages over , which only replaces by , and expands. So is Gaussian with mean and variance , and symmetrically for . At a fixed point both mean conditions hold, , and since is invertible the means of are the exact means . The variances are not exact. The inverse gives , so , which by the conditioning formula is the variance of given , not its marginal variance , and it is never larger. The width of is set by the narrowest direction of the posterior (Bishop, 2006, Section 10.1.2).
For unit variances and correlation , , so each factor has variance instead of 1: standard deviation instead of 1. This is zero-forcing at work. The reverse KL forbids to put mass outside the narrow ridge of the posterior, and a product of independent factors can only stay inside the ridge by being narrow in every direction.
The divergence at the optimum is . The best factorized in the forward direction is the product of the exact marginals, variance 1, with the same divergence. The two directions give the same value for every two-dimensional Gaussian; from three dimensions on they generally differ.
Derivation
For zero-mean Gaussians and in dimensions, take the log-densities and use (a scalar is its own trace, and the trace is cyclic):
The reverse optimum has , so the trace is and the divergence is . The forward optimum has ; swapping the roles of and gives . For both are . In two dimensions and , which makes the two expressions equal for every . In three dimensions with all correlations they are and .
The coordinate updates of the means are and (for ), the conditional means of the target. Substituting the first into the second gives , so each sweep multiplies the distance to the optimum by , the same factor that slows the Gibbs sampler on this target in the MCMC note. From , forty sweeps leave the means at and .
A factorized q for a correlated Gaussian
The remedy is to put strongly coupled variables into one block. A factor over jointly keeps their correlation; this structured mean field costs a harder update for that block.
Separated modes#
A posterior with separated modes is approximated by a on one of them. Mixture models always have this structure: relabelling the components gives equivalent modes. For predictions the choice does not matter. For the bound it does: misses about of the log evidence. When the copies barely overlap, the posterior is close to their equal mixture, so on the copy where sits it is about of that copy’s normalized density, and adds to the divergence. Bishop (2006, Section 10.2.4) adds it back before comparing mixtures with different .
More generally, comparing two models by their bounds compares minus two different gaps. It is reliable only when the gaps are small next to the difference in evidence, and nothing in the method measures the gaps (Blei, Kucukelbir and McAuliffe, 2017).
Overconfidence#
In both examples is too narrow. This is the usual direction of the error, though not a theorem for every model: the reverse KL penalizes mass where the posterior is small, so the variances of tend to be too small, and credible intervals from mean field are narrower than the exact ones. More iterations do not fix it. A richer family or more data does, and only a comparison with a more exact method, such as the sampler of the next note, shows how large the error is.
The variational mixture of Gaussians#
The standard showcase of variational inference is the Bayesian mixture of Gaussians: a Dirichlet prior on the weights , Gauss–Wishart priors on the means and precisions , and a latent component for each point. The only assumption is that latent assignments and parameters are independent, . The update formula then factorizes further on its own: splits over points, and into . These induced factorizations follow from the structure of the model (Bishop, 2006, Section 10.2.5).
The updates look like EM. Each point gets a responsibility for each component, proportional to with
where is the dimension of the data. This is the general update for : when , the log joint contains , the logarithm of the Gaussian density written out is the last three terms, and the update averages it over the parameters (Bishop, 2006, Eq. 10.46). Expectations under take the place of EM’s point estimates. The Dirichlet factor gets the parameters , the prior pseudo-count plus , and the Gauss–Wishart factors are updated with the responsibility-weighted statistics.
Two things change compared with EM for the same mixture. Maximum likelihood can collapse a component onto a single point, with variance shrinking to zero and the likelihood growing without bound; the prior and the averaging over parameters rule this out, because the scale matrix of each Wishart factor is the prior’s plus the responsibility-weighted scatter of the points, so the expected precision stays finite even for a single point. And with a small , below 1, components that explain few points see their weights driven to zero. The responsibilities contain , with the digamma function, and for small . A component with has , a very negative , and so even smaller responsibilities at the next update. A mixture started with too many components switches the extra ones off, as Bayesian PCA switched off directions in the previous note. Latent Dirichlet allocation, later in the course, is fitted the same way.
Where variational inference sits#
Choosing an approximation and computing its objective are two separate decisions. A small example lets us measure the difference. Suppose that for the observed , a binary latent variable has joint probabilities and . Then and the posterior probabilities are and . This model is small enough to solve exactly, so it can serve as a check.
Fix . The log-joint-minus-log- contribution is in the first state and in the second. Averaging gives
The gap is . Directly computing gives the same number. Allowing to change to closes the gap completely.
We could instead estimate the bound by drawing states from the fixed uniform and averaging their contributions. More draws reduce sampling error around ; they do not close the approximation gap. This sample-average form of the ELBO is also used in Pyro’s Trace_ELBO.loss. In a larger model, the choice of a tractable controls what dependencies can be represented, while exact expectations or stochastic estimates control how we evaluate and optimize the bound. The black-box VI note develops the gradient estimators. Whether to optimize some model parameters as point values, as in EM, is another modeling decision.
What you should remember#
- : maximizing the bound minimizes the reverse KL, using only the joint density.
- : fit the data, stay near the prior.
- Mean field: ; with conditional conjugacy each factor stays in its family.
- CAVI never decreases ; a decrease is a bug.
- Mean field gets the means right and the variances too small: for the normal model, for a correlated Gaussian.
- The reverse KL is zero-forcing and mode-seeking; the bound misses about for a mixture.
Code#
The exact posterior and evidence of the normal model, CAVI with the bound after every update, the gap computed as a KL divergence by numerical integration, the closed-form variance ratio, and mean field for a correlated Gaussian. It uses NumPy and SciPy and runs in a few seconds, most of them in the numerical integration; exact numbers can differ slightly across platforms and library versions.
import numpy as np
from scipy.special import gammaln, digamma
from scipy.stats import norm, gamma
from scipy.integrate import dblquad
# the normal model: x_i ~ N(mu, 1/tau), prior mu | tau ~ N(mu0, 1/(l0 tau)), tau ~ Gam(a0, b0) (rate b0)
# tau is the precision lambda of the text, l0 is kappa_0, and lam below is the precision omega of q(mu)
x = np.array([3.0, -1.6, 1.4, 0.4, 0.5, 0.8, -1.0, 0.8])
N, xbar = len(x), x.mean()
mu0, l0, a0, b0 = 0.0, 1.0, 2.0, 2.0
# exact posterior: normal-gamma, and the exact log evidence
lN, mN, aE = l0 + N, (l0 * mu0 + N * xbar) / (l0 + N), a0 + N / 2
bE = b0 + 0.5 * ((x - xbar) ** 2).sum() + l0 * N * (xbar - mu0) ** 2 / (2 * lN)
logZ = gammaln(aE) - gammaln(a0) + a0 * np.log(b0) - aE * np.log(bE) + 0.5 * np.log(l0 / lN) - N / 2 * np.log(2 * np.pi)
print(round(mN, 3), round(aE / bE, 3), round(np.sqrt(bE / ((aE - 1) * lN)), 3), round(logZ, 4)) # 0.478 0.661 0.449 -15.5113
def elbo(m, lam, a, b): # L(q) for q(mu) = N(m, 1/lam), q(tau) = Gam(a, b)
Elog, Et = digamma(a) - np.log(b), a / b
Esq, Ep = ((x - m) ** 2).sum() + N / lam, (m - mu0) ** 2 + 1 / lam
lik = N / 2 * Elog - N / 2 * np.log(2 * np.pi) - Et * Esq / 2
pmu = 0.5 * (np.log(l0) + Elog - np.log(2 * np.pi)) - l0 * Et * Ep / 2
ptau = a0 * np.log(b0) - gammaln(a0) + (a0 - 1) * Elog - b0 * Et
Hmu, Htau = 0.5 * np.log(2 * np.pi * np.e / lam), a - np.log(b) + gammaln(a) + (1 - a) * digamma(a)
return lik + pmu + ptau + Hmu + Htau
# coordinate ascent from q(mu) = N(1.4, 0.2^2), q(tau) = Gam(6.5, 6.5 / 1.2)
m, lam, a, b = 1.4, 25.0, 6.5, 6.5 / 1.2
trace = [elbo(m, lam, a, b)]
for sweep in range(30):
m, lam = mN, lN * a / b # update q(mu)
trace.append(elbo(m, lam, a, b))
a = a0 + (N + 1) / 2 # update q(tau)
b = b0 + 0.5 * (((x - m) ** 2).sum() + N / lam + l0 * ((m - mu0) ** 2 + 1 / lam))
trace.append(elbo(m, lam, a, b))
if sweep == 0: print(round(lam, 2), round(a / b, 3)) # 10.8 0.685
print(np.round(trace[:5], 4), bool(np.all(np.diff(trace) >= -1e-12)))
# [-21.5957 -16.8674 -15.622 -15.5562 -15.5527] True
print(round(a / b, 3), round(1 / np.sqrt(lam), 3), round(np.sqrt(a) / b, 3), round(np.sqrt(aE) / bE, 3))
# 0.661 0.41 0.259 0.27: E[tau] is exact, the standard deviations are too small
print(round(trace[-1], 4), round(logZ - trace[-1], 4)) # -15.5524 0.0411
# the gap is KL(q || p(mu, tau | x)), here by numerical integration
logq = lambda mu, t: norm.logpdf(mu, m, 1 / np.sqrt(lam)) + gamma.logpdf(t, a, scale=1 / b)
logp = lambda mu, t: norm.logpdf(mu, mN, 1 / np.sqrt(lN * t)) + gamma.logpdf(t, aE, scale=1 / bE)
kl = dblquad(lambda mu, t: np.exp(logq(mu, t)) * (logq(mu, t) - logp(mu, t)), 1e-6, 5, -4, 5)[0]
print(round(kl, 4)) # 0.0411
print(round((aE - 1) / aE, 4), round((1 / lam) / (bE / ((aE - 1) * lN)), 4)) # 0.8333 0.8333: Var_q / Var_p = (a_n - 1) / a_n
# a correlated Gaussian, rho = 0.9: mean-field updates m1 <- rho m2, m2 <- rho m1, variances 1 - rho^2
rho = 0.9
m1, m2 = -2.4, 2.4
for sweep in range(40): m1 = rho * m2; m2 = rho * m1
print(round(m1, 5), round(m2, 5), round(1 - rho ** 2, 2), round(-0.5 * np.log(1 - rho ** 2), 3)) # 0.00058 0.00052 0.19 0.83
Next#
Mean field is fast and deterministic, and its errors are systematic: the variances it reports are too small, by an amount it cannot measure. Each new model also needs its own derivation, and every update of a global factor reads all the data; stochastic and black-box variational inference, later in the course, remove these two limits. The next note uses the same complete conditionals differently: instead of averaging over the other blocks, it draws each block from its conditional at the current values of the others. The result is a Markov chain whose samples come, in the limit, from the exact posterior: unbiased, but noisy and slower.
References#
- M. I. Jordan, Z. Ghahramani, T. S. Jaakkola, L. K. Saul. An Introduction to Variational Methods for Graphical Models. Machine Learning, 37, 183–233, 1999.
- 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. Sections 2–4 (the ELBO, mean field, CAVI, conditionally conjugate models).
- C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. Sections 10.1 (factorized distributions, their properties, the univariate Gaussian) and 10.2 (the variational mixture of Gaussians; 10.2.4, the number of components and the correction; 10.2.5, induced factorizations).
- K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. Chapter 10 (variational inference, including the univariate Gaussian).
- D. P. Vetrov, D. A. Kropotov. Байесовские методы машинного обучения, lecture course, Moscow State University, 2015. Course page; lecture 7, the variational approach as approximate Bayesian inference (notes) and variational inference (lecture notes).