Skip to content
BIASED

Latent variables and the ELBO

How to make the code distribution part of the model, why the likelihood of a latent-variable model is intractable, and how the evidence lower bound gets around it.

From autoencoders to latent variables

The topic Autoencoders ended with a model that compresses well but cannot generate. It has no distribution over codes, so there is nothing to draw a new code from. And its decoder was trained only at the codes of training images, so a code from anywhere else may decode to a smear.

The way out, as that topic suggested, is to make the distribution of codes part of the model. Choose a distribution over codes before training, let the decoder define the probability of an image given its code, and train both so that the codes stay where that distribution expects them. A model built this way is a latent-variable model. Its language — joint, marginal and conditional distributions — comes first.

Joint, marginal, conditional

Take two random variables: the data xx and a latent variable zz. Their joint density p(x,z)p(x, z) is a cloud over the (x,z)(x, z) plane.

Projecting the cloud onto an axis gives a marginal. Marginalization integrates the other variable out:

p(x)=∫p(x,z) dz.p(x) = \int p(x, z)\, dz .

A conditional is a slice of the joint at a fixed value of the condition, renormalized so that it is again a density:

p(x∣z)=p(x,z)p(z).p(x \mid z) = \frac{p(x, z)}{p(z)} .

For example, p(x∣z=3)p(x \mid z = 3) is the slice of p(x,z)p(x, z) along the line z=3z = 3, divided by p(z=3)p(z = 3) so that it integrates to one over xx. Read backwards, the same definition is the product rule, p(x,z)=p(x∣z) p(z)=p(z∣x) p(x)p(x, z) = p(x \mid z)\, p(z) = p(z \mid x)\, p(x), which we will use in both directions. For discrete variables, replace integrals with sums.

The latent-variable model

A latent-variable model generates data in two steps: draw a code from the prior p(z)p(z), then draw an image from the decoder (the likelihood) pθ(x∣z)p_\theta(x \mid z). This defines the joint

pθ(x,z)=p(z) pθ(x∣z).p_\theta(x, z) = p(z)\, p_\theta(x \mid z).

The prior is chosen, not learned; the standard choice is p(z)=N(0,I)p(z) = \mathcal N(0, I). All the learnable structure lives in the decoder with parameters θ\theta.

The model's distribution over images is the marginal, called the evidence:

pθ(x)=∫pθ(x∣z) p(z) dz.p_\theta(x) = \int p_\theta(x \mid z)\, p(z)\, dz .

Maximum-likelihood training means maximizing ∑nlog⁡pθ(xn)\sum_n \log p_\theta(x_n) over the training images.

The reverse question, "which codes explain this image?", is answered by the posterior. By Bayes' theorem,

pθ(z∣x)=pθ(x∣z) p(z)pθ(x).p_\theta(z \mid x) = \frac{p_\theta(x \mid z)\, p(z)}{p_\theta(x)} .

Why the likelihood is intractable

Both quantities we care about involve the evidence: the likelihood is the evidence itself, and the posterior has it in the denominator. And the evidence is an integral over the whole latent space Rd\mathbb R^d.

With a neural-network decoder, pθ(x∣z)p_\theta(x \mid z) is an arbitrary nonlinear function of zz, and the integral has no closed form. Numerical options fail too:

  • Quadrature. A grid with kk points per axis needs kdk^d decoder evaluations. For d=32d = 32 and a coarse k=10k = 10 that is 103210^{32} — per image, per training step.
  • Naive Monte Carlo. Write pθ(x)=Ez∼p(z)[pθ(x∣z)]p_\theta(x) = \mathbb E_{z \sim p(z)}\big[p_\theta(x \mid z)\big] and average over nn prior samples. The estimate is unbiased, but for a given xx almost every prior sample explains it badly: the average is dominated by rare lucky draws.

How bad that is can be measured. The nn terms are independent, each with mean p(x)p(x) and variance Ep(z)[p(x∣z)2]−p(x)2\mathbb E_{p(z)}\big[p(x \mid z)^2\big] - p(x)^2, and an average divides the variance by nn. Relative to p(x)2p(x)^2,

Var⁡[p^(x)]p(x)2=1n(Ep(z)[p(x∣z)2]p(x)2−1).\frac{\operatorname{Var}\big[\hat p(x)\big]}{p(x)^2} = \frac1n \left(\frac{\mathbb E_{p(z)}\big[p(x \mid z)^2\big]}{p(x)^2} - 1\right) .

