Auto-Encoding Variational Bayes
- 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}
}
If you have ever written a VAE, chances are you copied this line:
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 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.

A Gaussian has only two parameters. is the mean, which sets where the center of the bell is; is the standard deviation, which sets how wide the bell is. In the figure, the blue and orange curves both have a of 5, and moving the orange curve's from 170 to 180 shifts the whole curve to the right; the green curve's is also 170, but its doubles to 10, and the curve becomes lower and wider. As a formula, it is
Read as "the height, at position , of the Gaussian with mean and variance "; 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 is from , the more negative the exponent and the smaller the value, so the curve is highest at and falls off on both sides. The distance is divided by before it is squared, so the larger is, the more lightly the same distance is penalized, and the wider the curve. The factor 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 .
Likelihood
Now turn the question around. The three data points are already in hand, but the parameters are unknown. Which is more reasonable, or ?

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 and slide left and right, the product is largest when 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 . 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, , so the log-likelihood of one image is , 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 and B's is , 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 , with the fair coin and the biased one; call the outcome , with heads and tails. determines the probability of , but we only get to see , and a variable like this is called a latent variable. The whole process breaks down into two steps:
- : the probability of picking each coin, 0.5 for each. This is called the prior, our view of before seeing any outcome.
- : the probability of tossing once we know which coin was picked. The vertical bar reads "given," and this is called a conditional probability; for example, .
What is the total probability of heads, ? Either coin can come up heads, so add the two cases:
Going through every possible value of the unseen variable and summing, weighted by its probability, is called marginalization, and the resulting is called the marginal probability. Here 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:
Plugging in the numbers, . Before seeing heads, we thought the two coins were equally likely; after seeing heads, the biased coin's probability rises to 0.64. is called the posterior, our view of after seeing the data. The numerator is the prior times ; at this point is fixed and is treated as a function of , which is exactly the likelihood we met earlier.
Now the denominator. It is the 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 . With two coins, that's just two terms; but if is a continuous vector and 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 from a simple distribution , then, based on , draw a image from .
This has the same structure as the coins. is the latent variable; think of it as unlabeled factors such as "which digit, how thick the strokes, which way it slants." is the prior; the parameters of are produced by a neural network, and is that network's weights. The difference is that no longer has just two possible values; it is a continuous vector.
All we have in hand is a pile of . To learn , the goal is to maximize the log-likelihood of the data; the sum from the coin example becomes an integral when is continuous:
For now, read as "sum over all possible ." Since 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 contributes "the probability density of drawing this " times "the probability density of this producing ." has been integrated out, so is called the marginal likelihood.
When the integral can be computed
First, an example that can be computed. Let be one-dimensional, with prior and a linear decoder ; that is, draw a , then add noise with standard deviation 1 around it to get . Stacking two Gaussians still gives a Gaussian; the variance of is the 1 from itself plus the 1 from the noise, so the marginal distribution is . By Bayes' theorem, multiply the prior by the likelihood and divide by the marginal, and the posterior is Gaussian too:

Take . The dashed blue curve is the prior, centered at 0. The dotted orange curve is the likelihood, with fixed at 2 and varying; the closer is to 2, the better its chance of producing . The solid purple curve is the posterior . 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 with a tanh inside . The integral 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 , so the most direct approach is to draw values of from the prior and average . The trouble is that for a particular "7," a drawn at random from the prior will mostly decode to some other digit, making 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 , 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:
- Estimate , which lets us generate realistic new data;
- Given , infer , to use as a code or representation;
- Estimate , since tasks such as denoising, inpainting, and super-resolution need a prior over .
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 to approximate it. The paper calls it the recognition model, governed by a separate set of parameters .

