Skip to content
BIASED

Black-box variational inference and the VAE

How to get the gradient of the ELBO for any model that can only evaluate $\log p(x, z)$: the score-function estimator and its variance, Rao–Blackwellization and baselines, the reparameterization gradient, amortized inference and the VAE as its special case, and a short comparison with GANs.

When conjugacy is gone

The topic Stochastic variational inference made variational inference fast on large data, but it kept one requirement from the start: every complete conditional must lie in the exponential family, so that each update and each natural gradient has a closed form. Many models we care about break that.

Take Bayesian logistic regression with one weight, as in the topic The Laplace approximation and Bayesian classification. The prior is w∼N(0,1)w \sim \mathcal N(0, 1), the labels are yi∈{−1,+1}y_i \in \{-1, +1\}, and p(yi∣w)=σ(yiwxi)p(y_i \mid w) = \sigma(y_i w x_i) with the sigmoid σ\sigma. Choose q(w)=N(μ,σq2)q(w) = \mathcal N(\mu, \sigma_q^2). The ELBO contains

Eq[log⁡σ(yiwxi)],\mathbb E_{q}\big[\log \sigma(y_i w x_i)\big],

the expectation of a log-sigmoid under a Gaussian. It has no closed form. Coordinate ascent has no formula to iterate, and SVI has no natural gradient to step along. The classic way out is a model-specific trick: the Laplace approximation, or a hand-made bound on the sigmoid.

This topic asks for something more general. Can we get the gradient of the ELBO for any model, using only the ability to evaluate log⁡p(x,z)\log p(x, z) at a point? This is black-box variational inference (BBVI; Ranganath, Gerrish and Blei, 2014). The idea fits in one line: the ELBO is an expectation under qq, so its gradient can be written as an expectation too, and expectations can be estimated by Monte Carlo (the topic Monte Carlo and Markov chains).

The score-function estimator

Let q(z∣λ)q(z \mid \lambda) be the variational family with parameters λ\lambda; for a Gaussian, λ=(μ,σ)\lambda = (\mu, \sigma). Start with a plain expectation Eq[f(z)]\mathbb E_{q}[f(z)] of a function that does not depend on λ\lambda. Its gradient cannot simply be pushed inside as Eq[∇λf]\mathbb E_q[\nabla_\lambda f]: λ\lambda sits in the distribution, not in ff.

The way around is the log-derivative identity. Since ∇λlog⁡q=∇λq/q\nabla_\lambda \log q = \nabla_\lambda q / q,

∇λq(z∣λ)=q(z∣λ) ∇λlog⁡q(z∣λ).\nabla_\lambda q(z \mid \lambda) = q(z \mid \lambda)\, \nabla_\lambda \log q(z \mid \lambda).

Move the gradient inside the integral and apply it:

∇λ∫q(z∣λ)f(z) dz=∫q(z∣λ) ∇λlog⁡q(z∣λ) f(z) dz=Eq[∇λlog⁡q(z∣λ) f(z)].\nabla_\lambda \int q(z \mid \lambda) f(z)\, dz = \int q(z \mid \lambda)\, \nabla_\lambda \log q(z \mid \lambda)\, f(z)\, dz = \mathbb E_{q}\big[\nabla_\lambda \log q(z \mid \lambda)\, f(z)\big].

The vector h(z)=∇λlog⁡q(z∣λ)h(z) = \nabla_\lambda \log q(z \mid \lambda) is the score of qq. It has mean zero: Eq[h]=∫∇λq dz=∇λ1=0\mathbb E_q[h] = \int \nabla_\lambda q\, dz = \nabla_\lambda 1 = 0.

The ELBO is L(λ)=Eq[fλ(z)]\mathcal L(\lambda) = \mathbb E_q[f_\lambda(z)] with fλ(z)=log⁡p(x,z)−log⁡q(z∣λ)f_\lambda(z) = \log p(x, z) - \log q(z \mid \lambda), and here fλf_\lambda does depend on λ\lambda. The product rule gives one more term, Eq[∇λfλ]=−Eq[h]=0\mathbb E_q[\nabla_\lambda f_\lambda] = -\mathbb E_q[h] = 0, so it disappears. Replacing the expectation with an average over samples gives the score-function estimator:

