Course contents 13 / 15

13 / 15 · Scalable Inference

Stochastic variational inference

Coordinate-ascent variational inference reads the whole data set before it moves the shared parameters once. Stochastic variational inference moves them after every mini-batch, by a noisy natural-gradient step with shrinking step sizes.

On this page 8

Suppose we want topics for 3.8 million Wikipedia articles. Coordinate-ascent variational inference, as the previous note ran it, first updates the topic proportions of every article and only then the topics. One update of the topics, the quantity we came for, waits for 3.8 million inner loops, and each of those loops was fitted to topics that are still close to random.

The waste shows on a much smaller model. Take a Bayesian mixture of eight Gaussians in the plane and 200,000 points. After one full pass of coordinate ascent the evidence lower bound is still 0.95 nats per point below its optimum, and five passes are needed to get within 0.01. Each pass touches every point to move eight means a little.

A hundred random points already say roughly where the means are. Can the shared parameters move after every hundred points instead of after all of them? Stochastic variational inference (SVI) of Hoffman et al. (2013) does this. It keeps the model, the variational family and the objective of variational inference, and changes only how the objective is climbed.

Global and local variables#

SVI applies to models with two kinds of unknowns. A global latent variable β\beta is shared by all data points: the means of a mixture, the topics of LDA. A local latent variable ziz_i belongs to one data point xix_i: its cluster, or a document’s topic proportions and word assignments. The joint density is

p(β)∏i=1Np(xi,zi∣β).p(\beta) \prod_{i=1}^N p(x_i, z_i \mid \beta) .

The mean-field family is q(β∣λ)∏iq(zi∣ϕi)q(\beta \mid \lambda) \prod_i q(z_i \mid \phi_i), with a global variational parameter λ\lambda and local ones ϕi\phi_i. Under it the ELBO separates into a global term and a sum of local terms:

L(λ,ϕ)=Eq[log⁡p(β)]−Eq[log⁡q(β∣λ)]+∑i=1N(Eq[log⁡p(xi,zi∣β)]−Eq[log⁡q(zi∣ϕi)]).\begin{aligned} \mathcal L(\lambda, \phi) ={}& \mathbb E_q[\log p(\beta)] - \mathbb E_q[\log q(\beta \mid \lambda)] \\ &+ \sum_{i=1}^N \Big( \mathbb E_q[\log p(x_i, z_i \mid \beta)] - \mathbb E_q[\log q(z_i \mid \phi_i)] \Big) . \end{aligned}

The ii-th local term involves only xix_i, ϕi\phi_i and λ\lambda. So for a fixed λ\lambda each ϕi\phi_i can be optimized on its own, and its optimum ϕi(λ)\phi_i(\lambda) depends on nothing else. What remains is a function of the global parameter alone, L(λ)=max⁡ϕL(λ,ϕ)\mathcal L(\lambda) = \max_\phi \mathcal L(\lambda, \phi), and this is the objective SVI climbs. Its gradient is the partial gradient of L(λ,ϕ)\mathcal L(\lambda, \phi) at ϕ=ϕ(λ)\phi = \phi(\lambda). By the chain rule, assuming the optimum ϕ(λ)\phi(\lambda) is differentiable in λ\lambda,

ddλ L(λ,ϕ(λ))=∇λL+(∂ϕ∂λ) ⁣⊤∇ϕL=∇λL,\begin{aligned} \frac{d}{d\lambda}\, \mathcal L\big(\lambda, \phi(\lambda)\big) &= \nabla_\lambda \mathcal L + \Big(\frac{\partial \phi}{\partial \lambda}\Big)^{\!\top} \nabla_\phi \mathcal L \\ &= \nabla_\lambda \mathcal L , \end{aligned}

because ∇ϕL=0\nabla_\phi \mathcal L = 0 at an optimum in ϕ\phi. This is the envelope theorem.

The second ingredient is conjugacy. In the models of this course the complete conditional of β\beta, its distribution given everything else, is in an exponential family whose natural parameter is the prior’s plus one term per data point:

p(β∣x,z)=h(β)exp⁡(ηg(x,z)⊤u(β)−Ag(ηg(x,z))),ηg(x,z)=α+∑i=1Ns(xi,zi).\begin{aligned} p(\beta \mid x, z) &= h(\beta) \exp\big(\eta_g(x, z)^\top u(\beta) - A_g(\eta_g(x, z))\big), \\ \eta_g(x, z) &= \alpha + \sum_{i=1}^N s(x_i, z_i) . \end{aligned}

Here u(β)u(\beta) is the sufficient statistic, AgA_g the log-normalizer, α\alpha the natural parameter of the prior and s(xi,zi)s(x_i, z_i) the statistics one point contributes. The global factor q(β∣λ)q(\beta \mid \lambda) is taken from the same family, with natural parameter λ\lambda, and the mean-field update of the variational inference note sets it to the expected natural parameter, λ=Eϕ[ηg(x,z)]\lambda = \mathbb E_\phi[\eta_g(x, z)].

The running example: a Bayesian mixture#

The mixture of Blei, Kucukelbir and McAuliffe (2017), Section 3, has KK means μk∼N(0,σ02I)\mu_k \sim \mathcal N(0, \sigma_0^2 I) in RD\mathbb R^D, an assignment cic_i uniform over {1,…,K}\{1, \dots, K\}, and xi∼N(μci,I)x_i \sim \mathcal N(\mu_{c_i}, I). The family is q(μk)=N(mk,Pk−1I)q(\mu_k) = \mathcal N(m_k, P_k^{-1} I), with mean mkm_k and precision PkP_k, and q(ci=k)=ϕikq(c_i = k) = \phi_{ik}. Coordinate ascent alternates two updates:

ϕik∝exp⁡(xi⊤mk−12(∥mk∥2+D/Pk)),Pk=1σ02+∑i=1Nϕik,Pkmk=∑i=1Nϕik xi.\begin{aligned} \phi_{ik} &\propto \exp\Big(x_i^\top m_k - \tfrac12 \big(\lVert m_k \rVert^2 + D/P_k\big)\Big), \\ P_k &= \frac{1}{\sigma_0^2} + \sum_{i=1}^N \phi_{ik}, \\ P_k m_k &= \sum_{i=1}^N \phi_{ik}\, x_i . \end{aligned}