The gray is observed data, and the white is unseen; the in the bottom-right corner of the box means each of the data points has its own . The solid lines are the generative model , pointing from to ; the dashed line is the approximate posterior , pointing the other way, from back to . and are learned together.
From a coding point of view, is a code for . So the paper calls a probabilistic encoder: given an image, it outputs a distribution, such as a Gaussian, describing which the image might have come from. 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 is a network that takes as input, all data share the same , 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 in place, we next need an objective we can optimize. We start from and take it apart step by step.
Before taking it apart, one piece of notation. is called the expectation of under , which means a weighted average: plug every possible into and weight it by the probability 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 .
When is continuous, the weighted average becomes an integral and often can't be computed. But as long as we can sample from , we can draw a few and average 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, contains no , so it is the same number for every , and a weighted average of it is still itself. We can therefore write it as an expectation under :
Second, use Bayes' theorem to replace with . is the probability of and 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 and split it into two terms. Below, is shorthand for :
The second term is exactly the KL divergence from to the true posterior.
The KL divergence (Kullback–Leibler divergence) measures how much two distributions differ. It is defined as : at each possible value, take the log ratio of the two distributions, then average with 's probabilities as the weights. Take the heads and tails probabilities of the two coins as an example, with the fair coin's (0.5, 0.5) and the biased coin's (0.9, 0.1):
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 . 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 , and we have the paper's Eq. (1):
The KL divergence is never less than 0, so can never exceed . This is the lower bound of Eq. (2):
As the coin example showed, the denominator of Bayes' theorem, , is called the evidence, so 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 guesses, the tighter the bound; if it guesses exactly, equality holds.
- does not depend on . Raising with respect to can only come from shrinking that KL, that is, from pushing toward the true posterior; raising with respect to pushes up the lower bound on . One objective handles both inference and learning, which is something wake-sleep cannot do.
Take it apart once more. ; group with , and another KL appears, giving Eq. (3):
Read this way, it is an autoencoder. The first term draws a with the encoder, then asks how likely the decoder is to produce the original 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 . Its marginal distribution is , so
Let's try two approximate posteriors. The reconstruction term is , and if , then . We'll see how to compute the KL term when we derive Appendix B shortly; for now, we just use the result.
| Recon. term | KL term | ELBO | |
|---|---|---|---|
| , ignores | −3.42 | 0 | −3.42 |
| , true posterior | −1.67 | 0.60 | −2.27 |
Computed for this note from Eq. (3) and Appendix B of the paper, in nats.
The first is simply the prior, so its KL term is 0, but the it draws have nothing to do with , and the reconstruction term is poor. The second 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 exactly, because it is the true posterior. The first 's ELBO is 1.15 nats below the true value, and you can check directly that this gap is exactly the KL from to the true posterior .
With a neural network decoder, can't be computed, and we don't know what the true posterior looks like; but as long as we can sample from , 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 . To estimate it, sample from and average. Differentiating with respect to is no problem, since the gradient can move straight inside the expectation; the trouble is , because the distribution we sample from is itself determined by .
The common choice at the time was the score function estimator (called REINFORCE in reinforcement learning). Move inside the integral and use :
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 and (the reconstruction term without its constant), and differentiate with respect to at ; the correct answer is 2. Take one sample ; since , the score function estimate is
Expanding it with the moments of the normal distribution, , , and , its mean is 2 and its variance is 21.75.
Now shift all of 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 , and log-likelihoods, unfortunately, usually have large absolute values.
The reparameterization trick
The paper's solution is to produce a different way. A one-dimensional Gaussian can be written as
All the randomness is handed to , and the distribution of has no parameters at all; becomes a deterministic function of , , and . The expectation can then be taken over instead:
The distribution on the right doesn't depend on or , so the gradient can move straight inside and be computed with the chain rule:
Back to the same example, . The single-sample estimate for is , which at and has mean 2 and variance 1; shifting by 100 has no effect on it, because it only looks at the slope of . The estimate for , , has mean , the same as differentiating directly.
Same gradient, one sample each, and the variance is 1 versus 21.75; the larger the absolute value of , the wider the gap grows.
The general form is the paper's Eqs. (4) and (5). Find a differentiable function and a noise distribution that doesn't depend on the parameters, such that follows exactly , and the expectation can be estimated with samples of the noise:
Which distributions admit such a ? Section 2.4 lists three kinds:
- Tractable inverse CDF: let and take to be the inverse cumulative distribution function of ; examples include the exponential, Cauchy, logistic, and Gumbel distributions.
- Location-scale families: like the Gaussian, , where is the location, the scale, and 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 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 directly, written . If the KL term has an analytic solution, only the reconstruction term is sampled; this is in Eq. (7):
Here . With one less term to estimate, the variance is usually smaller too. These estimators are called SGVB (Stochastic Gradient Variational Bayes).
With data points in the dataset and drawn each time to form a minibatch, the minibatch sum multiplied by is an estimate of the bound for the whole dataset (Eq. 8):
Algorithm 1 puts these together into a loop. Each iteration draws a minibatch, draws noise for each data point, computes the gradients with respect to , and updates with SGD or Adagrad, until convergence. This is AEVB (Auto-Encoding Variational Bayes). The experiments use and , drawing just one 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, ; the approximate posterior is a Gaussian with diagonal covariance, whose mean and standard deviation are output by the encoder (Eq. 9):
When has 20 dimensions, and 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 and .
First, the expectation of under . , and is the squared mean plus the variance:
Next, the expectation of . , where , so the last term's expectation is :
Subtract one from the other, and cancels:
Summing over 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. pulls the mean back to 0; the derivative of with respect to is , so it is smallest at . A dimension's KL is therefore 0 only when and , 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 and . The KL of the first dimension is 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 in the table earlier comes from the same expression.
Following one MNIST image through

