Course contents 14 / 15

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.

On this page 7

Eight labelled points and one weight: a logistic regression with p(yi=1∣w)=1/(1+e−wxi)p(y_i = 1 \mid w) = 1/(1 + e^{-w x_i}) and a prior w∼N(0,1)w \sim \mathcal N(0, 1). We want a Gaussian q(w)=N(μ,σ2)q(w) = \mathcal N(\mu, \sigma^2) close to the posterior. The evidence lower bound contains Eq[log⁡(1+e−wxi)]\mathbb E_q[\log(1 + e^{-w x_i})], 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 Eϕ[ηg]−λ\mathbb E_\phi[\eta_g] - \lambda, 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 log⁡p(x,z)\log p(x, z) 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 qq, so it can be estimated from samples of qq and followed by stochastic gradient ascent.

The score-function gradient#

Let q(z∣λ)q(z \mid \lambda) be the variational distribution with parameters λ\lambda, for example λ=(μ,σ)\lambda = (\mu, \sigma) for a Gaussian. The ELBO is L(λ)=Eq[fλ(z)]\mathcal L(\lambda) = \mathbb E_q[f_\lambda(z)], where fλ(z)=log⁡p(x,z)−log⁡q(z∣λ)f_\lambda(z) = \log p(x, z) - \log q(z \mid \lambda). Both the density and the integrand depend on λ\lambda. Write qq for q(z∣λ)q(z \mid \lambda) and ff for fλ(z)f_\lambda(z). Besides the product rule, the derivation needs one identity, the chain rule applied to the logarithm:

∇λlog⁡q=∇λqq  ⟹  ∇λq=q ∇λlog⁡q.\nabla_\lambda \log q = \frac{\nabla_\lambda q}{q} \;\Longrightarrow\; \nabla_\lambda q = q\, \nabla_\lambda \log q .

This log-derivative identity turns the gradient of a density back into an expectation under that density. Step by step:

∇λL=∇λ∫q f dz=∫∇λ(q f) dz(exchange)=∫(∇λq) f dz+∫q ∇λf dz(product)=∫q (∇λlog⁡q) f dz+∫q ∇λf dz(log-derivative)=Eq[∇λlog⁡q  f]−Eq[∇λlog⁡q].\begin{aligned} \nabla_\lambda \mathcal L &= \nabla_\lambda \int q\, f \, dz \\ &= \int \nabla_\lambda (q\, f) \, dz \quad \text{(exchange)} \\ &= \int (\nabla_\lambda q)\, f \, dz + \int q\, \nabla_\lambda f \, dz \quad \text{(product)} \\ &= \int q\, (\nabla_\lambda \log q)\, f \, dz + \int q\, \nabla_\lambda f \, dz \quad \text{(log-derivative)} \\ &= \mathbb E_q\big[\nabla_\lambda \log q\; f\big] - \mathbb E_q\big[\nabla_\lambda \log q\big] . \end{aligned}

The last line uses ∇λf=−∇λlog⁡q\nabla_\lambda f = -\nabla_\lambda \log q, since log⁡p(x,z)\log p(x, z) does not depend on λ\lambda. The second expectation vanishes, by the same identity read backwards:

Eq[∇λlog⁡q]=∫q ∇λqq dz=∇λ∫q dz=∇λ1=0.\begin{aligned} \mathbb E_q\big[\nabla_\lambda \log q\big] &= \int q\, \frac{\nabla_\lambda q}{q} \, dz \\ &= \nabla_\lambda \int q \, dz \\ &= \nabla_\lambda 1 = 0 . \end{aligned}

The score ∇λlog⁡q\nabla_\lambda \log q has mean zero under qq, and what remains is

∇λL=Eq[∇λlog⁡q(z∣λ) (log⁡p(x,z)−log⁡q(z∣λ))].\nabla_\lambda \mathcal L = \mathbb E_q\big[\nabla_\lambda \log q(z \mid \lambda)\, \big(\log p(x, z) - \log q(z \mid \lambda)\big)\big] .

