AI Logic

Architectures

Variational Autoencoder (VAE)

Updated:

The VAE architecture. The left side shows the training flow, in which the encoder turns the input into a mean μ and log σ², a latent variable z is formed by drawing ε, and the decoder reconstructs the input from z; the right side shows the variational lower bound (reconstruction term and KL term), the reparameterization, and how data is generated

Background and overview

The VAE (Variational Auto-Encoder) is a probabilistic generative model shaped like an autoencoder. The encoder turns an input not into a single code but into "a distribution over codes (a mean and a variance)", and the decoder produces data from a code drawn from that distribution. After training, feeding random numbers drawn from a standard normal distribution into the decoder is enough to generate new data resembling the training data.

Kingma and Welling proposed it in 2013 in the paper "Auto-Encoding Variational Bayes". The paper set out to solve the following problem.

  • Data x\boldsymbol{x} is assumed to be generated from an unobserved continuous variable (a latent variable) z\boldsymbol{z}.
  • When the decoder is a complex model such as a neural network, neither the probability of x\boldsymbol{x}, pθ(x)p_\theta(\boldsymbol{x}), nor the distribution of z\boldsymbol{z} given x\boldsymbol{x} (the posterior), pθ(z∣x)p_\theta(\boldsymbol{z} \mid \boldsymbol{x}), can be computed, because the integrals are intractable.
  • The dataset is large, so training should proceed a little at a time with mini-batches.

The paper introduces an encoder qϕ(z∣x)q_\phi(\boldsymbol{z} \mid \boldsymbol{x}) that approximates the posterior and rewrites the lower bound on the log-likelihood (the variational lower bound) in a form that ordinary stochastic gradient methods can maximize. The key is a trick called "reparameterization". Using neural networks for the encoder and decoder gives the VAE.

The VAE is mainly used for the following.

  • Generating new data: draw a latent variable from the prior and pass it through the decoder.
  • Representation and visualization: map data into a low-dimensional latent space with the encoder.

Theory

The VAE assumes that data is generated in the following two stages (Section 2.1 of the paper).

  1. Draw a latent variable z\boldsymbol{z} from the prior pθ(z)p_\theta(\boldsymbol{z}). The VAE uses the standard normal distribution N(0,I)\mathcal{N}(\boldsymbol{0}, \boldsymbol{I}).
  2. Draw data x\boldsymbol{x} from the distribution pθ(x∣z)p_\theta(\boldsymbol{x} \mid \boldsymbol{z}) represented by the decoder.

The variational lower bound

Since log⁡pθ(x)\log p_\theta(\boldsymbol{x}) cannot be computed directly, it is split as follows using the encoder qϕ(z∣x)q_\phi(\boldsymbol{z} \mid \boldsymbol{x}) (Eq. 1).

log⁡pθ(x)=DKL(qϕ(z∣x) ∥ pθ(z∣x))+L(θ,ϕ;x)\log p_\theta(\boldsymbol{x}) = D_{\mathrm{KL}}\big(q_\phi(\boldsymbol{z} \mid \boldsymbol{x}) \,\|\, p_\theta(\boldsymbol{z} \mid \boldsymbol{x})\big) + \mathcal{L}(\theta, \phi; \boldsymbol{x})

Since the KL divergence is non-negative, the second term L\mathcal{L} is a lower bound on log⁡pθ(x)\log p_\theta(\boldsymbol{x}). It is called the variational lower bound and can be written as follows (Eq. 3).

L(θ,ϕ;x)=−DKL(qϕ(z∣x) ∥ pθ(z))+Eqϕ(z∣x)[log⁡pθ(x∣z)]\mathcal{L}(\theta, \phi; \boldsymbol{x}) = -D_{\mathrm{KL}}\big(q_\phi(\boldsymbol{z} \mid \boldsymbol{x}) \,\|\, p_\theta(\boldsymbol{z})\big) + \mathbb{E}_{q_\phi(\boldsymbol{z} \mid \boldsymbol{x})}\big[\log p_\theta(\boldsymbol{x} \mid \boldsymbol{z})\big]
  • The first term (the KL term) pulls the distribution produced by the encoder toward the prior N(0,I)\mathcal{N}(\boldsymbol{0}, \boldsymbol{I}). It corresponds to the regularizer of an autoencoder.
  • The second term (the reconstruction term) grows the better the original x\boldsymbol{x} can be recovered from z\boldsymbol{z}. It corresponds to the autoencoder's reconstruction error with the sign flipped.

