VAE with a VampPrior
- Publication
- AISTATS 2018Conference
- First submitted to arXiv
- arXiv:1705.07120
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{imagegenerationvampprior2017,
title = {{VAE with a VampPrior}},
author = {Jakub M. Tomczak and Max Welling},
year = {2017},
eprint = {1705.07120},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1705.07120}
}
Train a VAE, draw a from , hand it to the decoder, and quite often you get back a blurry blob that doesn't look like anything.
The decoder has only learned to draw in the regions the encoder actually used. The standard normal is a prior we picked for the latent space because it is convenient to compute with, and the region it covers can be very different from the region the encoder really uses.
The authors of this paper are Jakub Tomczak and Max Welling of the University of Amsterdam; Welling is also one of the two authors of the original VAE paper. They replaced the prior with the Variational Mixture of Posteriors prior, VampPrior for short, which sounds like "vampire." The method really is a bit vampiric. The prior has no Gaussian parameters of its own; each of its components is an approximate posterior borrowed by feeding a "fake input" into the encoder.
This note first takes the KL term of the ELBO apart to find out what the prior is really being asked to do; then looks at how the authors approximate the best prior with K learnable fake images, along with the two-layer version; and finally at how far the evidence goes, and which parts need a discount.
Defining the Problem
What the prior governs in the ELBO
First, the notation. The training data is , and is the empirical distribution, i.e., "draw an image uniformly from the training set." is the encoder (approximate posterior), is the decoder, is the prior, and are their respective parameters. Eq. (1) of the paper is the ELBO averaged over the whole training set:
The first term is the reconstruction term, and the last two together are .
The standard VAE fixes the prior to , with no to learn. The gradient of with respect to is , so whether the input is a 3 or a 7, the prior pulls toward the origin. The paper says this causes over-regularization, with worse latent representations and fewer useful dimensions.
Splitting the KL term in two
The authors follow the decomposition from Hoffman and Johnson's 2016 "ELBO surgery." Average the KL term over all the training data and first split it into two expectations:
The first expectation is the average entropy of the individual posteriors. It has nothing to do with the prior and simply encourages each image's posterior to be a little wider.
Only the second expectation involves the prior. Note that the integrand doesn't depend on "which image" it is, so the posteriors can be summed first and integrated afterward:
is called the aggregated posterior. Feed the whole training set into the encoder, and each image leaves a blob of posterior in latent space; add up all the blobs and divide by , and you get the region the encoder actually occupies.
At this point the prior has a single job left in the ELBO, which is to keep its cross-entropy with the aggregated posterior, , as small as possible (Eqs. (4)–(6) of the paper).
The best prior
The cross-entropy can be split once more:
doesn't depend on the prior; the KL divergence is greater than or equal to 0, and equals 0 only when the two distributions are identical. So with the encoder fixed, the prior that maximizes the ELBO is the aggregated posterior itself:
The paper solves for it with a Lagrange multiplier (Eqs. (7) and (8)) and gets the same result.
An example with two images
A small example shows how big the gap can be. Suppose the latent space is 2-dimensional, the training set has only two images, and the encoder sends them to and respectively.
Start with the standard normal prior. The KL between two Gaussians has a closed form, per dimension. Summed over the two dimensions:
Each image's KL is 5.615 nats.
Now use the aggregated posterior as the prior, that is, a mixture with half the weight on each of the two Gaussian blobs. For the first image, near its posterior is almost exactly , so the KL drops to just nats. Those 0.693 nats are exactly the information needed to tell "which of the two" images it is.
The extra nats are . In general, when the prior equals the aggregated posterior, what remains of the KL term is the mutual information between and "which training image," at most .
The problem at generation time shows up here too. Sampling from , only about 1.2% of samples land within three standard deviations (radius 0.3) of either posterior blob; the rest land where the aggregated posterior is nearly zero, and at the origin, for instance, is about . The decoder was never trained in those places, and what it draws there is the blurry blob from the start of this note. Tomczak's blog later called such regions, where the prior assigns plenty of probability but the aggregated posterior is nearly zero, holes.
So why not just use the aggregated posterior?
The paper gives two reasons.
The first is computation. Every evaluation of means computing the posteriors of all training images. Static MNIST has 50,000 training images, so every step would run the encoder 50,000 times.
The second is overfitting. The paper only says it "may potentially lead to overfitting," but the analysis above makes it more concrete. When the prior equals the aggregated posterior, the KL never exceeds however sharp each posterior blob gets, about 10.8 nats at ; under a standard normal prior, the sharper the posterior, the larger the KL. So the model can safely put each training image on a spike of its own and let the decoder memorize every one. The ELBO on the training set looks great, but the model's distribution sits entirely on the training images, and test images get no probability.
The standard normal is too simple, and the aggregated posterior is too expensive and memorizes the answers. A common compromise is to make the prior a mixture of Gaussians (MoG), each component with its own learnable mean and variance. The authors include it in the experiments as a baseline, but what they propose is a different compromise.
Solving the Problem
K fake images
VampPrior replaces the training images with learnable pseudo-inputs (Eq. (9)):
is a -dimensional vector with the same shape as an input image; on MNIST it is a fake image. The pseudo-inputs are trained by backpropagation along with the network weights, and the prior's parameters are , where is shared with the encoder.
This formula looks exactly like the aggregated posterior, except that the sum runs over learned images instead of the real training images. The experiments use (1,000 for OMNIGLOT), two orders of magnitude fewer than the 50,000 training images. With a limited number of components, the prior can't keep a spike for every training image; with enough components, it can still grow a multimodal shape and won't pull every posterior toward the same point.
In the two-image example, if and happen to be learned as those two images, VampPrior is exactly the aggregated posterior.
Putting the pseudo-inputs in image space has its costs. At every step, besides the batch of training images, the encoder has to run on more fake images; with batch 100 and , the encoder processes 600 images at a time. The parameters live in image space too. On MNIST, 500 fake images of 784 dimensions are 392,000 numbers, while a MoG prior with the same 500 components in a 40-dimensional latent space needs only means and variances. In the wall-clock times measured in the supplementary material, compared with the standard normal prior, the MLP version is about 1.4 times slower, the convolutional version 1.9 times () to 2.1 times () slower, and the PixelCNN version 1.4 to 1.7 times slower.
What the implementation looks like
The official code writes the pseudo-inputs as a linear layer without bias whose input is the identity matrix, with the output passed through a Hardtanh clamped to . Multiplying the identity matrix by the weights just pulls out the weights themselves, so "learning pseudo-inputs" becomes "learning the weights of a linear layer," which any ordinary optimizer can update directly; Hardtanh keeps the fake images' pixel values within the range of real images.
is the log of a mixture of Gaussians and needs logsumexp to avoid numerical underflow. Below is a version compiled from the official models/Model.py and models/VAE.py, rewritten for current PyTorch:
import math
import torch
import torch.nn as nn
class VampPrior(nn.Module):
def __init__(self, encoder, K=500, D=784):
super().__init__()
self.encoder = encoder # the same encoder as q(z|x)
self.pseudo = nn.Linear(K, D, bias=False) # column k of the weight is u_k
nn.init.normal_(self.pseudo.weight, 0.05, 0.01)
self.register_buffer("eye", torch.eye(K))
def log_prob(self, z): # z: [B, M]
u = torch.clamp(self.pseudo(self.eye), 0.0, 1.0) # [K, D]
mu, logvar = self.encoder(u) # [K, M]
# log density of a diagonal Gaussian; the official code drops -M/2·ln(2π), which cancels with ln q(z|x) in the KL
log_comp = -0.5 * (logvar + (z[:, None] - mu) ** 2 / logvar.exp()).sum(-1) # [B, K]
return torch.logsumexp(log_comp, dim=1) - math.log(log_comp.shape[1])
# during training: z is one reparameterized sample from q(z|x)
# kl = log_normal_diag(z, mu_q, logvar_q) - prior.log_prob(z)
The KL term can only be estimated by sampling. A standard VAE can use the Gaussian-to-Gaussian closed form, but here the prior is a mixture, and the KL from a Gaussian to a Gaussian mixture has no closed form, so the official code computes directly on the reparameterized . In 2021, someone asked in issue #5 whether the closed-form KL could be used instead; nobody has replied to this day.
To generate, pick a uniformly from the pseudo-inputs, feed it into the encoder to get , sample from that, and hand it to the decoder. The official generate_x simply takes the first pseudo-inputs and samples once from each; in 2019, someone asked in issue #3 how to sample from the prior itself, and in the end it was another user who answered: "uniformly sample one of the pseudo inputs u and then pass it through the encoder."
How it differs from a Gaussian mixture prior
A MoG prior is also multimodal and can also approximate the aggregated posterior. The difference is that VampPrior's components are produced by the encoder, which ties the prior to the posterior.
First, look at how the prior pulls on . The log-gradient of a mixture is a weighted average of the components' gradients:
is the "responsibility" of component for ; whichever component is close to gets the larger weight. Each component is a diagonal Gaussian, with (element-wise), where are the encoder's outputs on . So the prior pulls toward nearby component centers, unlike the standard normal prior's , which always pulls toward the origin. Back in the two-image example, a near gets pulled toward , not toward the origin.
A MoG prior can do this too. What VampPrior adds is a gradient with respect to the encoder parameters . Eq. (25) of the supplementary material expands the gradient of the KL term with respect to a single weight , and every component carries a difference of the form . If some closely resembles , the two posteriors are computed by the same encoder, so when changes they move together, and this difference is close to 0. What gradient remains comes mainly from the pseudo-inputs that don't resemble .
The authors' reading is that under the standard normal prior the gradient always pulls the posterior toward 0 (supplementary Eq. (26)); under VampPrior, the components that resemble the input exert no pressure, so the encoder tends to assign different data to different regions of the latent space. The paper also views the pseudo-inputs as hyperparameters of the prior, learned by maximizing the ELBO, the same idea as empirical Bayes (type-II maximum likelihood).
The two-layer version
The prior's problems are worse in multilayer VAEs. The IWAE paper measured a statistic, the "activity" of latent dimension , , i.e., how much the posterior mean varies with the input; a unit counts as active only if . They found that the second layer of two-layer models was barely used, with fewer than 10 of its 50 dimensions active.
The paper's explanation is that generation runs top-down while inference runs bottom-up, so the deeper a latent layer sits, the less information from the real data it receives, and the more easily the KL term squashes it into the prior.

