Generative Models/Variational Autoencoders

Lesson 8.32,206 words

Variational Autoencoders

An autoencoder compresses, but its latent space has gaps: sample a point between two encodings and the decoder produces noise. The variational autoencoder fixes this by training a probabilistic encoder against a prior, so the latent space becomes a smooth, samplable density.

╌╌╌╌

An ordinary autoencoder learns a deterministic code and a reconstruction , and nothing constrains where in code-space the encodings land. The trained codes form isolated islands; the gaps between them decode to garbage, so the autoencoder compresses but cannot generate: there is no distribution to sample from. The variational autoencoder (VAE) repairs exactly this. It makes the encoder output a distribution over codes, trains that distribution to match a fixed prior , and thereby turns the latent space into a smooth density we can sample. The cost is a detour through variational inference; the result is a principled, gradient-trainable generative model.1

The latent-variable model

A VAE is a latent-variable generative model: each datum is generated by first drawing a hidden code from a simple prior, then mapping it through a decoder .

We take the standard Gaussian prior and a decoder network that maps a code to the parameters of an output distribution:

so the data density is the marginal over all codes,

The generative model: a code drawn from the prior is mapped by decoder to the parameters of .

To train this by maximum likelihood we would maximize . The integral, however, is intractable: it ranges over the entire latent space, and the decoder is a nonlinear network, so there is no closed form. The posterior we would need to invert the generative process,

inherits the same intractable normalizer in its denominator. We cannot compute it, and so we cannot directly do maximum likelihood. Variational inference works around this.2

Variational inference and the ELBO

The idea of variational inference is to give up on the exact posterior and instead introduce a tractable approximate posterior (a second network, the encoder) chosen from a family we can sample and differentiate. We pick a Gaussian with diagonal covariance whose mean and variance are emitted by the encoder network :

The encoder is also called the inference network because it performs approximate inference: given , it guesses which codes could have produced it. The decoder is the generative network. We now derive a tractable objective that bounds the log-evidence from below.

The bound is the evidence lower bound (ELBO). Maximizing it does double duty: because with the evidence fixed in , pushing up simultaneously raises a lower bound on the data likelihood and squeezes the inference gap, tightening toward the true posterior.3

The log-evidence splits into the ELBO plus the inference gap; maximizing the ELBO raises the bound and shrinks the gap, tight when matches the posterior.

Reading the two terms

The ELBO reads as a reconstruction term minus a regularizer, and this is the entire intuition behind the architecture:

TermEncouragesPulls towardWithout it
codes that decode back to faithful reconstructionuseless codes, blurry output
posteriors near the prior a smooth, samplable latent spaceholey latent space (a plain autoencoder)

With a unit-variance Gaussian decoder, is squared error up to a constant, so the reconstruction term is the familiar autoencoder loss. The KL term is the new ingredient: it is precisely what an ordinary autoencoder lacks, the term that packs the encodings against the prior so the gaps close.

The reparameterization trick

The ELBO contains an expectation over , and we must differentiate it with respect to — but controls the very distribution we are sampling from. The naive estimator differentiates the sampling density directly (the score-function or REINFORCE estimator),

which is unbiased but notoriously high-variance: swings widely and the weight does not cancel that swing, so estimates are noisy and training crawls.

The reparameterization trick removes the randomness from the gradient path. A Gaussian sample can be written as a deterministic, differentiable transform of a fixed, parameter-free noise source:

Now the only stochastic node is , which carries no parameters; the sample is a smooth function of and . The expectation becomes an expectation over the fixed distribution of , and the gradient slips inside it:

a low-variance estimate we can compute with a single sample of and ordinary backpropagation.4

Reparameterization. Before, the stochastic sample blocks the gradient; after, moves randomness into , leaving a deterministic path the gradient follows.
EstimatorFormVarianceRequires
Score-function (REINFORCE)highonly that be differentiable
Reparameterized (pathwise)low reparameterizable, differentiable in

The trick is what makes the VAE trainable end-to-end: it lets a single gradient pass through the sampled code and into the encoder's weights.

The closed-form KL term

The KL regularizer between two Gaussians has a closed form, so the second ELBO term needs no sampling at all. For a diagonal posterior against the prior in latent dimensions,

Each coordinate is penalized for drifting its mean off () and for a variance that strays from (the term, which is and vanishes only at ). Substituting the reparameterized reconstruction term, the per-example objective the network maximizes is fully explicit:

In practice the encoder emits rather than (the log keeps the variance positive without a constraint and stabilizes the gradient), and the expectation is approximated by the single noise draw per example. The whole VAE is now a single differentiable graph.

A worked ELBO computation

For example, take a two-dimensional latent space () and an encoder that, for a particular input , emits

The KL term first, coordinate by coordinate, using :

So nats. Coordinate pays most of it: its mean sits well off the origin () and its variance is squeezed to , both of which the prior penalizes. Coordinate is nearly free because its mean is small and its variance is close to — almost exactly the prior already.

Now the reconstruction term. Draw one noise sample and reparameterize:

Push through the decoder to get . With a unit-variance Gaussian decoder over, say, a -pixel output, the reconstruction log-density is . If the squared reconstruction error came out to , then

The ELBO is their difference:

The optimizer minimizes . The KL of is small next to the reconstruction cost, which is typical early in training — the network first learns to reconstruct, and the KL only bites once the codes are informative enough that packing them against the prior costs fidelity. The weight below controls exactly that ratio.

The full VAE: encoder produces , reparameterization samples , and decoder reconstructs .

Training the VAE

Training maximizes the ELBO by minimizing its negation, averaged over minibatches, with a single reparameterized sample per example. Every line is an ordinary differentiable operation, so a standard optimizer trains both networks jointly.

Algorithm:TrainVAE(fϕ,gθ,D,η)\textsc{TrainVAE}(f_\phi, g_\theta, \mathcal{D}, \eta) — amortized variational inference
  1. 1
    initialize encoder ϕ\phi, decoder θ\theta
  2. 2
    repeat
  3. 3
    sample a minibatch {xi}D\{x_i\} \sim \mathcal{D}
  4. 4
    for each xix_i do
  5. 5
    (μ,s)fϕ(xi)(\mu, s) \gets f_\phi(x_i)
    encoder emits mean and log\log-variance ss
  6. 6
    ϵ\epsilon \gets sample from N(0,I)\mathcal{N}(0, I)
    parameter-free noise
  7. 7
    zμ+exp(s/2)ϵz \gets \mu + \exp(s / 2) \odot \epsilon
    reparameterized code
  8. 8
    Lreclogpθ(xiz)L_{\text{rec}} \gets -\log p_\theta(x_i \mid z)
    reconstruction (e.g. squared error)
  9. 9
    Lkl12j(μj2+exp(sj)sj1)L_{\text{kl}} \gets \tfrac12 \sum_j (\mu_j^2 + \exp(s_j) - s_j - 1)
    closed-form KL
  10. 10
    LiLrec+Lkl\mathcal{L}_i \gets L_{\text{rec}} + L_{\text{kl}}
    negative ELBO
  11. 11
    gϕ,θ1miLig \gets \nabla_{\phi,\theta}\, \tfrac{1}{m}\sum_i \mathcal{L}_i
    backprop through the sample
  12. 12
    (ϕ,θ)(ϕ,θ)ηg(\phi, \theta) \gets (\phi, \theta) - \eta \cdot g
    joint gradient step
  13. 13
    until converged
  14. 14
    return ϕ,θ\phi, \theta

Sampling, interpolation, and the smooth latent space

Once trained, the encoder can be discarded for generation: because was pressed against , an unconditional sample from the prior lands where the decoder expects data.

This is what the KL term buys. In a plain autoencoder the codes occupy an unknown, holey region, and a prior sample almost surely misses it; the VAE's regularizer guarantees the prior is the code distribution, so sampling works. The same smoothness makes latent-space interpolation meaningful: a straight line between two codes decodes to a continuous morph because nearby codes decode to nearby data.5

Latent-space interpolation: decoding on a grid across the 2D latent space, icons morph continuously because the KL term made the space smooth.

The grid is the canonical VAE diagnostic: sweeping the two latent coordinates and decoding each point traces a continuous atlas of the data manifold, with no torn seams between encodings.

Two distributions, one pull

It helps to picture the KL term geometrically. The approximate posterior is a bell centered at with width ; the prior is the unit bell at the origin. The KL regularizer pulls every per-example bell toward the prior; the reconstruction term opposes it, placing each at a distinct, confident code.

The KL term pulls the posterior toward the prior while the reconstruction term pushes its mean off-origin; their balance sets the learned posterior.

The weight generalizes the objective to : favors reconstruction (sharper samples, looser prior match), favors disentangled, prior-aligned codes (the -VAE), and is the exact ELBO.6

The tradeoff: raising tightens the code's match to the prior (KL falls) at the cost of reconstruction fidelity; sharpens samples, large risks posterior collapse.