Maximizing L\mathcal{L} with respect to both θ\theta (the decoder) and ϕ\phi (the encoder) raises the likelihood of the data while bringing the encoder closer to the true posterior.

Reparameterization

The reconstruction term is computed by drawing z\boldsymbol{z} from qϕq_\phi, so as it stands the gradient with respect to ϕ\phi cannot be obtained through the "draw a random number" operation. Naive estimators exist, but according to the paper their variance is very high and they are impractical. So the randomness is moved outside (Section 2.4).

z=μ+σ⊙ϵ,ϵ∼N(0,I)\boldsymbol{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I})

⊙\odot denotes the element-wise product. Since the random number ϵ\boldsymbol{\epsilon} does not depend on the parameters, z\boldsymbol{z} becomes a differentiable function of μ,σ\boldsymbol{\mu}, \boldsymbol{\sigma}, and backpropagation carries gradients all the way to the encoder. Picture moving "the person who rolls the dice" from inside the network to outside, so that the network only receives the result and computes with it.

The loss of the Gaussian VAE

The VAE in the paper makes the encoder output a diagonal normal distribution qϕ(z∣x)=N(z;μ,σ2I)q_\phi(\boldsymbol{z} \mid \boldsymbol{x}) = \mathcal{N}(\boldsymbol{z}; \boldsymbol{\mu}, \boldsymbol{\sigma}^2 \boldsymbol{I}). Since the prior is also normal, the KL term can be computed in closed form (Appendix B). The lower bound for a single data point x\boldsymbol{x} is the following (Eq. 10).

L≃12∑j=1J(1+log⁡σj2−μj2−σj2)+1L∑l=1Llog⁡pθ(x∣z(l))\mathcal{L} \simeq \frac{1}{2} \sum_{j=1}^{J} \Big(1 + \log \sigma_j^2 - \mu_j^2 - \sigma_j^2\Big) + \frac{1}{L} \sum_{l=1}^{L} \log p_\theta\big(\boldsymbol{x} \mid \boldsymbol{z}^{(l)}\big)

JJ is the dimension of the latent variable, and LL is the number of samples of ϵ\boldsymbol{\epsilon} drawn per data point.

The training procedure is as follows (Algorithm 1).

  1. Take a mini-batch of MM data points from the training data.
  2. Compute μ\boldsymbol{\mu} and log⁡σ2\log \boldsymbol{\sigma}^2 for each data point with the encoder.
  3. Draw ϵ∼N(0,I)\boldsymbol{\epsilon} \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I}) and form z=μ+σ⊙ϵ\boldsymbol{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon}.
  4. Use the decoder to produce the parameters of pθ(x∣z)p_\theta(\boldsymbol{x} \mid \boldsymbol{z}) from z\boldsymbol{z}, and compute L\mathcal{L} in the equation above.
  5. Update θ\theta and ϕ\phi together with the gradient of L\mathcal{L} (the paper gives SGD and AdaGrad as examples).

The paper's experiments use M=100M = 100 and L=1L = 1. It reports that one sample per data point is enough as long as the mini-batch is large enough.

Inside the encoder and decoder

The encoder and decoder in the paper are fully connected networks (MLPs) with a single hidden layer, and the hidden layer's activation function is tanh (Appendix C).