On the right, (b) is the authors' two-layer model; solid lines are generation and dashed lines are inference (Eqs. (10)–(15)):
- Inference first computes the top layer directly from , then computes from and together.
- Generation starts from , goes through , and the final decoder takes both and .
- VampPrior sits only at the top layer, .
All conditional distributions are diagonal Gaussians. The structure makes two deliberate choices. The top-layer posterior looks only at , so feeding straight into the encoder gives the prior's components, with no need to sample a for the fake image first. The decoder also takes directly (the curved solid line in the figure), so has a direct path to and is more than just a prior for .
The ELBO of the whole model is:
Inside the expectation, first sample , then . The official code draws a single set of samples per image and simply adds up the five log densities.
Experimental setup
All six datasets are small images. Static MNIST uses a fixed binarization and dynamic MNIST is re-binarized every time during training; the rest are OMNIGLOT (50 alphabets, 1,623 handwritten characters), Caltech 101 Silhouettes (black silhouettes of objects from 101 classes, with only 4,100 training images), Frey Faces (one person's face, about 2,000 images, ) and Histopathology (grayscale patches of tissue sections). The first four use Bernoulli decoders and the last two a discretized logistic distribution.
The main architecture is an MLP, with two gated fully connected layers of 300 units for each distribution and 40 dimensions each for and , a permutation-invariant setting that doesn't exploit the spatial structure of images. Two other versions replace the MLP with gated convolutions (convHVAE), and additionally replace the decoder with a PixelCNN (PixelHVAE).
Training uses Adam with learning rate or and batch size 100. Warm-up runs over the first 100 epochs, with the weight of the KL term rising linearly from 0 to 1; early stopping uses a look-ahead window of 50 epochs.
Evaluation uses the marginal log-likelihood on the test set, estimated by importance sampling with 5,000 samples, in nats, where closer to 0 is better. Frey Faces and Histopathology report bits/dim instead, where lower is better.
Discussion
Swapping the prior, once for each architecture
Table 1 trains each of the four architectures once with the standard normal prior and once with VampPrior. The original table has eight columns; here it is split into two, with each cell reading "standard normal / VampPrior."
| Data | VAE | HVAE |
|---|---|---|
| static MNIST | −88.56 / −85.57 | −86.05 / −83.19 |
| dynamic MNIST | −84.50 / −82.38 | −82.42 / −81.24 |
| OMNIGLOT | −108.50 / −104.75 | −103.52 / −101.18 |
| Caltech 101 | −123.43 / −114.55 | −112.08 / −108.28 |
| Frey Faces | 4.63 / 4.57 | 4.61 / 4.51 |
| Histopathology | 6.07 / 6.04 | 5.82 / 5.75 |
| Data | convHVAE | PixelHVAE |
|---|---|---|
| static MNIST | −82.41 / −81.09 | −80.58 / −79.78 |
| dynamic MNIST | −80.40 / −79.75 | −79.70 / −78.45 |
| OMNIGLOT | −97.65 / −97.56 | −90.11 / −89.76 |
| Caltech 101 | −106.35 / −104.22 | −85.51 / −86.22 |
| Frey Faces | 4.49 / 4.45 | 4.43 / 4.38 |
| Histopathology | 5.59 / 5.58 | 4.84 / 4.82 |
Compiled from Table 1 of the paper. The first four rows are log-likelihoods (nats), the last two bits/dim.
The two MLP columns show the clearest gains. The single-layer VAE improves by about 3 nats on static MNIST and about 8.9 nats on Caltech 101; the two-layer HVAE also gains 1.2 to 3.8 nats.
The stronger the decoder, the less swapping the prior does. convHVAE differs by only 0.09 nats on OMNIGLOT; PixelHVAE's gains fall between 0.35 and 1.25 nats, and Caltech 101 is the only cell in the whole table that goes backward, from −85.51 to −86.22. The supplementary material mentions that PixelHVAE's reconstructions sometimes show "fantasizing," strokes that aren't in the original image, which the authors put down to the decoder being too strong and ignoring part of the latent information. When the decoder can draw the image well on its own, there was never much room for the latent prior to improve things.
There's one more thing to watch for in this table. The paper only says that the standard deviation on Frey Faces is no more than 0.03 (over 3 repeats); the other datasets have no error ranges at all. For convHVAE's gaps of less than 0.1 on OMNIGLOT and Histopathology, it's hard to tell whether they are anything more than random variation.
Controls for the prior
If VampPrior works, is it because it is multimodal, because it is tied to the posterior, or because the pseudo-inputs are learnable? Table 2, on static MNIST, swaps four different priors into the top layer of the two-layer HVAE:
| Model | Log-likelihood |
|---|---|
| Two-layer VAE (from the IWAE paper) | −87.86 |
| Two-layer IWAE (from the IWAE paper) | −85.32 |
| HVAE + standard normal | −85.89 |
| HVAE + MoG | −85.07 |
| HVAE + VampPrior data | −85.71 |
| HVAE + VampPrior | −83.19 |
Compiled from Table 2 of the paper.
VampPrior data uses a random batch of real training images as fixed, non-trainable pseudo-inputs. The four HVAE rows can be read like this:
- The structure itself contributes. With the same standard normal prior, the authors' HVAE (−85.89) beats the two-layer VAE from the IWAE paper (−87.86) by nearly 2 nats. The two differ in dimensions and networks, so these 2 nats can't be credited to the prior.
- Multiple modes help. MoG beats the standard normal by 0.82 nats.
- Real images as components help very little. VampPrior data beats the standard normal by only 0.18 nats, and loses to MoG.
- Learnable pseudo-inputs are the main source. VampPrior beats the standard normal by 2.70 nats and MoG by 1.88 nats.
Point 3 is a bit surprising. Randomly picked real images look like they should be a decent approximation of the aggregated posterior, yet they turn out to be almost useless; the pseudo-inputs have to be learned together with the encoder to end up in the right places.

This figure sweeps over , with the test-set ELBO on the vertical axis. The ELBO is a lower bound, several nats below the importance-sampled log-likelihoods in Table 2, but the three lines can be compared with one another.
The blue line is the standard normal prior, which has no to tune, at about −94.4. The red MoG line is flat around −92.4 from very small onward, and drops past 500. The green VampPrior line is about level with MoG at very small , climbs as grows to −90.6 at 500, and then slips back to −90.9 as more are added. The authors themselves say they were somewhat surprised that more pseudo-inputs didn't help. This sweep was run only on static MNIST, and the paper doesn't answer whether the number 500 carries over to other datasets.
Latent dimensions woken up

This figure counts active units. Solid lines are the first layer , closest to , and dashed lines are the top layer ; blue and red are the VAE and IWAE, and green is HVAE with VampPrior.
VampPrior's has 36 to 37 active units, and its has 29 at . The VAE's two layers have 17 and 6, IWAE's 24 and 7. According to the paper, the top layer's active units quadruple and the first layer's grow about 1.5 times; even with a single component, the top layer has nearly three times as many.
This comparison needs a discount. The blue and red lines are horizontal lines taken from the appendix of the IWAE paper (fixed-binarization MNIST), whose models had latent layers of 100 and 50 dimensions and a different network altogether; the green line is the authors' own 40 + 40-dimensional HVAE, with both the inference and the generative structure changed. The figure has no line for HVAE with a standard normal prior (exactly the one line that most needed to be there), so how much of the "quadrupling" comes from the prior and how much from the structure can't be read off this figure.
The point makes this even clearer. With only one component, VampPrior is just a diagonal Gaussian with a learnable mean and variance; the shift and scale of such a prior can be absorbed by the first linear layer of the network that follows, so the models it can express are roughly the same as with a standard normal prior. In this setting the top layer already has around 19 active units, and the excess over IWAE's 7 more likely comes from the authors' two-layer structure and from differences in latent dimensions and training settings between the two.
Against the strongest models of the time
In the permutation-invariant MLP setting, HVAE with VampPrior is the best in the table on all four datasets; in parentheses is the best of the other papers' methods in the table. Static MNIST −83.19 (VAE + NF −85.10), dynamic MNIST −81.24 (VAE + VGP −81.32), OMNIGLOT −101.18 (Ladder VAE −102.11), Caltech 101 −108.28 (VR-max −117.10).
With convolutional and PixelCNN decoders, the comparison shifts to models that also use convolutional or autoregressive decoders, such as VLAE, IAF and PixelVAE. PixelHVAE reaches −78.45 on dynamic MNIST, slightly better than VLAE's −78.53 and PixelVAE's −78.96; on OMNIGLOT it is −89.76 against VLAE's −89.83, a 0.07-nat difference that amounts to a tie. On static MNIST, VLAE's −79.03 beats PixelHVAE's −79.78, and the paper explains in a footnote that VLAE used a different training procedure on this dataset.
What the fake images look like

Each set in the top row is 24 images generated from the same pseudo-input (the top-left cell). The MNIST set is all 8s, but with different thicknesses, slants and loop sizes; the Frey Faces set is the same face with different expressions. There is enough variation under a single component that the model is not just copying out some training image.
The bottom row is the trained pseudo-inputs. The paper calls them "prototypical objects (digits, characters, silhouettes)." MNIST and Omniglot do show blurry strokes, while the Caltech 101 Silhouettes column looks like TV static (so where are the silhouettes?). In the main text the authors admit that the Frey Faces pseudo-inputs are noisy, and say that pseudo-inputs are hard to train when the sample is small or the decoder too flexible. Caltech 101 has only 4,100 training images, and it is also exactly the dataset on which PixelHVAE went backward in Table 1 after switching to VampPrior. Whether the two share a cause, the paper ran no experiment to check.
Tomczak also wrote later, in the blog post "VAE priors," that the main drawback of the VampPrior lies in initializing the pseudo-inputs. On MNIST, the official code by default starts from nearly black images drawn from , with a separate option to initialize from training images.
Later fixes
The paper closes by mentioning that Alemi et al. replaced the uniform weights with learnable (Eq. (16) of the paper), letting the model decide which pseudo-inputs are useful. The 2020 Exemplar VAE went the other way and simply used the whole training set as mixture components, computing only a few nearby components via approximate nearest-neighbor search and using leave-one-out to keep the model from memorizing the training images; this is exactly the aggregated posterior that VampPrior had rejected as too expensive and prone to overfitting.
In October 2026, "VampPrior Unleashed" (Stirn et al.) went after the very advantage this paper emphasized back then, the tying of prior and posterior. Each VampPrior component uses the variance output by the encoder directly, so the same set of parameters has to produce two kinds of distributions with opposite requirements. The posterior has to be sharp (low entropy) for reconstruction to be accurate; the prior's components have to be wide (high entropy) to cover the whole aggregated posterior. They split each component's covariance off into an independently learnable , with the mean still computed by the encoder on . Across 36 settings covering MNIST and FashionMNIST, three initialization schemes and , the decoupled version was better on average in every one, with gains in log marginal likelihood of up to 3.6 nats.
Conclusion
The best prior is the aggregated posterior, which you can see just by taking the ELBO apart; VampPrior turns it into an approximation that can actually be trained, passing learnable fake images through the encoder once each and mixing the results into the prior. On MLP architectures it brings gains of 1 to 9 nats on four binary-image datasets and lowers bits/dim on both grayscale datasets; combined with the authors' two-layer structure, it posted the best numbers in the table for the permutation-invariant setting of the time. Once the decoder becomes a PixelCNN, the gains shrink to around 1 nat, and Caltech 101 even goes backward; and the quadrupling of active units has differences in structure and setup mixed into it.
To try it on your own VAE, the only thing to change is the prior function; neither the encoder nor the decoder needs touching. Compute with logsumexp and switch the KL to a sampled estimate; initialize the pseudo-inputs from training images, and after training plot them and take a look, because if all you see is noise, they didn't learn anything. Leave room for longer training too, since at the encoder processes 500 extra images at every step.
In November of the same year, DeepMind's VQ-VAE went the opposite way, training with a uniform discrete prior and only fitting a PixelCNN to learn the real prior after the encoder was done training.