From classic to probabilistic
A classic autoencoder, often shortened to AE, does two things: it compresses an input (for example an image) into a compact vector z, then it reconstructs the input from z. The set of values z can take is called the latent space, "latent" because those coordinates are never observed in the data; the network invents them in order to summarize it.
The problem? The resulting latent space is chaotic. Two nearby points z don't necessarily correspond to similar images. And if you draw a random z, you get noise, not a coherent image. The classic autoencoder is a compressor, not a generator.
The Variational Autoencoder, almost always abbreviated VAE, proposed by Kingma and Welling in 2013, solves this problem by adding a probabilistic structure to the latent space. Instead of producing a single point z, the encoder produces the parameters of a distribution over z. It's this nuance that transforms a simple compressor into a true generative model.
Auto-Encoding Variational Bayes
Intuition: a probabilistic generative model
The fundamental idea of the VAE is to model the generation process of data. We assume that each data point (image, text, etc.) was "generated" by a two-step process:
- Nature chooses a latent vector from a simple distribution: . The sign reads "is drawn at random from"; is the normal, or Gaussian, distribution (the familiar bell curve); the says it is centred on the origin, and the (identity matrix) that each coordinate of z has width 1 and is independent of the others. This starting distribution is called the prior, it's our hypothesis about what z looks like before having seen any data.
- This vector z is transformed into observable data by a complex process: . The vertical bar reads "given": is the probability of getting image given that we started from code .
The VAE's decoder learns this generation process: given a z, it produces a realistic x. To generate a new image, you simply draw a random z and pass it through the decoder. Simple and elegant. (On what "drawing at random from a distribution" actually involves, see sampling.)
The role of the encoder
But to train this system, you need the inverse: given an image x, which z generated it? This is the encoder's role, which approximates , the posterior distribution. The prior is what we believe about z before seeing the image. The posterior is what we believe about z after seeing the image. The encoder tries to guess: "this cat image, which z probably generated it?"
Concretely, the encoder doesn't produce a single z but the parameters of a Gaussian distribution:
Symbol by symbol: is the input image; is the latent code we are after; denotes the true probabilities, the ones out in the world, which we do not know; denotes the approximation the encoder builds of them, two different letters for two different things, that is the convention and it is worth watching; (the Greek letter mu) is the centre of the small zone targeted in latent space; (sigma) is its width, and the square of that width, called the variance. Writing them as and signals that they depend on the image: every image gets its own centre and its own width.
In one sentence: for each input image the encoder returns not a point but a centre and a width, i.e., a small fuzzy zone of latent space. A smiling face will have its zone somewhere, a neutral face somewhere else, and the two overlap if the faces are similar.
This is the costliest confusion on this page, so let us clear it up straight away. The only things learned in a VAE are the encoder weights (traditionally written , the Greek letter phi) and the decoder weights (written , theta). They are what training modifies, and nothing else; once training is over they never move again.
By contrast , , and are not learned parameters: they are values recomputed for every image. and are what the encoder outputs when shown an image; is then drawn at random from the zone they describe. Running the same face twice through the same trained network gives the same and the same , but two different values of . That is why you sometimes see and written out: the subscript reminds you which learned weights the distribution depends on.
Using distributions rather than fixed points is what structures the latent space. Similar images produce overlapping distributions, creating continuous regions in latent space. Between a handwritten "3" and an "8," there exist valid intermediate forms. This is what makes generation and interpolation possible, and this is what classic autoencoders were missing.
The gradient problem: the reparameterization trick
Why it's a problem
During training, you need to sample between the encoder and decoder. But sampling is a random and non-differentiable operation. However, backpropagation (the method that adjusts the weights) needs to compute derivatives through the entire network.
The problem is clear: how do you pass a gradient through a random draw? If you draw z = 3.7 from a Gaussian, what's the "derivative" of that draw with respect to parameters and ? It's not defined in a standard way.
The solution: externalize the randomness
The reparameterization trick is a simple but brilliant mathematical trick. Instead of directly drawing , you decompose the draw into two parts:
Symbol by symbol: is the centre computed by the encoder; the width, also computed by the encoder; (epsilon) is noise drawn from a centred Gaussian of width 1, with no connection to the network at all; is the resulting code. In one sentence: start at the centre and step away from it by a random amount proportional to the width.
The randomness is thus "externalized" into , which is pure noise independent of the network's weights. The variable z is now a deterministic computation from , , and : once has been drawn, nothing is random any more. The gradient can therefore travel back to and , because it only crosses ordinary operations (one multiplication, one addition).
The analogy: instead of saying "draw a random number between 3 and 7" (opaque operation), you say "take 5 (the mean) and add noise times 2 (the standard deviation)." The result is statistically the same, but the second formulation allows computing how the result changes if you modify the mean or standard deviation.
The reparameterization trick changes nothing about the distribution of z, it's exactly the same Gaussian . But it makes the computation differentiable, which allows training the VAE with ordinary gradient descent (stochastic gradient descent, abbreviated SGD, or its Adam variant). Without this trick, you'd need gradient estimators based on repeated random draws, known as Monte Carlo estimators (like the REINFORCE algorithm, used in reinforcement learning), which are much noisier and slower to converge.
The ELBO loss: the heart of the VAE
What are we optimizing?
The ideal objective would be to maximize the log-likelihood of the data: . The likelihood is the probability that our model, left to its own devices, produces image ; we take its logarithm only because that turns products of very small numbers into sums, which are easier to handle (maximum likelihood has its own lesson). In plain language: "the probability that our model generates data that looks like real data should be maximal."
Unfortunately, computing exactly is impossible: you would have to add up, over every conceivable z, the probability that this z leads to this image, a computation far out of reach. Instead, we optimize a lower bound called the ELBO (Evidence Lower BOund, literally "lower bound of the evidence"). The "evidence" here is just another name for , the probability the model assigns to the data. We can't compute this value directly, but we can compute a lower bound, a number that's always below the true value. By maximizing this bound, we indirectly push upward:
Every symbol on that line:
- is the expectation, i.e., an average weighted by probabilities. The subscript says which distribution the average is taken over: here you draw several z values from the zone the encoder produced, and average whatever is in the brackets. In practice you often draw just one z per image per pass, the averaging takes care of itself across the thousands of images seen during training.
- measures how probable the decoder finds image when handed this . Higher means better reconstruction.
- is the Kullback-Leibler divergence, almost always shortened to KL: a number, zero or positive, measuring how far apart two distributions are, and equal to zero only if they are identical. It has its own lesson. The double bar is just a separator between the two distributions being compared, and the order matters, since KL is not symmetric.
- is the latent zone the encoder proposes for this image; is the prior fixed in advance.
In one sentence: reward good reconstruction, punish any gap between the zone the encoder proposes and the standard Gaussian we settled on beforehand.
Why is it a lower bound? You can show that the log-likelihood decomposes exactly into:
Watch the difference between the last two formulas: here the KL compares to the true (the true posterior), not to the prior . Since a KL divergence is always , we have , it is indeed a lower bound. We can't compute directly because the true posterior is out of reach (you'd need to know , which is precisely what we're trying to estimate). But the ELBO is computable. By maximizing it, we maximize an approximation of , and the closer our approximation is to the true posterior, the tighter the bound.
Or, as a "loss to minimize", just flip the sign, since maximizing the ELBO is the same as minimizing its negative:
The two terms in detail
Term 1: Reconstruction ()
This term measures reconstruction quality. Concretely, you draw a z from , pass it through the decoder, and measure how closely the output resembles the input. The minus sign in front is there because we want to maximize the resemblance but minimize the loss. In practice, it's a mean squared error (MSE) for grayscale images or a binary cross-entropy (BCE) for binary images, see loss functions.
This term pushes the encoder to put enough information in z so the decoder can faithfully reconstruct. If z doesn't contain enough information, the reconstruction is blurry.
Term 2: KL Regularization ()
This is the Kullback-Leibler divergence between the distribution the encoder proposes, , and the prior (the standard Gaussian we chose as our starting hypothesis). Intuitively, this divergence measures "how much extra information" is needed to describe when we expected . The more the encoded zone deviates from the standard Gaussian, the more this penalty increases.
This term forces the latent space to remain regular and structured. Without it, the encoder could place each image at an isolated point in space (width shrinking to 0), which would destroy the continuity needed for generation.
When the two distributions being compared are Gaussians, which is the case here by construction, the KL has a closed form, with no integral to approximate, why those integrals are otherwise out of reach is explained in integrals in ML:
Symbol by symbol: numbers the dimensions of the latent space (if z has 32 coordinates, runs from 1 to 32); and are the centre and width of coordinate number , both output by the encoder; adds up each coordinate's contribution. The factor is not a tuning knob: it falls out of the exact KL between two Gaussians, whose density already carries an exponent of .
Intuition for each term in the sum (for dimension ):
- : normalization constant ensuring when
- : penalizes variances that are too small, the model shouldn't be too "confident" by concentrating all its mass on a single point
- : penalizes means far from 0, pushes the encoded distribution toward a centered Gaussian
- : penalizes variances that are too large, the model shouldn't be too "uncertain" by spreading its distribution everywhere
When and , you get : the encoder produces exactly the prior , and there's no penalty.
The two loss terms are in conflict. The reconstruction term wants precise, informative codes (small width, positions far from each other). The KL term wants smooth, regular codes (close to , overlapping distributions). Training a VAE is a balancing act: enough information to reconstruct, enough regularity to generate.
Problem: posterior collapse
When the model cheats
Sometimes the model finds an undesirable shortcut: it learns to completely ignore z. The decoder, if it's powerful enough (e.g., an autoregressive decoder, one that produces its output piece by piece, leaning on what it has already written), can generate plausible data without using the information from z. The encoder, having no reason to put information in z, sees its distribution collapse to the prior . The KL drops to 0, reconstruction is fine, but z has become useless.
This is posterior collapse: the VAE degenerates into a classic autoencoder without the desired generative properties.
Solutions
- KL annealing: gradually increase the weight of the KL term during training. Start with a weight of 0 (the encoder first learns to encode useful information), then gradually ramp up to 1 (to regularize)
- Free bits: impose a minimum KL per latent dimension, i.e., force the model to push a minimum amount of information through each coordinate of the code
- beta-VAE: put a coefficient (beta) in front of the KL term. favors reconstruction, favors latent space structure and encourages disentangled representations, where each coordinate of the code controls one attribute and only one
- Deliberately weak decoder: limit the decoder's capacity so it needs z
Posterior collapse has been studied in depth by Chen, Kingma et al. in the Variational Lossy Autoencoder. Their key point: you need to explicitly control the information flow between encoder and decoder. If the decoder has access to too much context (e.g., via powerful autoregressive connections), it has no reason to use z. The paper proposes techniques to "force" information to flow through the latent code, by strategically limiting what the decoder can see directly.
Variational Lossy Autoencoder (Chen et al., 2017)Generation and latent space exploration
Generating new data
This is the VAE's reason for being. Once trained:
- Draw a random z from the prior:
- Pass z through the decoder:
Thanks to KL regularization, the prior covers the latent space well. A randomly drawn z therefore has a good chance of corresponding to coherent data.
Interpolation
Interpolation is one of the most satisfying properties of the VAE:
- Encode two images, keeping only the centre of their zone: ,
- Linearly interpolate: . The dial (alpha) runs from 0 to 1: at you sit exactly on the first image, at on the second, and in between you get a measured blend.
- Decode each intermediate point:
You get smooth, semantically coherent transitions. Between a handwritten "3" and an "8," you'll gradually see the 3 transform into an 8, passing through plausible intermediate forms. This is proof that the VAE has learned a continuous, structured representation.
Latent arithmetic
Just like with word embeddings (representations of a word as a list of numbers, where one observes that "king − man + woman ≈ queen" (see word2vec)) you can do arithmetic in latent space:
This isn't guaranteed to work perfectly, but when it does, it's proof that the latent space has captured interpretable semantic factors. The "smile vector" is a direction in latent space that you can apply to any face.
The VAE has spawned a rich family of models:
- Conditional VAE (CVAE): conditions generation on a label or class (generates a "5" on demand)
- VQ-VAE (Vector Quantized VAE): replaces the continuous latent space with a discrete one, a finite catalogue of reference vectors (the codebook) into which every code must be filed. It's the basis of DALL-E 1 and many audio models
- Hierarchical VAE: latent variables at multiple scales (global -> local), to capture both the overall structure and fine details
- VAE-diffusion bridges: several lines of work connect VAEs and diffusion models in a common theoretical frame, a diffusion model can be read as a VAE with very many latent layers
As a standalone generative model, the VAE has been superseded: its images are blurry, and diffusion models have done better since 2021-2022. But it did not disappear, it changed jobs. Inside a present-day image generator, a VAE (usually from the VQ-VAE family) serves as the latent compressor: it shrinks the image to a much smaller version, diffusion works in that reduced space, and the VAE's decoder brings it back up to the final image. In other words, the mechanism described on this page still runs for every image a Stable-Diffusion-style model produces, it is simply no longer the part that invents the image, it is the part that compresses and restores it. See latent diffusion.
Final summary
The VAE transforms the classic autoencoder into a generative model through a simple idea: replacing points with distributions in the latent space. The reparameterization trick makes the whole thing trainable by gradient descent. The ELBO loss balances faithful reconstruction and a structured latent space. The result: a model capable of generating new data, interpolating between them, and navigating a space of continuous representations. Its main limitation (sometimes blurry reconstructions, because a loss computed pixel by pixel does not measure what the human eye perceives) motivated the development of diffusion models, which took over for high-quality image generation while keeping the VAE as their compressor.
1. A VAE is trained and its weights are frozen. You feed it the exact same face twice. What do you get?
2. What is the reparameterization trick, z = mu + sigma × epsilon, actually for?
3. In the VAE loss, why is the KL regularization term indispensable?
4. What is posterior collapse?
5. In 2026, what role does the VAE play inside a Stable-Diffusion-style image generator?