Back to paper library
Paper notesarXiv 2013ICLR 2014

VAE

The Integral That Won't Add Up

Original paper

Auto-Encoding Variational Bayes

Paper authors

Diederik P Kingma · Max Welling

Publication
ICLR 2014Conference
First submitted to arXiv
arXiv:1312.6114
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{imagegenerationvae2013,
  title = {{Auto-Encoding Variational Bayes}},
  author = {Diederik P Kingma and Max Welling},
  year = {2013},
  eprint = {1312.6114},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1312.6114}
}
On this page

If you have ever written a VAE, chances are you copied this line:

python
KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())

It comes from vae/main.py in the official PyTorch examples, where the comment above it reads "see Appendix B from VAE paper." Appendix B is only half a page long; subtract one Gaussian integral from another, and out comes this expression.

The problem behind this expression is in the first sentence of the paper's abstract, and it is phrased as a question: "How can we perform efficient inference and learning in directed probabilistic models, in the presence of continuous latent variables with intractable posterior distributions, and large datasets?"

This note follows that question all the way down to that one line of code. Why can't p(x)p(x) be computed? If it can't be computed, where does a lower bound on it come from? The sampling step blocks the gradient, so how do we get the gradient through? And why does the KL divergence between Gaussians happen to have a closed-form solution? Finally, we look at the experiments the paper uses to back the method up.

Defining the problem

The bell curve

Suppose we measure the heights of three classmates: 165, 170, and 175 cm. To describe "where heights tend to fall" with a rule, the most common choice is the Gaussian distribution, also called the normal distribution, which is that familiar bell curve.

Three bell curves, with height from 140 to 200 cm on the horizontal axis and probability density on the vertical axis. The solid blue curve is centered at 170 with standard deviation 5, and the region between 165 and 175 is shaded light blue and labeled area ≈ 0.68; the dashed green curve is also centered at 170, with standard deviation 10, lower and wider; the solid orange curve is centered at 180 with standard deviation 5, the same shape as the blue one, only shifted to the right.
Drawn for this note from the Gaussian formula.

A Gaussian has only two parameters. μ\mu is the mean, which sets where the center of the bell is; σ\sigma is the standard deviation, which sets how wide the bell is. In the figure, the blue and orange curves both have a σ\sigma of 5, and moving the orange curve's μ\mu from 170 to 180 shifts the whole curve to the right; the green curve's μ\mu is also 170, but its σ\sigma doubles to 10, and the curve becomes lower and wider. As a formula, it is

N(x;μ,σ2)=1σ2πexp⁡ ⁣(−(x−μ)22σ2)\mathcal N(x;\mu,\sigma^2)=\frac{1}{\sigma\sqrt{2\pi}}\exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)

Read N(x;μ,σ2)\mathcal N(x;\mu,\sigma^2) as "the height, at position xx, of the Gaussian with mean μ\mu and variance σ2\sigma^2"; the variance is just the square of the standard deviation. There's no need to memorize the formula; understanding three parts of it is enough. The farther xx is from μ\mu, the more negative the exponent and the smaller the value, so the curve is highest at μ\mu and falls off on both sides. The distance (x−μ)(x-\mu) is divided by σ\sigma before it is squared, so the larger σ\sigma is, the more lightly the same distance is penalized, and the wider the curve. The factor 1σ2π\frac{1}{\sigma\sqrt{2\pi}} in front makes the total area under the curve exactly 1, so when the curve gets wider, it has to get lower as well.

The height of the curve is called the probability density, and on its own it is not yet a probability. Height is continuous, so the probability of being exactly 170.000… cm is 0; what makes sense is the probability of falling within an interval, which is the area under the curve over that interval. The light blue region in the figure is the area between 165 and 175 cm, about 0.68. When the interval is narrow, the area is roughly height times width; for example, the blue curve's height at 170 is 0.0798, so the probability of a height between 169.5 and 170.5 cm is about 0.0798×1≈8%0.0798\times1\approx8\%.

Likelihood

Now turn the question around. The three data points are already in hand, but the parameters are unknown. Which is more reasonable, μ=170\mu=170 or μ=180\mu=180?

Two bell curves: blue A centered at 170 and orange B centered at 180, both with standard deviation 5. Three black dots on the horizontal axis are the data points 165, 170, and 175, and above each dot stand one blue and one orange bar, whose heights equal that point's value on the two curves. The blue bars are all tall; the orange bar is barely visible at 165, short at 170, and as tall as the blue one at 175. Below, the likelihood of A is given as about 0.00019 and the likelihood of B as about 0.00000046.
Drawn for this note, computed from the Gaussian formula.

To compare them, plug each data point into a candidate curve, read off its height, and multiply everything together. When the three data points are independent, this product is the probability density of "seeing exactly these three data points under this set of parameters." A's curve holds all three points up high, and the product is about 0.00019; B is centered at 180, so the point at 165 falls almost outside the curve, with a height of only 0.0009, and the product is about 0.00000046. A comes out roughly 400 times larger than B.

Hold the data fixed and view this product as a function of the parameters, and it is called the likelihood. Picking the parameters that make the likelihood as large as possible is called maximum likelihood estimation. In this example, if we fix σ=5\sigma=5 and slide μ\mu left and right, the product is largest when μ\mu equals the mean of the three data points, 170, so A happens to be the best one.

Why take the log

With three data points, the product is already down to 0.00019. An MNIST handwritten-digit image has 784 pixels; if the model gives each pixel a probability of 0.5, the likelihood of one image is 0.5784≈10−2360.5^{784}\approx10^{-236}. Multiply in a second image, and the number is too small even for a computer's 64-bit floating point to store; it simply becomes 0.

Taking the logarithm solves this. The log turns multiplication into addition, log⁡(abc)=log⁡a+log⁡b+log⁡c\log(abc)=\log a+\log b+\log c, so the log-likelihood of one image is 784×log⁡0.5≈−543784\times\log 0.5\approx-543, and summing over any number of images never turns into 0. The log is also an increasing function, so the larger the original number, the larger its log; the parameters that maximize the likelihood also maximize the log-likelihood, and the answer stays the same. Using the natural log, A's log-likelihood is −8.59-8.59 and B's is −14.59-14.59, in the same order as before.

So in plain words, "maximizing the log-likelihood of the data" means adjusting the model's parameters until the model finds the data we have in hand as likely as possible. That is what the whole paper sets out to do, except that the model is no longer a bell curve but a neural network, with an unseen variable hidden inside.

The unseen variable

Two coins will show what an "unseen variable" is.

There are two coins in a box. One is a fair coin that lands heads with probability 0.5; the other is a biased coin that lands heads with probability 0.9. Each round, one coin is picked blindly, each with an even chance, and tossed once; you are told only whether it came up heads or tails, not which coin was picked.

Call the coin picked zz, with z=1z=1 the fair coin and z=2z=2 the biased one; call the outcome xx, with x=1x=1 heads and x=0x=0 tails. zz determines the probability of xx, but we only get to see xx, and a variable like this is called a latent variable. The whole process breaks down into two steps:

  • p(z)p(z): the probability of picking each coin, 0.5 for each. This is called the prior, our view of zz before seeing any outcome.
  • p(x∣z)p(x|z): the probability of tossing xx once we know which coin was picked. The vertical bar reads "given," and this is called a conditional probability; for example, p(x=1∣z=2)=0.9p(x{=}1|z{=}2)=0.9.