What VAEs became

The VAE of Kingma and Welling was published in 2014 alongside an independent derivation by Rezende, Mohamed, and Wierstra, who called the same object a deep latent Gaussian model and its reparameterized gradient stochastic backpropagation.7 Both papers solved the same problem — how to backpropagate through a sampled latent — and the trick has since become standard machinery well outside generative modeling, anywhere an expectation over a learned distribution appears in a loss.

Discrete latents needed a new trick. Reparameterization as stated requires a continuous, differentiable transform, which rules out categorical codes. The Gumbel-softmax (or Concrete) relaxation fixed this by reparameterizing a categorical draw as a temperature-controlled softmax over Gumbel noise, recovering a differentiable path to discrete latents.8 The VQ-VAE took the opposite route — a hard nearest-neighbor lookup into a learned codebook, with a straight-through gradient — and its discrete codes are what let autoregressive and, later, diffusion models operate in a compact latent space rather than on raw pixels.9

The -VAE turned the KL weight into a research program. Raising above was found to encourage disentangled representations, where individual latent coordinates track independent factors of variation such as pose or lighting; the same paper reframed the whole objective as a constrained optimization with the KL as an information bottleneck.10 That information-theoretic reading — the KL term is the number of nats the code is allowed to carry about the input — is the cleanest way to understand both disentanglement and posterior collapse.

The blur problem drove the field toward other models. VAEs reconstruct through a likelihood term that, with a Gaussian decoder, is squared error, and averaging over the posterior produces the characteristic soft, blurry samples. This is the practical reason GANs and diffusion models overtook the plain VAE for high-fidelity image synthesis — though the VAE's encoder-decoder latent space survives inside them, most visibly as the compression front-end of latent diffusion.

Takeaways

  • A VAE is a latent-variable model with prior ; the integral and the posterior are intractable, so we cannot do direct maximum likelihood.
  • Variational inference introduces an encoder and the ELBO , whose gap is exactly — maximizing the bound both fits the data and tightens the approximation.
  • The ELBO reads as reconstruction minus a KL regularizer; the KL term is the force a plain autoencoder lacks, packing codes against the prior so the latent space becomes smooth and samplable.
  • The reparameterization trick moves randomness onto a parameter-free , replacing the high-variance score-function estimator with a low-variance pathwise gradient that backpropagates through the sample.
  • The Gaussian-vs-Gaussian KL is closed-form, sampling from the prior generates data, latent interpolation morphs smoothly, and posterior collapse is the characteristic failure when the decoder ignores the code.

Footnotes

  1. Goodfellow, Deep Learning, §20.10.3 — the variational autoencoder as a directed latent-variable model trained by maximizing the ELBO with an amortized inference network.
  2. Goodfellow, Deep Learning, Ch. 19 (§19.1) — inference as optimization: the true posterior is intractable because of the evidence integral, motivating a variational surrogate.
  3. Goodfellow, Deep Learning, §19.1 — the evidence lower bound , and why maximizing it both bounds the likelihood and tightens the posterior approximation.
  4. Goodfellow, Deep Learning, §20.9 — the reparameterization (pathwise) gradient estimator, contrasted with the high-variance score-function/REINFORCE estimator of §20.9.1.
  5. Chollet, Deep Learning with Python, §8.4 — generating images with a VAE in practice: the encoder emits , the sampling layer applies , and decoding a latent grid traces a continuous manifold.
  6. Goodfellow, Deep Learning, §20.10.3 — the failure mode where a sufficiently powerful decoder ignores and drives the KL to zero (posterior collapse), and the role of a weight on the KL term.
  7. Rezende, Mohamed & Wierstra, Stochastic Backpropagation and Approximate Inference in Deep Generative Models, ICML 2014 — the independent derivation of the reparameterized gradient for deep latent Gaussian models.
  8. Jang, Gu & Poole, Categorical Reparameterization with Gumbel-Softmax, ICLR 2017 (and Maddison, Mnih & Teh, The Concrete Distribution, ICLR 2017) — a differentiable relaxation that reparameterizes discrete categorical latents.
  9. van den Oord, Vinyals & Kavukcuoglu, Neural Discrete Representation Learning (VQ-VAE), NeurIPS 2017 — discrete latents via a learned codebook and straight-through gradients.
  10. Higgins et al., -VAE: Learning Basic Visual Concepts with a Constrained Variational Framework, ICLR 2017 — weighting the KL term above one to encourage disentangled representations.

╌╌ END ╌╌