Both follow from the mean-field rule log⁡qj∗=E−j[log⁡p]+const\log q_j^* = \mathbb E_{-j}[\log p] + \text{const} of the variational inference note. The local update is the expected log likelihood of the point under component kk, and the global update is the conjugate posterior of μk\mu_k in which point xix_i counts with weight ϕik\phi_{ik}.

Derivation of the two updates

For the label, only the likelihood term of point ii depends on cic_i, and the uniform prior adds a constant:

log⁡q∗(ci=k)=Eq[log⁡N(xi∣μk,I)]+const=xi⊤Eq[μk]−12Eq∥μk∥2+const=xi⊤mk−12(∥mk∥2+D/Pk)+const.\begin{aligned} \log q^*(c_i = k) &= \mathbb E_q\big[\log \mathcal N(x_i \mid \mu_k, I)\big] + \text{const} \\ &= x_i^\top \mathbb E_q[\mu_k] - \tfrac12 \mathbb E_q \lVert \mu_k \rVert^2 + \text{const} \\ &= x_i^\top m_k - \tfrac12 \big(\lVert m_k \rVert^2 + D/P_k\big) + \text{const} . \end{aligned}

The second line drops −12∥xi∥2-\frac12 \lVert x_i \rVert^2 and the 2π2\pi term, which do not involve kk. The third uses that a second moment is the squared mean plus the variance, here summed over DD coordinates of variance 1/Pk1/P_k. For a mean, each label cic_i contributes the term of component kk with probability ϕik\phi_{ik}:

log⁡q∗(μk)=−∥μk∥22σ02+∑iϕik(xi⊤μk−12∥μk∥2)+const=−12Pk∥μk∥2+μk⊤∑iϕik xi+const.\begin{aligned} \log q^*(\mu_k) &= -\frac{\lVert \mu_k \rVert^2}{2\sigma_0^2} + \sum_{i} \phi_{ik} \Big(x_i^\top \mu_k - \tfrac12 \lVert \mu_k \rVert^2\Big) + \text{const} \\ &= -\tfrac12 P_k \lVert \mu_k \rVert^2 + \mu_k^\top \sum_{i} \phi_{ik}\, x_i + \text{const} . \end{aligned}

A quadratic in μk\mu_k with coefficient −12Pk-\frac12 P_k is the log density of a Gaussian with precision PkP_k; completing the square puts its mean at mkm_k with Pkmk=∑iϕikxiP_k m_k = \sum_i \phi_{ik} x_i.

In the coordinates (Pkmk,Pk)(P_k m_k, P_k), a linear transform of the natural parameters, the prior contributes α=(0,1/σ02)\alpha = (0, 1/\sigma_0^2) and point ii contributes (xi,1)(x_i, 1) to component cic_i.

The natural gradient of the ELBO#

Fix the local parameters and look at L\mathcal L as a function of λ\lambda. Only the terms with β\beta matter, and log⁡p(x,z,β)=log⁡p(β∣x,z)+log⁡p(x,z)\log p(x, z, \beta) = \log p(\beta \mid x, z) + \log p(x, z), where the second term does not involve β\beta. Write ηˉ=Eϕ[ηg(x,z)]\bar\eta = \mathbb E_\phi[\eta_g(x, z)] for the expected natural parameter of the complete conditional. Substituting both exponential-family densities, the base measures h(β)h(\beta) cancel, and

L(λ)=Eq[log⁡p(β∣x,z)]−Eq[log⁡q(β∣λ)]+const=ηˉ⊤Eq[u(β)]−λ⊤Eq[u(β)]+Ag(λ)+const=ηˉ⊤∇Ag(λ)−λ⊤∇Ag(λ)+Ag(λ)+const.\begin{aligned} \mathcal L(\lambda) &= \mathbb E_q[\log p(\beta \mid x, z)] - \mathbb E_q[\log q(\beta \mid \lambda)] + \text{const} \\ &= \bar\eta^\top \mathbb E_q[u(\beta)] - \lambda^\top \mathbb E_q[u(\beta)] + A_g(\lambda) + \text{const} \\ &= \bar\eta^\top \nabla A_g(\lambda) - \lambda^\top \nabla A_g(\lambda) + A_g(\lambda) + \text{const} . \end{aligned}

The second line substitutes the two densities. Mean field makes q(β)q(\beta) and q(z)q(z) independent, so Eq[ηg⊤u(β)]=ηˉ⊤Eq[u(β)]\mathbb E_q[\eta_g^\top u(\beta)] = \bar\eta^\top \mathbb E_q[u(\beta)], and the term Eq[Ag(ηg(x,z))]\mathbb E_q[A_g(\eta_g(x, z))] depends on ϕ\phi but not on λ\lambda and joins the constant. The third line uses Eq[u(β)]=∇Ag(λ)\mathbb E_q[u(\beta)] = \nabla A_g(\lambda), since qq has natural parameter λ\lambda; the conjugate priors note derives it by differentiating the normalization of the density. Differentiating by the product rule,

∇λL=∇2Ag(λ) ηˉ−∇Ag(λ)−∇2Ag(λ) λ+∇Ag(λ)=∇2Ag(λ) (ηˉ−λ).\begin{aligned} \nabla_\lambda \mathcal L &= \nabla^2 A_g(\lambda)\, \bar\eta - \nabla A_g(\lambda) - \nabla^2 A_g(\lambda)\, \lambda + \nabla A_g(\lambda) \\ &= \nabla^2 A_g(\lambda)\, (\bar\eta - \lambda) . \end{aligned}

This is equation 14 of Hoffman et al. (2013). The factor ∇2Ag(λ)\nabla^2 A_g(\lambda) is the covariance of u(β)u(\beta) under qq, and it is also the Fisher information of q(β∣λ)q(\beta \mid \lambda):

