Course contents 08 / 15

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.

On this page 8

Take the simplest model with two unknowns. Observations x1,…,xnx_1, \dots, x_n come from N(μ,λ−1)\mathcal N(\mu, \lambda^{-1}), with an unknown mean μ\mu and an unknown precision λ\lambda, the inverse variance. Give them the priors most people would write first, independent of each other: a normal prior on μ\mu and a gamma prior on λ\lambda.

Each unknown is easy given the other. With λ\lambda fixed, the posterior of μ\mu is normal; with μ\mu fixed, the posterior of λ\lambda is gamma. Yet the joint posterior p(μ,λ∣X)p(\mu, \lambda \mid X) belongs to no standard family, because the evidence p(X)=∬p(X,μ,λ) dμ dλp(X) = \iint p(X, \mu, \lambda)\, d\mu\, d\lambda has no closed form. Integrating out λ\lambda is a gamma integral and leaves the normal prior of μ\mu times (b0+12∑i(xi−μ)2)−(a0+n/2)\big(b_0 + \frac12 \sum_i (x_i - \mu)^2\big)^{-(a_0 + n/2)}, the shape of a Student-tt density, and a normal density times a Student-tt density has no closed-form integral. The models used in practice are harder. The posterior of a Bayesian mixture of KK Gaussians has one term for each of the KnK^n ways of assigning points to components: 3100≈5⋅10473^{100} \approx 5 \cdot 10^{47} 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 p(X)p(X)? 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 ZZ collect all unknowns and q(Z)q(Z) be any distribution over them. Start from the KL divergence from qq to the posterior and use p(Z∣X)=p(X,Z)/p(X)p(Z \mid X) = p(X, Z) / p(X):

DKL(q ∥ p(Z∣X))=Eq[log⁡q(Z)−log⁡p(Z∣X)]=Eq[log⁡q(Z)−log⁡p(X,Z)]+log⁡p(X).\begin{aligned} D_{\mathrm{KL}}\big(q \,\|\, p(Z \mid X)\big) &= \mathbb E_q\big[\log q(Z) - \log p(Z \mid X)\big] \\ &= \mathbb E_q\big[\log q(Z) - \log p(X, Z)\big] + \log p(X) . \end{aligned}

Rearranging gives the decomposition that the whole note rests on:

log⁡p(X)=Eq[log⁡p(X,Z)]−Eq[log⁡q(Z)]⏟L(q)+DKL(q ∥ p(Z∣X)).\log p(X) = \underbrace{\mathbb E_q\big[\log p(X, Z)\big] - \mathbb E_q\big[\log q(Z)\big]}_{\mathcal L(q)} + D_{\mathrm{KL}}\big(q \,\|\, p(Z \mid X)\big) .

The first term is the evidence lower bound (ELBO), L(q)\mathcal L(q). The same bound follows in one line from Jensen’s inequality applied to log⁡Eq[p(X,Z)/q(Z)]\log \mathbb E_q[p(X, Z)/q(Z)]; the decomposition says more, because it names the gap.

Read it two ways. The left side does not depend on qq, so making L(q)\mathcal L(q) larger makes qq closer to the posterior: L\mathcal L is an objective for approximating the posterior. And since a KL divergence is never negative, L(q)≤log⁡p(X)\mathcal L(q) \le \log p(X) for every qq: L\mathcal L is also a lower bound on the evidence, with equality only at the exact posterior. The gap is finite only if qq puts no mass where the posterior has none.

Splitting the joint as p(X∣Z) p(Z)p(X \mid Z)\, p(Z) gives a third reading:

L(q)=Eq[log⁡p(X∣Z)]−DKL(q(Z) ∥ p(Z)).\mathcal L(q) = \mathbb E_q\big[\log p(X \mid Z)\big] - D_{\mathrm{KL}}\big(q(Z) \,\|\, p(Z)\big) .

The first term rewards qq for putting mass on values that explain the data; the second keeps qq close to the prior. The variational autoencoder trains with exactly this form.

Why is L\mathcal L computable when p(X)p(X) 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 qq 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 qq, and raising it lowers DKL(q ∥ p)D_{\mathrm{KL}}(q \,\|\, p) without that divergence ever being computed. The reverse divergence grows without limit where qq puts mass and the posterior has almost none, and it costs nothing where the posterior has mass that qq misses. So the optimal qq 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 DKL(p ∥ q)D_{\mathrm{KL}}(p \,\|\, q) 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: qq is restricted to a family Q\mathcal Q. Everything else is exact. Enlarging the family can only bring the bound closer to log⁡p(X)\log p(X), so a richer qq 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 Z1,…,ZmZ_1, \dots, Z_m and makes them independent:

q(Z)=∏j=1mqj(Zj).q(Z) = \prod_{j=1}^m q_j(Z_j) .

Fix every factor except qjq_j and look at L\mathcal L as a function of qjq_j alone. Write E−j\mathbb E_{-j} for the expectation over all factors except qjq_j. The expectation of the log joint over the product splits into an expectation over qjq_j of E−j\mathbb E_{-j}, and the entropy of a product is the sum of the factors’ entropies:

L(q)=∫qj E−j[log⁡p(X,Z)] dZj−∫qjlog⁡qj dZj+const=∫qjlog⁡p~j(Zj)qj(Zj) dZj+log⁡Cj+const=−DKL(qj ∥ p~j)+log⁡Cj+const.\begin{aligned} \mathcal L(q) &= \int q_j \, \mathbb E_{-j}\big[\log p(X, Z)\big]\, dZ_j - \int q_j \log q_j \, dZ_j + \text{const} \\ &= \int q_j \log \frac{\tilde p_j(Z_j)}{q_j(Z_j)} \, dZ_j + \log C_j + \text{const} \\ &= -D_{\mathrm{KL}}\big(q_j \,\|\, \tilde p_j\big) + \log C_j + \text{const} . \end{aligned}

Here p~j(Zj)=exp⁡(E−j[log⁡p(X,Z)])/Cj\tilde p_j(Z_j) = \exp\big(\mathbb E_{-j}[\log p(X, Z)]\big) / C_j is a normalized density, CjC_j its normalizing constant, and “const” collects the terms without qjq_j. The only term that depends on qjq_j is a negative KL divergence, which is largest, zero, when qj=p~jq_j = \tilde p_j. So the best factor given the others is

  log⁡qj∗(Zj)=E−j[log⁡p(X,Z)]+const  \boxed{\;\log q_j^*(Z_j) = \mathbb E_{-j}\big[\log p(X, Z)\big] + \text{const}\;}

with the constant fixed by normalization.

Three facts make the formula usable.

Only the neighbourhood of ZjZ_j matters. Terms of log⁡p(X,Z)\log p(X, Z) without ZjZ_j fall into the constant, so the update can be written with the complete conditional, log⁡qj∗=E−j[log⁡p(Zj∣Z−j,X)]+const\log q_j^* = \mathbb E_{-j}[\log p(Z_j \mid Z_{-j}, X)] + \text{const}. In a graphical model this conditional involves only the Markov blanket of ZjZ_j: its parents, children and the children’s other parents. The reason is the factorization of the joint: the only factors that contain ZjZ_j 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,

p(Zj∣Z−j,X)=h(Zj)exp⁡(ηj⊤u(Zj)−A(ηj)),p(Z_j \mid Z_{-j}, X) = h(Z_j) \exp\big(\eta_j^\top u(Z_j) - A(\eta_j)\big),