What is the total probability of heads, p(x=1)p(x{=}1)? Either coin can come up heads, so add the two cases:

p(x=1)=p(z=1) p(x=1∣z=1)+p(z=2) p(x=1∣z=2)=0.5×0.5+0.5×0.9=0.7\begin{aligned} p(x{=}1) &= p(z{=}1)\,p(x{=}1|z{=}1)\\ &\quad+p(z{=}2)\,p(x{=}1|z{=}2)\\ &= 0.5\times0.5+0.5\times0.9=0.7 \end{aligned}

Going through every possible value of the unseen variable and summing, weighted by its probability, is called marginalization, and the resulting p(x)p(x) is called the marginal probability. Here zz has only two possible values, so two terms are enough.

Seeing the result, guessing backward

This round came up heads. What is the probability that the biased coin was picked?

Intuition says a bit more than half, because the biased coin comes up heads more easily. Bayes' theorem turns this intuition into a number:

p(z∣x)=p(z) p(x∣z)p(x)p(z|x)=\frac{p(z)\,p(x|z)}{p(x)}

Plugging in the numbers, p(z=2∣x=1)=0.5×0.9/0.7≈0.64p(z{=}2|x{=}1)=0.5\times0.9/0.7\approx0.64. Before seeing heads, we thought the two coins were equally likely; after seeing heads, the biased coin's probability rises to 0.64. p(z∣x)p(z|x) is called the posterior, our view of zz after seeing the data. The numerator is the prior times p(x∣z)p(x|z); at this point xx is fixed and p(x∣z)p(x|z) is treated as a function of zz, which is exactly the likelihood we met earlier.

Now the denominator. It is the p(x)=0.7p(x)=0.7 we just got by marginalization, which in Bayesian statistics is also called the evidence. To compute the posterior, you first have to sum over every zz. With two coins, that's just two terms; but if zz is a continuous vector and p(x∣z)p(x|z) is a neural network, the sum can't be carried out, and the posterior can't be computed either. This denominator is exactly where the VAE gets stuck.

A generative story

Back to handwritten digits. Suppose each image is produced like this: first draw an unseen vector zz from a simple distribution pθ(z)p_\theta(z), then, based on zz, draw a 28×2828\times28 image xx from pθ(x∣z)p_\theta(x|z).

This has the same structure as the coins. zz is the latent variable; think of it as unlabeled factors such as "which digit, how thick the strokes, which way it slants." pθ(z)p_\theta(z) is the prior; the parameters of pθ(x∣z)p_\theta(x|z) are produced by a neural network, and θ\theta is that network's weights. The difference is that zz no longer has just two possible values; it is a continuous vector.

All we have in hand is a pile of xx. To learn θ\theta, the goal is to maximize the log-likelihood of the data; the sum from the coin example becomes an integral when zz is continuous:

log⁡pθ(x)=log⁡∫pθ(z) pθ(x∣z) dz\log p_\theta(x) = \log \int p_\theta(z)\,p_\theta(x|z)\,dz

For now, read ∫⋯dz\int\cdots dz as "sum over all possible zz." Since zz is continuous, it has infinitely many possible values, and the sum becomes an area under a curve, just as we used area earlier to get the probability of a height falling within some range. As with the coins, each zz contributes "the probability density of drawing this zz" times "the probability density of this zz producing xx." zz has been integrated out, so pθ(x)p_\theta(x) is called the marginal likelihood.

When the integral can be computed

First, an example that can be computed. Let zz be one-dimensional, with prior p(z)=N(0,1)p(z)=\mathcal N(0,1) and a linear decoder p(x∣z)=N(x;z,1)p(x|z)=\mathcal N(x;z,1); that is, draw a zz, then add noise with standard deviation 1 around it to get xx. Stacking two Gaussians still gives a Gaussian; the variance of xx is the 1 from zz itself plus the 1 from the noise, so the marginal distribution is N(0,2)\mathcal N(0,2). By Bayes' theorem, multiply the prior by the likelihood and divide by the marginal, and the posterior is Gaussian too:

p(z∣x)=N ⁣(z; x2, 12)p(z|x) = \mathcal N\!\left(z;\ \tfrac{x}{2},\ \tfrac12\right)
The horizontal axis is the latent variable z, from −3 to 4. The dashed blue curve is the prior N(0, 1), centered at 0; the dotted orange curve is the likelihood p(x = 2 | z), centered at 2 and as wide as the prior; the solid purple curve is the posterior N(1, ½), centered at 1, taller and narrower than the other two, with the area under it shaded light purple.
Drawn for this note from the linear Gaussian example above.

Take x=2x=2. The dashed blue curve is the prior, centered at 0. The dotted orange curve is the likelihood, with xx fixed at 2 and zz varying; the closer zz is to 2, the better its chance of producing x=2x=2. The solid purple curve is the posterior N(1,12)\mathcal N(1,\tfrac12). The posterior's center, 1, lies between the prior's 0 and the data's 2, each side giving ground; it is narrower than both, because the prior and the data each contribute some information, and together they are more certain than either one alone.

Section 4 of the paper notes that PCA corresponds exactly to the maximum likelihood solution of this kind of linear Gaussian model as the noise goes to 0. We'll use this example again shortly.

Now swap the decoder for a network with a nonlinear hidden layer, for example pθ(x∣z)=N(x;fθ(z),I)p_\theta(x|z)=\mathcal N\big(x;f_\theta(z),I\big) with a tanh inside fθf_\theta. The integral ∫N(z;0,I) N(x;fθ(z),I) dz\int\mathcal N(z;0,I)\,\mathcal N\big(x;f_\theta(z),I\big)\,dz no longer has a closed-form solution, meaning there is no formula you can write down and simply plug numbers into. Section 2.1 of the paper lists this as the first difficulty, and points out that it already shows up with "moderately complicated likelihood functions," such as "a neural network with a nonlinear hidden layer."

Without a closed form, could we estimate it by sampling? This integral is really an average weighted by p(z)p(z), so the most direct approach is to draw KK values of zz from the prior and average pθ(x∣zk)p_\theta(x|z_k). The trouble is that for a particular "7," a zz drawn at random from the prior will mostly decode to some other digit, making pθ(x∣zk)p_\theta(x|z_k) negligibly small, so the whole average rests on the very few samples that happen to land in the right place. Once the latent space has many dimensions, the number of draws needed to hit those samples becomes impractical.

The posterior can't be computed either. In pθ(z∣x)=pθ(x∣z) pθ(z)/pθ(x)p_\theta(z|x)=p_\theta(x|z)\,p_\theta(z)/p_\theta(x), the denominator is exactly that integral, stuck at the same spot as in the coin example. The EM algorithm, the classic maximum likelihood method for latent variables, needs the posterior at every step, so it is out; traditional mean-field variational inference needs a set of expectations under the approximate posterior computed analytically, and those can't be computed here either.