G(λ)=Eq[∇λlog⁡q  ∇λlog⁡q⊤]=Eq[(u−∇Ag)(u−∇Ag)⊤]=∇2Ag(λ).\begin{aligned} G(\lambda) &= \mathbb E_q\big[\nabla_\lambda \log q \; \nabla_\lambda \log q^\top\big] \\ &= \mathbb E_q\big[(u - \nabla A_g)(u - \nabla A_g)^\top\big] \\ &= \nabla^2 A_g(\lambda) . \end{aligned}

The first line is the definition. The second differentiates log⁡q=log⁡h(β)+λ⊤u(β)−Ag(λ)\log q = \log h(\beta) + \lambda^\top u(\beta) - A_g(\lambda), which gives ∇λlog⁡q=u(β)−∇Ag(λ)\nabla_\lambda \log q = u(\beta) - \nabla A_g(\lambda). The third is the identity Cov⁡q[u]=∇2Ag(λ)\operatorname{Cov}_q[u] = \nabla^2 A_g(\lambda) of the same section on the log-partition function.

The natural gradient (Amari, 1998) premultiplies the gradient by G(λ)−1G(\lambda)^{-1}, and the factor cancels:

  ∇^λL=G(λ)−1 ∇λL=Eϕ[ηg(x,z)]−λ  \boxed{\;\hat\nabla_\lambda \mathcal L = G(\lambda)^{-1}\, \nabla_\lambda \mathcal L = \mathbb E_\phi[\eta_g(x, z)] - \lambda\;}

(Hoffman et al., equation 22). The inverse exists when no linear combination of the statistics u(β)u(\beta) is constant under qq, as in the minimal families used here: then the covariance ∇2Ag\nabla^2 A_g is positive definite. A natural-gradient step of length ρ\rho moves λ\lambda to (1−ρ)λ+ρ ηˉ(1 - \rho)\lambda + \rho\,\bar\eta, and with ρ=1\rho = 1 it lands on ηˉ\bar\eta, the coordinate-ascent update. So coordinate ascent on the global parameter is natural-gradient ascent with step 1 (Sato, 2001). The natural gradient is also the cheaper one: no matrix is formed or inverted.

Worked example. One mean μ\mu with prior N(0,100)\mathcal N(0, 100), and ten points with average 2 and noise variance 1. The factor q(μ)=N(m,s2)q(\mu) = \mathcal N(m, s^2) has statistics u(μ)=(μ,μ2)u(\mu) = (\mu, \mu^2) and natural parameters λ=(m/s2,−1/(2s2))\lambda = (m/s^2, -1/(2s^2)). The complete conditional is the exact posterior, with precision 0.01+10=10.010.01 + 10 = 10.01 and natural parameter ηˉ=(20,−10.01/2)\bar\eta = (20, -10.01/2). We start at m=0m = 0, s=1s = 1:

QuantityValue
start λ\lambda(0,−0.5)(0, -0.5)
natural gradient ηˉ−λ\bar\eta - \lambda(20,−4.505)(20, -4.505)
Fisher information: the covariance of (μ,μ2)(\mu, \mu^2) under N(0,1)\mathcal N(0, 1)diag⁡(1,2)\operatorname{diag}(1, 2)
ordinary gradient(20,−9.01)(20, -9.01)
after a step of 1 along the natural gradientmean 1.9981.998, precision 10.0110.01
after a step of 1 along the ordinary gradientmean 1.0521.052, precision 19.0219.02

The Fisher information is the covariance of u=(μ,μ2)u = (\mu, \mu^2) under N(0,1)\mathcal N(0, 1): Var⁡μ=1\operatorname{Var}\mu = 1, Cov⁡(μ,μ2)=Eμ3=0\operatorname{Cov}(\mu, \mu^2) = \mathbb E\mu^3 = 0 and Var⁡μ2=Eμ4−(Eμ2)2=3−1=2\operatorname{Var}\mu^2 = \mathbb E\mu^4 - (\mathbb E\mu^2)^2 = 3 - 1 = 2. The ordinary gradient is G (ηˉ−λ)=(20,2⋅(−4.505))G\,(\bar\eta - \lambda) = (20, 2 \cdot (-4.505)). A step of 1 along it gives λ=(20,−9.51)\lambda = (20, -9.51), so precision −2λ2=19.02-2\lambda_2 = 19.02 and mean λ1/19.02=1.052\lambda_1/19.02 = 1.052.

The natural step lands on the posterior. The ordinary gradient points elsewhere, and since (20,−9.01)(20, -9.01) is not a multiple of (20,−4.505)(20, -4.505), no step size along it reaches the posterior.

Why measure steps by the Fisher information#

Optional depth: the geometry behind the natural gradient. The rest of the note uses only its formula.

The ordinary gradient is the steepest direction when a step is measured by its Euclidean length ∥dλ∥\lVert d\lambda \rVert. That length says little about how much the distribution changes. For two normals with the same variance s2s^2 and means aa and bb, averaging the difference of the log densities over x∼N(a,s2)x \sim \mathcal N(a, s^2) gives

DKL=E[(x−b)2−(x−a)2]2s2=s2+(a−b)2−s22s2=(a−b)22s2.\begin{aligned} D_{\mathrm{KL}} &= \frac{\mathbb E\big[(x - b)^2 - (x - a)^2\big]}{2s^2} \\ &= \frac{s^2 + (a - b)^2 - s^2}{2s^2} = \frac{(a - b)^2}{2s^2} . \end{aligned}

Moving the mean of N(0,102)\mathcal N(0, 10^2) by 1 gives a distribution that is hard to tell from the first, with a KL divergence of 1/(2⋅100)=0.0051/(2 \cdot 100) = 0.005. Moving the mean of N(0,0.12)\mathcal N(0, 0.1^2) by 1 gives one that barely overlaps it, with a divergence of 50. The two steps have the same Euclidean length.

A step can instead be measured by the change of the distribution. In an exponential family, log⁡qλ−log⁡qλ+dλ=Ag(λ+dλ)−Ag(λ)−dλ⊤u(β)\log q_\lambda - \log q_{\lambda + d\lambda} = A_g(\lambda + d\lambda) - A_g(\lambda) - d\lambda^\top u(\beta). Averaging over qλq_\lambda, with E[u]=∇Ag(λ)\mathbb E[u] = \nabla A_g(\lambda), leaves the remainder of a Taylor expansion of AgA_g, so the KL divergence is