with natural parameter ηj\eta_j depending on Z−jZ_{-j} and XX. Its logarithm is linear in the sufficient statistics u(Zj)u(Z_j), so the update is a member of the same family, with natural parameter E−j[ηj]\mathbb E_{-j}[\eta_j] (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 qjq_j is −DKL(qj ∥ p~j)≤0-D_{\mathrm{KL}}(q_j \,\|\, \tilde p_j) \le 0 and the update makes it zero. So L\mathcal L never decreases, and a non-decreasing sequence bounded above by log⁡p(X)\log p(X) 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 L\mathcal L 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 μ\mu is tied to λ\lambda:

μ∣λ∼N(μ0,(κ0λ)−1),λ∼Gamma(a0,b0).\begin{aligned} \mu \mid \lambda &\sim \mathcal N\big(\mu_0, (\kappa_0 \lambda)^{-1}\big), \\ \lambda &\sim \mathrm{Gamma}(a_0, b_0) . \end{aligned}

The gamma density with shape aa and rate bb is Gamma(λ∣a,b)=baλa−1e−bλ/Γ(a)\mathrm{Gamma}(\lambda \mid a, b) = b^a \lambda^{a-1} e^{-b\lambda} / \Gamma(a), with mean a/ba/b. The exact posterior is normal–gamma, μ∣λ,X∼N(μn,(κnλ)−1)\mu \mid \lambda, X \sim \mathcal N\big(\mu_n, (\kappa_n \lambda)^{-1}\big) and λ∣X∼Gamma(an,bn)\lambda \mid X \sim \mathrm{Gamma}(a_n, b_n), with

κn=κ0+n,μn=κ0μ0+nxˉκ0+n,an=a0+n2,bn=b0+12∑i=1n(xi−xˉ)2+κ0n(xˉ−μ0)22(κ0+n).\begin{aligned} \kappa_n &= \kappa_0 + n, \\ \mu_n &= \frac{\kappa_0 \mu_0 + n \bar x}{\kappa_0 + n}, \\ a_n &= a_0 + \frac n2, \\ b_n &= b_0 + \frac12 \sum_{i=1}^n (x_i - \bar x)^2 + \frac{\kappa_0 n (\bar x - \mu_0)^2}{2(\kappa_0 + n)} . \end{aligned}

This posterior does not factorize: the conditional variance of μ\mu is 1/(κnλ)1/(\kappa_n \lambda), so μ\mu and λ\lambda are dependent, and a factorized q(μ) q(λ)q(\mu)\, q(\lambda) has something to lose (Bishop, 2006, Section 10.1.3).

We use eight observations, 3.0,−1.6,1.4,0.4,0.5,0.8,−1.0,0.83.0, -1.6, 1.4, 0.4, 0.5, 0.8, -1.0, 0.8, and the prior μ0=0\mu_0 = 0, κ0=1\kappa_0 = 1, a0=b0=2a_0 = b_0 = 2:

QuantityValue
xˉ\bar x and ∑i(xi−xˉ)2\sum_i (x_i - \bar x)^20.53750.5375 and 13.89913.899
κn\kappa_n, μn\mu_n, ana_n, bnb_n99, 0.4780.478, 66, 9.0789.078
posterior mean of λ\lambda, an/bna_n/b_n0.6610.661
posterior standard deviation of μ\mu (a Student tt)0.4490.449
log evidence log⁡p(X)\log p(X)−15.5113-15.5113
Where the last two rows come from

The marginal of μ\mu is the Student tt of the conjugate priors note. Its variance follows from the law of total variance, with E[1/λ]=b/(a−1)\mathbb E[1/\lambda] = b/(a - 1) for a gamma variable (the gamma integral, for a>1a \gt 1):

Var⁡(μ)=E[Var⁡(μ∣λ)]+Var⁡(E[μ∣λ])=E[1κnλ]+Var⁡(μn)=bn(an−1) κn+0=9.0785⋅9=0.4492.\begin{aligned} \operatorname{Var}(\mu) &= \mathbb E\big[\operatorname{Var}(\mu \mid \lambda)\big] + \operatorname{Var}\big(\mathbb E[\mu \mid \lambda]\big) \\ &= \mathbb E\Big[\frac{1}{\kappa_n \lambda}\Big] + \operatorname{Var}(\mu_n) \\ &= \frac{b_n}{(a_n - 1)\,\kappa_n} + 0 = \frac{9.078}{5 \cdot 9} = 0.449^2 . \end{aligned}

The evidence is the ratio of the normalizing constants of posterior and prior (conjugacy). The normal–gamma density has the constant Γ(a) b−a2π/κ\Gamma(a)\, b^{-a} \sqrt{2\pi/\kappa}, and the likelihood brings (2π)−n/2(2\pi)^{-n/2}:

log⁡p(X)=log⁡Γ(an)−log⁡Γ(a0)+a0log⁡b0−anlog⁡bn+12log⁡κ0κn−n2log⁡2π.\begin{aligned} \log p(X) ={}& \log\Gamma(a_n) - \log\Gamma(a_0) + a_0 \log b_0 \\ &- a_n \log b_n + \tfrac12 \log\frac{\kappa_0}{\kappa_n} - \tfrac n2 \log 2\pi . \end{aligned}

The log joint, up to a constant, is

log⁡p(X,μ,λ)=n2log⁡λ−λ2∑i=1n(xi−μ)2+12log⁡(κ0λ)−κ0λ2(μ−μ0)2+(a0−1)log⁡λ−b0λ+const.\begin{aligned} \log p(X, \mu, \lambda) ={}& \frac n2 \log \lambda - \frac\lambda2 \sum_{i=1}^n (x_i - \mu)^2 \\ &+ \frac12 \log(\kappa_0 \lambda) - \frac{\kappa_0 \lambda}{2} (\mu - \mu_0)^2 \\ &+ (a_0 - 1) \log \lambda - b_0 \lambda + \text{const} . \end{aligned}

The factor q(μ)q(\mu). We keep the terms with μ\mu and average over q(λ)q(\lambda), which only replaces λ\lambda by E[λ]\mathbb E[\lambda]. Completing the square, the bracket is (κ0+n)μ2−2μ(κ0μ0+nxˉ)+const(\kappa_0 + n)\mu^2 - 2\mu(\kappa_0 \mu_0 + n\bar x) + \text{const}, so

log⁡q∗(μ)=−E[λ]2(∑i=1n(xi−μ)2+κ0(μ−μ0)2)+const=−(κ0+n) E[λ]2 (μ−μn)2+const.\begin{aligned} \log q^*(\mu) &= -\frac{\mathbb E[\lambda]}{2} \Big(\sum_{i=1}^n (x_i - \mu)^2 + \kappa_0 (\mu - \mu_0)^2\Big) + \text{const} \\ &= -\frac{(\kappa_0 + n)\, \mathbb E[\lambda]}{2}\, (\mu - \mu_n)^2 + \text{const} . \end{aligned}

The factor is q∗(μ)=N(μ∣μn,ω−1)q^*(\mu) = \mathcal N(\mu \mid \mu_n, \omega^{-1}), centred on the exact posterior mean μn\mu_n, with precision ω=(κ0+n) E[λ]\omega = (\kappa_0 + n)\, \mathbb E[\lambda].

The factor q(λ)q(\lambda). We keep the terms with λ\lambda and average over q(μ)q(\mu):

log⁡q∗(λ)=(a0−1+n+12)log⁡λ−λ(b0+12 Eμ[∑i=1n(xi−μ)2+κ0(μ−μ0)2])+const.\log q^*(\lambda) = \Big(a_0 - 1 + \frac{n + 1}{2}\Big) \log \lambda - \lambda \Big(b_0 + \frac12\, \mathbb E_\mu\Big[\sum_{i=1}^n (x_i - \mu)^2 + \kappa_0 (\mu - \mu_0)^2\Big]\Big) + \text{const} .

This is the logarithm of a gamma density, q∗(λ)=Gamma(λ∣a~,b~)q^*(\lambda) = \mathrm{Gamma}(\lambda \mid \tilde a, \tilde b), with

a~=a0+n+12,b~=b0+12(∑i(xi−μn)2+nω+κ0(μn−μ0)2+κ0ω),\begin{aligned} \tilde a &= a_0 + \frac{n + 1}{2}, \\ \tilde b &= b_0 + \frac12 \Big(\sum_i (x_i - \mu_n)^2 + \frac n\omega + \kappa_0 (\mu_n - \mu_0)^2 + \frac{\kappa_0}\omega\Big), \end{aligned}

where we used Eμ[(xi−μ)2]=(xi−μn)2+1/ω\mathbb E_\mu[(x_i - \mu)^2] = (x_i - \mu_n)^2 + 1/\omega: write xi−μ=(xi−μn)−(μ−μn)x_i - \mu = (x_i - \mu_n) - (\mu - \mu_n) and expand; the cross term has mean zero under q(μ)q(\mu). The shape has (n+1)/2(n + 1)/2 rather than the exact posterior’s n/2n/2 because the prior of μ\mu depends on λ\lambda and contributes its half. Bishop’s printed equation (10.29) has N/2N/2 here; the derivation above agrees with Murphy (2023, chapter 10).

Iterating. Start from q(μ)=N(1.4,0.22)q(\mu) = \mathcal N(1.4, 0.2^2) and a q(λ)q(\lambda) with mean 1.21.2. The first update of q(μ)q(\mu) moves its mean to 0.4780.478 and sets its precision to 9⋅1.2=10.89 \cdot 1.2 = 10.8. The first update of q(λ)q(\lambda) then gives a~=6.5\tilde a = 6.5 and

b~=2+12(13.927+8/10.8+0.4782+1/10.8)=9.494,E[λ]=6.5/9.494=0.685.\begin{aligned} \tilde b &= 2 + \tfrac12 \big(13.927 + 8/10.8 + 0.478^2 + 1/10.8\big) = 9.494, \\ \mathbb E[\lambda] &= 6.5 / 9.494 = 0.685 . \end{aligned}

The bound climbs with every update, as CAVI promises:

AfterL(q)\mathcal L(q)
the start−21.596-21.596
update 1, q(μ)q(\mu)−16.867-16.867
update 2, q(λ)q(\lambda)−15.622-15.622
update 3, q(μ)q(\mu)−15.556-15.556
update 4, q(λ)q(\lambda)−15.553-15.553
convergence−15.5524-15.5524

The log evidence is −15.5113-15.5113, so the remaining gap, 0.04110.0411, is DKL(q ∥ p)D_{\mathrm{KL}}(q \,\|\, p); the Code section obtains the same number by integrating the divergence directly.

Figure

Coordinate ascent for q(μ) q(λ)

Coordinate ascent for q(μ) q(λ)The (μ, λ) plane. The blue contours of the exact posterior are tilted: at small λ it is wider in μ. The red contours of the factorized q have axes along the coordinates; they move from the upper right to the centre of the posterior and end narrower than it in μ.00.511.52−0.500.511.52μλ1234exact posterior p(μ, λ | X)mean field q(μ) q(λ)contours at e^(−1/2), e^(−2) of the maximumCoordinate ascent for q(μ) q(λ)The (μ, λ) plane. The blue contours of the exact posterior are tilted: at small λ it is wider in μ. The red contours of the factorized q have axes along the coordinates; they move from the upper right to the centre of the posterior and end narrower than it in μ.00.511.52−0.500.511.52μλ1234exact posterior p(μ, λ | X)mean field q(μ) q(λ)contours at e^(−1/2), e^(−2) of the maximum
Eight observations, prior μ | λ ~ N(0, 1/λ), λ ~ Gamma(2, 2). Blue: the exact posterior (normal–gamma), with mean of μ 0.478, E[λ] = 0.661 and standard deviation of μ 0.449. Red: q(μ) q(λ) after each update (steps 1–3, dashed) and after convergence (step 4, solid). Each update is the formula log qⱼ = E₋ⱼ[log p] + const and changes one factor only, so the contour of q moves alternately along μ and along λ. In the limit the mean and E[λ] are exact and the standard deviation of μ is 0.410: q cannot express that the posterior is wider in μ where λ is small.

The fixed point in closed form. At convergence the mean of λ\lambda is exact and the variance of μ\mu is not. Two identities follow from the definition of μn\mu_n: xˉ−μn=κ0(xˉ−μ0)/(κ0+n)\bar x - \mu_n = \kappa_0(\bar x - \mu_0)/(\kappa_0 + n) and μn−μ0=n(xˉ−μ0)/(κ0+n)\mu_n - \mu_0 = n(\bar x - \mu_0)/(\kappa_0 + n). With S=∑i(xi−xˉ)2S = \sum_i (x_i - \bar x)^2 and δ=xˉ−μ0\delta = \bar x - \mu_0,

∑i(xi−μn)2=S+n(xˉ−μn)2split around xˉ=S+nκ02 δ2(κ0+n)2first identity,κ0(μn−μ0)2=κ0n2 δ2(κ0+n)2second identity,their sum=S+κ0n δ2κ0+n=2(bn−b0)definition of bn.\begin{aligned} \textstyle\sum_i (x_i - \mu_n)^2 &= S + n(\bar x - \mu_n)^2 && \text{split around } \bar x \\ &= S + \frac{n \kappa_0^2\, \delta^2}{(\kappa_0 + n)^2} && \text{first identity}, \\ \kappa_0 (\mu_n - \mu_0)^2 &= \frac{\kappa_0 n^2\, \delta^2}{(\kappa_0 + n)^2} && \text{second identity}, \\ \text{their sum} &= S + \frac{\kappa_0 n\, \delta^2}{\kappa_0 + n} = 2(b_n - b_0) && \text{definition of } b_n . \end{aligned}

Then

b~=bn+n+κ02ω=bn+12 E[λ]since ω=(κ0+n) E[λ],a~=an+12,E[λ] b~=a~the mean of q(λ),E[λ] bn+12=an+12,E[λ]=anbn.\begin{aligned} \tilde b &= b_n + \frac{n + \kappa_0}{2\omega} = b_n + \frac{1}{2\, \mathbb E[\lambda]} && \text{since } \omega = (\kappa_0 + n)\,\mathbb E[\lambda], \\ \tilde a &= a_n + \frac12, \\ \mathbb E[\lambda]\, \tilde b &= \tilde a && \text{the mean of } q(\lambda), \\ \mathbb E[\lambda]\, b_n + \frac12 &= a_n + \frac12 , \\ \mathbb E[\lambda] &= \frac{a_n}{b_n} . \end{aligned}

The mean of the precision is exactly the posterior mean, 0.6610.661. The variance of μ\mu under qq is 1/ω=bn/(anκn)1/\omega = b_n/(a_n\kappa_n), against the exact bn/((an−1)κn)b_n/((a_n - 1)\kappa_n):

Var⁡q(μ)Var⁡p(μ)=an−1an=56.\frac{\operatorname{Var}_q(\mu)}{\operatorname{Var}_p(\mu)} = \frac{a_n - 1}{a_n} = \frac56 .

So qq reports a standard deviation of 0.4100.410 for μ\mu where the truth is 0.4490.449. The exact marginal of μ\mu is a Student tt: a mixture of Gaussians with variances 1/(κnλ)1/(\kappa_n \lambda) over the uncertain λ\lambda, in which small values of λ\lambda widen the tails. The factorized qq uses one Gaussian with the average precision and loses that spread. As nn grows, an=a0+n/2a_n = a_0 + n/2 grows, the ratio tends to 1, and both q(μ)q(\mu) and the exact posterior collapse onto xˉ\bar x. The standard deviation of λ\lambda is also slightly too small, 0.2590.259 against 0.2700.270.

What mean field gets wrong#

Correlated unknowns#

Let the posterior be a Gaussian N(m,Λ−1)\mathcal N(m, \Lambda^{-1}) in two blocks, with precision matrix Λ\Lambda. The general update averages the quadratic form over z2z_2:

log⁡q1∗(z1)=Ez2[−12(z−m)⊤Λ(z−m)]+const=Ez2[−12Λ11(z1−m1)2−Λ12(z1−m1)(z2−m2)]+const=−12Λ11z12+z1(Λ11m1−Λ12(E[z2]−m2))+const.\begin{aligned} \log q_1^*(z_1) &= \mathbb E_{z_2}\Big[-\tfrac12 (z - m)^\top \Lambda (z - m)\Big] + \text{const} \\ &= \mathbb E_{z_2}\Big[-\tfrac12 \Lambda_{11} (z_1 - m_1)^2 \\ &\qquad - \Lambda_{12} (z_1 - m_1)(z_2 - m_2)\Big] + \text{const} \\ &= -\tfrac12 \Lambda_{11} z_1^2 + z_1 \big(\Lambda_{11} m_1 - \Lambda_{12} (\mathbb E[z_2] - m_2)\big) + \text{const} . \end{aligned}

The second line drops the term Λ22(z2−m2)2\Lambda_{22}(z_2 - m_2)^2, which has no z1z_1; the third averages over z2z_2, which only replaces z2z_2 by E[z2]\mathbb E[z_2], and expands. So q1∗q_1^* is Gaussian with mean m1−Λ11−1Λ12(E[z2]−m2)m_1 - \Lambda_{11}^{-1} \Lambda_{12} (\mathbb E[z_2] - m_2) and variance Λ11−1\Lambda_{11}^{-1}, and symmetrically for q2q_2. At a fixed point both mean conditions hold, Λ(E[z]−m)=0\Lambda(\mathbb E[z] - m) = 0, and since Λ\Lambda is invertible the means of qq are the exact means mm. The variances are not exact. The 2×22 \times 2 inverse gives Λ11=Σ22/det⁡Σ\Lambda_{11} = \Sigma_{22}/\det\Sigma, so 1/Λ11=Σ11−Σ122/Σ221/\Lambda_{11} = \Sigma_{11} - \Sigma_{12}^2/\Sigma_{22}, which by the conditioning formula is the variance of z1z_1 given z2z_2, not its marginal variance Σ11\Sigma_{11}, and it is never larger. The width of qq is set by the narrowest direction of the posterior (Bishop, 2006, Section 10.1.2).

For unit variances and correlation ρ=0.9\rho = 0.9, Λ11=1/(1−ρ2)\Lambda_{11} = 1/(1 - \rho^2), so each factor has variance 0.190.19 instead of 1: standard deviation 0.4360.436 instead of 1. This is zero-forcing at work. The reverse KL forbids qq 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 −12log⁡(1−ρ2)=0.830-\frac12 \log(1 - \rho^2) = 0.830. The best factorized qq 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 q=N(0,Σq)q = \mathcal N(0, \Sigma_q) and p=N(0,Σ)p = \mathcal N(0, \Sigma) in dd dimensions, take the log-densities and use Eq[z⊤Az]=tr⁡(AΣq)\mathbb E_q[z^\top A z] = \operatorname{tr}(A \Sigma_q) (a scalar is its own trace, and the trace is cyclic):

DKL(q ∥ p)=12(tr⁡(Σ−1Σq)−d+log⁡det⁡Σdet⁡Σq).D_{\mathrm{KL}}(q \,\|\, p) = \tfrac12 \Big(\operatorname{tr}(\Sigma^{-1}\Sigma_q) - d + \log\frac{\det\Sigma}{\det\Sigma_q}\Big) .

The reverse optimum has Σq=diag⁡(1/Λjj)\Sigma_q = \operatorname{diag}(1/\Lambda_{jj}), so the trace is dd and the divergence is 12(log⁡det⁡Σ+∑jlog⁡Λjj)\frac12\big(\log\det\Sigma + \sum_j \log\Lambda_{jj}\big). The forward optimum has Σq=diag⁡(Σjj)\Sigma_q = \operatorname{diag}(\Sigma_{jj}); swapping the roles of pp and qq gives 12(∑jlog⁡Σjj−log⁡det⁡Σ)\frac12\big(\sum_j \log\Sigma_{jj} - \log\det\Sigma\big). For ρ=0.9\rho = 0.9 both are −12log⁡(1−ρ2)-\frac12\log(1 - \rho^2). In two dimensions Λ11=Σ22/det⁡Σ\Lambda_{11} = \Sigma_{22}/\det\Sigma and Λ22=Σ11/det⁡Σ\Lambda_{22} = \Sigma_{11}/\det\Sigma, which makes the two expressions equal for every Σ\Sigma. In three dimensions with all correlations 0.50.5 they are 0.2620.262 and 0.3470.347.

The coordinate updates of the means are m1←ρ m2m_1 \leftarrow \rho\, m_2 and m2←ρ m1m_2 \leftarrow \rho\, m_1 (for m=0m = 0), the conditional means of the target. Substituting the first into the second gives m2←ρ2m2m_2 \leftarrow \rho^2 m_2, so each sweep multiplies the distance to the optimum by ρ2=0.81\rho^2 = 0.81, the same factor that slows the Gibbs sampler on this target in the MCMC note. From (−2.4,2.4)(-2.4, 2.4), forty sweeps leave the means at 0.000580.00058 and 0.000520.00052.

Figure

A factorized q for a correlated Gaussian

A factorized q for a correlated GaussianTwo panels with the same ellipse p stretched along the diagonal. On the left q is a small circle at the centre, entirely inside the ellipse, with a staircase path of the means from the upper left. On the right q is a large circle that covers the ellipse and extends far beyond it across the diagonal.(a) min KL(q ‖ p): mean fieldstartq: sd 0.436 on each axisKL(q ‖ p) = 0.830z₁z₂(b) min KL(p ‖ q): product of marginalsq: sd 1 on each axisKL(p ‖ q) = 0.830z₁z₂target p, ρ = 0.9best factorized qmeans of q under CAVIA factorized q for a correlated GaussianTwo panels with the same ellipse p stretched along the diagonal. On the left q is a small circle at the centre, entirely inside the ellipse, with a staircase path of the means from the upper left. On the right q is a large circle that covers the ellipse and extends far beyond it across the diagonal.(a) min KL(q ‖ p): mean fieldstartq: sd 0.436 on each axisKL(q ‖ p) = 0.830z₁z₂(b) min KL(p ‖ q): product of marginalsq: sd 1 on each axisKL(p ‖ q) = 0.830z₁z₂target p, ρ = 0.9best factorized qmeans of q under CAVI
The target p is a bivariate normal with unit variances and correlation 0.9 (blue ellipses of distance 1 and 2). Red: the best q(z₁) q(z₂) for the two directions of KL (circles of 1 and 2 standard deviations). (a) The reverse KL that variational inference minimizes: the means of q equal those of p and the variances are 1/Λⱼⱼ = 1 − ρ² = 0.19, so q sits inside p and badly underestimates the spread along the diagonal. Amber: the means of q under coordinate updates from (−2.4, 2.4); each update moves one mean to the conditional mean of p, mⱼ ← ρ m₋ⱼ, and the path converges to zero by a factor ρ² = 0.81 per sweep. (b) The forward KL: q is the product of the marginals, with unit variances; it covers p but puts mass where p is almost zero. Both optima have KL = −½ log(1 − ρ²) = 0.830.

The remedy is to put strongly coupled variables into one block. A factor over (z1,z2)(z_1, z_2) 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 qq on one of them. Mixture models always have this structure: relabelling the KK components gives K!K! equivalent modes. For predictions the choice does not matter. For the bound it does: L\mathcal L misses about log⁡K!\log K! of the log evidence. When the K!K! copies barely overlap, the posterior is close to their equal mixture, so on the copy where qq sits it is about 1/K!1/K! of that copy’s normalized density, and log⁡(pcopy/K!)\log(p_{\text{copy}}/K!) adds log⁡K!\log K! to the divergence. Bishop (2006, Section 10.2.4) adds it back before comparing mixtures with different KK.

More generally, comparing two models by their bounds compares log⁡p(X)\log p(X) 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 qq 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 qq 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 KK Gaussians: a Dirichlet prior on the weights π\pi, Gauss–Wishart priors on the means and precisions (μk,Λk)(\mu_k, \Lambda_k), and a latent component ziz_i for each point. The only assumption is that latent assignments and parameters are independent, q(Z) q(π,μ,Λ)q(Z)\, q(\pi, \mu, \Lambda). The update formula then factorizes further on its own: q(Z)q(Z) splits over points, and q(π,μ,Λ)q(\pi, \mu, \Lambda) into q(π)∏kq(μk,Λk)q(\pi) \prod_k q(\mu_k, \Lambda_k). 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 rikr_{ik} for each component, proportional to r~ik\tilde r_{ik} with

log⁡r~ik=E[log⁡πk]+12 E[log⁡det⁡Λk]−D2log⁡2π−12 E[(xi−μk)⊤Λk(xi−μk)],\log \tilde r_{ik} = \mathbb E\big[\log \pi_k\big] + \tfrac12\, \mathbb E\big[\log \det \Lambda_k\big] - \tfrac D2 \log 2\pi - \tfrac12\, \mathbb E\big[(x_i - \mu_k)^\top \Lambda_k (x_i - \mu_k)\big] ,

where DD is the dimension of the data. This is the general update for q(zi)q(z_i): when zi=kz_i = k, the log joint contains log⁡πk+log⁡N(xi∣μk,Λk−1)\log \pi_k + \log \mathcal N(x_i \mid \mu_k, \Lambda_k^{-1}), 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 qq take the place of EM’s point estimates. The Dirichlet factor gets the parameters αk=α0+Nk\alpha_k = \alpha_0 + N_k, the prior pseudo-count plus Nk=∑irikN_k = \sum_i r_{ik}, 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 α0\alpha_0, below 1, components that explain few points see their weights driven to zero. The responsibilities contain E[log⁡πk]=ψ(αk)−ψ(∑lαl)\mathbb E[\log \pi_k] = \psi(\alpha_k) - \psi(\sum_l \alpha_l), with ψ\psi the digamma function, and ψ(α)≈−1/α\psi(\alpha) \approx -1/\alpha for small α\alpha. A component with Nk≈0N_k \approx 0 has αk≈α0\alpha_k \approx \alpha_0, a very negative E[log⁡πk]\mathbb E[\log \pi_k], 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 xx, a binary latent variable has joint probabilities p(x,Z=0)=0.12p(x, Z = 0) = 0.12 and p(x,Z=1)=0.08p(x, Z = 1) = 0.08. Then p(x)=0.20p(x) = 0.20 and the posterior probabilities are 0.60.6 and 0.40.4. This model is small enough to solve exactly, so it can serve as a check.

Fix q(0)=q(1)=0.5q(0) = q(1) = 0.5. The log-joint-minus-log-qq contribution is log⁡(0.12/0.5)=log⁡0.24\log(0.12/0.5) = \log 0.24 in the first state and log⁡(0.08/0.5)=log⁡0.16\log(0.08/0.5) = \log 0.16 in the second. Averaging gives

L(q)=12log⁡0.24+12log⁡0.16≈−1.62985,log⁡p(x)=log⁡0.20≈−1.60944.\mathcal L(q) = \tfrac12\log 0.24 + \tfrac12\log 0.16 \approx -1.62985, \qquad \log p(x) = \log 0.20 \approx -1.60944.

The gap is log⁡0.20−12log⁡0.24−12log⁡0.16=12log⁡(25/24)≈0.02041\log 0.20 - \tfrac12\log 0.24 - \tfrac12\log 0.16 = \tfrac12\log(25/24) \approx 0.02041. Directly computing DKL(q ∥ p)=12log⁡(0.5/0.6)+12log⁡(0.5/0.4)D_{\mathrm{KL}}(q\,\|\,p) = \tfrac12\log(0.5/0.6) + \tfrac12\log(0.5/0.4) gives the same number. Allowing qq to change to (0.6,0.4)(0.6, 0.4) closes the gap completely.

We could instead estimate the bound by drawing states from the fixed uniform qq and averaging their contributions. More draws reduce sampling error around −1.62985-1.62985; they do not close the 0.020410.02041 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 qq 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#

  • log⁡p(X)=L(q)+DKL(q ∥ p(Z∣X))\log p(X) = \mathcal L(q) + D_{\mathrm{KL}}(q \,\|\, p(Z \mid X)): maximizing the bound minimizes the reverse KL, using only the joint density.
  • L(q)=Eq[log⁡p(X∣Z)]−DKL(q ∥ p(Z))\mathcal L(q) = \mathbb E_q[\log p(X \mid Z)] - D_{\mathrm{KL}}(q \,\|\, p(Z)): fit the data, stay near the prior.
  • Mean field: log⁡qj∗=E−j[log⁡p(X,Z)]+const\log q_j^* = \mathbb E_{-j}[\log p(X, Z)] + \text{const}; with conditional conjugacy each factor stays in its family.
  • CAVI never decreases L\mathcal L; a decrease is a bug.
  • Mean field gets the means right and the variances too small: (an−1)/an(a_n - 1)/a_n for the normal model, 1−ρ21 - \rho^2 for a correlated Gaussian.
  • The reverse KL is zero-forcing and mode-seeking; the bound misses about log⁡K!\log K! 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#