The second difficulty is the amount of data. When there is so much data that full-batch optimization is too expensive, we want to update the parameters with minibatches, or even one data point at a time. Monte Carlo EM replaces the intractable posterior with sampling, but every update requires running an MCMC sampling loop for each data point (a kind of method that has to iterate for many steps before it can draw samples from a hard-to-compute distribution), which is too slow.

For online learning in this class of models at the time, the paper names only wake-sleep. It also trains a recognition model to guess the posterior, but it optimizes two objective functions at the same time, and together they do not correspond to any lower bound on the marginal likelihood.

The paper wants to solve three things at once:

  1. Estimate θ\theta, which lets us generate realistic new data;
  2. Given xx, infer zz, to use as a code or representation;
  3. Estimate p(x)p(x), since tasks such as denoising, inpainting, and super-resolution need a prior over xx.

And all three should be doable with minibatch stochastic gradients, using a single objective function.

Solving the problem

Let an encoder guess the posterior

Since the true posterior can't be computed, train a separate distribution qϕ(z∣x)q_\phi(z|x) to approximate it. The paper calls it the recognition model, governed by a separate set of parameters ϕ\phi.

A directed graphical model. A box stands for N data points; inside it, a white circle z sits above a gray circle x. A solid arrow points from z to x, and the parameter θ, outside the box, points to z and x with solid lines; a dashed arrow curves from x back to z, and the parameter φ, outside the box, points to z with a dashed line.
Original Figure 1, Kingma and Welling, from PDF page 2, arXiv license, scholarly quotation.

The gray xx is observed data, and the white zz is unseen; the NN in the bottom-right corner of the box means each of the NN data points has its own zz. The solid lines are the generative model pθ(z) pθ(x∣z)p_\theta(z)\,p_\theta(x|z), pointing from zz to xx; the dashed line is the approximate posterior qϕ(z∣x)q_\phi(z|x), pointing the other way, from xx back to zz. θ\theta and ϕ\phi are learned together.

From a coding point of view, zz is a code for xx. So the paper calls qϕ(z∣x)q_\phi(z|x) a probabilistic encoder: given an image, it outputs a distribution, such as a Gaussian, describing which zz the image might have come from. pθ(x∣z)p_\theta(x|z) is then the probabilistic decoder.

This differs from traditional variational inference in one respect. The mean-field approach computes separate variational parameters for each data point from closed-form expectations; the paper's qϕq_\phi is a network that takes xx as input, all data share the same ϕ\phi, and when new data come in, a single forward pass gives the approximate posterior. Later literature calls this amortized inference.

The evidence lower bound

With qϕq_\phi in place, we next need an objective we can optimize. We start from log⁡pθ(x)\log p_\theta(x) and take it apart step by step.

Before taking it apart, one piece of notation. Eq(z)[f(z)]\mathbb E_{q(z)}\big[f(z)\big] is called the expectation of f(z)f(z) under qq, which means a weighted average: plug every possible zz into ff and weight it by the probability qq gives it. With the coins, each is picked with probability 0.5; if picking the fair coin scores 1 point and the biased coin 3 points, the expectation is 0.5×1+0.5×3=20.5\times1+0.5\times3=2.

When zz is continuous, the weighted average becomes an integral and often can't be computed. But as long as we can sample from qq, we can draw a few zz and average f(z)f(z) as an estimate; the more we draw, the closer we get to the true expectation. This is called Monte Carlo estimation, and every gradient that follows relies on it.

First, log⁡pθ(x)\log p_\theta(x) contains no zz, so it is the same number for every zz, and a weighted average of it is still itself. We can therefore write it as an expectation under qϕ(z∣x)q_\phi(z|x):

log⁡pθ(x)=Eqϕ(z∣x)[log⁡pθ(x)]\log p_\theta(x) = \mathbb E_{q_\phi(z|x)}\big[\log p_\theta(x)\big]

Second, use Bayes' theorem to replace pθ(x)p_\theta(x) with pθ(x,z)/pθ(z∣x)p_\theta(x,z)/p_\theta(z|x). pθ(x,z)=pθ(z) pθ(x∣z)p_\theta(x,z)=p_\theta(z)\,p_\theta(x|z) is the probability of zz and xx occurring together, called the joint probability, which is the numerator of Bayes' theorem; rearranging Bayes' theorem gives this form. Then multiply the top and bottom of the fraction by qϕ(z∣x)q_\phi(z|x) and split it into two terms. Below, Eq\mathbb E_q is shorthand for Eqϕ(z∣x)\mathbb E_{q_\phi(z|x)}:

log⁡pθ(x)=Eq[log⁡pθ(x,z)pθ(z∣x)]=Eq[log⁡pθ(x,z)qϕ(z∣x)]+Eq[log⁡qϕ(z∣x)pθ(z∣x)]\begin{aligned} \log p_\theta(x) &= \mathbb E_{q}\left[\log \frac{p_\theta(x,z)}{p_\theta(z|x)}\right] \\ &= \mathbb E_{q}\left[\log \frac{p_\theta(x,z)}{q_\phi(z|x)}\right] \\ &\quad + \mathbb E_{q}\left[\log \frac{q_\phi(z|x)}{p_\theta(z|x)}\right] \end{aligned}

The second term is exactly the KL divergence from qϕ(z∣x)q_\phi(z|x) to the true posterior.

The KL divergence (Kullback–Leibler divergence) measures how much two distributions differ. It is defined as DKL(q ∥ p)=Eq[log⁡q(z)p(z)]D_{\mathrm{KL}}(q\,\|\,p)=\mathbb E_{q}\big[\log\frac{q(z)}{p(z)}\big]: at each possible value, take the log ratio of the two distributions, then average with qq's probabilities as the weights. Take the heads and tails probabilities of the two coins as an example, with qq the fair coin's (0.5, 0.5) and pp the biased coin's (0.9, 0.1):

DKL(q ∥ p)=0.5log⁡0.50.9+0.5log⁡0.50.1≈0.51\begin{aligned} D_{\mathrm{KL}}(q\,\|\,p)&=0.5\log\frac{0.5}{0.9}+0.5\log\frac{0.5}{0.1}\\ &\approx0.51 \end{aligned}

The derivation ahead uses only three of its properties. It is never less than 0; it equals 0 only when the two distributions are identical; and it is not symmetric, so swapping the two sides gives DKL(p ∥ q)≈0.37D_{\mathrm{KL}}(p\,\|\,q)\approx0.37. Computed with the natural log, the unit is called nats; computed with log base 2, it is bits, and 0.51 nats is about 0.74 bits.

Back to the derivation. Call the first term L\mathcal L, and we have the paper's Eq. (1):

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

The KL divergence is never less than 0, so L\mathcal L can never exceed log⁡pθ(x)\log p_\theta(x). This is the lower bound of Eq. (2):

L(θ,ϕ;x)=Eq[log⁡pθ(x,z)−log⁡qϕ(z∣x)]≤log⁡pθ(x)\begin{aligned} \mathcal L(\theta,\phi;x) &= \mathbb E_{q}\big[\log p_\theta(x,z) - \log q_\phi(z|x)\big] \\ &\le \log p_\theta(x) \end{aligned}