DKL(qλ ∥ qλ+dλ)=Ag(λ+dλ)−Ag(λ)−dλ⊤∇Ag(λ)=12 dλ⊤∇2Ag(λ) dλ+O(∥dλ∥3)=12 dλ⊤G(λ) dλ+O(∥dλ∥3).\begin{aligned} D_{\mathrm{KL}}\big(q_\lambda \,\|\, q_{\lambda + d\lambda}\big) &= A_g(\lambda + d\lambda) - A_g(\lambda) - d\lambda^\top \nabla A_g(\lambda) \\ &= \tfrac12\, d\lambda^\top \nabla^2 A_g(\lambda)\, d\lambda + O(\lVert d\lambda \rVert^3) \\ &= \tfrac12\, d\lambda^\top G(\lambda)\, d\lambda + O(\lVert d\lambda \rVert^3) . \end{aligned}

The linear term cancels because the score has mean zero, and the quadratic term is the Fisher information. Maximizing the linear change ∇L⊤dλ\nabla \mathcal L^\top d\lambda subject to 12 dλ⊤G dλ=ϵ\tfrac12\, d\lambda^\top G\, d\lambda = \epsilon with a Lagrange multiplier ν\nu gives the stationarity condition ∇L=ν G dλ\nabla \mathcal L = \nu\, G\, d\lambda, so dλ=ν−1G−1∇Ld\lambda = \nu^{-1} G^{-1} \nabla \mathcal L.

So the natural gradient is the steepest ascent per unit of KL divergence. It also does not depend on how λ\lambda is parameterized. Write λ=λ(θ)\lambda = \lambda(\theta) with an invertible Jacobian J=∂λ/∂θJ = \partial\lambda/\partial\theta. By the chain rule ∇θL=J⊤∇λL\nabla_\theta \mathcal L = J^\top \nabla_\lambda \mathcal L, and the same rule inside the definition of GG gives Gθ=J⊤GλJG_\theta = J^\top G_\lambda J. The natural step in θ\theta, mapped back to λ\lambda, is

J Gθ−1∇θL=J J−1Gλ−1J−⊤J⊤∇λL=Gλ−1∇λL,\begin{aligned} J\, G_\theta^{-1} \nabla_\theta \mathcal L &= J\, J^{-1} G_\lambda^{-1} J^{-\top} J^\top \nabla_\lambda \mathcal L \\ &= G_\lambda^{-1} \nabla_\lambda \mathcal L , \end{aligned}

the same change of the distribution. Hoffman et al. (2013, Section 2.3) use the symmetrized divergence, which agrees with this one to second order: the reverse direction has the quadratic term 12dλ⊤G(λ+dλ) dλ\frac12 d\lambda^\top G(\lambda + d\lambda)\, d\lambda, and G(λ+dλ)=G(λ)+O(∥dλ∥)G(\lambda + d\lambda) = G(\lambda) + O(\lVert d\lambda \rVert). The same idea, with the divergence between two policies, gives the trust-region update of TRPO. In the worked example the Euclidean step treats both natural parameters on one scale, and it overshoots the precision, 19.0219.02 against 10.0110.01.

Mini-batches: a noisy natural gradient#

The natural gradient still needs ηˉ=α+∑i=1NEϕi[s(xi,zi)]\bar\eta = \alpha + \sum_{i=1}^N \mathbb E_{\phi_i}[s(x_i, z_i)], a sum over all points. Draw one index II uniformly from {1,…,N}\{1, \dots, N\} and replace the sum by NN copies of its II-th term. Since

EI[N EϕI[s(xI,zI)]]=∑i=1N1N⋅N Eϕi[s(xi,zi)]=∑i=1NEϕi[s(xi,zi)],\begin{aligned} \mathbb E_I\Big[N\, \mathbb E_{\phi_I}[s(x_I, z_I)]\Big] &= \sum_{i=1}^N \frac1N \cdot N\, \mathbb E_{\phi_i}[s(x_i, z_i)] \\ &= \sum_{i=1}^N \mathbb E_{\phi_i}[s(x_i, z_i)], \end{aligned}

the result is an unbiased estimate of ηˉ\bar\eta. A batch drawn without replacement is unbiased too: each point enters it with probability B/NB/N, which the factor N/BN/B below cancels. It is exactly the coordinate-ascent update for a data set made of NN copies of xIx_I (Hoffman et al., Section 2.4). Averaging BB such draws gives the intermediate global parameter of a mini-batch SS, and the SVI update blends it into the current value:

λ^S=α+NB∑i∈SEϕi(λ)[s(xi,zi)],λ(t)=(1−ρt) λ(t−1)+ρt λ^S\boxed{ \begin{aligned} \hat\lambda_S &= \alpha + \frac{N}{B} \sum_{i \in S} \mathbb E_{\phi_i(\lambda)}\big[s(x_i, z_i)\big], \\ \lambda^{(t)} &= \big(1 - \rho_t\big)\,\lambda^{(t-1)} + \rho_t\, \hat\lambda_S \end{aligned} }

Here ϕi(λ)\phi_i(\lambda) is the local optimum for the current λ\lambda, computed only for the points of the batch, and λ^S−λ(t−1)\hat\lambda_S - \lambda^{(t-1)} is an unbiased estimate of the natural gradient. One step costs BB local updates instead of NN. Murphy (2023, Section 10.1.4) writes the same idea as stochastic gradient ascent on the ELBO of a mini-batch scaled by N/BN/B.

Figure

One step of stochastic variational inference