PartOutputEquation
Encoderμ\boldsymbol{\mu} and log⁡σ2\log \boldsymbol{\sigma}^2 of a normal distributionh=tanh⁡(W3x+b3)\boldsymbol{h} = \tanh(\boldsymbol{W}_3 \boldsymbol{x} + \boldsymbol{b}_3), μ=W4h+b4\boldsymbol{\mu} = \boldsymbol{W}_4 \boldsymbol{h} + \boldsymbol{b}_4, log⁡σ2=W5h+b5\log \boldsymbol{\sigma}^2 = \boldsymbol{W}_5 \boldsymbol{h} + \boldsymbol{b}_5
Decoder (binary data)Bernoulli probabilities y\boldsymbol{y}y=sigmoid(W2tanh⁡(W1z+b1)+b2)\boldsymbol{y} = \mathrm{sigmoid}\big(\boldsymbol{W}_2 \tanh(\boldsymbol{W}_1 \boldsymbol{z} + \boldsymbol{b}_1) + \boldsymbol{b}_2\big)
Decoder (real-valued data)Mean and log⁡σ2\log \boldsymbol{\sigma}^2 of a normal distributionSame form as the encoder, with z\boldsymbol{z} and x\boldsymbol{x} swapped

For binary data, log⁡pθ(x∣z)=∑i[xilog⁡yi+(1−xi)log⁡(1−yi)]\log p_\theta(\boldsymbol{x} \mid \boldsymbol{z}) = \sum_i \big[x_i \log y_i + (1 - x_i) \log(1 - y_i)\big], so the reconstruction term is the binary cross-entropy with the sign flipped.

Having the encoder output log⁡σ2\log \boldsymbol{\sigma}^2 instead of σ\boldsymbol{\sigma} guarantees that σ=exp⁡(12log⁡σ2)\boldsymbol{\sigma} = \exp(\tfrac{1}{2} \log \boldsymbol{\sigma}^2) is positive even when the output is negative. Appendix C of the paper uses this form as well.

Why it works

The reasons the VAE trains well can be summarized in three points.

  • Reparameterization reduces gradient variance: moving the randomness outside lets the estimate of the lower bound be differentiated directly, so the model trains with the same stochastic gradient methods as an ordinary network. There is no need to run expensive sampling (such as MCMC) for each data point.
  • The KL term organizes the latent space: the KL term keeps the code distribution of every data point from straying too far from N(0,I)\mathcal{N}(\boldsymbol{0}, \boldsymbol{I}). As a result, "holes" without data are less likely to form in the latent space, and a z\boldsymbol{z} drawn from the prior and fed into the decoder tends to produce data resembling the training data. An ordinary autoencoder has no such mechanism.
  • No separate choice of regularization strength: sparse and denoising autoencoders require a person to set the strength of the regularization. The VAE's KL term arises naturally from the lower bound, so there is no hyperparameter to tune for it (Section 4 of the paper).

The paper reports that increasing the dimension of the latent variable beyond what is needed did not cause overfitting, and explains this by the KL term acting as a regularizer.

As an everyday analogy, an ordinary autoencoder assigns each data point "a single point" on a map. The VAE assigns each data point "a slightly spread-out round region" and gathers all the regions near the center of the map. Because the regions overlap, wherever one points on the map, it tends to correspond to some meaningful data.

Experimental results

The paper trained generative models of images on MNIST and Frey Face (face images) and compared the VAE with methods that can train the same kind of latent variable model. The results are shown as figures, and the main conclusions are as follows.

  • Comparison with the wake-sleep algorithm (variational lower bound, latent dimension JJ = 2 to 200): in every experiment, the VAE (AEVB) converged much faster and reached a better lower bound.
  • Comparison on the marginal likelihood (MNIST, 3-dimensional latent variable, 100 hidden units): compared with wake-sleep and Monte Carlo EM (MCEM). Because MCEM processes the whole dataset at once, it cannot be applied efficiently to the full MNIST training set.
  • Even when the latent dimension was increased, no overfitting occurred.
  • With a 2-dimensional latent space, passing grid points of the latent space through the decoder showed digits and facial expressions changing smoothly (Figure 4 in Appendix A).

The experimental settings are as follows (Section 5).