As the coin example showed, the denominator of Bayes' theorem, p(x)p(x), is called the evidence, so L\mathcal L later came to be widely known as the evidence lower bound (ELBO); the paper itself calls it the variational lower bound.

Eq. (1) says two things.

  • The gap between the bound and the true value is exactly the KL from the approximate posterior to the true posterior. The better qϕq_\phi guesses, the tighter the bound; if it guesses exactly, equality holds.
  • log⁡pθ(x)\log p_\theta(x) does not depend on ϕ\phi. Raising L\mathcal L with respect to ϕ\phi can only come from shrinking that KL, that is, from pushing qϕq_\phi toward the true posterior; raising L\mathcal L with respect to θ\theta pushes up the lower bound on log⁡pθ(x)\log p_\theta(x). One objective handles both inference and learning, which is something wake-sleep cannot do.

Take it apart once more. log⁡pθ(x,z)=log⁡pθ(x∣z)+log⁡pθ(z)\log p_\theta(x,z)=\log p_\theta(x|z)+\log p_\theta(z); group log⁡pθ(z)\log p_\theta(z) with −log⁡qϕ(z∣x)-\log q_\phi(z|x), and another KL appears, giving Eq. (3):

L(θ,ϕ;x)=Eq[log⁡pθ(x∣z)]−DKL(qϕ(z∣x) ∥ pθ(z))\begin{aligned} \mathcal L(\theta,\phi;x) ={}& \mathbb E_{q}\big[\log p_\theta(x|z)\big] \\ &- D_{\mathrm{KL}}\big(q_\phi(z|x)\,\|\,p_\theta(z)\big) \end{aligned}

Read this way, it is an autoencoder. The first term draws a zz with the encoder, then asks how likely the decoder is to produce the original xx back; it corresponds to an autoencoder's reconstruction error (up to a minus sign) and is called the reconstruction term. The second term asks the encoder's output distribution not to stray too far from the prior, playing the role of a regularizer. In its related work, the paper points out that autoencoders such as denoising and sparse autoencoders need separately tuned regularization hyperparameters to learn useful representations; here the regularization term is determined directly by the bound.

The bound on an example we can compute

Back to the one-dimensional linear Gaussian model, with x=2x=2. Its marginal distribution is N(0,2)\mathcal N(0,2), so

log⁡p(x=2)=−12log⁡(4π)−1≈−2.27\log p(x{=}2) = -\tfrac12\log(4\pi) - 1 \approx -2.27

Let's try two approximate posteriors. The reconstruction term is Eq[log⁡N(2;z,1)]=−12log⁡2π−12 Eq[(2−z)2]\mathbb E_q\big[\log\mathcal N(2;z,1)\big] = -\tfrac12\log 2\pi - \tfrac12\,\mathbb E_q\big[(2-z)^2\big], and if q=N(m,s2)q=\mathcal N(m,s^2), then Eq[(2−z)2]=(2−m)2+s2\mathbb E_q[(2-z)^2]=(2-m)^2+s^2. We'll see how to compute the KL term when we derive Appendix B shortly; for now, we just use the result.

q(z∣x=2)q(z\mid x{=}2)Recon. termKL termELBO
N(0,1)\mathcal N(0,1), ignores xx−3.420−3.42
N(1,12)\mathcal N(1,\tfrac12), true posterior−1.670.60−2.27

Computed for this note from Eq. (3) and Appendix B of the paper, in nats.

The first qq is simply the prior, so its KL term is 0, but the zz it draws have nothing to do with x=2x=2, and the reconstruction term is poor. The second qq takes on 0.60 nats of KL and lifts the reconstruction term from −3.42 to −1.67, an improvement of 1.75 nats; its ELBO equals log⁡p(x)\log p(x) exactly, because it is the true posterior. The first qq's ELBO is 1.15 nats below the true value, and you can check directly that this gap is exactly the KL from N(0,1)\mathcal N(0,1) to the true posterior N(1,12)\mathcal N(1,\tfrac12).

With a neural network decoder, log⁡p(x)\log p(x) can't be computed, and we don't know what the true posterior looks like; but as long as we can sample from qq, both the reconstruction term and the KL term can still be estimated. This is what the whole paper is about.

The gradient gets stuck at the sampling step

The ELBO's expectation is taken under qϕ(z∣x)q_\phi(z|x). To estimate it, sample from qϕq_\phi and average. Differentiating with respect to θ\theta is no problem, since the gradient can move straight inside the expectation; the trouble is ϕ\phi, because the distribution we sample from is itself determined by ϕ\phi.

The common choice at the time was the score function estimator (called REINFORCE in reinforcement learning). Move ∇ϕ\nabla_\phi inside the integral and use ∇ϕqϕ=qϕ ∇ϕlog⁡qϕ\nabla_\phi q_\phi = q_\phi\,\nabla_\phi\log q_\phi:

∇ϕ Eqϕ(z)[f(z)]=∫f(z) ∇ϕqϕ(z) dz=Eqϕ(z)[f(z) ∇ϕlog⁡qϕ(z)]\begin{aligned} &\nabla_\phi\,\mathbb E_{q_\phi(z)}\big[f(z)\big] \\ &\quad= \int f(z)\,\nabla_\phi q_\phi(z)\,dz \\ &\quad= \mathbb E_{q_\phi(z)}\big[f(z)\,\nabla_\phi\log q_\phi(z)\big] \end{aligned}

The last expectation can be estimated with a sample average, and the estimate is unbiased, meaning that on average it equals the correct answer exactly. Section 2.2 of the paper dismisses it in a single sentence, saying the estimator "exhibits very high variance" and "is impractical for our purposes." Most contemporary work added control variates to it, trying to push the variance down.

Let's use the example from before to see how high "very high" is. Let q=N(μ,1)q=\mathcal N(\mu,1) and f(z)=−12(2−z)2f(z)=-\tfrac12(2-z)^2 (the reconstruction term without its constant), and differentiate with respect to μ\mu at μ=0\mu=0; the correct answer is 2. Take one sample z=ε∼N(0,1)z=\varepsilon\sim\mathcal N(0,1); since ∇μlog⁡q=z−μ\nabla_\mu\log q=z-\mu, the score function estimate is

f(z) (z−μ)=−12(2−ε)2 εf(z)\,(z-\mu) = -\tfrac12(2-\varepsilon)^2\,\varepsilon

Expanding it with the moments of the normal distribution, E[ε2]=1\mathbb E[\varepsilon^2]=1, E[ε4]=3\mathbb E[\varepsilon^4]=3, and E[ε6]=15\mathbb E[\varepsilon^6]=15, its mean is 2 and its variance is 21.75.

Now shift all of ff down by 100. On MNIST, the bound per image sits around −100, as Figure 2 will show shortly. The correct gradient doesn't change, and the score function estimate still averages 2, but its variance becomes 10,721.75. This estimator is sensitive to the absolute size of ff, and log-likelihoods, unfortunately, usually have large absolute values.