One step of stochastic variational inferenceOn the left, a column of N = 200,000 data points; a mini-batch of B = 100 points is drawn from it. The local step computes the responsibilities φ of the batch points from the current global parameter λ (precision P = 24,000, mean m = 3.00): the responsibilities of the component sum to 12.5 and the weighted sum of the points is 40. Multiplying by N/B = 2000 gives the intermediate parameter λ̂ with precision 25,000 and mean 3.20. The new parameter is the blend (1 − ρ)λ + ρλ̂ with ρ = 0.187: precision 24,187, mean 3.039. An arrow returns to the local step for the next mini-batch.data, N = 200 000x₁x₂…x_Nmini-batch SB = 100 points1current λ, step t = 10P = 24 000, m = 3.00local step φᵢΣφ = 12.5, Σφx = 402× N/B = 2000intermediate λ̂P̂ = 25 000, m̂ = 3.203(1 − ρ)λ + ρλ̂ρ = 0.187new λP = 24 187, m = 3.0394t ← t + 15One step of stochastic variational inferenceOn the left, a column of N = 200,000 data points; a mini-batch of B = 100 points is drawn from it. The local step computes the responsibilities φ of the batch points from the current global parameter λ (precision P = 24,000, mean m = 3.00): the responsibilities of the component sum to 12.5 and the weighted sum of the points is 40. Multiplying by N/B = 2000 gives the intermediate parameter λ̂ with precision 25,000 and mean 3.20. The new parameter is the blend (1 − ρ)λ + ρλ̂ with ρ = 0.187: precision 24,187, mean 3.039. An arrow returns to the local step for the next mini-batch.current λ, step t = 10P = 24 000, m = 3.00dataN = 200 000 pointsmini-batch SB = 100 points1local step φᵢΣφ = 12.5, Σφx = 402× N/B = 2000intermediate λ̂P̂ = 25 000, m̂ = 3.203(1 − ρ)λ + ρλ̂ρ = 0.187new λP = 24 187, m = 3.0394t ← t + 15
One SVI step for one component of the mixture; q(μₖ) is stored by its precision P and the product Pm. The batch statistics are multiplied by N/B = 2000, and the prior precision 0.01 is added. The step ρ₁₀ = 11^(−0.7) blends natural parameters, and the mean moves from 3.00 to 3.039.

Worked example. One component of the mixture, first coordinate of its mean, with N=200,000N = 200{,}000, B=100B = 100 and prior precision 0.010.01. The current q(μk)q(\mu_k) has precision P=24,000P = 24{,}000 and mean m=3.00m = 3.00, so Pm=72,000Pm = 72{,}000. In the batch, the responsibilities of component kk sum to 12.512.5 and ∑i∈Sϕikxi=40\sum_{i \in S} \phi_{ik} x_i = 40. The step is t=10t = 10, with ρ10=11−0.7=0.187\rho_{10} = 11^{-0.7} = 0.187:

P^=0.01+2000⋅12.5=25,000.01,Pm^=2000⋅40=80,000,P′=0.813⋅24,000+0.187⋅25,000=24,187,(Pm)′=73,493,m′=73,493/24,187=3.039.\begin{aligned} \hat P &= 0.01 + 2000 \cdot 12.5 = 25{,}000.01, \\ \widehat{Pm} &= 2000 \cdot 40 = 80{,}000, \\ P' &= 0.813 \cdot 24{,}000 + 0.187 \cdot 25{,}000 = 24{,}187, \\ (Pm)' &= 73{,}493, \\ m' &= 73{,}493 / 24{,}187 = 3.039 . \end{aligned}

The intermediate mean is 80,000/25,000=3.2080{,}000 / 25{,}000 = 3.20. The blend acts on natural parameters, so the mean does not move exactly a fraction ρ\rho of the way from 3.003.00 to 3.203.20, which would give 3.0373.037. The Code section also checks that λ^S\hat\lambda_S is unbiased: averaged over 2000 batches at a fixed qq, its precisions agree with the full-data ones to within 0.6%0.6\%.

With ρ1=1\rho_1 = 1 and ρt=1/t\rho_t = 1/t, multiplying the update λ(t)=(1−1/t)λ(t−1)+λ^t/t\lambda^{(t)} = (1 - 1/t)\lambda^{(t-1)} + \hat\lambda_t/t by tt gives tλ(t)=(t−1)λ(t−1)+λ^tt\lambda^{(t)} = (t - 1)\lambda^{(t-1)} + \hat\lambda_t. So tλ(t)t\lambda^{(t)} is the running sum of the λ^s\hat\lambda_s, the start dropping out at t=1t = 1, and

λ(t)=1t∑s=1tλ^s,\lambda^{(t)} = \frac1t \sum_{s=1}^t \hat\lambda_s ,

the plain average of all intermediate estimates. Other schedules weight recent estimates more. That helps, because the early λ^s\hat\lambda_s were computed from local steps under a poor λ\lambda.

Step sizes: the Robbins–Monro conditions#

With a constant step, SVI ends in a cloud around the optimum whose size is proportional to the step, as any stochastic gradient method does (a constant step stalls in a noise ball). The classical conditions of Robbins and Monro (1951) are

∑t=1∞ρt=∞,∑t=1∞ρt2<∞.\begin{aligned} \sum_{t=1}^\infty \rho_t &= \infty, \\ \sum_{t=1}^\infty \rho_t^2 &< \infty . \end{aligned}

The first lets the steps travel any distance; the second keeps their accumulated noise finite. The convergence theorem needs more than the step sizes. Suppose L(λ)\mathcal L(\lambda) is bounded above with a Lipschitz-continuous gradient, the noisy step is unbiased for G−1∇LG^{-1} \nabla \mathcal L with the eigenvalues of GG bounded above and away from zero, and the variance of the noise grows at most like M+MV∥∇L∥2M + M_V \lVert \nabla \mathcal L \rVert^2. Then steps meeting both conditions give lim inf⁡tE∥∇L(λ(t))∥2=0\liminf_t \mathbb E \lVert \nabla \mathcal L(\lambda^{(t)}) \rVert^2 = 0 (Bottou, Curtis and Nocedal, 2018, Theorem 4.10): the iterates approach stationary points, in practice local maxima (Hoffman et al., Section 2.4). The schedule used in practice is their equation 26:

ρt=(t+τ)−κ,κ∈(0.5,1],τ≥0.\begin{aligned} \rho_t &= (t + \tau)^{-\kappa}, \\ \kappa &\in (0.5, 1], \\ \tau &\ge 0 . \end{aligned}