∇^λL=1S∑s=1S∇λlog⁡q(zs∣λ) (log⁡p(x,zs)−log⁡q(zs∣λ)),zs∼q(z∣λ).\hat\nabla_\lambda \mathcal L = \frac1S \sum_{s=1}^{S} \nabla_\lambda \log q(z_s \mid \lambda)\,\big(\log p(x, z_s) - \log q(z_s \mid \lambda)\big), \qquad z_s \sim q(z \mid \lambda).

Reinforcement learning knows the same estimator as REINFORCE (Williams, 1992); statistics calls it the likelihood-ratio method. The model enters only through values of log⁡p(x,z)\log p(x, z), so it really can be a black box.

One condition hides in "move the gradient inside the integral". It needs the integrand to be dominated by an integrable bound, and it fails when the support of qq moves with λ\lambda. For q=Uniform⁡(0,λ)q = \operatorname{Uniform}(0, \lambda) the derivative of the integral picks up a boundary term f(λ)/λf(\lambda)/\lambda that no score can produce.

What unbiasedness costs

The estimator is unbiased. The question is how noisy it is. Take the smallest possible example: q=N(μ,1)q = \mathcal N(\mu, 1) and f(z)=zf(z) = z, so Eq[f]=μ\mathbb E_q[f] = \mu and the exact gradient is 11.

Write z=μ+εz = \mu + \varepsilon with ε∼N(0,1)\varepsilon \sim \mathcal N(0, 1). The score in μ\mu is (z−μ)/1=ε(z - \mu)/1 = \varepsilon, so one sample gives

g=ε z=μ ε+ε2,E[g]=0+1=1.g = \varepsilon\, z = \mu\,\varepsilon + \varepsilon^2, \qquad \mathbb E[g] = 0 + 1 = 1 .

For the variance we need the moments of the standard normal: odd moments vanish, Eε2=1\mathbb E\varepsilon^2 = 1, Eε4=3\mathbb E\varepsilon^4 = 3. Then E[g2]=μ2+3\mathbb E[g^2] = \mu^2 + 3 and

Var⁡(g)=μ2+2.\operatorname{Var}(g) = \mu^2 + 2 .

At μ=5\mu = 5 the variance is 2727 for a gradient equal to 11. The noise grows with μ\mu even though the gradient does not. The reason is visible in the formula: g=ε (μ+ε)g = \varepsilon\,(\mu + \varepsilon), and the score is multiplied by the value of ff, including its large constant part μ\mu. That part contributes nothing on average, since E[ε]=0\mathbb E[\varepsilon] = 0, but it contributes μ2\mu^2 to the variance.

The same happens in the ELBO. log⁡p(x,z)\log p(x, z) is a sum over all data points and is usually a large negative number, so a plain score-function estimate is very noisy. Ranganath et al. needed two variance-reduction tools, and the next block introduces them.

Rao–Blackwellization and baselines

Rao–Blackwellization. Let qq be mean-field, q(z)=∏jq(zj∣λj)q(z) = \prod_j q(z_j \mid \lambda_j), and let hj(zj)=∇λjlog⁡q(zj∣λj)h_j(z_j) = \nabla_{\lambda_j} \log q(z_j \mid \lambda_j) be the score of factor jj. For any function gg of the other variables, independence under qq gives

Eq[hj(zj) g(z−j)]=Eq[hj] Eq[g]=0.\mathbb E_q\big[h_j(z_j)\, g(z_{-j})\big] = \mathbb E_q[h_j]\, \mathbb E_q[g] = 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 dropped from the gradient in λj\lambda_j. What remains are the factors of pp that contain zjz_j, which depend only on its Markov blanket, and log⁡q(zj∣λj)\log q(z_j \mid \lambda_j). Dropping a term whose expectation is known exactly (here, zero) is a Rao–Blackwellization: the mean is unchanged, and the variance only falls. In a model with many local variables, the gradient for one of them stops paying for the noise of all the others.