The reparameterization trick

The paper's solution is to produce zz a different way. A one-dimensional Gaussian z∼N(μ,σ2)z\sim\mathcal N(\mu,\sigma^2) can be written as

z=μ+σε,ε∼N(0,1)z = \mu + \sigma\varepsilon,\qquad \varepsilon\sim\mathcal N(0,1)

All the randomness is handed to ε\varepsilon, and the distribution of ε\varepsilon has no parameters at all; zz becomes a deterministic function of μ\mu, σ\sigma, and ε\varepsilon. The expectation can then be taken over ε\varepsilon instead:

EN(z;μ,σ2)[f(z)]=EN(ε;0,1)[f(μ+σε)]\mathbb E_{\mathcal N(z;\mu,\sigma^2)}\big[f(z)\big] = \mathbb E_{\mathcal N(\varepsilon;0,1)}\big[f(\mu+\sigma\varepsilon)\big]

The distribution on the right doesn't depend on μ\mu or σ\sigma, so the gradient can move straight inside and be computed with the chain rule:

∂∂μ E[f(z)]=E[f′(z)]∂∂σ E[f(z)]=E[f′(z) ε]\begin{aligned} \frac{\partial}{\partial\mu}\,\mathbb E\big[f(z)\big] &= \mathbb E\big[f'(z)\big] \\ \frac{\partial}{\partial\sigma}\,\mathbb E\big[f(z)\big] &= \mathbb E\big[f'(z)\,\varepsilon\big] \end{aligned}

Back to the same example, f′(z)=2−zf'(z)=2-z. The single-sample estimate for μ\mu is 2−μ−σε2-\mu-\sigma\varepsilon, which at μ=0\mu=0 and σ=1\sigma=1 has mean 2 and variance 1; shifting ff by 100 has no effect on it, because it only looks at the slope of ff. The estimate for σ\sigma, (2−μ−σε) ε(2-\mu-\sigma\varepsilon)\,\varepsilon, has mean −σ-\sigma, the same as differentiating E[f]=−12((2−μ)2+σ2)\mathbb E[f]=-\tfrac12\big((2-\mu)^2+\sigma^2\big) directly.

Same gradient, one sample each, and the variance is 1 versus 21.75; the larger the absolute value of ff, the wider the gap grows.

The general form is the paper's Eqs. (4) and (5). Find a differentiable function gϕ(ε,x)g_\phi(\varepsilon,x) and a noise distribution p(ε)p(\varepsilon) that doesn't depend on the parameters, such that z=gϕ(ε,x)z=g_\phi(\varepsilon,x) follows exactly qϕ(z∣x)q_\phi(z|x), and the expectation can be estimated with samples of the noise:

Eqϕ(z∣x)[f(z)]=Ep(ε)[f(gϕ(ε,x))]≃1L∑l=1Lf(gϕ(ε(l),x))\begin{aligned} \mathbb E_{q_\phi(z|x)}\big[f(z)\big] &= \mathbb E_{p(\varepsilon)}\big[f\big(g_\phi(\varepsilon,x)\big)\big] \\ &\simeq \frac1L\sum_{l=1}^{L} f\big(g_\phi(\varepsilon^{(l)},x)\big) \end{aligned}

Which distributions admit such a gϕg_\phi? Section 2.4 lists three kinds:

  • Tractable inverse CDF: let ε∼U(0,1)\varepsilon\sim\mathcal U(0,1) and take gϕg_\phi to be the inverse cumulative distribution function of qϕq_\phi; examples include the exponential, Cauchy, logistic, and Gumbel distributions.
  • Location-scale families: like the Gaussian, g=a+b εg=a+b\,\varepsilon, where aa is the location, bb the scale, and ε\varepsilon the standardized version; examples include the Laplace, Student's t, and uniform distributions.
  • Composition: build them from simple variables; for example, exponentiating a normal variable gives a log-normal, and adding up exponentially distributed variables gives a Gamma.

All three require zz to be a continuous variable. Discrete latent variables can't be written this way, and the paper admits in its related work that wake-sleep is more flexible on this point.

The SGVB estimator and the AEVB algorithm

Applying the reparameterization to the ELBO, the paper gets two estimators. Eq. (6) takes a sample average of log⁡pθ(x,z)−log⁡qϕ(z∣x)\log p_\theta(x,z)-\log q_\phi(z|x) directly, written L~A\tilde{\mathcal L}^A. If the KL term has an analytic solution, only the reconstruction term is sampled; this is L~B\tilde{\mathcal L}^B in Eq. (7):

L~B(θ,ϕ;x(i))=−DKL(qϕ(z∣x(i)) ∥ pθ(z))+1L∑l=1Llog⁡pθ(x(i)∣z(i,l))\begin{aligned} \tilde{\mathcal L}^{B}(\theta,\phi;x^{(i)}) ={}& -D_{\mathrm{KL}}\big(q_\phi(z|x^{(i)})\,\|\,p_\theta(z)\big) \\ &+ \frac1L\sum_{l=1}^{L}\log p_\theta\big(x^{(i)}|z^{(i,l)}\big) \end{aligned}

Here z(i,l)=gϕ(ε(l),x(i))z^{(i,l)}=g_\phi(\varepsilon^{(l)},x^{(i)}). With one less term to estimate, the variance is usually smaller too. These estimators are called SGVB (Stochastic Gradient Variational Bayes).

With NN data points in the dataset and MM drawn each time to form a minibatch, the minibatch sum multiplied by N/MN/M is an estimate of the bound for the whole dataset (Eq. 8):

L(θ,ϕ;X)≃NM∑i=1ML~(θ,ϕ;x(i))\mathcal L(\theta,\phi;X) \simeq \frac{N}{M}\sum_{i=1}^{M}\tilde{\mathcal L}(\theta,\phi;x^{(i)})

Algorithm 1 puts these together into a loop. Each iteration draws a minibatch, draws noise ε\varepsilon for each data point, computes the gradients with respect to θ,ϕ\theta,\phi, and updates with SGD or Adagrad, until convergence. This is AEVB (Auto-Encoding Variational Bayes). The experiments use M=100M=100 and L=1L=1, drawing just one zz per data point; the authors say that as long as the minibatch is large enough, one sample is enough. Intuitively, averaging over a hundred data points, each with its own noise, already cancels out a good deal of it.

When the recognition model is implemented with a neural network, the paper says, "we arrive at the variational auto-encoder." The name VAE first appears in the last sentence of the introduction.

The closed-form Gaussian KL

Section 3 makes everything concrete. The prior is a parameter-free standard normal, pθ(z)=N(0,I)p_\theta(z)=\mathcal N(0,I); the approximate posterior is a Gaussian with diagonal covariance, whose mean μ\mu and standard deviation σ\sigma are output by the encoder (Eq. 9):

qϕ(z∣x)=N(z; μ, σ2I)q_\phi(z|x) = \mathcal N\big(z;\ \mu,\ \sigma^2 I\big)