The first sum diverges because κ≤1\kappa \le 1; the second converges because 2κ>12\kappa > 1. Both are the pp-series test: ∑tt−p\sum_t t^{-p} converges exactly when p>1p > 1, and the shift τ\tau does not change that. Hoffman et al. call κ\kappa the forgetting rate and τ\tau the delay, which damps the first steps.

With τ=1\tau = 1 and κ=0.7\kappa = 0.7, the schedule of the experiment below:

Step ttρt\rho_tabout 1/ρt1/\rho_t batches remembered
100.1870.1875
10000.00790.0079126
40000.00300.0030330

Over a stretch where ρt≈ρ\rho_t \approx \rho barely changes, unrolling the update, and ignoring the start, gives

λ(t)≈∑k≥0ρ (1−ρ)k λ^t−k.\lambda^{(t)} \approx \sum_{k \ge 0} \rho\, (1 - \rho)^k\, \hat\lambda_{t - k} .

The newest 1/ρ1/\rho batches carry the total weight 1−(1−ρ)1/ρ≈1−e−1=0.631 - (1 - \rho)^{1/\rho} \approx 1 - e^{-1} = 0.63, since (1−ρ)1/ρ→e−1(1 - \rho)^{1/\rho} \to e^{-1} as ρ→0\rho \to 0. In this sense λ\lambda remembers roughly the last 1/ρt1/\rho_t batches. After two passes over 200,000 points that is 330 batches, or 33,000 points, and this memory sets the noise floor of the experiment. The batch size trades in the same terms: the variance of λ^S\hat\lambda_S, an average of BB independent draws, falls like 1/B1/B while the cost of a step grows like BB.

On their topic models, Hoffman et al. fixed τ=1\tau = 1, after finding the results insensitive to it, and tried κ\kappa from 0.50.5 to 11 and batches of 10 to 1000 documents. Forgetting rates near 1 and larger batches did best; their large-scale comparisons use κ=0.9\kappa = 0.9 and 500 documents per batch.

An experiment: SVI against batch coordinate ascent#

Both methods fit the mixture above with K=8K = 8 components in D=2D = 2 dimensions, true means drawn from N(0,52I)\mathcal N(0, 5^2 I), N=200,000N = 200{,}000 points and prior σ0=10\sigma_0 = 10. Both start from the same KK randomly chosen data points as means, with precision 1. Batch coordinate ascent runs 30 passes. SVI uses B=100B = 100, τ=1\tau = 1 and κ=0.7\kappa = 0.7 for two passes, 4000 steps.

The gap is the ELBO per point of the batch method after 30 passes, −4.7142-4.7142, minus the current ELBO per point, computed on all the data with every ϕi\phi_i at its optimum. A pass means NN points processed by the local step, the dominant cost of both methods.

Gap belowBatch, passesSVI, passes
0.10.140.01
0.010.0150.02
0.0010.00160.08
smallest gap2.1⋅10−62.1 \cdot 10^{-6} after 12 passes5.4⋅10−55.4 \cdot 10^{-5} in 2 passes
Figure

Passes over the data needed to reach a given ELBO

Passes over the data needed to reach a given ELBOThe gap between the ELBO per point and the batch optimum against the number of passes over the data, both axes on a log scale. Batch coordinate ascent: 0.95 after the first pass, 0.015 after the fourth, 0.0019 after the fifth, 0.00048 after the sixth and 2·10⁻⁶ after the twelfth. SVI with mini-batches of 100 points: 0.012 after a hundredth of a pass, below 0.001 after 0.08 passes, then it fluctuates between 6·10⁻⁵ and 4·10⁻⁴ and does not reach 10⁻⁵ in two passes.1010⁻¹10⁻³10⁻⁵0.010.1110passes over the data (log scale)ELBO gap, nats per point0.010.001560.020.08batch coordinate ascentSVI, B = 100, κ = 0.7Passes over the data needed to reach a given ELBOThe gap between the ELBO per point and the batch optimum against the number of passes over the data, both axes on a log scale. Batch coordinate ascent: 0.95 after the first pass, 0.015 after the fourth, 0.0019 after the fifth, 0.00048 after the sixth and 2·10⁻⁶ after the twelfth. SVI with mini-batches of 100 points: 0.012 after a hundredth of a pass, below 0.001 after 0.08 passes, then it fluctuates between 6·10⁻⁵ and 4·10⁻⁴ and does not reach 10⁻⁵ in two passes.1010⁻¹10⁻³10⁻⁵0.010.1110passes over the data (log scale)ELBO gap, nats per point0.010.001560.020.08batch coordinate ascentSVI, B = 100, κ = 0.7
Gap to the optimal ELBO per point against passes over the data, for the mixture of 8 Gaussians with 200,000 points and one shared start. Dashed lines mark gaps of 0.01 and 0.001: 5 and 6 passes for the batch method, 0.02 and 0.08 for SVI. Below 10⁻⁴ SVI stalls at its noise floor.

SVI needs 250 times fewer points than the batch method to get within 0.010.01, and 75 times fewer to get within 0.0010.001. Both end at the same optimum. The last row is the other side of the trade: below about 10−410^{-4} SVI is held up by the noise of its steps, while the batch method is exact at every pass and passes below SVI’s best value at pass 9. When a very precise optimum is needed, a common recipe is SVI first and a few batch passes at the end. These numbers come from one data set, one start and one seed; with more local optima the two methods can also end in different ones.

SVI for LDA#

For LDA with DD documents, the global variables are the topics, with Dirichlet variational parameters λkw\lambda_{kw} and prior η\eta; the local ones are each document’s topic proportions and word assignments. The local step on a document is the inner loop of coordinate ascent over its γd\gamma_d and ϕdn\phi_{dn}, run until it converges. The intermediate topics of a batch are

λ^kw=η+DB∑d∈S∑n=1Ndϕdnk [wdn=w],\hat\lambda_{kw} = \eta + \frac{D}{B} \sum_{d \in S} \sum_{n=1}^{N_d} \phi_{dnk}\, [w_{dn} = w],