ItemValue
Encoder and decoderMLP with one hidden layer (500 units for MNIST, 200 for Frey Face)
Decoder outputBernoulli for MNIST, normal for Frey Face (mean squashed to 0 to 1 with a sigmoid function)
Mini-batchM=100M = 100, L=1L = 1 per data point
OptimizationAdaGrad (learning rate chosen from 0.01, 0.02, and 0.1 based on performance over the first few updates)
RegularizationSmall weight decay (corresponding to a prior N(0,I)\mathcal{N}(\boldsymbol{0}, \boldsymbol{I}) on the parameters)
InitializationAll parameters drawn from N(0,0.01)\mathcal{N}(0, 0.01)
Compute timeAbout 20 to 40 minutes per million training samples (Intel Xeon CPU)

Practical considerations

Keep the following points in mind when using a VAE.

  • Training optimizes a lower bound: the variational lower bound is not log⁡pθ(x)\log p_\theta(\boldsymbol{x}) itself. Even as the bound rises, a gap to the likelihood (the KL divergence between the encoder and the true posterior) remains. The paper also gives a method for estimating the likelihood itself, but considers it reliable only when the latent variable is low-dimensional (fewer than 5 dimensions).
  • Match the decoder distribution to the data: a Bernoulli decoder assumes data with values between 0 and 1. For real-valued data, use a Gaussian decoder.
  • Aggregate the KL and reconstruction terms consistently: the KL term is a sum over the latent dimensions, and the reconstruction term is a sum over pixels. Averaging only one of them changes the balance between the two terms from the paper's equation.
  • Do not use the encoder for generation: to create new data, draw z\boldsymbol{z} from N(0,I)\mathcal{N}(\boldsymbol{0}, \boldsymbol{I}) and pass it through the decoder.

The KL term has a closed form only when both the encoder distribution and the prior are normal. For other combinations of distributions, the KL term must also be estimated by sampling, as in the paper's general estimator (Eq. 6). Also, reparameterization is a method for continuous latent variables and cannot be applied as is to discrete latent variables.

Comparison with other methods

The VAE is compared below with other methods that have similar goals, from the same viewpoints.

MethodLatent variable inferenceTraining objectiveGenerating new dataLikelihood evaluation
AutoencoderEncoder maps to a single pointMinimize reconstruction errorNot suitedNot possible
VAEEncoder outputs a distributionMaximize a lower bound on the log-likelihoodPossibleThe lower bound can be computed
Wake-sleepApproximated by a recognition modelAlternately optimizes two objectives (not a lower bound on the likelihood)PossibleNot a lower bound
Monte Carlo EMSampled with MCMC per data pointMaximize the likelihoodPossible—
GANNo encoderFool the discriminatorPossibleNot possible

Wake-sleep has the advantage of also working with discrete latent variables. Monte Carlo EM runs sampling for each data point, so it is not suited to large datasets.

Rough guidelines for choosing are as follows.

  • A meaningful latent space used for both representation and generation: the VAE is a good fit. Because it has an encoder, it can also map data into the latent space.
  • Only dimensionality reduction without labels: an ordinary autoencoder is enough.
  • High visual quality samples: GANs and diffusion models such as DDPM are also candidates. Compare them on metrics such as FID according to the goal.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

"""
The VAE of Kingma & Welling (2013) (MNIST, Bernoulli decoder)
The encoder and decoder are MLPs with one hidden layer (500 units, tanh). The loss is the variational lower bound (Eq. 10) with the sign flipped
"""

device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"

# the decoder is Bernoulli, so pixels are used as is in the range 0 to 1
loader = DataLoader(datasets.MNIST("./data", train=True, download=True, transform=transforms.ToTensor()),
                    batch_size=100, shuffle=True)   # M = 100