When zz has 20 dimensions, μ\mu and σ\sigma each have 20 numbers too, and every dimension has its own bell curve. Covariance describes whether the dimensions vary together; "diagonal" means keeping only each dimension's own variance, with no correlation between dimensions, so you can think of it as 20 one-dimensional Gaussians side by side. A footnote in the paper says the diagonal Gaussian is "just a (simplifying) choice, and not a limitation of our method."

With Gaussians on both sides, the KL term can be integrated. The diagonal covariance makes the dimensions independent of one another, so the KL splits into a sum over dimensions, and we only need to compute one. Let q=N(μ,σ2)q=\mathcal N(\mu,\sigma^2) and p=N(0,1)p=\mathcal N(0,1).

First, the expectation of log⁡p(z)\log p(z) under qq. log⁡p(z)=−12log⁡2π−12z2\log p(z)=-\tfrac12\log 2\pi-\tfrac12 z^2, and Eq[z2]\mathbb E_q[z^2] is the squared mean plus the variance:

Eq[log⁡p(z)]=−12log⁡2π−12(μ2+σ2)\mathbb E_q\big[\log p(z)\big] = -\tfrac12\log 2\pi - \tfrac12\big(\mu^2+\sigma^2\big)

Next, the expectation of log⁡q(z)\log q(z). log⁡q(z)=−12log⁡2π−12log⁡σ2−(z−μ)2/(2σ2)\log q(z)=-\tfrac12\log 2\pi-\tfrac12\log\sigma^2-(z-\mu)^2/(2\sigma^2), where Eq[(z−μ)2]=σ2\mathbb E_q[(z-\mu)^2]=\sigma^2, so the last term's expectation is 12\tfrac12:

Eq[log⁡q(z)]=−12log⁡2π−12(1+log⁡σ2)\mathbb E_q\big[\log q(z)\big] = -\tfrac12\log 2\pi - \tfrac12\big(1+\log\sigma^2\big)

Subtract one from the other, and log⁡2π\log 2\pi cancels:

−DKL(q ∥ p)=Eq[log⁡p(z)]−Eq[log⁡q(z)]=12(1+log⁡σ2−μ2−σ2)\begin{aligned} &-D_{\mathrm{KL}}(q\,\|\,p) \\ &\quad= \mathbb E_q\big[\log p(z)\big]-\mathbb E_q\big[\log q(z)\big] \\ &\quad= \tfrac12\big(1+\log\sigma^2-\mu^2-\sigma^2\big) \end{aligned}

Summing over JJ dimensions gives the result of Appendix B, which is the 1 + logvar - mu.pow(2) - logvar.exp() in the line of code we started with.

The shape of this expression is easy to read. −μ2-\mu^2 pulls the mean back to 0; the derivative of σ2−log⁡σ2\sigma^2-\log\sigma^2 with respect to σ2\sigma^2 is 1−1/σ21-1/\sigma^2, so it is smallest at σ2=1\sigma^2=1. A dimension's KL is therefore 0 only when μ=0\mu=0 and σ=1\sigma=1, and at that point this dimension's code has nothing to do with the input.

Take a 2-dimensional example. For some image, the encoder outputs μ=(1.2, 0)\mu=(1.2,\,0) and σ2=(0.25, 1)\sigma^2=(0.25,\,1). The KL of the first dimension is −12(1+log⁡0.25−1.44−0.25)≈1.04-\tfrac12(1+\log 0.25-1.44-0.25)\approx 1.04 nats, about 1.5 bits; plug in the second dimension, and it comes out exactly 0. The first dimension records a little information about this image, and its KL is that 1.04 nats; the second dimension is identical to the prior, its KL is 0, and it records nothing at all. The 0.60 for the true posterior N(1,12)\mathcal N(1,\tfrac12) in the table earlier comes from the same expression.

Following one MNIST image through

A top-to-bottom flowchart. Input x (784 pixels) enters the encoder q(z|x) (784 to 500, tanh), which outputs μ and log σ² (20 dimensions each); μ and log σ² connect on the right to the KL term, whose formula is minus one half times the sum of 1 plus log σ² minus μ² minus σ². The noise ε ~ N(0, I) in a dashed box on the left combines with μ and σ into z = μ + σ ⊙ ε (20 dimensions). z enters the decoder p(x|z) (20 to 500, tanh, then to 784), which outputs y (784 sigmoid probabilities), connected on the right to the reconstruction term Σ x log y + (1 − x) log(1 − y). At the bottom: ELBO equals the reconstruction term minus the KL term, with gradient ascent on θ and φ together.
Drawn for this note from Sections 3 and 5 and Appendix C of the paper.

Put these parts together and follow one MNIST image through. The latent dimension is 20, one of the settings in Figure 2.

  1. Input. xx is 784 pixels.
  2. Encoder. The Gaussian MLP of Appendix C.2 first computes h=tanh⁡(W3x+b3)h=\tanh(W_3x+b_3), with 500 hidden units in the MNIST experiments; two linear layers then output μ=W4h+b4\mu=W_4h+b_4 and log⁡σ2=W5h+b5\log\sigma^2=W_5h+b_5, 20 dimensions each. Outputting log⁡σ2\log\sigma^2 means there's no need to separately constrain σ\sigma to be positive.
  3. Sampling. Draw a 20-dimensional ε∼N(0,I)\varepsilon\sim\mathcal N(0,I) and compute z=μ+σ⊙εz=\mu+\sigma\odot\varepsilon, where ⊙\odot is element-wise multiplication.
  4. Decoder. The Bernoulli MLP of Appendix C.1 computes y=sigmoid(W2tanh⁡(W1z+b1)+b2)y=\mathrm{sigmoid}\big(W_2\tanh(W_1z+b_1)+b_2\big), giving 784 probabilities between 0 and 1, one per pixel. A Bernoulli distribution is just a possibly unfair coin with only two outcomes, 0 and 1; the decoder prepares one coin per pixel, and yiy_i is the probability that it lands on 1.
  5. The two terms of the objective. The reconstruction term is log⁡pθ(x∣z)=∑ixilog⁡yi+(1−xi)log⁡(1−yi)\log p_\theta(x|z)=\sum_i x_i\log y_i+(1-x_i)\log(1-y_i). When a pixel is 1, only log⁡yi\log y_i remains; when it is 0, only log⁡(1−yi)\log(1-y_i) remains. The 784 coins are independent, so their probabilities multiply, and after taking the log it becomes a sum of 784 terms, the same idea as in the height example. The KL term uses the closed form we just derived, computed directly from μ\mu and log⁡σ2\log\sigma^2.

Together, this is the paper's Eq. (10), here with L=1L=1:

L(θ,ϕ;x)≃12∑j=1J(1+log⁡σj2−μj2−σj2)+log⁡pθ(x∣z)\begin{aligned} \mathcal L(\theta,\phi;x) \simeq{}& \frac12\sum_{j=1}^{J}\Big(1+\log\sigma_j^2-\mu_j^2-\sigma_j^2\Big) \\ &+ \log p_\theta(x|z) \end{aligned}

In backpropagation, the gradient of the reconstruction term flows through the decoder to zz, then through z=μ+σ⊙εz=\mu+\sigma\odot\varepsilon splits into two paths back to μ\mu and σ\sigma, and finally enters the encoder; the gradient of the KL term lands directly on μ\mu and log⁡σ2\log\sigma^2. ε\varepsilon is just an external input and needs no gradient.

