Reparameterization Trick and Variational Autoencoders
Summary
Kingma & Welling (2013) make two contributions that bridge Bayesian VI and deep generative modeling. (1) The reparameterization trick: write a draw from qϕ(z∣x) as a deterministic, differentiable function of parameter-free noise, z=gϕ(ϵ,x) with ϵ∼p(ϵ), so that ∇ϕEqϕ[f(z)]=Ep(ϵ)[∇ϕf(gϕ(ϵ,x))] can be estimated by ordinary backpropagation with low variance (the SGVB estimator). (2) Amortized inference: instead of separate variational parameters per data point, train a single recognition model (encoder) qϕ(z∣x) jointly with the generative model (decoder) pθ(x∣z) on minibatches (the AEVB algorithm). With neural networks for both, the result is the variational autoencoder (VAE), whose loss is exactly the ELBO in its “reconstruction minus KL-to-prior” form.
Overview
The setting differs from the fully Bayesian one of ADVI in where the latent variables live. Here each of N i.i.d. data points x(i) has its own continuous latent z(i), generated as z(i)∼pθ(z), x(i)∼pθ(x∣z). The global parameters θ are estimated by (approximate) maximum likelihood or MAP; VI is applied to the z(i). This is variational EM with a learned E-step. (Appendix F of the paper gives the fully Bayesian variant that also places a variational posterior on θ, which is structurally ADVI.)
Kingma & Welling design for the case where everything classical fails at once (Sec. 2.1):
Intractability.pθ(x)=∫pθ(z)pθ(x∣z)dz is intractable, so is pθ(z∣x) (no EM), and so are the expectations that mean-field VB would need. This happens as soon as the likelihood is “a neural network with a nonlinear hidden layer.”
Large data. Batch optimization is too costly, and sampling-based EM would need “a typically expensive sampling loop per datapoint.”
(Eqs. 1-3). qϕ(z∣x) is the probabilistic encoder (“given a datapoint x it produces a distribution… over the possible values of the code z”); pθ(x∣z) is the probabilistic decoder. Unlike mean-field VI, qϕ “is not necessarily factorial and its parameters ϕ are not computed from some closed-form expectation.”
The difficulty is ∇ϕ: the expectation is taken under a distribution that depends on ϕ. The generic fix is the score-function estimator, ∇ϕEqϕ[f(z)]=Eqϕ[f(z)∇ϕlogqϕ(z)], which “exhibits very high variance… and is impractical for our purposes” (Sec. 2.2; see Stochastic and Black-Box Variational Inference).
The reparameterization trick ^thm-reparameterization
Let z=gϕ(ϵ,x) with ϵ∼p(ϵ) independent of ϕ and gϕ differentiable, such that z∼qϕ(z∣x). Since qϕ(z∣x)∏idzi=p(ϵ)∏idϵi,
(Eqs. 6-7). Version B integrates the KL analytically and “typically has less variance.” For a minibatch XM of size M from N points, L(θ,ϕ;X)≃MN∑i=1ML~(θ,ϕ;x(i)) (Eq. 8).
“The number of samples L per datapoint can be set to 1 as long as the minibatch size M was large enough, e.g. M=100.”
The variational autoencoder
VAE with Gaussian encoder ^def-vae
Prior p(z)=N(0,I). Decoder pθ(x∣z): Gaussian (real data) or Bernoulli (binary data) with parameters output by an MLP. Encoder qϕ(z∣x(i))=N(z;μ(i),σ2(i)I) with μ(i),σ(i) output by an MLP of x(i). Sampling: z(i,l)=μ(i)+σ(i)⊙ϵ(l). With J=dimz, Appendix B gives the closed-form KL, and the estimator is
(Eq. 10). The diagonal covariance is “just a (simplifying) choice, and not a limitation of our method.”
Why “autoencoder.” The second term is a negative reconstruction error: encode x to a noisy code z, decode, score x. The first term “acts as a regularizer,” pulling every per-datum posterior toward the prior. Classical autoencoders need ad hoc regularizers (denoising, contractive, sparse) to learn useful codes; here the regularizer is “dictated by the variational bound… lacking the usual nuisance regularization hyperparameter” (Sec. 4).
Amortization. Classical VI solves a separate optimization for each z(i) (the local step of CAVI/SVI). The encoder replaces N optimizations by one function x↦(μ(x),σ(x)) whose cost is spread (“amortized,” in Rezende & Mohamed’s 2015 term) across data, and which generalizes to new x at test time with a single forward pass. The price is an amortization gap: the network’s output need not be the per-datum optimum. The same idea, a network trained once to map data to a posterior approximation, is the core of Simulation-Based and Amortized Inference, Neural Simulation-Based Inference - Overview and the Barber-Agakov posterior estimator in Bayesian experimental design.
VAE as nonlinear probabilistic PCA
Kingma & Welling note (Sec. 4) the long-known link between linear autoencoders and linear-Gaussian latent variable models: PCA is the maximum-likelihood solution of p(z)=N(0,I), p(x∣z)=N(x;Wz,ϵI) as ϵ→0 (Roweis 1998). That model is probabilistic PCA, for which the posterior p(z∣x) is Gaussian and linear in x, so EM is exact. The VAE keeps the prior and replaces Wz by a neural network fθ(z). The posterior is no longer tractable, so the exact E-step is replaced by an encoder network and the log likelihood by the ELBO:
PPCA / factor analysis
VAE
Decoder mean
Wz+μ (linear)
fθ(z) (neural network)
Posterior p(z∣x)
Gaussian, closed form
intractable
Inference
exact E-step
amortized Gaussian qϕ(z∣x)
Objective
logpθ(x)
ELBO≤logpθ(x)
Fitting
EM / eigendecomposition
SGD with reparameterization
Evidence (Sec. 5)
On MNIST and Frey Face, AEVB was compared with the wake-sleep algorithm using the same encoder (500 hidden units for MNIST, 200 for Frey Face, minibatch M=100, L=1, Adagrad). AEVB “converged considerably faster and reached a better solution in all experiments” across latent dimensions Nz∈{3,5,10,20,200} (Fig. 2). Notably, “superfluous latent variables did not result in overfitting, which is explained by the regularizing nature of the variational bound.” With Nz=3, where the marginal likelihood can be estimated, AEVB also beat Monte Carlo EM with an HMC E-step, which cannot be run online on the full data set (Fig. 3).
Examples
A VAE in PyTorch ^ex-vae-code
import torch, torch.nn as nn, torch.nn.functional as Fclass VAE(nn.Module): def __init__(self, d_x=784, d_h=500, d_z=20): super().__init__() self.enc = nn.Sequential(nn.Linear(d_x, d_h), nn.Tanh()) self.mu, self.logvar = nn.Linear(d_h, d_z), nn.Linear(d_h, d_z) self.dec = nn.Sequential(nn.Linear(d_z, d_h), nn.Tanh(), nn.Linear(d_h, d_x)) def forward(self, x): h = self.enc(x) mu, logvar = self.mu(h), self.logvar(h) z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu) # reparameterization, L = 1 logits = self.dec(z) recon = -F.binary_cross_entropy_with_logits(logits, x, reduction="sum") neg_kl = 0.5 * torch.sum(1 + logvar - mu**2 - logvar.exp()) # Eq. 10, first term return -(recon + neg_kl) # negative ELBO summed over the minibatch
Without the torch.randn_like line written as a function of mu and logvar, no gradient would reach the encoder; that one line is the whole trick.
Where the same trick appears in applied Bayesian work ^ex-reparam-elsewhere
ADVI standardizes its Gaussian, ζ=μ+Lη, for exactly this reason; Kucukelbir et al. list “re-parameterization trick” as a synonym for their elliptical standardization.
Non-centered parameterization of hierarchical models, θj=μ+τθ~j with θ~j∼N(0,1), is the same location-scale identity used for a different purpose: improving posterior geometry for HMC (see Efficient MCMC) and, per Yao et al. (2018), for ADVI.
Synthetic data and embeddings for marketing. A VAE over customer or creative features gives a generative model plus a low-dimensional representation with an explicit prior, a nonlinear counterpart to factor-analytic summaries of correlated media or survey variables.