Control variates. Take any cc with a known mean and use

g^=g−a (c−E[c]).\hat g = g - a\,\big(c - \mathbb E[c]\big).

It is unbiased for every aa, and its variance Var⁡(g)+a2Var⁡(c)−2aCov⁡(g,c)\operatorname{Var}(g) + a^2 \operatorname{Var}(c) - 2a \operatorname{Cov}(g, c) is a parabola in aa with the minimum at

a∗=Cov⁡(g,c)Var⁡(c).a^* = \frac{\operatorname{Cov}(g, c)}{\operatorname{Var}(c)} .

BBVI takes c=hjc = h_j, the score itself, whose mean is zero. Then g^=hj (f−a)\hat g = h_j\,(f - a): subtract a constant baseline aa from ff before multiplying by the score. In the toy example g=εzg = \varepsilon z and c=εc = \varepsilon, so a∗=E[ε2z]=μa^* = \mathbb E[\varepsilon^2 z] = \mu, and g^=ε(z−μ)=ε2\hat g = \varepsilon(z - \mu) = \varepsilon^2 has variance 22 at every μ\mu. The baseline has removed exactly the constant part that was costing μ2\mu^2. In practice a∗a^* is estimated from a few extra samples.

The reparameterization gradient

There is a second, quite different estimator. Suppose a sample from qq can be written as a differentiable function of λ\lambda and of noise whose distribution does not depend on λ\lambda. For a Gaussian,

z=μ+σ⊙ε,ε∼N(0,I).z = \mu + \sigma \odot \varepsilon, \qquad \varepsilon \sim \mathcal N(0, I).

This is the reparameterization trick from the topic The reparameterization trick of the course Generative Models; there it trains an encoder, here it is a general estimator. Now λ\lambda lives inside the integrand, and the gradient goes through the sample:

∇λ Eq[f(z)]=Eε[∇λf(μ+σ⊙ε)].\nabla_\lambda\, \mathbb E_{q}[f(z)] = \mathbb E_{\varepsilon}\big[\nabla_\lambda f(\mu + \sigma \odot \varepsilon)\big].

For the ELBO with a Gaussian qq, the entropy of qq is ∑jlog⁡σj\sum_j \log \sigma_j plus a constant, so

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

The estimator now uses the derivative of the model, not just its values, and that is a lot more information per sample. In the toy example with f(z)=zf(z) = z the reparameterized gradient is ∂z/∂μ=1\partial z/\partial\mu = 1 for every sample: variance zero against μ2+2\mu^2 + 2. For f(z)=z2f(z) = z^2 at μ=2\mu = 2, σ=1\sigma = 1 (exact gradient 44), the single-sample variances are:

Estimator Variance
score function 8787
score function with the optimal baseline 3838
reparameterization, 2z2z 44

The reparameterization gradient asks for more in return:

  • log⁡p(x,z)\log p(x, z) must be differentiable in zz;
  • qq must be a differentiable transform of fixed noise: location–scale families, inverse CDFs, compositions such as exp⁡\exp of a Gaussian for a log-normal.

The score function needs neither. It works with discrete latent variables, with non-differentiable likelihoods, and with simulators that only return values. The two estimators complement each other.

Amortized inference and the VAE

In models with local variables, BBVI keeps one pair λi=(μi,σi)\lambda_i = (\mu_i, \sigma_i) per data point, as SVI did. Each pair is optimized on its own, and a new point needs a fresh optimization.

Amortized inference replaces the table of local parameters with a function. An encoder network with weights φ\varphi maps any xix_i to its parameters, λi=(μφ(xi),σφ(xi))\lambda_i = \big(\mu_\varphi(x_i), \sigma_\varphi(x_i)\big), and the ELBO is maximized over φ\varphi. Inference for a new point becomes one forward pass.