The step marked “exchange” moves a derivative inside an integral. This is allowed when, for all λ\lambda in a neighbourhood, the integrand is differentiable in λ\lambda and its gradient is bounded in norm by one integrable function of zz (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 qq with a log⁡p\log p of polynomial growth qualifies. A qq whose support moves with λ\lambda does not: for q=Uniform(0,λ)q = \mathrm{Uniform}(0, \lambda) the derivative of 1λ∫0λf dz\frac1\lambda \int_0^\lambda f\, dz contains the boundary term f(λ)/λf(\lambda)/\lambda, which the score −1/λ-1/\lambda never sees.

The Monte Carlo estimate with SS samples is

∇^λL=1S∑s=1S∇λlog⁡q(zs∣λ) fλ(zs),zs∼q(z∣λ)\boxed{ \begin{aligned} \hat\nabla_\lambda \mathcal L &= \frac1S \sum_{s=1}^S \nabla_\lambda \log q(z_s \mid \lambda)\, f_\lambda(z_s), \\ z_s &\sim q(z \mid \lambda) \end{aligned} }

with fλ(zs)=log⁡p(x,zs)−log⁡q(zs∣λ)f_\lambda(z_s) = \log p(x, z_s) - \log q(z_s \mid \lambda) (Ranganath et al., 2014, equations 2 and 3). It needs samples from qq, its score and values of log⁡p\log p; the model is a black box, and pp may even be unnormalized. In reinforcement learning the same estimator is REINFORCE (Williams, 1992), with the reward in place of ff; 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 Eq[z2]\mathbb E_q[z^2] in μ\mu for q=N(μ,σ2)q = \mathcal N(\mu, \sigma^2) at μ=σ=1\mu = \sigma = 1; the exact value is 2μ=22\mu = 2. Differentiating log⁡N(z∣μ,σ2)=−(z−μ)2/(2σ2)+const\log \mathcal N(z \mid \mu, \sigma^2) = -(z - \mu)^2/(2\sigma^2) + \text{const} gives the score in μ\mu, (z−μ)/σ2(z - \mu)/\sigma^2. With z=1+εz = 1 + \varepsilon and ε∼N(0,1)\varepsilon \sim \mathcal N(0, 1), one sample gives g=ε(1+ε)2g = \varepsilon (1 + \varepsilon)^2.

We need moments of ε\varepsilon. The standard normal density φ\varphi satisfies φ′(ε)=−ε φ(ε)\varphi'(\varepsilon) = -\varepsilon\, \varphi(\varepsilon), so integration by parts gives E[εm+1]=m E[εm−1]\mathbb E[\varepsilon^{m+1}] = m\, \mathbb E[\varepsilon^{m-1}]. Odd moments vanish by symmetry, Eε4=3 Eε2=3\mathbb E\varepsilon^4 = 3\, \mathbb E\varepsilon^2 = 3 and Eε6=5 Eε4=15\mathbb E\varepsilon^6 = 5\, \mathbb E\varepsilon^4 = 15. Expanding the square and keeping the even powers,

g=ε+2ε2+ε3,E[g]=0+2+0=2,g2=ε2+4ε3+6ε4+4ε5+ε6,E[g2]=1+0+18+0+15=34,Var⁡(g)=34−22=30.\begin{aligned} g &= \varepsilon + 2\varepsilon^2 + \varepsilon^3, \\ \mathbb E[g] &= 0 + 2 + 0 = 2, \\ g^2 &= \varepsilon^2 + 4\varepsilon^3 + 6\varepsilon^4 + 4\varepsilon^5 + \varepsilon^6, \\ \mathbb E[g^2] &= 1 + 0 + 18 + 0 + 15 = 34, \\ \operatorname{Var}(g) &= 34 - 2^2 = 30 . \end{aligned}

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 2.0052.005 and variance 30.130.1.

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 q=∏jq(zj∣λj)q = \prod_j q(z_j \mid \lambda_j). The score with respect to λj\lambda_j, hj(zj)=∇λjlog⁡q(zj∣λj)h_j(z_j) = \nabla_{\lambda_j} \log q(z_j \mid \lambda_j), depends on zjz_j alone. For any function gg of the other variables, independence under qq and the zero mean of the score give

Eq[hj(zj) g(z−j)]=E[hj(zj)] E[g(z−j)]=0.\mathbb E_q\big[h_j(z_j)\, g(z_{-j})\big] = \mathbb E\big[h_j(z_j)\big]\, \mathbb E\big[g(z_{-j})\big] = 0 .

So every term of log⁡p(x,z)−log⁡q(z)\log p(x, z) - \log q(z) that does not involve zjz_j can be deleted from the jj-th component of the estimator without changing its mean:

∇λjL=Eq[hj(zj) (log⁡pj(x,z(j))−log⁡q(zj∣λj))],\nabla_{\lambda_j} \mathcal L = \mathbb E_q\Big[h_j(z_j)\, \big(\log p_j(x, z_{(j)}) - \log q(z_j \mid \lambda_j)\big)\Big],

where log⁡pj\log p_j collects the factors of the joint that contain zjz_j; they depend only on zjz_j and its Markov blanket z(j)z_{(j)} (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 nn independent local variables, zi∼N(0,1)z_i \sim \mathcal N(0, 1) and xi∼Poisson⁡(ezi)x_i \sim \operatorname{Poisson}(e^{z_i}), and q(zi)=N(0,0.52)q(z_i) = \mathcal N(0, 0.5^2). For the gradient in μ1\mu_1, the plain estimator multiplies the score of z1z_1 by all nn terms of log⁡p−log⁡q\log p - \log q; the Rao–Blackwellized one keeps only the term of z1z_1. Single-sample variances from the Code section:

nnPlainRao–Blackwellized
18.28.28.28.2
10192119218.28.2
100374,011374{,}0118.28.2

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 c(z)c(z) with known mean that is correlated with the estimator. Take g^(z)=g(z)−a (c(z)−E[c])\hat g(z) = g(z) - a\,(c(z) - \mathbb E[c]). Its mean is E[g]−a(E[c]−E[c])=E[g]\mathbb E[g] - a(\mathbb E[c] - \mathbb E[c]) = \mathbb E[g], unchanged for every aa. Its variance expands by the bilinearity of covariance, and setting the derivative in aa to zero gives the best coefficient:

Var⁡(g^)=Var⁡(g)+a2Var⁡(c)−2aCov⁡(g,c),ddaVar⁡(g^)=2aVar⁡(c)−2Cov⁡(g,c)=0,a∗=Cov⁡(g,c)Var⁡(c).\begin{aligned} \operatorname{Var}(\hat g) &= \operatorname{Var}(g) + a^2 \operatorname{Var}(c) - 2a \operatorname{Cov}(g, c), \\ \frac{d}{da} \operatorname{Var}(\hat g) &= 2a \operatorname{Var}(c) - 2 \operatorname{Cov}(g, c) = 0, \\ a^* &= \frac{\operatorname{Cov}(g, c)}{\operatorname{Var}(c)} . \end{aligned}

The variance is a convex parabola in aa, so this stationary point is its minimum.

BBVI uses the score itself, c=hjc = h_j, whose mean is zero. The corrected component is then hj(z)(f(z)−aj)h_j(z)\big(f(z) - a_j\big): the integrand minus a constant baseline aja_j (Ranganath et al., 2014, equations 7 to 9). In practice aja_j is estimated from a few of the samples drawn for the gradient.

Why does a constant matter? Shifting log⁡p\log p by a constant cc adds c hj(z)c\, h_j(z) to the plain estimator. Its mean, c E[hj]c\, \mathbb E[h_j], is zero, so the estimator stays unbiased, but the variance becomes Var⁡(hjf)+2cCov⁡(hjf,hj)+c2Var⁡(hj)\operatorname{Var}(h_j f) + 2c \operatorname{Cov}(h_j f, h_j) + c^2 \operatorname{Var}(h_j), which for large ∣c∣\lvert c \rvert grows as c2Var⁡(hj)c^2 \operatorname{Var}(h_j). For a Gaussian qq the score in μj\mu_j is (zj−μj)/σj2=εj/σj(z_j - \mu_j)/\sigma_j^2 = \varepsilon_j/\sigma_j, with variance 1/σj21/\sigma_j^2, so the penalty for a large ∣log⁡p∣\lvert \log p \rvert grows as qq 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 94.794.7 to 0.200.20.

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 log⁡p\log p. When log⁡p(x,z)\log p(x, z) is differentiable in zz, its gradient can be used too, provided the randomness of qq can be moved out of λ\lambda. A distribution q(z∣λ)q(z \mid \lambda) is reparameterizable if there are a differentiable map t(λ,ε)t(\lambda, \varepsilon) and a distribution r(ε)r(\varepsilon) that does not depend on λ\lambda such that z=t(λ,ε)z = t(\lambda, \varepsilon), with ε∼r\varepsilon \sim r, has the distribution q(z∣λ)q(z \mid \lambda). For a Gaussian, t=μ+σ⊙εt = \mu + \sigma \odot \varepsilon and r=N(0,I)r = \mathcal N(0, I).

Since z=t(λ,ε)z = t(\lambda, \varepsilon) has the distribution qq, the expectation of any function ℓ\ell of zz can be computed over ε\varepsilon instead (the change of variables in an expectation). Now λ\lambda sits only inside the integrand, so the derivative moves inside, under the same condition as before but with rr fixed, and the chain rule finishes:

∇λEq[ℓ(z)]=∇λEr[ℓ(t(λ,ε))]=Er[∇λℓ(t(λ,ε))](exchange)=Er[Jλ⊤ ∇zℓ(z)](chain rule),\begin{aligned} \nabla_\lambda \mathbb E_{q}\big[\ell(z)\big] &= \nabla_\lambda \mathbb E_{r}\big[\ell(t(\lambda, \varepsilon))\big] \\ &= \mathbb E_{r}\big[\nabla_\lambda \ell(t(\lambda, \varepsilon))\big] \quad \text{(exchange)} \\ &= \mathbb E_{r}\big[J_\lambda^\top\, \nabla_z \ell(z)\big] \quad \text{(chain rule)}, \end{aligned}

where z=t(λ,ε)z = t(\lambda, \varepsilon) and Jλ=∂t/∂λJ_\lambda = \partial t/\partial \lambda is the Jacobian of the map. The estimate is the gradient of ℓ\ell at a sample, carried back to λ\lambda.

For the ELBO the integrand fλ=log⁡p−log⁡qf_\lambda = \log p - \log q also depends on λ\lambda through log⁡q\log q. For a Gaussian that part has a closed form. With DD the dimension of zz, substituting zj=μj+σjεjz_j = \mu_j + \sigma_j \varepsilon_j, so that (zj−μj)/σj=εj(z_j - \mu_j)/\sigma_j = \varepsilon_j:

log⁡q(z∣μ,σ)=−∑j=1D((zj−μj)22σj2+log⁡σj)−D2log⁡2π=−∑j=1D(12εj2+log⁡σj)−D2log⁡2π.\begin{aligned} \log q(z \mid \mu, \sigma) &= -\sum_{j=1}^D \Big(\frac{(z_j - \mu_j)^2}{2\sigma_j^2} + \log \sigma_j\Big) - \tfrac D2 \log 2\pi \\ &= -\sum_{j=1}^D \Big(\tfrac12 \varepsilon_j^2 + \log \sigma_j\Big) - \tfrac D2 \log 2\pi . \end{aligned}

Averaging with Eεj2=1\mathbb E\varepsilon_j^2 = 1, −Eq[log⁡q]=∑jlog⁡σj+D2(1+log⁡2π)-\mathbb E_q[\log q] = \sum_j \log \sigma_j + \frac D2 (1 + \log 2\pi), the entropy of the Gaussian. So

L(λ)=Eε[log⁡p(x,μ+σ⊙ε)]+∑jlog⁡σj+const.\mathcal L(\lambda) = \mathbb E_\varepsilon\big[\log p(x, \mu + \sigma \odot \varepsilon)\big] + \sum_j \log \sigma_j + \text{const} .

The first term is the case ℓ=log⁡p(x,⋅)\ell = \log p(x, \cdot) above, with a diagonal Jacobian, ∂zj/∂μj=1\partial z_j/\partial \mu_j = 1 and ∂zj/∂σj=εj\partial z_j / \partial \sigma_j = \varepsilon_j; the second differentiates to 1/σj1/\sigma_j:

∇μL=Eε[∇zlog⁡p(x,z)],∇σL=Eε[∇zlog⁡p(x,z)⊙ε]+1/σ,\begin{aligned} \nabla_\mu \mathcal L &= \mathbb E_\varepsilon\big[\nabla_z \log p(x, z)\big], \\ \nabla_\sigma \mathcal L &= \mathbb E_\varepsilon\big[\nabla_z \log p(x, z) \odot \varepsilon\big] + 1/\sigma , \end{aligned}

with z=μ+σ⊙εz = \mu + \sigma \odot \varepsilon and 1/σ1/\sigma taken elementwise. The Monte Carlo version averages over SS draws of ε\varepsilon:

∇^μL=1S∑s=1S∇zlog⁡p(x,zs),zs=μ+σ⊙εs\boxed{ \begin{aligned} \hat\nabla_\mu \mathcal L &= \frac1S \sum_{s=1}^S \nabla_z \log p(x, z_s), \\ z_s &= \mu + \sigma \odot \varepsilon_s \end{aligned} }

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.

Figure

Two unbiased estimators of one gradient

Two unbiased estimators of one gradientOn the left, the sample ε = 0.5 becomes z = μ + σε = 1.5 for μ = σ = 1. Top, the score-function estimator: the value f(z) = z² = 2.25 is multiplied by the score (z − μ)/σ² = 0.5, giving 1.125. Bottom, the reparameterization estimator: the derivative f′(z) = 2z = 3 is multiplied by ∂z/∂μ = 1, giving 3. On the right, over many samples both estimators average to the true gradient 2, but the variance of one sample is 30 for the first and 4 for the second.0.5εμ + σε1.5z1score function(z − μ)/σ²score: 0.5f(z) = z²a value: 2.25×1.1252reparameterizationf′(z) = 2za derivative: 3∂z/∂μ = 1from z = μ + σε×33over samplesmean 2, var 30over samplesmean 2, var 44Two unbiased estimators of one gradientOn the left, the sample ε = 0.5 becomes z = μ + σε = 1.5 for μ = σ = 1. Top, the score-function estimator: the value f(z) = z² = 2.25 is multiplied by the score (z − μ)/σ² = 0.5, giving 1.125. Bottom, the reparameterization estimator: the derivative f′(z) = 2z = 3 is multiplied by ∂z/∂μ = 1, giving 3. On the right, over many samples both estimators average to the true gradient 2, but the variance of one sample is 30 for the first and 4 for the second.0.5εμ + σε1.5z1score function(z − μ)/σ²score: 0.5f(z) = z²a value: 2.25×1.1252over samplesmean 2, var 304reparameterizationf′(z) = 2za derivative: 3∂z/∂μ = 1from z = μ + σε×33over samplesmean 2, var 4
The gradient of E[z²] in μ for q = N(μ, σ²) at μ = σ = 1, exact value 2. The score function uses only values of f; reparameterization uses its slope at the sample. For ε = 0.5 the estimates are 1.125 and 3; both average to 2, with single-sample variances 30 and 4.

On the toy objective Eq[z2]\mathbb E_q[z^2], one sample gives 2z=2(1+ε)2z = 2(1 + \varepsilon), 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 c⊤zc^\top z the reparameterization gradient in μ\mu is ∇z(c⊤z)=c\nabla_z (c^\top z) = c for every sample, with zero variance; the score-function sample (c⊤z) ε/σ(c^\top z)\, \varepsilon/\sigma still fluctuates.

The variance in numbers#

The figure computes, by quadrature, the single-sample variance of three estimators of ∂L/∂μ\partial \mathcal L / \partial \mu for the one-weight logistic regression of the opening, with σ\sigma held at its optimal value 0.5350.535.

Figure

Variance of three estimators of the ELBO gradient

Variance of three estimators of the ELBO gradientThe single-sample variance of three estimators of the derivative of the ELBO with respect to μ, for logistic regression with one weight, at σ = 0.535 and μ from −1 to 3, on a log scale. Score function: from 95 at the optimum to 523 at μ = −1. With the optimal constant control variate: from 0.2 at the optimum to 86. Reparameterization: between 0.47 and 5.1 over the whole range.0.11101001000-10123mean μ of the variational distributionvariance of one sample (log scale)optimum μ = 0.76score functionwith a control variatereparameterizationVariance of three estimators of the ELBO gradientThe single-sample variance of three estimators of the derivative of the ELBO with respect to μ, for logistic regression with one weight, at σ = 0.535 and μ from −1 to 3, on a log scale. Score function: from 95 at the optimum to 523 at μ = −1. With the optimal constant control variate: from 0.2 at the optimum to 86. Reparameterization: between 0.47 and 5.1 over the whole range.0.11101001000-10123mean μ of the variational distributionvariance of one sample (log scale)optimum μ = 0.76score functionwith a control variatereparameterization
Single-sample variance of three estimators of ∂L/∂μ, by quadrature, for one weight with prior N(0, 1), the eight labelled points of the Code section and a logistic likelihood; σ = 0.535, its optimal value. Near the optimum μ = 0.76 the baseline beats reparameterization; at μ = 3 it loses by a factor of 95.

At the optimum μ=0.76\mu = 0.76 the plain score function has variance 94.794.7 and the reparameterization gradient 3.63.6, 26 times less. The optimal baseline brings the score function down to 0.200.20, below the reparameterization gradient. The reason is exact at the posterior itself. If q(z)=p(z∣x)q(z) = p(z \mid x), then for every zz

f(z)=log⁡p(x,z)−log⁡p(z∣x)=log⁡p(x)(product rule of probability),\begin{aligned} f(z) &= \log p(x, z) - \log p(z \mid x) \\ &= \log p(x) \quad \text{(product rule of probability)}, \end{aligned}

a constant, and with a=log⁡p(x)a = \log p(x) every sample h(z)(f(z)−a)h(z)(f(z) - a) is zero. Near the optimum ff is almost constant over the bulk of qq, and a constant is exactly what a baseline removes. The reparameterization gradient has no such zero: ∇zlog⁡p(x,z)\nabla_z \log p(x, z) still varies with zz. Away from the optimum the baseline helps less; at μ=−1\mu = -1 the three variances are 523523, 8686 and 2.92.9.

Dimension changes the picture. Take Bayesian logistic regression with dd weights and 200 points, and sum the variances over the dd components of the μ\mu-gradient, measured with 20,000 samples. At the start, q=N(0,I)q = \mathcal N(0, I):

ddScoreScore + baselineReparameterization
29.5⋅1049.5 \cdot 10^49.5⋅1039.5 \cdot 10^32.2⋅1032.2 \cdot 10^3
101.0⋅1061.0 \cdot 10^68.4⋅1048.4 \cdot 10^45.4⋅1035.4 \cdot 10^3
501.8⋅1071.8 \cdot 10^76.2⋅1056.2 \cdot 10^59.0⋅1039.0 \cdot 10^3

At a qq fitted by BBVI:

ddScoreScore + baselineReparameterization
28.2⋅1058.2 \cdot 10^516.716.767.867.8
101.9⋅1061.9 \cdot 10^6188188259259
507.0⋅1067.0 \cdot 10^666406640886886

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 qq, where the score εj/σj\varepsilon_j/\sigma_j has grown with the shrinking σ\sigma. With a baseline it wins at the fitted qq for d=2d = 2 and d=10d = 10, and loses by a factor of 7.57.5 at d=50d = 50; 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 d−1d - 1 directions. The reparameterization gradient does not need to, because it differentiates.

The algorithm#

  1. Initialize λ\lambda; choose a step-size schedule ρt\rho_t that satisfies the Robbins–Monro conditions, or an adaptive rule such as AdaGrad.
  2. Draw SS samples from q(z∣λ)q(z \mid \lambda), or SS noise vectors εs\varepsilon_s for the reparameterization gradient.
  3. Compute the gradient estimate: the score function with Rao–Blackwellization and a baseline, or the reparameterization gradient.
  4. Step: λ←λ+ρt ∇^λL\lambda \leftarrow \lambda + \rho_t\, \hat\nabla_\lambda \mathcal L, and repeat from step 2.

With global and local variables, step 3 can also subsample the data, scaling the local terms by N/BN/B 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 qq. 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 «Байесовские методы в анализе данных»:

ObjectiveExact gradientOne-sample estimate
∑i=1Nfi(λ)\sum_{i=1}^N f_i(\lambda)∑i∇fi(λ)\sum_i \nabla f_i(\lambda)N ∇fj(λ)N\, \nabla f_j(\lambda), j∼U{1,…,N}j \sim \mathrm U\{1, \dots, N\}
Er(ε) f(λ,ε)\mathbb E_{r(\varepsilon)}\, f(\lambda, \varepsilon)Er ∇λf(λ,ε)\mathbb E_r\, \nabla_\lambda f(\lambda, \varepsilon)∇λf(λ,ε^)\nabla_\lambda f(\lambda, \hat\varepsilon), ε^∼r\hat\varepsilon \sim r
Eq(z∣λ) f(z)\mathbb E_{q(z \mid \lambda)}\, f(z)Eq[∇λlog⁡q  f]\mathbb E_q[\nabla_\lambda \log q\; f]∇λlog⁡q(z^∣λ) f(z^)\nabla_\lambda \log q(\hat z \mid \lambda)\, f(\hat z), z^∼q\hat z \sim q

Each row is unbiased. In the first, Ej[N∇fj]=∑i1NN∇fi\mathbb E_j[N \nabla f_j] = \sum_i \frac1N N \nabla f_i; the second exchanges ∇\nabla and Er\mathbb E_r; the third is the score-function identity. When the rows are combined, conditioning on the batch and the tower property E[X]=Ej[Eε[X∣j]]\mathbb E[X] = \mathbb E_j\big[\mathbb E_\varepsilon[X \mid j]\big] 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 BB indices averages BB 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 qq 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 λi=(μi,σi)\lambda_i = (\mu_i, \sigma_i) for every xix_i 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 ψ\psi outputs (μψ(xi),σψ(xi))\big(\mu_\psi(x_i), \sigma_\psi(x_i)\big), and the ELBO is maximized over ψ\psi instead of over the λi\lambda_i. 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

Eqψ(z∣xi)[log⁡pθ(xi∣z)]−DKL(qψ(z∣xi) ∥ p(z)),\mathbb E_{q_\psi(z \mid x_i)}\big[\log p_\theta(x_i \mid z)\big] - D_{\mathrm{KL}}\big(q_\psi(z \mid x_i) \,\|\, p(z)\big),

derived in the VAE note, with three choices that the previous sections explain:

  • a mean-field Gaussian qq and the reparameterization gradient, with one sample per point;
  • mini-batches of data points, so the estimate is doubly stochastic;
  • decoder parameters θ\theta fitted by maximizing the same ELBO, in the same gradient steps as ψ\psi.

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 λi\lambda_i separately, because the encoder’s outputs are one particular choice of the λi\lambda_i. Cremer, Li and Duvenaud (2018) split the gap between log⁡p(x)\log p(x) and the ELBO into an approximation gap, from the family of qq, and an amortization gap, from the encoder, and found that the amortization gap is often the larger one. Optimizing the λi\lambda_i 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 qq 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 log⁡p\log p differentiable in zz and qq 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 z∼Bernoulli⁡(θ)z \sim \operatorname{Bernoulli}(\theta) with θ=0.3\theta = 0.3, and f(z)=zf(z) = z, so Eq[f]=θ\mathbb E_q[f] = \theta and the true gradient is 1. The natural sampler is z=[u<θ]z = [u < \theta] with uu uniform. For every uu this is a step function of θ\theta, flat except at one point, so its derivative is 0 almost surely. The score function is computed from log⁡q(z)=zlog⁡θ+(1−z)log⁡(1−θ)\log q(z) = z \log\theta + (1 - z) \log(1 - \theta):

∂θlog⁡q(z)=zθ−1−z1−θ,g=f(z) ∂θlog⁡q(z)=zθ(since z(1−z)=0),E[g]=θ⋅1θ=1,E[g2]=θ⋅1θ2=1θ.\begin{aligned} \partial_\theta \log q(z) &= \frac z\theta - \frac{1 - z}{1 - \theta}, \\ g = f(z)\, \partial_\theta \log q(z) &= \frac z\theta \quad \text{(since } z(1 - z) = 0\text{)}, \\ \mathbb E[g] &= \theta \cdot \tfrac1\theta = 1, \\ \mathbb E[g^2] &= \theta \cdot \tfrac1{\theta^2} = \tfrac1\theta . \end{aligned}

So its single-sample variance is 1/θ−11/\theta - 1:

EstimatorMeanSingle-sample variance
pathwise, through z=[u<θ]z = [u < \theta]0000
score function, f(z) ∂θlog⁡q(z)f(z)\, \partial_\theta \log q(z)1.01.01/θ−1=2.331/\theta - 1 = 2.33

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 qq 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: ∇L=Eq[∇λlog⁡q (log⁡p−log⁡q)]\nabla \mathcal L = \mathbb E_q[\nabla_\lambda \log q \,(\log p - \log q)]; it needs only samples of qq and values of log⁡p\log p.
  • Rao–Blackwellization drops the terms outside the Markov blanket; a baseline aj=Cov⁡(gj,hj)/Var⁡(hj)a_j = \operatorname{Cov}(g_j, h_j)/\operatorname{Var}(h_j) subtracts a constant. Both stay unbiased.
  • Reparameterization: z=μ+σ⊙εz = \mu + \sigma \odot \varepsilon, average ∇zlog⁡p\nabla_z \log p. Variance 4 against 30 on E[z2]\mathbb E[z^2]; 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#