the expected number of times word ww is assigned to topic kk in the batch, scaled up to the corpus. This is the online LDA of Hoffman, Blei and Bach (2010), the first special case of SVI. With it, Hoffman et al. (2013) fitted topic models to about 350,000 articles of Nature, 1.8 million articles of The New York Times and 3.8 million Wikipedia articles. On all three of their corpora, SVI on the full data reached a better held-out predictive likelihood, and sooner, than batch inference on a subset small enough for it (their Figure 7).

scikit-learn’s LatentDirichletAllocation(learning_method='online') implements this update (checked in version 1.9.1): learning_offset is τ\tau (default 10), learning_decay is κ\kappa (default 0.7) and batch_size is BB (default 128). fit scales the batch by the true number of documents. partial_fit scales it by the parameter total_samples, whose default is 10610^6; when streaming a corpus of another size, set it to that size, or the intermediate topics are scaled wrongly.

Where it breaks#

The delay τ\tau looks like a detail, and with one point per step it decides whether the fit survives its first step. Run the mixture with B=1B = 1, the basic algorithm of Hoffman et al., for 0.2 passes, 40,000 steps, at κ=0.7\kappa = 0.7 and three delays, from two random seeds:

τ\tauρ1\rho_1Gap after 0.2 passesComponents left empty
01.001.004.74.7 and 2.22.25 and 4 of 8
10.620.620.190.19 and 0.360.361 and 0
100.190.190.00150.0015 and 0.00340.0034none

With τ=0\tau = 0 the first step has ρ1=1\rho_1 = 1 and replaces λ\lambda entirely by the intermediate parameter of one point, counted NN times. In the first step of the run with seed 2, three components move onto that point and the other five, which receive almost no weight, are reset to the prior: mean near 0 and precision near 0.010.01. For such a component Eq∥μk∥2≈D/Pk=200\mathbb E_q \lVert \mu_k \rVert^2 \approx D/P_k = 200, so its responsibility for every point carries a factor of about e−100e^{-100}, and it never receives data again. A larger delay keeps most of the starting means through the first, noisiest steps. Hoffman et al. found their topic models, fitted with batches of 10 to 1000 documents, insensitive to τ\tau; the scikit-learn default, τ=10\tau = 10, is on the safe side.

SVI still needs conditional conjugacy: the natural gradient has the closed form ηˉ−λ\bar\eta - \lambda only when the complete conditional of β\beta is in the family of q(β)q(\beta), and a logistic likelihood or a neural network breaks this. The local step must be cheap: in LDA it is an inner loop per document, and in models with richer local structure it can dominate the cost. And SVI optimizes the same mean-field ELBO, so it inherits what mean field gets wrong: posterior variances that are too small and local optima. It reaches them faster.

Monitoring needs care as well. The full ELBO costs a pass over the data, which defeats the purpose; Hoffman et al. instead tracked the predictive likelihood of 10,000 held-out documents.

What you should remember#

  • With global and local variables, the ELBO is a global term plus one local term per point; each local optimum depends only on its point and λ\lambda.
  • With conditional conjugacy, the natural gradient in λ\lambda is Eϕ[ηg]−λ\mathbb E_\phi[\eta_g] - \lambda; coordinate ascent is the natural-gradient step of length 1.
  • SVI: λ^S=α+(N/B)∑i∈SEϕi[s(xi,zi)]\hat\lambda_S = \alpha + (N/B) \sum_{i \in S} \mathbb E_{\phi_i}[s(x_i, z_i)] is unbiased, and λ←(1−ρt)λ+ρtλ^S\lambda \leftarrow (1 - \rho_t)\lambda + \rho_t \hat\lambda_S.
  • ρt=(t+τ)−κ\rho_t = (t + \tau)^{-\kappa} with κ∈(0.5,1]\kappa \in (0.5, 1] meets Robbins–Monro; λ\lambda remembers about 1/ρt1/\rho_t batches.
  • On 200,000 points, 10−310^{-3} nats per point in 0.08 passes against 6; then a noise floor near 10−410^{-4}.
  • A first step with ρ1=1\rho_1 = 1 and a tiny batch can empty components for good.

Code#

The natural against the ordinary gradient on one Gaussian mean, one SVI step with the numbers of the worked example, the unbiasedness of the intermediate parameter, the experiment, and the failure with B=1B = 1. Seeds are fixed; exact numbers can vary across platforms and library versions. The script runs in about 11 seconds on a laptop CPU, most of it in the 240,000 single-point steps at the end.

import numpy as np

# 1. natural against Euclidean gradient: q(mu) = N(m, s^2) with natural parameters (m / s^2, -1 / (2 s^2)),
#    statistics u(mu) = (mu, mu^2); ten points with mean 2, noise variance 1, prior N(0, 100); start at m = 0, s = 1
lam, eta_bar = np.array([0.0, -0.5]), np.array([10 * 2.0, -(0.01 + 10) / 2])   # eta_bar: the exact posterior
m, s2 = 0.0, 1.0
fisher = np.array([[s2, 2 * m * s2], [2 * m * s2, 2 * s2 ** 2 + 4 * m ** 2 * s2]])   # covariance of (mu, mu^2) under q
natural, euclid = eta_bar - lam, fisher @ (eta_bar - lam)
mean_prec = lambda l: (round(float(l[0] / (-2 * l[1])), 4), round(float(-2 * l[1]), 2))
print(natural, euclid, mean_prec(lam + natural), mean_prec(lam + euclid))
# [20.    -4.505] [20.   -9.01] (1.998, 10.01) (1.0515, 19.02)

# 2. one SVI step for one component, the worked example: N = 200,000, B = 100, prior precision 0.01
N, B, prior_prec = 200_000, 100, 0.01
P, h = 24_000.0, 72_000.0                       # current q(mu_k): precision P and h = P m, so m = 3.0
P_hat, h_hat = prior_prec + N / B * 12.5, N / B * 40.0   # batch: sum of phi_ik = 12.5, sum of phi_ik x_i = 40
rho = (10 + 1) ** -0.7                           # step t = 10, tau = 1, kappa = 0.7
P, h = (1 - rho) * P + rho * P_hat, (1 - rho) * h + rho * h_hat
print(round(rho, 4), round(h_hat / P_hat, 4), round(P, 1), round(h / P, 4))
# 0.1866 3.2 24186.7 3.0386