Now let the likelihood be a neural network too, a decoder pθ(x∣z)p_\theta(x \mid z) with the prior p(z)=N(0,I)p(z) = \mathcal N(0, I). The per-point ELBO is

L(θ,φ;xi)=Eqφ(z∣xi)[log⁡pθ(xi∣z)]−KL(qφ(z∣xi) ∥ p(z)).\mathcal L(\theta, \varphi; x_i) = \mathbb E_{q_\varphi(z \mid x_i)}\big[\log p_\theta(x_i \mid z)\big] - \mathrm{KL}\big(q_\varphi(z \mid x_i) \,\|\, p(z)\big).

This is the variational autoencoder, and it is BBVI with four specific choices:

  • a mean-field Gaussian qq and the reparameterization gradient, one sample per point;
  • the encoder for the local parameters (amortization);
  • mini-batches, so the estimate is doubly stochastic: random in the batch and in ε\varepsilon, still unbiased;
  • the decoder weights θ\theta fitted by the same ELBO in the same gradient steps, like an M-step of EM.

The KL between two Gaussians is computed in closed form rather than sampled: compute exactly what can be computed, the same move as Rao–Blackwellization. The derivation of this ELBO and a full training step are in the topics Latent variables and the ELBO and The reparameterization trick of the course Generative Models; we do not repeat them here.

Amortization has a price. The encoder must serve all points at once, so its ELBO cannot exceed what per-point optimization would reach. Cremer, Li and Duvenaud (2018) split the gap log⁡p(x)−L\log p(x) - \mathcal L into an approximation gap (the family of qq is too poor) and an amortization gap (the encoder is not the best qq in that family); the second is often the larger one.

VAE, GAN and what comes next

Two warnings keep the VAE in its place within this course. First, there are two different KLs. The gap between log⁡pθ(x)\log p_\theta(x) and the ELBO is KL(qφ(z∣x) ∥ pθ(z∣x))\mathrm{KL}\big(q_\varphi(z \mid x) \,\|\, p_\theta(z \mid x)\big), to the true posterior; the loss contains KL(qφ(z∣x) ∥ p(z))\mathrm{KL}\big(q_\varphi(z \mid x) \,\|\, p(z)\big), to the prior. Second, a VAE is Bayesian only about zz. The weights θ\theta and φ\varphi are point estimates, found by gradient ascent.

A GAN (see the topic GANs as a two-player game in Generative Models) also generates x=Gθ(z)x = G_\theta(z) from noise z∼p(z)z \sim p(z), but trains it against a discriminator Dψ(x)∈(0,1)D_\psi(x) \in (0, 1):

min⁡θmax⁡ψ Ex∼pdata[log⁡Dψ(x)]+Ez∼p(z)[log⁡(1−Dψ(Gθ(z)))].\min_\theta \max_\psi\ \mathbb E_{x \sim p_{\text{data}}}\big[\log D_\psi(x)\big] + \mathbb E_{z \sim p(z)}\big[\log\big(1 - D_\psi(G_\theta(z))\big)\big].
VAE GAN
Training maximize the ELBO adversarial game
Encoder x→zx \to z yes, qφ(z∣x)q_\varphi(z \mid x) none in the basic model
Density of xx defined, pθ(x)p_\theta(x) is bounded by the ELBO implicit, no formula
Typical trouble posterior approximation too crude, blurry samples with some likelihoods unstable game, mode collapse

Blur and mode collapse are typical problems of the basic models, not theorems about every member of each family.

BBVI turns posterior inference for any differentiable model into stochastic optimization, and the VAE applies it with a neural network as the likelihood. What it leaves untouched are the network weights themselves. The extension topic Bayesian deep learning makes the weights the latent variable: Bayes by backprop is the reparameterization gradient applied to q(w)q(w) over millions of weights, and it is compared there with cheaper approximations — MC dropout, deep ensembles and the Laplace approximation.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.