07 / 34 · Variational Autoencoders
Variational autoencoders
How an autoencoder becomes a generator: a latent-variable model trained through the evidence lower bound, an encoder that approximates the posterior, the reparameterization trick, what the prior constrains, posterior collapse, and the conditional VAE.
Autoencoders · Multivariate Gaussian distributions · Entropy, cross-entropy and KL divergence
On this page 10
An autoencoder learns to reconstruct observed inputs. That objective alone does not specify a distribution for new latent codes, or constrain every gap between the training codes. Good reconstructions therefore do not establish that drawing a random code will produce useful new data.
The variational autoencoder (VAE) of Kingma and Welling (2014), proposed at the same time by Rezende, Mohamed and Wierstra (2014), builds that in. Each image is encoded to a Gaussian instead of a point, and all these Gaussians are pulled toward one fixed distribution. It is also the first neural model of the course trained by a bound on maximum likelihood, the objective the entropy note singled out.
From autoencoders to generation#
The autoencoder maps to and back to . Drawing from a convenient Gaussian is an extra modeling choice: the reconstruction objective has not required the codes to follow it. Fitting a density to the codes is possible, but its fit and the decoder’s behavior on its samples need separate evaluation.
A small constructed example exposes the missing constraint. Take three scalar training observations and encoder . Both decoders and reconstruct every training point exactly. At the unseen code , however, they output and . The training loss cannot choose between them.
This is an identifiability example with explicit functions, not a trained digit experiment. Architectural smoothness or additional regularization can restrict the alternatives; reconstruction alone does not.
Same reconstructions, different unseen outputs
A VAE makes a generative distribution part of the model and trains it with a tractable likelihood bound.
The latent-variable model and its posterior#
Start from the simplest model of this kind. Probabilistic PCA draws a code from a prior and places the image , with , near a linear function of it:
Everything is Gaussian, so both the evidence and the posterior have closed forms. The image , with noise , is an affine map of the Gaussian pair , so by the affine-map rule. Completing the square in (folded below) gives the posterior
Derivation of the posterior
Bayes’ rule keeps only the factors that depend on ; the rest is a constant:
The third line expands the square and collects . A Gaussian has the log density . Matching the quadratic term gives , and matching the linear term, , gives .
Maximum likelihood sets to the data mean, where the gradient of a Gaussian log-likelihood vanishes for any covariance . EM fits and by alternating two exact steps: set to this posterior, then maximize the expected log joint (EM as coordinate ascent). Probabilistic PCA is thus a VAE with a linear decoder and an exact Gaussian encoder (probabilistic PCA), diagonal when the columns of are orthogonal and is diagonal.
A linear subspace can be too restrictive for complex observations. The VAE keeps this two-stage model and replaces with a neural network. In the Gaussian version used here, the decoder has a mean, and possibly a variance, supplied by that network. This PPCA-to-VAE route follows BMML lecture 6, §§6.1–6.2; the adapted exposition is credited under its MIT documentation license. The model distribution is the marginal of (joint and marginal densities), called the evidence:
Maximum likelihood maximizes over the training images. The reverse question, which codes explain a given image, is answered by the posterior:
A general neural decoder leaves no closed-form integral, so an exact posterior E-step is generally unavailable. Approximate inference will replace it.
An observation updates the code distribution
Why not estimate the integral by sampling? Draw from the prior and average . The terms are independent with mean , so the average is unbiased, with variance . Relative to it is
When prior samples rarely explain an observation well, a few large likelihoods can dominate the average. Consider this explicit example: let each of coordinates be independent, with and . At every coordinate multiplies the ratio inside the brackets by , and samples bring the relative error, the square root of the relative variance, to at most 10%:
| ratio | samples for a 10% relative error | |
|---|---|---|
| 1 | 2.4 | 141 |
| 10 | 6350.83 | 634,983 |
| 100 |
Where 2.40 comes from
For one coordinate with noise variance , and, by the affine-map rule, . The square of the likelihood is again a Gaussian shape in , and the Gaussian integral with gives
The coordinates are independent, so with of them both numerator and denominator are products over coordinates, and the ratio is .
The cost grows exponentially in this particular independent-coordinate construction, not in every latent-variable model. It illustrates the difficulty of prior sampling discussed by Isachenko (2025), lecture 3. An encoder can concentrate samples in regions that help explain the observation.
Variational approximation and the ELBO#
The way out keeps EM’s lower bound and gives up the exact E-step: is restricted to a simple family and optimized together with . Replacing an intractable posterior by the closest member of a simple family is variational inference, the subject of the variational inference note of the Bayesian Methods course.
The plainest choice gives each training image its own diagonal Gaussian . That works, but the variational parameters grow with the data, and every new image needs its own optimization. The VAE replaces the table of by an encoder network with parameters :
One network that outputs for any is amortized inference: the cost of inference is paid once, in training the encoder (Kingma and Welling, 2019, section 2.1; amortization in numbers).
Encoder and decoder are trained together by maximizing the evidence lower bound (ELBO), derived below:
The first term is the expected reconstruction log likelihood. For a fixed decoder with a finite maximum, concentrating near a maximizer of can improve this term alone: an average cannot exceed the maximum. This does not require a unique best code, and a flat decoder is a counterexample to inevitable concentration. The second term, the KL penalty, charges for departures from the prior, including variance shrinking to zero. The two-term interpretation adapts BMML lecture 6 §6.3 under the same notice.
The two terms of the ELBO
With a Gaussian decoder of fixed variance , whose network outputs the mean , the reconstruction term is a squared error:
The last term does not depend on the networks. With the expected squared error, summed over the pixels, plus the KL term is the negative ELBO up to a constant; a mean over pixels corresponds to . Any other reweights the two terms: multiplying by gives the squared error plus times the KL, the weight of the β-VAE.
If the decoder also learns its variance, the log-variance term must remain. For one variance shared by all observations and coordinates, its optimum depends on the average expected squared residual, not on one image’s residual. If all relevant residuals can vanish, a Gaussian likelihood can become unbounded as the variance tends to zero; a variance floor avoids that degeneracy. Binary observations can instead use a Bernoulli decoder and binary cross-entropy (the two readings).
The loss with a learned shared variance
Hold the encoder and decoder mean fixed and let . The mean negative reconstruction log likelihood, up to a constant, is . Differentiating in gives , so for the unique optimum is . Substitution gives plus a constant. This is the logarithm of the overall expected MSE; it is not an average of separate per-image logarithms.
With fixed decoder variance , one sampled code per image gives an unbiased estimate of the negative ELBO up to a constant:
with , where and are the encoder’s outputs for and the variance is applied coordinate-wise. Neither term contains the posterior or the evidence: the loss needs only the encoder, the prior and the decoder, which we can all evaluate.
The weights and are point estimates, fitted by stochastic gradient ascent on the ELBO like the parameters of an M-step (the VAE as variational EM). Only the code is integrated over and sampled, as are the noisy images of the later diffusion models. A distribution over the weights too would make a Bayesian neural network.
The reparameterization trick#
For a sum of per-image ELBOs, an unbiased minibatch gradient is times the average per-image gradient in a uniformly sampled minibatch. For the mean objective no such factor is needed. Assume differentiation can pass through the expectation and the density has parameter-independent support. For a function with no direct dependence, differentiating the encoder density gives:
This score-function or REINFORCE estimator can be used beyond Gaussian distributions when those regularity conditions hold. Its variance can be large because it uses multiplied by a zero-mean score, rather than the local derivative of . For , and , the single-sample gradient in is : its mean is and variance . The pathwise gradient has the same mean and variance . These moments are recomputed by the local verifier; this comparison is not a universal variance ordering. If also depends directly on , its direct derivative must be added.
A Gaussian also permits a pathwise estimator. Reparameterization moves the randomness into an input, as in sampling any Gaussian from standard noise:
where is the element-wise product. The distribution of is unchanged, but now and , so, under the differentiation assumptions, the reconstruction gradient flows back into the encoder (Kingma and Welling, 2014, section 2.4). Expectations over become expectations over , which does not depend on :
Fix the noise and vary the parameters
The KL term needs no sampling. Between two Gaussians it has a closed form, derived below:
The encoder outputs rather than . In exact arithmetic, exponentiating a finite is positive; implementations still need to avoid floating-point underflow and overflow. A linear layer can output any real number, a tiny variance such as becomes a moderate , and the KL is written directly in .
What the organized latent space buys#
The KL term encourages the encoder distributions toward the prior, but does not guarantee that prior samples land where the decoder is reliable. Generation follows the model: draw , then . The encoder is not needed. Showing only a Gaussian decoder’s mean omits observation noise; it is not a complete model sample. With , a sample adds independent noise of standard deviation per coordinate.
For a continuous decoder mean, changes continuously, but continuity alone says nothing about semantic quality. Our three-pixel illustration below uses an explicitly defined sigmoid map; it shows the calculation, not learned image quality. In high dimension the midpoint of two independent codes follows : its norm concentrates near rather than , inside the prior’s typical shell.
Interpolation through an explicit decoder
An attribute direction can be a useful empirical heuristic. Carter and Nielsen (2017) demonstrate a font-bolding direction, and explicitly show artifacts and limitations. Such a direction is not a consequence of the ELBO; no fonts or trained model from that example are used here.
Two separate mechanisms can hurt samples. First, the aggregate encoder distribution can differ from the prior, leaving prior regions poorly represented during reconstruction training. Second, with a fixed-variance Gaussian decoder and overlapping encoder distributions, one code can correspond to several observations; the optimal decoder mean is their conditional average. That average can blur distinct details. Diagonal Gaussian posteriors do have overlapping support; neither their separation nor a particular amount of blur is guaranteed.
A second view relates the average ELBO to a joint forward KL, under the density and finiteness assumptions stated below (Kingma and Welling, 2019, §2.7). In a restricted model family this objective penalizes low model density where the data-encoder joint has mass; the resulting compromise depends on the family. It does not prove that every VAE overestimates variance or produces blurry images.
The average ELBO as a forward KL
Assume the population data distribution and the model have densities with respect to a common base measure, with finite terms in the identity below. Combine and the encoder into . Then:
The data entropy is constant in the parameters, so maximizing the mean ELBO minimizes this KL. For an empirical distribution of point masses against a continuous observation model, the joint KL is instead infinite: that finite-KL interpretation must not be applied literally. The per-observation ELBO and its sample average remain well-defined whenever their own terms are finite.
Sample fidelity and coverage need separate measurement for both VAEs and adversarial models. Richer observation distributions and hierarchical latents can improve the basic Gaussian VAE. For example, Vahdat and Kautz (2020) reported successful NVAE generation at resolution; that published result is not reproduced here, and no images, weights or dataset from it are included.
Where the ELBO comes from#
Drop and for the derivation. Multiply the integrand of the evidence by , which needs wherever , true for a nondegenerate Gaussian :
The inequality is Jensen’s for the concave logarithm, .
Jensen's inequality for the concave logarithm
Writing splits the bound into the two terms used above:
Jensen shows that the bound holds; it does not say how loose it is. Writing instead gives the exact gap:
The bound is tight exactly when is the true posterior. The variational inference note derives the same decomposition for any latent-variable model and explains why this objective targets the reverse KL.
The gap shows what each network does. Over the encoder, is fixed, so raising only brings closer to the posterior in reverse KL. Over the decoder, can also rise by making the true posterior easier for to fit, which biases the model toward such posteriors. Maximizing the ELBO maximizes the likelihood only approximately (Kingma and Welling, 2019, section 2.2.1).
Which distribution is fixed? The prior#
The prior is fixed. The posteriors are not: every image gets its own and , and the KL term only charges for how far they stray.
For one coordinate, with and ,
Under we have and , so
For the diagonal encoder, both and factorize. The log ratio is then a sum over of terms that each depend on alone, and linearity of expectation adds the one-coordinate results (Kingma and Welling, 2014, appendix B):
The value is zero only at , , because with equality only at . A full covariance gives by the same steps with a trace in place of each square (folded below); correlation then has its own price, for two unit-variance coordinates with correlation , which the diagonal encoder never pays because it cannot correlate at all.
The trace step for a full covariance
A scalar equals its own trace, and the trace is linear and cyclic, so for
With and , the terms cancel and
For and with unit diagonal and off-diagonal , and , which leaves .
Read the formula as a fine:
| (nats) | ||
|---|---|---|
| 0 | 1 | 0 |
| 1 | 1 | 0.5 |
| 2 | 1 | 2 |
| 0 | 0.5 | 0.318 |
| 0 | 2 | 0.807 |
| 0 | 0.1 | 1.808 |
| 0 | 0.01 | 4.105 |
Moving the mean costs . Shrinking the variance costs about , which grows only logarithmically, yet without bound: a point code, as in a plain autoencoder, would pay an infinite fine, since a point mass has no finite KL against a density. Each image can therefore afford a fairly narrow, off-centre Gaussian when that helps reconstruction, but never a single point.
The KL fine grows only logarithmically as σ → 0
What does the KL term ask of the codes as a whole? Take training images and their aggregate posterior, the mixture of all their posteriors:
Treat the index as uniform on . The average KL term then splits in two (Hoffman and Johnson, 2016):
Derivation of the split
Write as and average the logarithm over and . The first factor averages to the mutual information between an image’s index and its code, by its definition. The second depends on alone, and averaging over then is averaging over the mixture , which gives the marginal KL.
The mutual information is bounded by . Reconstructing distinguishable observations accurately may require information about their index, but duplicates and a powerful conditional decoder can change how much is necessary. The marginal KL measures aggregate mismatch; it does not certify decoder quality. In particular, Gaussian mixtures have positive density everywhere, so “holes” here mean regions of very low encoder density relative to the prior, not literally absent support.
The prior appears only in the marginal KL, so, among unrestricted prior densities with the encoder fixed, the best prior is the aggregate posterior itself. That suggests learning the prior instead of fixing it, for instance with a normalizing flow over . The VQ-VAE of the next note learns its prior after the autoencoder is trained.
The DDPM construction can be read as a hierarchical latent-variable model with a fixed forward noising distribution and a learned reverse chain (DDPM objective). Latent diffusion applies diffusion in an autoencoder’s lower-dimensional representation. Compression reduces the number of coordinates; a Gaussian aggregate code distribution does not follow from compression or from a finite KL penalty alone.
Where it breaks: posterior collapse#
A decoder strong enough to model the images on its own can ignore the code. The encoder then outputs the prior for every image, the KL term is zero, and the code carries nothing. This is posterior collapse (Bowman et al., 2016).
The ELBO does not prevent it, and a one-dimensional Gaussian model shows why exactly. Let the data be , the prior , and the decoder with . Every such decoder gives the data its true distribution, so all of them have the same likelihood. The exact posterior is Gaussian, so the best Gaussian encoder equals it and the ELBO is tight. The rate, the average KL term, then equals the mutual information (folded below):
| decoder | rate (nats) | |||
|---|---|---|---|---|
| uses the code | 1 | 0.1 | 1.199 | |
| partly | 0.5 | 0.85 | 0.129 | |
| collapsed | 0 | 1.1 | 0 |
Where the rate comes from
With the exact posterior, the aggregate posterior is the prior: averaging over the model’s own , which here is the data distribution, returns . The marginal KL of the ELBO surgery vanishes, and the rate is the mutual information . By the conditional formula with , and , the posterior variance is , the same for every . A Gaussian of variance has entropy ; the cancels in the difference, so
For , this is ; the likelihood column is for all three.
In this constructed population example the bound is equally good at all three solutions, so it does not identify how much information the code should carry. A fixed-variance factorized Gaussian that ignores has only one unconditional mean; its squared-error optimum is the data mean. An expressive autoregressive decoder can model much richer data without , making collapse a practical concern. KL annealing gradually raises the KL weight from zero to one (Bowman et al., 2016). Free bits replace the KL cost for each latent group by , with the bar an average over a minibatch in the formulation of Kingma and Welling (2019), §2.8.1. Below the threshold, reducing KL no longer improves that term. Both modify the optimization incentives; neither guarantees useful codes.
Conditioning on a label: the conditional VAE#
The basic VAE cannot be told what to generate. The conditional VAE (CVAE) adds an observed condition , such as a class label or a vector of binary attributes, to every part of the model (Sohn, Yan and Lee, 2015, section 4): a prior , often simply for every ; a decoder ; and an encoder . The derivation of the ELBO goes through with everything conditioned on :
with the gap . With the fixed prior, training uses the same reparameterization and the same closed-form KL; a learned Gaussian prior needs the general KL between two Gaussians. In the networks, is usually concatenated to the encoder’s input and to before the decoder.
Conditioning gives the decoder information it need not transmit through , but does not ensure disentanglement. A transparent constructed example is with . Holding fixed gives means and , a shift of . Here that behavior is guaranteed by the chosen formula. In a learned image model, keeping and changing need not preserve identity, pose or any other unconditioned attribute. The conditional GAN uses an adversarial objective for a related conditioning task.
What you should remember#
- ; the prior KL inside is a different quantity from this posterior gap.
- Prior Monte Carlo can require exponentially many samples, as the independent-coordinate example demonstrates.
- Reparameterization provides a pathwise gradient under the differentiation conditions; diagonal-Gaussian KL is analytic.
- Fixed decoder variance gives summed squared error plus KL; a shared learned variance depends on the overall expected MSE.
- Prior mismatch and conditional averaging are separate sample-quality problems; continuous interpolation does not guarantee meaningful intermediate objects.
- Collapse can coexist with an optimal ELBO. Annealing and free bits change the training objective, without guaranteeing informative codes.
Notebook#
Run python3 scripts/notes/generative-practice.py vae. The standalone script uses four newly specified scalar observations, , a standard normal latent variable and a decoder with mean and variance 0.36. It evaluates an encoder with mean and variance 0.4. All Gaussian parameters and observations are defined in the file.
- Calculate expected reconstruction log probability and prior KL separately. Their difference is the ELBO. The saved results give mean ELBO −1.996397 and mean log likelihood −1.633903; their gap 0.362494 equals the average KL to the exact posterior.
- Check the exact posterior: mean and variance 0.155172. An encoder can have nonzero KL to the prior while having zero gap to the posterior; the two KL terms answer different questions.
- At , generate 40,000 reparameterized latent samples. Their mean reconstruction log probability is −1.564136, close to the analytic −1.558252. This checks the stochastic expectation and the sign of the bound. It does not train a convolutional VAE or measure generated-image quality.
The example, script and observations were newly authored for this course with Codex assistance; the numerical results are from the linked run.
The analytic checks and both new illustrative decoders are reproduced by python3 scripts/notes/check-vae-renewal.py. Its saved output also checks the shared-variance optimum, estimator moments, aggregate-KL split and collapse table. These are constructed calculations, not image-model benchmarks.
Next#
The VAE gives a tractable learning objective for a latent-variable generator. Its inference family, observation model and prior each impose constraints. The next note changes those choices through weighted KL penalties and discrete codes with a separately trained prior.
References#
- D. P. Kingma, M. Welling. Auto-encoding variational Bayes. ICLR, 2014. Section 2.4: the reparameterization trick; appendix B: the Gaussian KL.
- D. J. Rezende, S. Mohamed, D. Wierstra. Stochastic backpropagation and approximate inference in deep generative models. ICML, 2014.
- D. P. Kingma, M. Welling. An introduction to variational autoencoders. Foundations and Trends in Machine Learning, 12(4), 2019. Section 2.1: amortized inference; 2.2.1: the two effects of maximizing the ELBO; 2.8.1: optimization issues, free bits; 2.8.2: blurriness.
- BMML team. Bayesian Methods in Machine Learning, lecture 6, 2026. PPCA, variational learning and the two ELBO terms. Exposition adapted with corrections; MIT documentation notice.
- R. Isachenko. Deep Generative Models, MIPT and YSDA, autumn 2025. Lecture 3: naive Monte Carlo for latent-variable models, the ELBO, amortization; lecture 4: ELBO surgery and the optimal prior.
- M. D. Hoffman, M. J. Johnson. ELBO surgery: yet another way to carve up the variational evidence lower bound. NIPS Workshop on Advances in Approximate Bayesian Inference, 2016.
- S. R. Bowman, L. Vilnis, O. Vinyals, A. M. Dai, R. Jozefowicz, S. Bengio. Generating sentences from a continuous space. CoNLL, 2016. Posterior collapse and KL cost annealing.
- K. Sohn, X. Yan, H. Lee. Learning structured output representation using deep conditional generative models. NIPS, 2015. Section 4: the conditional ELBO.
- S. Carter, M. Nielsen. Using artificial intelligence to augment human intelligence. Distill, 2017. Attribute vectors in the latent space of a VAE.
- A. Vahdat, J. Kautz. NVAE: A deep hierarchical variational autoencoder. NeurIPS, 2020.