# 3. data from the Bayesian mixture: K = 8 means in 2-D drawn from N(0, 5^2 I), unit-variance clusters, equal weights
rng = np.random.default_rng(0)
K, D, s0 = 8, 2, 10.0                            # s0: prior standard deviation of each mean, 1 / s0^2 = 0.01
X = rng.normal(0, 5, (K, D))[rng.integers(K, size=N)] + rng.normal(size=(N, D))

# q(mu_k) = N(m_k, I / P_k), stored by h_k = P_k m_k and P_k
def local_step(Xb, h, P):
    """phi_ik proportional to exp(E_q[log p(x_i | mu_k)]): the coordinate update of the local variables."""
    m = h / P[:, None]
    logit = Xb @ m.T - 0.5 * ((m ** 2).sum(1) + D / P)
    phi = np.exp(logit - logit.max(1, keepdims=True))
    return phi / phi.sum(1, keepdims=True)

def elbo(h, P):
    """ELBO per data point, with every phi_i at its optimum for the current global parameters."""
    m, s2 = h / P[:, None], 1 / P
    logit = X @ m.T - 0.5 * ((m ** 2).sum(1) + D * s2)
    mx = logit.max(1)
    data = mx + np.log(np.exp(logit - mx[:, None]).sum(1)) - np.log(K) - 0.5 * (X ** 2).sum(1) - np.log(2 * np.pi)
    glob = -D * np.log(s0) - ((m ** 2).sum(1) + D * s2) / (2 * s0 ** 2) + 0.5 * D * np.log(s2) + 0.5 * D
    return (data.sum() + glob.sum()) / N

def start():                                     # the same start for both methods: K data points as means, precision 1
    return X[np.random.default_rng(1).choice(N, K, replace=False)].copy(), np.ones(K)

# 4. the intermediate global parameter of a mini-batch is unbiased: average it over 2000 batches at a fixed q
h0, P0 = start()
full = 1 / s0 ** 2 + local_step(X, h0, P0).sum(0)
r = np.random.default_rng(5)
est = np.mean([1 / s0 ** 2 + N / B * local_step(X[r.integers(N, size=B)], h0, P0).sum(0) for _ in range(2000)], 0)
print(np.round(full[:4]), np.round(est[:4]))
# [39145. 25268. 51657. 11502.] [39145. 25180. 51951. 11468.]

# 5. batch coordinate ascent: each global update waits for a pass over all N points
h, P = start(); batch = [elbo(h, P)]
for it in range(30):
    phi = local_step(X, h, P)
    P, h = 1 / s0 ** 2 + phi.sum(0), phi.T @ X   # lambda = E_phi[eta_g(x, z)]: a natural-gradient step of length 1
    batch.append(elbo(h, P))
best = batch[-1]

# 6. SVI: mini-batches of B points, rho_t = (t + tau)^(-kappa); the ELBO is recorded every 0.01 pass
def svi(B=100, tau=1.0, kappa=0.7, passes=2.0, seed=2):
    h, P = start(); r = np.random.default_rng(seed); trace = []
    for t in range(1, int(passes * N / B) + 1):
        idx = r.integers(N, size=B)
        phi = local_step(X[idx], h, P)
        P_hat, h_hat = 1 / s0 ** 2 + N / B * phi.sum(0), N / B * phi.T @ X[idx]   # as if the batch were seen N / B times
        rho = (t + tau) ** -kappa
        P, h = (1 - rho) * P + rho * P_hat, (1 - rho) * h + rho * h_hat
        if t % (N // B // 100) == 0:
            trace.append((t * B / N, elbo(h, P)))
    return trace, P

trace, _ = svi()
print('optimum per point %.4f, batch after one pass %.3f, SVI after one pass %.4f, after two %.4f'
      % (best, batch[1], trace[99][1], trace[-1][1]))
for tol in (0.1, 0.01, 0.001):
    b = next(i for i, v in enumerate(batch) if v >= best - tol)
    s = next(p for p, v in trace if v >= best - tol)
    print('gap below %g: batch after %d passes, SVI after %.2f passes' % (tol, b, s))
floor = min(best - v for p, v in trace)
print('smallest SVI gap %.1e; batch goes below it at pass %d' % (floor, next(i for i, v in enumerate(batch) if best - v < floor)))
# optimum per point -4.7142, batch after one pass -5.661, SVI after one pass -4.7145, after two -4.7143
# gap below 0.1: batch after 4 passes, SVI after 0.01 passes
# gap below 0.01: batch after 5 passes, SVI after 0.02 passes
# gap below 0.001: batch after 6 passes, SVI after 0.08 passes
# smallest SVI gap 5.4e-05; batch goes below it at pass 9

# 7. where it breaks: one point per step (B = 1) for 0.2 passes; the delay tau sets the first step rho_1 = (1 + tau)^(-0.7)
for tau in (0, 1, 10):
    gaps, empty = [], []
    for seed in (2, 3):
        trace, P = svi(B=1, tau=tau, passes=0.2, seed=seed)
        gaps.append(best - trace[-1][1]); empty.append(int((P < 1).sum()))   # P_k < 1: almost no data left in component k
    print('tau %2d, rho_1 %.2f: gaps %.2g %.2g, empty components %d %d' % (tau, (1 + tau) ** -0.7, *gaps, *empty))
# tau  0, rho_1 1.00: gaps 4.7 2.2, empty components 5 4
# tau  1, rho_1 0.62: gaps 0.19 0.36, empty components 1 0
# tau 10, rho_1 0.19: gaps 0.0015 0.0034, empty components 0 0

Next#

SVI made each step of variational inference cheap, but it still needs a model in which the complete conditional of every variable is in a known exponential family: only then is the natural gradient ηˉ−λ\bar\eta - \lambda available in closed form. Bayesian logistic regression already breaks this, and a model with a neural network inside breaks it everywhere. The next note estimates the gradient of the ELBO by Monte Carlo for any model whose log joint density can be evaluated, and arrives at the variational autoencoder. Vetrov and Kropotov’s course teaches the two in one lecture, number 12 (references).

References#