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.
Variational inference · Latent Dirichlet allocation · Conjugate priors and the exponential family · Stochastic gradient descent
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 is shared by all data points: the means of a mixture, the topics of LDA. A local latent variable belongs to one data point : its cluster, or a document’s topic proportions and word assignments. The joint density is
The mean-field family is , with a global variational parameter and local ones . Under it the ELBO separates into a global term and a sum of local terms:
The -th local term involves only , and . So for a fixed each can be optimized on its own, and its optimum depends on nothing else. What remains is a function of the global parameter alone, , and this is the objective SVI climbs. Its gradient is the partial gradient of at . By the chain rule, assuming the optimum is differentiable in ,
because at an optimum in . This is the envelope theorem.
The second ingredient is conjugacy. In the models of this course the complete conditional of , its distribution given everything else, is in an exponential family whose natural parameter is the prior’s plus one term per data point:
Here is the sufficient statistic, the log-normalizer, the natural parameter of the prior and the statistics one point contributes. The global factor is taken from the same family, with natural parameter , and the mean-field update of the variational inference note sets it to the expected natural parameter, .
The running example: a Bayesian mixture#
The mixture of Blei, Kucukelbir and McAuliffe (2017), Section 3, has means in , an assignment uniform over , and . The family is , with mean and precision , and . Coordinate ascent alternates two updates:
Both follow from the mean-field rule of the variational inference note. The local update is the expected log likelihood of the point under component , and the global update is the conjugate posterior of in which point counts with weight .
Derivation of the two updates
For the label, only the likelihood term of point depends on , and the uniform prior adds a constant:
The second line drops and the term, which do not involve . The third uses that a second moment is the squared mean plus the variance, here summed over coordinates of variance . For a mean, each label contributes the term of component with probability :
A quadratic in with coefficient is the log density of a Gaussian with precision ; completing the square puts its mean at with .
In the coordinates , a linear transform of the natural parameters, the prior contributes and point contributes to component .
The natural gradient of the ELBO#
Fix the local parameters and look at as a function of . Only the terms with matter, and , where the second term does not involve . Write for the expected natural parameter of the complete conditional. Substituting both exponential-family densities, the base measures cancel, and
The second line substitutes the two densities. Mean field makes and independent, so , and the term depends on but not on and joins the constant. The third line uses , since has natural parameter ; the conjugate priors note derives it by differentiating the normalization of the density. Differentiating by the product rule,
This is equation 14 of Hoffman et al. (2013). The factor is the covariance of under , and it is also the Fisher information of :
The first line is the definition. The second differentiates , which gives . The third is the identity of the same section on the log-partition function.
The natural gradient (Amari, 1998) premultiplies the gradient by , and the factor cancels:
(Hoffman et al., equation 22). The inverse exists when no linear combination of the statistics is constant under , as in the minimal families used here: then the covariance is positive definite. A natural-gradient step of length moves to , and with it lands on , 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 with prior , and ten points with average 2 and noise variance 1. The factor has statistics and natural parameters . The complete conditional is the exact posterior, with precision and natural parameter . We start at , :
| Quantity | Value |
|---|---|
| start | |
| natural gradient | |
| Fisher information: the covariance of under | |
| ordinary gradient | |
| after a step of 1 along the natural gradient | mean , precision |
| after a step of 1 along the ordinary gradient | mean , precision |
The Fisher information is the covariance of under : , and . The ordinary gradient is . A step of 1 along it gives , so precision and mean .
The natural step lands on the posterior. The ordinary gradient points elsewhere, and since is not a multiple of , 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 . That length says little about how much the distribution changes. For two normals with the same variance and means and , averaging the difference of the log densities over gives
Moving the mean of by 1 gives a distribution that is hard to tell from the first, with a KL divergence of . Moving the mean of 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, . Averaging over , with , leaves the remainder of a Taylor expansion of , so the KL divergence is
The linear term cancels because the score has mean zero, and the quadratic term is the Fisher information. Maximizing the linear change subject to with a Lagrange multiplier gives the stationarity condition , so .
So the natural gradient is the steepest ascent per unit of KL divergence. It also does not depend on how is parameterized. Write with an invertible Jacobian . By the chain rule , and the same rule inside the definition of gives . The natural step in , mapped back to , is
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 , and . 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, against .
Mini-batches: a noisy natural gradient#
The natural gradient still needs , a sum over all points. Draw one index uniformly from and replace the sum by copies of its -th term. Since
the result is an unbiased estimate of . A batch drawn without replacement is unbiased too: each point enters it with probability , which the factor below cancels. It is exactly the coordinate-ascent update for a data set made of copies of (Hoffman et al., Section 2.4). Averaging such draws gives the intermediate global parameter of a mini-batch , and the SVI update blends it into the current value:
Here is the local optimum for the current , computed only for the points of the batch, and is an unbiased estimate of the natural gradient. One step costs local updates instead of . Murphy (2023, Section 10.1.4) writes the same idea as stochastic gradient ascent on the ELBO of a mini-batch scaled by .
One step of stochastic variational inference
Worked example. One component of the mixture, first coordinate of its mean, with , and prior precision . The current has precision and mean , so . In the batch, the responsibilities of component sum to and . The step is , with :
The intermediate mean is . The blend acts on natural parameters, so the mean does not move exactly a fraction of the way from to , which would give . The Code section also checks that is unbiased: averaged over 2000 batches at a fixed , its precisions agree with the full-data ones to within .
With and , multiplying the update by gives . So is the running sum of the , the start dropping out at , and
the plain average of all intermediate estimates. Other schedules weight recent estimates more. That helps, because the early were computed from local steps under a poor .
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
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 is bounded above with a Lipschitz-continuous gradient, the noisy step is unbiased for with the eigenvalues of bounded above and away from zero, and the variance of the noise grows at most like . Then steps meeting both conditions give (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:
The first sum diverges because ; the second converges because . Both are the -series test: converges exactly when , and the shift does not change that. Hoffman et al. call the forgetting rate and the delay, which damps the first steps.
With and , the schedule of the experiment below:
| Step | about batches remembered | |
|---|---|---|
| 10 | 5 | |
| 1000 | 126 | |
| 4000 | 330 |
Over a stretch where barely changes, unrolling the update, and ignoring the start, gives
The newest batches carry the total weight , since as . In this sense remembers roughly the last 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 , an average of independent draws, falls like while the cost of a step grows like .
On their topic models, Hoffman et al. fixed , after finding the results insensitive to it, and tried from to and batches of 10 to 1000 documents. Forgetting rates near 1 and larger batches did best; their large-scale comparisons use and 500 documents per batch.
An experiment: SVI against batch coordinate ascent#
Both methods fit the mixture above with components in dimensions, true means drawn from , points and prior . Both start from the same randomly chosen data points as means, with precision 1. Batch coordinate ascent runs 30 passes. SVI uses , and for two passes, 4000 steps.
The gap is the ELBO per point of the batch method after 30 passes, , minus the current ELBO per point, computed on all the data with every at its optimum. A pass means points processed by the local step, the dominant cost of both methods.
| Gap below | Batch, passes | SVI, passes |
|---|---|---|
| 4 | 0.01 | |
| 5 | 0.02 | |
| 6 | 0.08 | |
| smallest gap | after 12 passes | in 2 passes |
Passes over the data needed to reach a given ELBO
SVI needs 250 times fewer points than the batch method to get within , and 75 times fewer to get within . Both end at the same optimum. The last row is the other side of the trade: below about 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 documents, the global variables are the topics, with Dirichlet variational parameters and prior ; 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 and , run until it converges. The intermediate topics of a batch are
the expected number of times word is assigned to topic 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 (default 10), learning_decay is (default 0.7) and batch_size is (default 128). fit scales the batch by the true number of documents. partial_fit scales it by the parameter total_samples, whose default is ; when streaming a corpus of another size, set it to that size, or the intermediate topics are scaled wrongly.
Where it breaks#
The delay looks like a detail, and with one point per step it decides whether the fit survives its first step. Run the mixture with , the basic algorithm of Hoffman et al., for 0.2 passes, 40,000 steps, at and three delays, from two random seeds:
| Gap after 0.2 passes | Components left empty | ||
|---|---|---|---|
| 0 | and | 5 and 4 of 8 | |
| 1 | and | 1 and 0 | |
| 10 | and | none |
With the first step has and replaces entirely by the intermediate parameter of one point, counted 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 . For such a component , so its responsibility for every point carries a factor of about , 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 ; the scikit-learn default, , is on the safe side.
SVI still needs conditional conjugacy: the natural gradient has the closed form only when the complete conditional of is in the family of , 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 .
- With conditional conjugacy, the natural gradient in is ; coordinate ascent is the natural-gradient step of length 1.
- SVI: is unbiased, and .
- with meets Robbins–Monro; remembers about batches.
- On 200,000 points, nats per point in 0.08 passes against 6; then a noise floor near .
- A first step with 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 . 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 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#
- M. D. Hoffman, D. M. Blei, C. Wang, J. Paisley. Stochastic variational inference. Journal of Machine Learning Research, 14:1303–1347, 2013. Section 2.3 (the natural gradient, equations 14 and 22), Section 2.4 (the noisy natural gradient, Figure 4, the schedule of equation 26), Section 4 (LDA and HDP on large corpora, Figures 7 and 11–15).
- M. D. Hoffman, D. M. Blei, F. Bach. Online learning for latent Dirichlet allocation. NeurIPS, 2010.
- 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. Section 3 (the Bayesian mixture of Gaussians).
- M.-A. Sato. Online model selection based on the variational Bayes. Neural Computation, 13(7):1649–1681, 2001.
- S. Amari. Natural gradient works efficiently in learning. Neural Computation, 10(2):251–276, 1998.
- L. Bottou, F. E. Curtis, J. Nocedal. Optimization methods for large-scale machine learning. SIAM Review, 60(2):223–311, 2018. Section 4.3, Theorem 4.10 (nonconvex objective, diminishing step sizes).
- H. Robbins, S. Monro. A stochastic approximation method. Annals of Mathematical Statistics, 22(3):400–407, 1951.
- K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. Section 10.1.4 (stochastic VI).
- Д. П. Ветров, Д. А. Кропотов. Байесовские методы машинного обучения, course of lectures, Moscow State University, 2015. Lecture 12 (stochastic variational inference and the variational autoencoder), taught from Hoffman et al. (2013) and Kingma and Welling (2014).