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 as a deterministic, differentiable function of parameter-free noise, with , so that 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) jointly with the generative model (decoder) 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 i.i.d. data points has its own continuous latent , generated as , . The global parameters are estimated by (approximate) maximum likelihood or MAP; VI is applied to the . 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):

  1. Intractability. is intractable, so is (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.”
  2. Large data. Batch optimization is too costly, and sampling-based EM would need “a typically expensive sampling loop per datapoint.”

Main Content

Per-datapoint variational bound ^def-vae-bound

(Eqs. 1-3). is the probabilistic encoder (“given a datapoint it produces a distribution… over the possible values of the code ”); is the probabilistic decoder. Unlike mean-field VI, “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, , 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 with independent of and differentiable, such that . Since ,

and the Monte Carlo estimate is differentiable with respect to (Sec. 2.4). Univariate Gaussian: , .

When is such a available? Three routes (Sec. 2.4):

  1. Tractable inverse CDF: , inverse CDF (exponential, Cauchy, logistic, Rayleigh, Pareto, Weibull, Gumbel, …).
  2. Location-scale families: (Gaussian, Laplace, Student-, logistic, uniform, …).
  3. Composition: log-normal (exponentiated normal), Gamma (sum of exponentials), Dirichlet (normalized Gammas), Beta, , .

Not available for discrete , which is the niche left to score-function methods.

SGVB estimators ^def-sgvb

Applying the trick to the bound with :

(Eqs. 6-7). Version B integrates the KL analytically and “typically has less variance.” For a minibatch of size from points, (Eq. 8).

Auto-Encoding Variational Bayes (Kingma & Welling, Algorithm 1) ^alg-aevb

  1. Initialize .
  2. Repeat until convergence:
    • random minibatch of data points;
    • samples from ;
    • ;
    • update with SGD or Adagrad.

“The number of samples per datapoint can be set to 1 as long as the minibatch size was large enough, e.g. .”

The variational autoencoder

VAE with Gaussian encoder ^def-vae

Prior . Decoder : Gaussian (real data) or Bernoulli (binary data) with parameters output by an MLP. Encoder with output by an MLP of . Sampling: . With , 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 to a noisy code , decode, score . 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 (the local step of CAVI/SVI). The encoder replaces optimizations by one function whose cost is spread (“amortized,” in Rezende & Mohamed’s 2015 term) across data, and which generalizes to new 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 , as (Roweis 1998). That model is probabilistic PCA, for which the posterior is Gaussian and linear in , so EM is exact. The VAE keeps the prior and replaces by a neural network . 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 analysisVAE
Decoder mean (linear) (neural network)
Posterior Gaussian, closed formintractable
Inferenceexact E-stepamortized Gaussian
Objective
FittingEM / eigendecompositionSGD 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 , , Adagrad). AEVB “converged considerably faster and reached a better solution in all experiments” across latent dimensions (Fig. 2). Notably, “superfluous latent variables did not result in overfitting, which is explained by the regularizing nature of the variational bound.” With , 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 F
 
class 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, , for exactly this reason; Kucukelbir et al. list “re-parameterization trick” as a synonym for their elliptical standardization.
  • Non-centered parameterization of hierarchical models, with , 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.

Connections

See Also