Frey Face consists of continuous grayscale face images, so the decoder switches to the Gaussian MLP of Appendix C.2, except that its output mean passes through a sigmoid to stay between 0 and 1; the hidden layer shrinks to 200 units, because this dataset is much smaller and the authors were worried about overfitting.

In code, the core is the few lines below, excerpted from the official PyTorch example with the variable names unchanged:

python
def reparameterize(mu, logvar):
    std = torch.exp(0.5 * logvar)   # σ = exp(½ log σ²)
    eps = torch.randn_like(std)     # ε ~ N(0, I), parameter-free
    return mu + eps * std           # z = μ + σ ⊙ ε

def loss_function(recon_x, x, mu, logvar):
    # −log p(x|z): Bernoulli decoder, summed over 784 pixels
    BCE = F.binary_cross_entropy(recon_x, x.view(-1, 784), reduction='sum')
    # D_KL(q(z|x) ‖ N(0, I)): closed form from Appendix B, summed over 20 latent dimensions
    KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
    return BCE + KLD                # negative ELBO, to be minimized

loss_function returns the negative ELBO, so the sign in front of the KL is the opposite of Appendix B's; in 2020, someone asked about this minus sign in the example's issue #824, and the asker figured out on their own that the quantity being minimized is the negative ELBO. The example also differs from the paper's setup in a few places; its hidden layers have 400 ReLU units, and the optimizer is Adam.

Discussion

Experimental setup

The experiments use only two datasets, MNIST handwritten digits and Frey Face faces, and compare against wake-sleep and Monte Carlo EM (MCEM). All parameters are randomly initialized from N(0,0.01)\mathcal N(0,0.01) and updated with Adagrad, with the global step size picked from {0.01, 0.02, 0.1} based on training performance in the first few iterations; minibatches have M=100M=100, with L=1L=1 per data point. A small weight decay is added to the objective, equivalent to placing an N(0,I)\mathcal N(0,I) prior on θ\theta, so strictly speaking this is approximate MAP estimation. Wake-sleep uses the same encoder as the VAE.

The lower bound

Nine line charts. The top row of five is MNIST, with latent dimension Nz of 3, 5, 10, 20, and 200; the bottom row of four is Frey Face, with Nz of 2, 5, 10, and 20. The horizontal axis is the number of training samples seen, on a log scale from 10 to the 5th to 10 to the 8th; the vertical axis is the average lower bound per data point. Red lines are AEVB and green lines wake-sleep, solid for training and dashed for test. In every MNIST panel the red lines are above the green ones; at Nz of 20 and 200, AEVB's test bound is about −100 and wake-sleep's about −103 to −104. On Frey Face, the green lines stall at about 570 to 580, while the red lines climb all the way to 900 to 1,500.
Original Figure 2, Kingma and Welling, from PDF page 7, arXiv license, scholarly quotation.

The top row is MNIST, with latent dimension NzN_z from 3 to 200; the bottom row is Frey Face, with NzN_z from 2 to 20. The horizontal axis is the number of training samples seen so far, on a log scale from 10510^5 to 10810^8; the vertical axis is the average lower bound per data point, and higher is better. Red lines are AEVB and green lines are wake-sleep; solid lines are the training set and dashed lines the test set. MNIST uses 500 hidden units, and Frey Face uses 200.

Start with MNIST. In every panel, the red line climbs earlier than the green one and levels off higher. Taking Nz=20N_z=20 as an example, near 10810^8 training samples, AEVB's test bound is about −100 and wake-sleep's about −104 (approximate values read off the plot); at Nz=3N_z=3 the difference is larger, about −133 versus −138.

Now the rightmost panel, Nz=200N_z=200. The latent dimension is ten times that of Nz=20N_z=20, yet the test bound gets no worse, staying around −100, and the gap between training and test doesn't widen either. The paper attributes this to "the regularizing effect of the lower bound." Going back to the KL expression from earlier, unused dimensions can set μ\mu to 0 and σ\sigma to 1, costing no KL and recording nothing, so they never get a chance to memorize the training data. This is this note's reading; the paper never actually counted how many dimensions sit idle. Such dimensions were only counted later, by IWAE.

The Frey Face numbers are positive because a continuous Gaussian density is used here. Pixel values lie between 0 and 1, and the predicted standard deviation is small, so the density can be far greater than 1, and its log becomes positive. What stands out most in this row is the green lines. After about 6×1056\times10^5 samples, wake-sleep flattens out at around 570 to 580 and never moves again, while AEVB keeps climbing, with the test bounds for Nz=10N_z=10 and 2020 reaching around 1,300. The dataset is small, and training and test start to separate, at about 1,490 versus 1,320 for Nz=20N_z=20.

As for cost, the caption says each million training samples took about 20 to 40 minutes on an Intel Xeon CPU "running at an effective 40 GFLOPS." At that pace, getting to 10810^8 on the horizontal axis takes somewhere between thirty-odd and sixty-odd hours.

Marginal likelihood

A lower bound is, after all, only a lower bound. AEVB's bound being higher could also just mean its qq guesses better, while the model itself is not necessarily better. The second set of experiments estimates log⁡pθ(x)\log p_\theta(x) directly.

Estimating the marginal likelihood is hard, so the authors had to shrink the latent space to 3 dimensions and the encoder and decoder to 100 hidden units; the paper says that with more dimensions, the estimate becomes unreliable. The estimate in Appendix D takes three steps:

  1. Use Hybrid Monte Carlo (HMC) to sample from the true posterior pθ(z∣x)p_\theta(z|x). HMC only needs ∇zlog⁡pθ(z)+∇zlog⁡pθ(x∣z)\nabla_z\log p_\theta(z)+\nabla_z\log p_\theta(x|z), not pθ(x)p_\theta(x).
  2. Fit a density estimate q(z)q(z) to these samples.
  3. Draw a new batch of posterior samples z(l)z^{(l)} and plug them into the formula below.
pθ(x)≃(1L∑l=1Lq(z(l))pθ(z(l)) pθ(x∣z(l)))−1p_\theta(x) \simeq \left(\frac1L\sum_{l=1}^{L}\frac{q(z^{(l)})}{p_\theta(z^{(l)})\,p_\theta(x|z^{(l)})}\right)^{-1}

This formula comes from 1/pθ(x)=∫pθ(z∣x) q(z)/pθ(x,z) dz1/p_\theta(x)=\int p_\theta(z|x)\,q(z)/p_\theta(x,z)\,dz, which holds as long as qq is a density that integrates to 1. Reciprocal estimators like this depend heavily on how well q(z)q(z) fits, and fitting gets hard as the dimension grows; the paper only claims accurate estimates below 5 dimensions. Each model is evaluated on the first 1,000 data points of both the training set and the test set, with 50 posterior samples per data point drawn by HMC with 4 leapfrog steps.

MCEM uses no encoder. Before each update, it runs 10 HMC leapfrog steps to sample from the posterior (with the step size automatically tuned for a 90% acceptance rate), then makes 5 weight updates with that sample.