Put these parts together and follow one MNIST image through. The latent dimension is 20, one of the settings in Figure 2.
- Input. is 784 pixels.
- Encoder. The Gaussian MLP of Appendix C.2 first computes , with 500 hidden units in the MNIST experiments; two linear layers then output and , 20 dimensions each. Outputting means there's no need to separately constrain to be positive.
- Sampling. Draw a 20-dimensional and compute , where is element-wise multiplication.
- Decoder. The Bernoulli MLP of Appendix C.1 computes , 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 is the probability that it lands on 1.
- The two terms of the objective. The reconstruction term is . When a pixel is 1, only remains; when it is 0, only 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 and .
Together, this is the paper's Eq. (10), here with :
In backpropagation, the gradient of the reconstruction term flows through the decoder to , then through splits into two paths back to and , and finally enters the encoder; the gradient of the KL term lands directly on and . 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:
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 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 , with per data point. A small weight decay is added to the objective, equivalent to placing an prior on , so strictly speaking this is approximate MAP estimation. Wake-sleep uses the same encoder as the VAE.
The lower bound

The top row is MNIST, with latent dimension from 3 to 200; the bottom row is Frey Face, with from 2 to 20. The horizontal axis is the number of training samples seen so far, on a log scale from to ; 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 as an example, near training samples, AEVB's test bound is about −100 and wake-sleep's about −104 (approximate values read off the plot); at the difference is larger, about −133 versus −138.
Now the rightmost panel, . The latent dimension is ten times that of , 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 to 0 and 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 samples, wake-sleep flattens out at around 570 to 580 and never moves again, while AEVB keeps climbing, with the test bounds for and reaching around 1,300. The dataset is small, and training and test start to separate, at about 1,490 versus 1,320 for .
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 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 guesses better, while the model itself is not necessarily better. The second set of experiments estimates 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:
- Use Hybrid Monte Carlo (HMC) to sample from the true posterior . HMC only needs , not .
- Fit a density estimate to these samples.
- Draw a new batch of posterior samples and plug them into the formula below.
This formula comes from , which holds as long as is a density that integrates to 1. Reciprocal estimators like this depend heavily on how well 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.

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

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 through the Gaussian's inverse CDF, then hand each to the decoder and plot . 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 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 , which rules out discrete .
- 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 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 or ? 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.