class VAE(nn.Module):
  def __init__(self, x_dim=784, h_dim=500, z_dim=20):
    super().__init__()
    # encoder q_phi(z|x): outputs mu and log sigma^2 (Appendix C.2)
    self.enc = nn.Linear(x_dim, h_dim)
    self.enc_mu = nn.Linear(h_dim, z_dim)
    self.enc_logvar = nn.Linear(h_dim, z_dim)
    # decoder p_theta(x|z): outputs the logit of each pixel being 1 (Appendix C.1)
    self.dec = nn.Linear(z_dim, h_dim)
    self.dec_out = nn.Linear(h_dim, x_dim)

  def encode(self, x):
    h = torch.tanh(self.enc(x))
    return self.enc_mu(h), self.enc_logvar(h)

  def decode(self, z):
    return self.dec_out(torch.tanh(self.dec(z)))   # the sigmoid function is computed inside the loss

  def forward(self, x):
    mu, logvar = self.encode(x)
    eps = torch.randn_like(mu)                    # epsilon ~ N(0, I)
    z = mu + torch.exp(0.5 * logvar) * eps        # reparameterization: z = mu + sigma * epsilon
    return self.decode(z), mu, logvar


def negative_elbo(logits, x, mu, logvar):
  # reconstruction term: -log p(x|z) (binary cross-entropy, summed over pixels)
  rec = F.binary_cross_entropy_with_logits(logits, x, reduction="sum")
  # KL term: D_KL(q(z|x) || N(0, I)) = -1/2 * sum(1 + log sigma^2 - mu^2 - sigma^2)
  kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
  return (rec + kl) / x.size(0)                   # "negative variational lower bound" per data point


model = VAE().to(device)
# the paper uses AdaGrad and a small weight decay
optimizer = torch.optim.Adagrad(model.parameters(), lr=0.01, weight_decay=1e-4)

for epoch in range(20):
  model.train()
  for x, _ in loader:                             # labels are not used
    x = x.to(device).flatten(1)
    logits, mu, logvar = model(x)
    loss = negative_elbo(logits, x, mu, logvar)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
  print(f"epoch {epoch + 1}: variational lower bound {-loss.item():.1f}")

# generation: skip the encoder, draw z from the prior N(0, I), and pass it through the decoder
model.eval()
with torch.no_grad():
  z = torch.randn(64, 20, device=device)
  samples = torch.sigmoid(model.decode(z)).view(64, 1, 28, 28)   # probability of each pixel being 1

FAQ

Q. What is the difference between a VAE and an ordinary autoencoder?
A.

An ordinary autoencoder maps an input to a single point in the latent space and is trained only on the reconstruction error. A VAE maps an input to a normal distribution (mean μ\boldsymbol{\mu} and variance σ2\boldsymbol{\sigma}^2) and also learns a KL term that pulls that distribution toward the standard normal distribution. This makes it possible to generate new data by feeding the decoder a z\boldsymbol{z} drawn from the standard normal distribution.

Q. Why can't the model be trained without reparameterization?
A.

If z\boldsymbol{z} is drawn directly from the encoder's distribution, the gradient with respect to the encoder's parameters cannot be obtained through the "draw a random number" operation. Naive gradient estimators exist, but according to the paper their variance is very high and they are impractical. Rewriting it as z=μ+σ⊙ϵ\boldsymbol{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon} makes the random number ϵ\boldsymbol{\epsilon} independent of the parameters, so gradients can be computed with ordinary backpropagation.

Q. What does the "KL term" in the VAE loss do?
A.

It pulls the distribution qϕ(z∣x)q_\phi(\boldsymbol{z} \mid \boldsymbol{x}) produced by the encoder toward the prior N(0,I)\mathcal{N}(\boldsymbol{0}, \boldsymbol{I}). The codes of all data points gather near the origin, and holes are less likely to form in the latent space, which makes it easier to use for generation. Since both distributions are normal, it can be computed as the negative of 12∑j(1+log⁡σj2−μj2−σj2)\frac{1}{2}\sum_j (1 + \log \sigma_j^2 - \mu_j^2 - \sigma_j^2). See KL divergence for details.

References

  1. Kingma, D. P., & Welling, M. (2013). Auto-Encoding Variational Bayes. arXiv:1312.6114(ICLR 2014).