Two line charts, with the estimated marginal log-likelihood on the vertical axis and the number of training samples seen (in millions) on the horizontal axis. Left, a training set of 1,000: AEVB's and MCEM's training curves both rise to about −109, and their test curves level off at about −143 and −141.5; wake-sleep is about −125 on training and −145 on test. Right, a training set of 50,000: AEVB is about −131 on training and −138 on test; wake-sleep about −137 on training and −141 on test; MCEM's two blue lines rise slowly from the bottom of the plot, reaching about −147 and −148.5 at 68 million samples.
Original Figure 3, Kingma and Welling, from PDF page 8, arXiv license, scholarly quotation.

The left plot trains on only 1,000 MNIST images, the right on 50,000. The horizontal axis is the number of training samples seen, in millions; the vertical axis is the estimated marginal log-likelihood.

On the left, AEVB's and MCEM's training curves both climb to about −109, but their test values are only about −143 and −141.5, with MCEM's test value slightly higher. With only a thousand data points, both methods overfit badly. Wake-sleep's training value stalls around −125.

The right plot is what AEVB set out to prove. With fifty times as much data, MCEM has to run a stretch of HMC before every step, and after 68 million samples its training and test values are still creeping upward around −147 to −148; AEVB's test value is about −138, and wake-sleep's about −141. The caption also states plainly that "Monte Carlo EM is not an on-line algorithm" and "can't be applied efficiently for the full MNIST dataset."

A model with a 3-dimensional latent space and 100 hidden units is tiny, so −138 can only be compared with the other curves in the same figure; the MNIST log-likelihoods reported in later literature come from very different models and evaluation conditions.

A 2D latent space

Two grids of generated images. Left, (a) Frey Face: faces in 10 columns and 10 rows, whose mouths change from top to bottom, from pressed lips to a toothy smile. Right, (b) MNIST: handwritten digits in about 20 columns and 20 rows, changing continuously between neighboring cells, with 6 and 0 at the top, 2, 3, 5, and 8 through the middle, 9 on the left, and along the bottom a 7 on the left turning into a 1 toward the right.
Original Figure 4, Kingma and Welling, from PDF page 10, arXiv license, scholarly quotation.

Appendix A shrinks the latent space to 2 dimensions and plots it directly. The authors take evenly spaced grid points on the unit square, map them to zz through the Gaussian's inverse CDF, then hand each zz to the decoder and plot pθ(x∣z)p_\theta(x|z). Since the prior is Gaussian, mapping through the inverse CDF gives every cell the same prior probability, so no grid cells are wasted on far-off regions the prior almost never reaches.

In the MNIST grid on the right, the digits change gradually from one cell to the next. Along the bottom, a 7 grows thinner and straighter toward the right until it becomes a 1; at the top, a 6 turns into a 0 toward the right; through the middle, 2, 3, 5, and 8 blend into one another. In the Frey Face grid on the left, from top to bottom, the mouth goes from pressed shut to a smile that shows teeth.

This figure also exposes a limitation. The 2D zz has to represent both "which digit" and "how it's written," and the two get mixed together; on the way from 7 to 1, a few cells look like something in between. There are no labels during training, and the model has no reason to put the digit class along any one direction of its own.

Two implementation pitfalls

The mistakes most easily made in implementation are in details the paper doesn't spell out line by line. The issues on the official PyTorch example preserve two typical cases.

The first is the scale of the two terms. The reconstruction term is a sum over 784 pixels and the KL term a sum over 20 latent dimensions, and the two have to be added on the same scale; averaging over the minibatch is fine, as long as both terms are averaged together. In October 2017, a user reported in #234 having changed the reconstruction term to average over pixels as well, while the KL was averaged over the batch only. That scales up the KL's relative weight 784 times, and both the reconstructed and the generated images came out "faint and blurry," "just like digit 8." In February 2018 the example switched to summing everything (#296). If you deliberately change the KL's weight, you already have a different model, and that is where the later β-VAE starts.

The second is the choice of likelihood. A Bernoulli distribution is defined only on 0 and 1, and the paper states plainly that the Bernoulli decoder is for binary data; the example, however, computes binary cross-entropy directly on grayscale pixels between 0 and 1, and what comes out is no longer a normalized log-likelihood. Someone pointed this out in #460 as early as late 2018. In 2019, Loaiza-Ganem and Cunningham's "The continuous Bernoulli" supplied the missing normalizing constant and called this practice a "pervasive error in variational autoencoders," and Loaiza-Ganem even sent a PR to fix the example (#683). That PR was closed in March 2022, on the grounds that the examples should "stick boring methods that work" (#460, meanwhile, is still open). When training on grayscale images, either binarize the pixels first or switch to a likelihood defined on continuous values.

A concurrent paper

At almost the same time, in January 2014, Rezende, Mohamed, and Wierstra of DeepMind released "Stochastic Backpropagation and Approximate Inference in Deep Generative Models," which likewise uses a recognition model as a stochastic encoder, likewise passes gradients through random variables, and trains the generative model and the recognition model jointly. The VAE paper states in its related work that their work "was developed independently of ours."

In 2024, ICLR gave its Test of Time Award for the first time, and from the papers of 2013 and 2014 it picked this one; the official announcement also made a point of mentioning the concurrent work of Rezende et al.

Limitations

  • Continuous latent variables only. The reparameterization needs a differentiable gϕg_\phi, which rules out discrete zz.
  • The approximate posterior is a diagonal Gaussian. The dimensions are assumed to be independent of one another; as soon as the true posterior has correlations between dimensions, the KL gap in Eq. (1) can't be 0. The paper says this is only a simplification, yet its experiments try only this one choice.
  • Small models and small comparisons. The encoder and decoder are both single-hidden-layer MLPs, the datasets are only MNIST and Frey Face, and the only competitors are wake-sleep and MCEM; every result is plotted as a curve, without a single table of numbers.
  • The marginal likelihood can only be estimated for low-dimensional models. The estimator in Appendix D is used only on a 3-dimensional latent space, and the paper itself says it is unreliable at 5 dimensions and above.

Conclusion

This paper rewrote the hardest-to-differentiate step of variational inference as "draw noise first, then apply a deterministic transformation"; add an encoder that takes xx as input, and the generative model and the inference model can be trained together with the same bound and the same minibatch gradients. The experiments are small, but within what they compare, AEVB converges faster than wake-sleep, reaches a higher bound, and remains practical on large data where MCEM is not.

When writing your own VAE, check three places first. Does the encoder output log⁡σ2\log\sigma^2 or σ\sigma? The reparameterization line has to match. Are the reconstruction and KL terms summed on the same scale? Does the decoder's likelihood fit the data type? Use Bernoulli for binary data and switch to a continuous distribution for continuous data. Get any of these three wrong, and the code still runs, and the loss still goes down.

The caption of Figure 2 goes out of its way to note that "more latent variables does not result in more overfitting." Less than two years later, Bowman et al. swapped the decoder for an LSTM language model, the approximate posterior collapsed entirely back onto the prior, and the KL term dropped to 0.