Take a toy with dd independent coordinates, zj∼N(0,1)z_j \sim \mathcal N(0, 1) and xj∣zj∼N(zj,0.1)x_j \mid z_j \sim \mathcal N(z_j, 0.1), at x=0x = 0. Per coordinate, p(0)=(2π⋅1.1)−1/2p(0) = (2\pi \cdot 1.1)^{-1/2}, and the Gaussian integral of the squared likelihood gives E[p(0∣z)2]=(2π⋅0.1)−1 (1+2/0.1)−1/2\mathbb E\big[p(0 \mid z)^2\big] = (2\pi \cdot 0.1)^{-1}\, (1 + 2/0.1)^{-1/2}. Their ratio is 1.1/0.21≈2.401.1/\sqrt{0.21} \approx 2.40, and with dd coordinates it is 2.40d2.40^d. A 10% relative error needs n=100 (2.40d−1)n = 100\,(2.40^d - 1) samples: 140 for d=1d = 1, about 635,000 for d=10d = 10, about 104010^{40} for d=100d = 100. The cost grows exponentially with the latent dimension, per image and per training step.

So the likelihood we want to maximize and the posterior we would need for encoding are both intractable. Samples drawn from the posterior instead of the prior would all land where xx is explained. We cannot draw them, but we can learn something close.

The approximate posterior

The way out is to stop asking for the exact posterior and approximate it by a member of a simple family. The VAE uses a diagonal Gaussian whose mean and variances are produced by an encoder network with parameters φ\varphi:

qφ(z∣x)=N(μφ(x), σφ2(x))≈pθ(z∣x).q_\varphi(z \mid x) = \mathcal N\big(\mu_\varphi(x),\ \sigma_\varphi^2(x)\big) \approx p_\theta(z \mid x).

Replacing an intractable posterior with the member of a simple family closest to it in DKL(q ∥ pθ(z∣x))D_{\mathrm{KL}}\big(q \,\|\, p_\theta(z \mid x)\big) is variational inference.

Classic variational inference fits a separate pair (μn,σn)(\mu_n, \sigma_n) for every data point by its own optimization, and has to repeat it for every new point. The VAE instead trains one network that maps any xx to the parameters of its qq. The cost of inference is paid once, during training, and shared across all inputs: this is amortized inference.

One problem remains: the KL above contains the very posterior we cannot compute, so we cannot minimize it directly. The next block shows how to get around that.

Where the ELBO comes from

Start from the evidence and multiply by 1=q(z∣x)/q(z∣x)1 = q(z \mid x)/q(z \mid x) inside the integral (we drop θ\theta and φ\varphi for now; a Gaussian qq is positive everywhere, so the division is safe):

log⁡p(x)=log⁡∫q(z∣x) p(x,z)q(z∣x) dz=log⁡Eq(z∣x) ⁣[p(x,z)q(z∣x)]≥Eq(z∣x) ⁣[log⁡p(x,z)q(z∣x)]=:L(x).\begin{aligned} \log p(x) &= \log \int q(z \mid x)\, \frac{p(x, z)}{q(z \mid x)}\, dz = \log \mathbb E_{q(z \mid x)}\!\left[\frac{p(x, z)}{q(z \mid x)}\right] \\ &\ge \mathbb E_{q(z \mid x)}\!\left[\log \frac{p(x, z)}{q(z \mid x)}\right] =: \mathcal L(x). \end{aligned}

The inequality is Jensen's: the logarithm is concave, so log⁡E[Y]≥E[log⁡Y]\log \mathbb E[Y] \ge \mathbb E[\log Y]. L(x)\mathcal L(x) is the evidence lower bound (ELBO).

How loose is it? Write the gap log⁡p(x)−L(x)\log p(x) - \mathcal L(x) as a single expectation under qq (the constant log⁡p(x)\log p(x) can go inside), substitute p(x,z)=p(z∣x) p(x)p(x, z) = p(z \mid x)\, p(x), and log⁡p(x)\log p(x) cancels. With the parameters restored, the result is an exact identity:

log⁡pθ(x)=L(x)+DKL(qφ(z∣x) ∥ pθ(z∣x)).\log p_\theta(x) = \mathcal L(x) + D_{\mathrm{KL}}\big(q_\varphi(z \mid x) \,\|\, p_\theta(z \mid x)\big).

