14 / 15 · Scalable Inference
Black-box variational inference and the VAE
Variational inference for models without conjugacy: estimate the gradient of the evidence lower bound from samples, keep its variance in check, and arrive at the variational autoencoder.
Stochastic variational inference · Variational inference · The Laplace approximation and Bayesian classification
On this page 7
Eight labelled points and one weight: a logistic regression with and a prior . We want a Gaussian close to the posterior. The evidence lower bound contains , the expectation of a log-sigmoid under a Gaussian, and that integral has no closed form. Coordinate ascent has no update to apply, and stochastic variational inference has no natural gradient , because no complete conditional is in a known exponential family.
The usual ways out are model-specific. The Laplace approximation puts a Gaussian at the mode; a quadratic lower bound on the log-sigmoid (Jaakkola and Jordan, 2000) restores conjugacy for this one likelihood. Every new model needs a new derivation. Can the gradient of the ELBO be obtained from nothing more than the ability to evaluate at a point?
Black-box variational inference (BBVI) of Ranganath, Gerrish and Blei (2014) answers yes. The gradient of the ELBO is itself an expectation under , so it can be estimated from samples of and followed by stochastic gradient ascent.
The score-function gradient#
Let be the variational distribution with parameters , for example for a Gaussian. The ELBO is , where . Both the density and the integrand depend on . Write for and for . Besides the product rule, the derivation needs one identity, the chain rule applied to the logarithm:
This log-derivative identity turns the gradient of a density back into an expectation under that density. Step by step:
The last line uses , since does not depend on . The second expectation vanishes, by the same identity read backwards:
The score has mean zero under , and what remains is
The step marked “exchange” moves a derivative inside an integral. This is allowed when, for all in a neighbourhood, the integrand is differentiable in and its gradient is bounded in norm by one integrable function of (Folland, 1999, Theorem 2.27, a consequence of dominated convergence). The intuition: a difference quotient of the integral is the integral of difference quotients, and the common bound lets the limit pass inside. A Gaussian with a of polynomial growth qualifies. A whose support moves with does not: for the derivative of contains the boundary term , which the score never sees.
The Monte Carlo estimate with samples is
with (Ranganath et al., 2014, equations 2 and 3). It needs samples from , its score and values of ; the model is a black box, and may even be unnormalized. In reinforcement learning the same estimator is REINFORCE (Williams, 1992), with the reward in place of ; the policy gradients note derives it for trajectories and reduces its variance with the same baselines as below. In statistics it is the likelihood-ratio method.
Worked example. Take the gradient of in for at ; the exact value is . Differentiating gives the score in , . With and , one sample gives .
We need moments of . The standard normal density satisfies , so integration by parts gives . Odd moments vanish by symmetry, and . Expanding the square and keeping the even powers,
The variance of one sample is 7.5 times the square of what we are estimating. A million samples in the Code section give mean and variance .
Reducing the variance#
The estimator is unbiased, but a variance of 30 for a quantity of size 2 means hundreds of samples per step for a reliable direction, and real models are much worse. Two generic tools from the Monte Carlo toolbox cut it without model-specific work.
Rao–Blackwellization: drop the terms that cannot matter#
Take a mean-field . The score with respect to , , depends on alone. For any function of the other variables, independence under and the zero mean of the score give
So every term of that does not involve can be deleted from the -th component of the estimator without changing its mean:
where collects the factors of the joint that contain ; they depend only on and its Markov blanket (Ranganath et al., 2014, equation 5). The deleted terms had mean zero and contributed only variance. This is a form of Rao–Blackwellization: the expectation over the irrelevant variables is computed exactly, and it is zero.
Worked example. A non-conjugate model with independent local variables, and , and . For the gradient in , the plain estimator multiplies the score of by all terms of ; the Rao–Blackwellized one keeps only the term of . Single-sample variances from the Code section:
| Plain | Rao–Blackwellized | |
|---|---|---|
| 1 | ||
| 10 | ||
| 100 |
The plain variance grows with the number of irrelevant terms, and the Rao–Blackwellized one stays put. In a model where every variable touches every likelihood term, as in logistic regression, the Markov blanket is everything, and the trick removes only the entropy and prior terms of the other coordinates.
Control variates: subtract a baseline#
A control variate is a function with known mean that is correlated with the estimator. Take . Its mean is , unchanged for every . Its variance expands by the bilinearity of covariance, and setting the derivative in to zero gives the best coefficient:
The variance is a convex parabola in , so this stationary point is its minimum.
BBVI uses the score itself, , whose mean is zero. The corrected component is then : the integrand minus a constant baseline (Ranganath et al., 2014, equations 7 to 9). In practice is estimated from a few of the samples drawn for the gradient.
Why does a constant matter? Shifting by a constant adds to the plain estimator. Its mean, , is zero, so the estimator stays unbiased, but the variance becomes , which for large grows as . For a Gaussian the score in is , with variance , so the penalty for a large grows as concentrates. For the one-weight logistic model of the opening, at the optimum of the ELBO, the optimal baseline lowers the single-sample variance from to .
Ranganath et al. report that on their model of patient records, Rao–Blackwellization lowered the variance by several orders of magnitude and the control variate lowered it further (their Figure 2). Even so, they drew 1000 samples per gradient and set per-coordinate step sizes with AdaGrad.
The reparameterization gradient#
The score-function estimator uses only values of . When is differentiable in , its gradient can be used too, provided the randomness of can be moved out of . A distribution is reparameterizable if there are a differentiable map and a distribution that does not depend on such that , with , has the distribution . For a Gaussian, and .
Since has the distribution , the expectation of any function of can be computed over instead (the change of variables in an expectation). Now sits only inside the integrand, so the derivative moves inside, under the same condition as before but with fixed, and the chain rule finishes:
where and is the Jacobian of the map. The estimate is the gradient of at a sample, carried back to .
For the ELBO the integrand also depends on through . For a Gaussian that part has a closed form. With the dimension of , substituting , so that :
Averaging with , , the entropy of the Gaussian. So
The first term is the case above, with a diagonal Jacobian, and ; the second differentiates to :
with and taken elementwise. The Monte Carlo version averages over draws of :
This is the reparameterization gradient (Kingma and Welling, 2014, Section 2.4; Rezende, Mohamed and Wierstra, 2014; Titsias and Lázaro-Gredilla, 2014). The VAE note introduces the same trick for an encoder; here it is a general-purpose gradient estimator for any differentiable model.
Two unbiased estimators of one gradient
On the toy objective , one sample gives , with variance 4 against the score function’s 30. The reparameterization gradient transports the slope of the integrand at the sample, while the score function has to infer the slope from how the values vary across samples. For a linear integrand the reparameterization gradient in is for every sample, with zero variance; the score-function sample still fluctuates.
The variance in numbers#
The figure computes, by quadrature, the single-sample variance of three estimators of for the one-weight logistic regression of the opening, with held at its optimal value .
Variance of three estimators of the ELBO gradient
At the optimum the plain score function has variance and the reparameterization gradient , 26 times less. The optimal baseline brings the score function down to , below the reparameterization gradient. The reason is exact at the posterior itself. If , then for every
a constant, and with every sample is zero. Near the optimum is almost constant over the bulk of , and a constant is exactly what a baseline removes. The reparameterization gradient has no such zero: still varies with . Away from the optimum the baseline helps less; at the three variances are , and .
Dimension changes the picture. Take Bayesian logistic regression with weights and 200 points, and sum the variances over the components of the -gradient, measured with 20,000 samples. At the start, :
| Score | Score + baseline | Reparameterization | |
|---|---|---|---|
| 2 | |||
| 10 | |||
| 50 |
At a fitted by BBVI:
| Score | Score + baseline | Reparameterization | |
|---|---|---|---|
| 2 | |||
| 10 | |||
| 50 |
The plain score function is 40 to 2000 times worse than the reparameterization gradient at the start, and 7000 to 12,000 times worse at the fitted , where the score has grown with the shrinking . With a baseline it wins at the fitted for and , and loses by a factor of at ; at the start it loses by factors of 4, 15 and 70. The baseline is one number per coordinate and cannot follow how the integrand varies along the other directions. The reparameterization gradient does not need to, because it differentiates.
The algorithm#
- Initialize ; choose a step-size schedule that satisfies the Robbins–Monro conditions, or an adaptive rule such as AdaGrad.
- Draw samples from , or noise vectors for the reparameterization gradient.
- Compute the gradient estimate: the score function with Rao–Blackwellization and a baseline, or the reparameterization gradient.
- Step: , and repeat from step 2.
With global and local variables, step 3 can also subsample the data, scaling the local terms by as SVI does. The estimate is then doubly stochastic (Titsias and Lázaro-Gredilla, 2014): random in the mini-batch and in the samples of . Each source of randomness has its own one-sample rule, in the spirit of the table of stochastic gradients in the lecture notes of the course «Байесовские методы в анализе данных»:
| Objective | Exact gradient | One-sample estimate |
|---|---|---|
| , | ||
| , | ||
| , |
Each row is unbiased. In the first, ; the second exchanges and ; the third is the score-function identity. When the rows are combined, conditioning on the batch and the tower property carry unbiasedness through: the inner expectation gives the exact gradient of the batch term, and the outer one the sum over the data. A batch of indices averages such draws. Titsias and Lázaro-Gredilla’s paper is also the reading for the lecture on non-conjugate variational inference, number 13, in Vetrov and Kropotov’s course. In the Code section, 3000 steps of the reparameterization gradient, with 10 samples each and all 200 points per step, fit the logistic regressions of the tables. Automatic differentiation variational inference (Kucukelbir et al., 2017) packages this route for a whole class of models: it maps every constrained latent variable to the real line, places a Gaussian there and differentiates the log density automatically.
Amortized inference and the VAE#
With one local latent variable per data point, BBVI keeps local variational parameters for every and optimizes them point by point, and again for every new point at test time. Amortized inference replaces this table by a function: an encoder network with weights outputs , and the ELBO is maximized over instead of over the . Inference for a new point then costs one forward pass, and what is learned about inference on some points transfers to the others.
The variational autoencoder is exactly this. For each point it maximizes the ELBO
derived in the VAE note, with three choices that the previous sections explain:
- a mean-field Gaussian and the reparameterization gradient, with one sample per point;
- mini-batches of data points, so the estimate is doubly stochastic;
- decoder parameters fitted by maximizing the same ELBO, in the same gradient steps as .
Kingma and Welling (2014) take mini-batches of 100 points and one sample each (their Algorithm 1). The KL term between two Gaussians is computed in closed form instead of by sampling, which, they note, typically lowers the variance: the same move as Rao–Blackwellization, an expectation computed exactly. Murphy (2023, Section 10.1.5) calls the scheme amortized stochastic variational EM.
Amortization has a price. The ELBO reached by an encoder can be no higher than the one reached by optimizing every separately, because the encoder’s outputs are one particular choice of the . Cremer, Li and Duvenaud (2018) split the gap between and the ELBO into an approximation gap, from the family of , and an amortization gap, from the encoder, and found that the amortization gap is often the larger one. Optimizing the of a test point for a few steps, starting from the encoder’s output, recovers part of it.
Where it breaks#
The two estimators ask for different things. The score function needs a that can be sampled and whose score can be computed, so it works for discrete latent variables, non-differentiable likelihoods and simulators. The reparameterization gradient needs differentiable in and written as a differentiable transform of fixed noise. Kingma and Welling (2014, Section 2.4) list three ways: location-scale families, an inverse CDF, and compositions such as a log-normal from a normal.
A discrete variable has no such transform, and trying anyway gives a wrong answer without an error. Let with , and , so and the true gradient is 1. The natural sampler is with uniform. For every this is a step function of , flat except at one point, so its derivative is 0 almost surely. The score function is computed from :
So its single-sample variance is :
| Estimator | Mean | Single-sample variance |
|---|---|---|
| pathwise, through | ||
| score function, |
The pathwise estimate is confidently wrong: zero variance and the wrong value. Automatic differentiation through a sampled discrete variable does exactly this. Discrete variables need the score function with strong control variates, or a continuous relaxation that trades bias for variance (Mohamed et al., 2020, Sections 4, 5 and 7, review the options).
Variance remains the bottleneck for everything else. Step sizes must suit the noisiest coordinate, the Monte Carlo ELBO used for monitoring is noisy too, and a stalled objective may only mean that the steps are too small. The family of is still the limit: a mean-field Gaussian cannot represent correlations or several modes, and BBVI makes richer families usable, such as full-covariance Gaussians or normalizing flows, without choosing them.
What you should remember#
- Score function: ; it needs only samples of and values of .
- Rao–Blackwellization drops the terms outside the Markov blanket; a baseline subtracts a constant. Both stay unbiased.
- Reparameterization: , average . Variance 4 against 30 on ; the gap grows with dimension.
- Mini-batches make the estimate doubly stochastic and still unbiased.
- VAE = BBVI + reparameterization + an encoder for the local parameters + a decoder fitted by the same ELBO.
- Through a discrete sample the pathwise gradient is zero and wrong.
Code#
The toy gradient of the worked example, the three estimators on the one-weight logistic model of the figure, the comparison across dimensions, Rao–Blackwellization on a model with independent local variables, and the discrete failure. NumPy and SciPy; seeds are fixed, and exact numbers can vary slightly across platforms and library versions. The script runs in about 2 seconds.
import numpy as np
from scipy.optimize import minimize
from scipy.special import gammaln
LOG2PI = np.log(2 * np.pi)
# 1. the toy objective E_q[z^2] with q = N(mu, sigma^2) at mu = sigma = 1: true gradient in mu is 2 mu = 2
rng = np.random.default_rng(0)
eps = rng.normal(size=1_000_000); mu, sigma = 1.0, 1.0
z = mu + sigma * eps
g_score = (z - mu) / sigma ** 2 * z ** 2 # score times the function value
g_reparam = 2 * z * 1.0 # derivative of the function times dz/dmu = 1
print(g_score.mean().round(3), g_score.var().round(2), g_reparam.mean().round(3), g_reparam.var().round(2))
# 2.005 30.12 2.002 4.01 (exact: 2, 30 and 2, 4)
# 2. one weight, eight points: logistic likelihood, prior N(0, 1), q = N(mu, sigma^2); variances by quadrature
x1 = np.array([-2, -1.5, -1, -0.5, 0.5, 1, 1.5, 2.0]); y1 = np.array([0, 0, 1, 0, 1, 0, 1, 1.0])
e = np.linspace(-9, 9, 6001); we = np.exp(-e ** 2 / 2); we /= we.sum() # weights of a standard normal grid
logjoint1 = lambda w: (y1 * np.outer(w, x1) - np.logaddexp(0, np.outer(w, x1))).sum(1) - w ** 2 / 2 - LOG2PI / 2
dlogjoint1 = lambda w: ((y1 - 1 / (1 + np.exp(-np.outer(w, x1)))) * x1).sum(1) - w
def elbo1(p):
w = p[0] + np.exp(p[1]) * e
return (we * (logjoint1(w) + e ** 2 / 2 + p[1] + LOG2PI / 2)).sum() # E[log p] - E[log q]
opt = minimize(lambda p: -elbo1(p), [0.0, 0.0]).x; mu1, sg1 = opt[0], np.exp(opt[1])
def variances1(mu, sg):
w = mu + sg * e; f = logjoint1(w) + e ** 2 / 2 + np.log(sg) + LOG2PI / 2 # log p(x, w) - log q(w)
h = e / sg # score of q with respect to mu
a = (we * h * f * h).sum() / (we * h * h).sum() # optimal constant a* = Cov(h f, h) / Var(h)
var = lambda g: (we * g * g).sum() - (we * g).sum() ** 2
return var(h * f), var(h * (f - a)), var(dlogjoint1(w))
print(round(mu1, 3), round(sg1, 3), [round(float(v), 2) for v in variances1(mu1, sg1)], [round(float(v), 2) for v in variances1(-1.0, sg1)])
# 0.76 0.535 [94.68, 0.2, 3.6] [523.15, 86.1, 2.87]
# 3. Bayesian logistic regression with d weights, 200 points; mean-field q; single-sample variance of the mu-gradient
def make(d, n=200, seed=0):
r = np.random.default_rng(seed); X = r.normal(size=(n, d)); w_true = 3 * r.normal(size=d) / np.sqrt(d)
return X, (r.random(n) < 1 / (1 + np.exp(-X @ w_true))).astype(float)
def logjoint(W, X, y):
s = W @ X.T
return (y * s - np.logaddexp(0, s)).sum(1) - 0.5 * (W ** 2).sum(1) - 0.5 * W.shape[1] * LOG2PI
def grad_logjoint(W, X, y):
return (y - 1 / (1 + np.exp(-W @ X.T))) @ X - W
def fit(X, y, steps=3000, seed=1): # BBVI with the reparameterization gradient, 10 samples per step
d = X.shape[1]; m, log_s = np.zeros(d), np.zeros(d); r = np.random.default_rng(seed)
for t in range(steps):
E = r.normal(size=(10, d)); s = np.exp(log_s); G = grad_logjoint(m + s * E, X, y)
lr = 0.01 / (1 + t / 500)
m += lr * G.mean(0); log_s += lr * ((G * E * s).mean(0) + 1) # +1: gradient of the entropy in log sigma
return m, np.exp(log_s)
def variances(X, y, m, s, S=20_000, seed=3):
E = np.random.default_rng(seed).normal(size=(S, len(m))); W = m + s * E
f = logjoint(W, X, y) - (-0.5 * E ** 2 - np.log(s) - 0.5 * LOG2PI).sum(1) # log p(x, w) - log q(w)
H = E / s # score with respect to each mu_j
G_score = H * f[:, None]
a = ((G_score - G_score.mean(0)) * H).mean(0) / (H * H).mean(0) # one control-variate weight per mu_j
G_cv = G_score - a * H
G_rep = grad_logjoint(W, X, y) # log q(m + s e) does not depend on m, so only log p contributes
return [G.var(0).sum() for G in (G_score, G_cv, G_rep)]
for d in (2, 10, 50):
X, y = make(d)
v0 = variances(X, y, np.zeros(d), np.ones(d))
v1 = variances(X, y, *fit(X, y))
print(d, ['%.3g' % v for v in v0], ['%.3g' % v for v in v1])
# 2 ['9.49e+04', '9.48e+03', '2.24e+03'] ['8.23e+05', '16.7', '67.8']
# 10 ['1.03e+06', '8.39e+04', '5.44e+03'] ['1.85e+06', '188', '259']
# 50 ['1.79e+07', '6.24e+05', '8.96e+03'] ['7.02e+06', '6.64e+03', '886']
# 4. Rao-Blackwellization: n independent local variables, z_i ~ N(0, 1), x_i ~ Poisson(exp(z_i)), q(z_i) = N(0, 0.5^2)
r = np.random.default_rng(4); xp = r.poisson(np.exp(r.normal(size=100))); E = r.normal(size=(20_000, 100)); s = 0.5
Z = s * E # samples of q; log p and log q are sums of one term per i
terms = xp * Z - np.exp(Z) - gammaln(xp + 1) - 0.5 * Z ** 2 - 0.5 * LOG2PI - (-0.5 * E ** 2 - np.log(s) - 0.5 * LOG2PI)
h1 = E[:, 0] / s # score with respect to mu_1
for n in (1, 10, 100):
print(n, round(float((h1 * terms[:, :n].sum(1)).var()), 1), round(float((h1 * terms[:, 0]).var()), 1))
# 1 8.2 8.2
# 10 1920.7 8.2
# 100 374010.7 8.2
# 5. where it breaks: a discrete z ~ Bernoulli(theta), f(z) = z, so E_q[f] = theta and the true gradient is 1
theta, u = 0.3, np.random.default_rng(6).random(1_000_000)
z = (u < theta).astype(float) # z = [u < theta]: a step in theta, derivative 0 almost everywhere
g_score = z * (z / theta - (1 - z) / (1 - theta)) # f(z) times the score d/dtheta log q(z)
print(round(g_score.mean(), 3), round(g_score.var(), 2), round(1 / theta - 1, 2)) # the pathwise estimate is 0
# 1.0 2.33 2.33
Next#
BBVI turns posterior inference for any differentiable model into stochastic optimization, and the VAE applies it to latent variables with a neural network as the likelihood. The last note of the course turns the setting around: the unknowns become the weights of the network itself. The next note asks what a posterior over millions of weights buys, and compares the reparameterization route, Bayes by Backprop, with the cheaper approximations used in practice: MC dropout, deep ensembles and the Laplace approximation.
References#
- R. Ranganath, S. Gerrish, D. M. Blei. Black box variational inference. AISTATS, 2014. Section 2 (the score-function gradient, equations 2 and 3), Section 3.1 (Rao–Blackwellization, equation 5), Section 3.2 (control variates, equations 7 to 9), Section 4 (AdaGrad, subsampling), Figure 2.
- G. B. Folland. Real Analysis: Modern Techniques and Their Applications, 2nd ed. Wiley, 1999. Theorem 2.27 (differentiation under the integral sign).
- «Байесовские методы в анализе данных», lecture notes, 2026. Lecture 6: the table of stochastic gradients, REINFORCE and the reparameterization trick.
- R. J. Williams. Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine Learning, 8:229–256, 1992.
- D. P. Kingma, M. Welling. Auto-encoding variational Bayes. ICLR, 2014. Section 2.3 (the SGVB estimators and Algorithm 1), Section 2.4 (the reparameterization trick).
- D. J. Rezende, S. Mohamed, D. Wierstra. Stochastic backpropagation and approximate inference in deep generative models. ICML, 2014.
- M. Titsias, M. Lázaro-Gredilla. Doubly stochastic variational Bayes for non-conjugate inference. ICML, 2014.
- A. Kucukelbir, D. Tran, R. Ranganath, A. Gelman, D. M. Blei. Automatic differentiation variational inference. Journal of Machine Learning Research, 18(14):1–45, 2017.
- S. Mohamed, M. Rosca, M. Figurnov, A. Mnih. Monte Carlo gradient estimation in machine learning. Journal of Machine Learning Research, 21(132):1–62, 2020. Sections 4 and 5 (score-function and pathwise estimators), Section 7 (variance reduction).
- C. Cremer, X. Li, D. Duvenaud. Inference suboptimality in variational autoencoders. ICML, 2018.
- T. S. Jaakkola, M. I. Jordan. Bayesian parameter estimation via variational methods. Statistics and Computing, 10:25–37, 2000.
- K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. Section 10.1.5 (amortized VI), Section 10.2 (gradient-based VI, including black-box VI).
- Д. П. Ветров, Д. А. Кропотов. Байесовские методы машинного обучения, course of lectures, Moscow State University, 2015. Lecture 12 (the variational autoencoder, from Kingma and Welling, 2014) and lecture 13 (non-conjugate variational inference, from Titsias and Lázaro-Gredilla, 2014).