Since KL is non-negative, this is the bound again, and it is tight exactly when qq equals the true posterior. Note what depends on what: log⁡pθ(x)\log p_\theta(x) involves only θ\theta. A step in θ\theta usually raises the ELBO by raising the likelihood, though it can also make the posterior easier for qq to fit, so maximizing the ELBO only approximately maximizes the likelihood.

Reconstruction and regularization

Writing p(x,z)=pθ(x∣z) p(z)p(x, z) = p_\theta(x \mid z)\, p(z) inside the ELBO splits it into two terms:

L(x)=Eqφ(z∣x)[log⁡pθ(x∣z)]⏟reconstruction−DKL(qφ(z∣x) ∥ p(z))⏟regularization.\mathcal L(x) = \underbrace{\mathbb E_{q_\varphi(z \mid x)}\big[\log p_\theta(x \mid z)\big]}_{\text{reconstruction}} - \underbrace{D_{\mathrm{KL}}\big(q_\varphi(z \mid x) \,\|\, p(z)\big)}_{\text{regularization}} .

Reconstruction measures how well an image survives the trip image → code → image. Regularization measures how far each code distribution is from the prior. They pull in opposite directions. Reconstruction averages log⁡pθ(x∣z)\log p_\theta(x \mid z) over qq, and an average never exceeds its maximum, so on its own it would put all of qφ(z∣x)q_\varphi(z \mid x) on the single best code: a point, the plain autoencoder again. The KL charges for that collapse to a point and for every departure from N(0,I)\mathcal N(0, I).

To make reconstruction concrete, take the Gaussian decoder from Autoencoders: the network outputs a mean image x^(z)\hat x(z), and every pixel gets the same fixed variance s2s^2, so pθ(x∣z)=N(x; x^(z), s2I)p_\theta(x \mid z) = \mathcal N\big(x;\ \hat x(z),\ s^2 I\big). As we saw there, and in the log-density of Multivariate Gaussians, −log⁡pθ(x∣z)-\log p_\theta(x \mid z) is then a scaled squared error plus a constant that does not depend on the network. With s2=12s^2 = \tfrac12 the scale is exactly 1, and the training loss, the negative ELBO with one sampled zz, becomes ∥x−x^(z)∥2+DKL\|x - \hat x(z)\|^2 + D_{\mathrm{KL}} up to a constant. Another s2s^2 reweights the KL by 2s22s^2 — the idea behind β-VAE. The KL between two Gaussians has a closed form, which the next topic computes.

The prior is fixed, not the posterior

What exactly does the prior N(0,I)\mathcal N(0, I) constrain?

What is fixed is the prior p(z)p(z): it is chosen before training and never learned. The posterior is not fixed: for each input the encoder outputs its own two vectors, μφ(x)\mu_\varphi(x) and log⁡σφ2(x)\log \sigma_\varphi^2(x).

The KL term pulls each qφ(z∣x)q_\varphi(z \mid x) toward the prior, but only as far as reconstruction allows. An input can afford a fairly narrow, off-centre Gaussian when that helps the decoder tell it apart from other inputs. What it cannot afford is to run off to some arbitrary corner of Rd\mathbb R^d, or to shrink to a single point: a point code would pay an infinite KL. So all codes end up in one known region around the origin, at unit scale.

That is what makes generation possible. Strictly, it is the mixture of all posteriors, q(z)=1N∑nqφ(z∣xn)q(z) = \frac1N \sum_n q_\varphi(z \mid x_n), that should fill the prior without holes; training pushes it there only approximately. Where it succeeds, a fresh z∼N(0,I)z \sim \mathcal N(0, I) lands where training codes live, and the decoder turns it into a sensible image.

So training a VAE means maximizing the ELBO over θ\theta and φ\varphi together. Its reconstruction term is an expectation over qφ(z∣x)q_\varphi(z \mid x), which in practice we estimate with a sampled zz. How to train the encoder through that sample is the next topic, The reparameterization trick.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • ELBO on a binary-latent toyoptional

    Compare log p(x), ELBO at a mismatched q, and equality at the true posterior. Self-check in the notebook.

    ~25 min · easier on a computer · The ELBO topic read.

    Self-check in the notebook — not part of mastery or the certificate.

Full notes

Answers are saved on the server and tied to this browser until you sign in.