Type at least 2 letters. Enter opens the first result, Esc closes.

    Generative Models · Lesson 1 · Likelihood and latent variables

    Generative models, latent variables and the ELBO

    Intermediate 75 min 4 interactive figures 4 videos Colab notebook

    Before this lesson: the KL divergence and Jensen's inequality (information theory, lesson 03); forward and reverse KL (information theory, lesson 06); Bayes' rule, maximum likelihood and the Gaussian density (the probability and statistics track). Gaussian mixtures and EM appear in the ML fundamentals track (not yet published), but this lesson explains what it needs. The ELBO is also derived in information theory, lesson 09; here we use it to train generative models. Time: about 75 minutes, plus the notebook.


    Why this matters #

    Generative models produce images (Stable Diffusion), text (GPT), audio, protein structures and weather forecasts (GenCast). They differ in architecture, but they share a few ideas, and this lesson gives the first ones:

    • Maximum likelihood as a KL divergence. It explains why likelihood-trained models cover all the data but may put mass between modes, and why GANs behave differently (lesson 05).
    • Latent variables. Gaussian mixtures, factor analysis, VAEs (lesson 02) and diffusion models (lesson 07, with latents x1,…,xTx_1, \dots, x_T) all build a complex pθ(x)p_\theta(x) from simple parts.
    • The ELBO. It is the training loss of VAEs, and the DDPM loss is a reweighted ELBO. The IWAE bound is the standard way to report the test log-likelihood of a VAE.
    • The language of the track. "Exact likelihood", "a bound", "no likelihood": every later lesson places its model in the family table of section 2.

    1. Predict first #

    2. The picture #

    What a generative model is #

    We have data x1,…,xnx_1, \dots, x_n, drawn from an unknown data distribution pdatap_{\text{data}}. A generative model is a distribution pθ(x)p_\theta(x) that should be close to pdatap_{\text{data}}. We use it in three ways:

    1. Sample: draw new x∼pθx \sim p_\theta (new images, new weather fields).
    2. Score: evaluate the density pθ(x)p_\theta(x) of a given xx (to detect unusual inputs, to compare models, to compress).
    3. Represent and condition: map xx to a code zz, or sample xx given a condition yy (text-to-image, a forecast given today's weather).

    Not every family can do all three. The table below shows which can.

    Maximum likelihood fits the forward KL #

    The standard way to fit pθp_\theta is maximum likelihood estimation (MLE): choose the θ\theta that makes the data most probable, max⁡θ1n∑ilog⁡pθ(xi)\max_\theta \frac1n \sum_i \log p_\theta(x_i). Section 3 proves that this is the same as minimizing the forward KL divergence KL(pdata ∥ pθ)\mathrm{KL}(p_{\text{data}} \,\|\, p_\theta). The other order, the reverse KL KL(pθ ∥ pdata)\mathrm{KL}(p_\theta \,\|\, p_{\text{data}}), behaves very differently. The picture first: fit one Gaussian to two bumps.

    Interactive figure: loading…

    Choose "forward KL", press "Find the best q", then do the same for "reverse KL". The blue curve is the data density p=12N(−3,1)+12N(3,1)p = \tfrac12\mathcal N(-3, 1) + \tfrac12\mathcal N(3, 1); the orange curve is one Gaussian qq. Forward KL (what MLE minimizes) gives a wide qq that covers both bumps and puts mass in the empty gap. Reverse KL gives a narrow qq on one bump. Then press "track toy ±1": the bumps overlap, pp has only one mode, and both fits are almost the same.

    Why the difference? Write both divergences as averages:

    • Forward: KL(p ∥ q)=Ex∼p[log⁡p(x)−log⁡q(x)]\mathrm{KL}(p \,\|\, q) = \mathbb E_{x \sim p}\big[\log p(x) - \log q(x)\big]. The average is over the data. Wherever the data has mass and qq is tiny, −log⁡q(x)-\log q(x) is huge. So qq must put mass on every region that has data. This is mode covering (also called mass covering).
    • Reverse: KL(q ∥ p)=Ex∼q[log⁡q(x)−log⁡p(x)]\mathrm{KL}(q \,\|\, p) = \mathbb E_{x \sim q}\big[\log q(x) - \log p(x)\big]. The average is over qq. Regions that qq ignores cost nothing, but mass in places where pp is tiny costs a lot. So qq stays inside one mode. This is mode seeking.

    The numbers for the two bumps at ±3\pm 3: the forward fit is N(0,10)\mathcal N(0, 10), which is the mean and the variance of pp (moment matching, proved in section 3). The reverse fit is close to N(2.98,1.022)\mathcal N(2.98, 1.02^2) (or its mirror image), with reverse KL 0.689≈log⁡20.689 \approx \log 2 nats: it captures one of two equal halves. The track's 1D toy, "two Gaussians" 12N(−1,1)+12N(1,1)\tfrac12\mathcal N(-1, 1) + \tfrac12\mathcal N(1, 1), has its means only 22 standard deviations apart, so its density has a single flat-topped mode; there the two fits are nearly equal (σ=1.41\sigma = 1.41 and σ=1.39\sigma = 1.39).

    Quick check

    A model is trained by maximum likelihood, but it is too simple to fit every mode of the data. What does the fit usually look like?

    The families of generative models #

    The families of this track differ in what they give you. All of them can sample, but only some can evaluate pθ(x)p_\theta(x):

    Family Density pθ(x)p_\theta(x) Sampling cost Latent space Lesson
    Autoregressive (PixelCNN, GPT) exact DD sequential steps for DD dimensions none 03
    Normalizing flow (RealNVP, Glow) exact one pass zz, same size as xx 04
    VAE lower bound (ELBO) one pass zz, usually smaller than xx 01–02
    GAN none one pass zz 05
    Energy-based model unnormalized: e−Eθ(x)/Zθe^{-E_\theta(x)}/Z_\theta, ZθZ_\theta unknown MCMC, many steps none 06
    Diffusion and score models a bound (ELBO); exact via an ODE, but costly many denoising steps noisy xtx_t, same size as xx 07–10
    Interactive figure: loading…

    Click each family, then drag the yellow probe. The data are the track's "8 Gaussians" (eight bumps on a circle of radius 2). The figure shows what each family gives you: a density (blue shading), samples (orange) and the score ∇xlog⁡p(x)\nabla_x \log p(x) (violet arrows). The readout says what the family can tell you about the probe point. All values are exact, computed from the known mixture; nothing is trained here.

    The track uses a few shared toy datasets, so that you can compare the families on the same data: "two Gaussians" in 1D (this lesson), a 1D Gaussian N(0,σdata2)\mathcal N(0, \sigma_{\text{data}}^2) where every diffusion formula has a closed form, "two points" x0∈{−1,+1}x_0 \in \{-1, +1\}, "8 Gaussians" in 2D (the figure above, standard deviation 0.150.15 per bump), and "two moons" from scikit-learn, used where a network is trained.

    Latent variables: a sampling recipe #

    A latent variable model has a hidden variable zz and two simple parts:

    • a prior p(z)p(z), a simple distribution over the latent;
    • a likelihood (or decoder) pθ(x∣z)p_\theta(x \mid z), a simple distribution over xx for each zz.

    To sample, draw zz first, then xx given zz. This is ancestral sampling. The model's density is the marginal, also called the evidence:

    pθ(x)=∑zp(z) pθ(x∣z)orpθ(x)=∫p(z) pθ(x∣z) dz.p_\theta(x) = \sum_z p(z)\, p_\theta(x \mid z) \quad\text{or}\quad p_\theta(x) = \int p(z)\, p_\theta(x \mid z)\, dz .

    Running example: two Gaussians. z∈{1,2}z \in \{1, 2\} with p(z=1)=p(z=2)=12p(z = 1) = p(z = 2) = \tfrac12, and x∣z=k∼N(μk,1)x \mid z = k \sim \mathcal N(\mu_k, 1) with μ1=−1\mu_1 = -1, μ2=+1\mu_2 = +1. So

    p(x)=12N(x;−1,1)+12N(x;1,1).p(x) = \tfrac12\mathcal N(x; -1, 1) + \tfrac12\mathcal N(x; 1, 1).

    The posterior. After we see xx, Bayes' rule gives the probability of each cause: p(z=k∣x)=p(z=k) p(x∣z=k)/p(x)p(z = k \mid x) = p(z = k)\,p(x \mid z = k)/p(x). In our example the log-odds are simple:

    log⁡p(z=2∣x)p(z=1∣x)=(x+1)2−(x−1)22=2x,\log\frac{p(z = 2 \mid x)}{p(z = 1 \mid x)} = \frac{(x + 1)^2 - (x - 1)^2}{2} = 2x,

    so p(z=2∣x)=σ(2x)p(z = 2 \mid x) = \sigma(2x), where σ(u)=1/(1+e−u)\sigma(u) = 1/(1 + e^{-u}) is the logistic function.

    Numbers at x=0.5x = 0.5. p(x,z=1)=12N(0.5;−1,1)=0.0648p(x, z{=}1) = \tfrac12\mathcal N(0.5; -1, 1) = 0.0648 and p(x,z=2)=12N(0.5;1,1)=0.1760p(x, z{=}2) = \tfrac12\mathcal N(0.5; 1, 1) = 0.1760. So p(x)=0.2408p(x) = 0.2408, log⁡p(x)=−1.4238\log p(x) = -1.4238, and the posterior is (0.2689,0.7311)=(σ(−1),σ(1))(0.2689, 0.7311) = (\sigma(-1), \sigma(1)).

    A floor under the ceiling #

    Choose any distribution q(z∣x)q(z \mid x) over the latent; it is our guess for the posterior and is called the variational distribution. Compute

    ELBO(q)=Eq(z∣x)[log⁡p(x,z)−log⁡q(z∣x)].\mathrm{ELBO}(q) = \mathbb E_{q(z \mid x)}\big[\log p(x, z) - \log q(z \mid x)\big].

    Section 3 proves that this is a floor under the fixed ceiling log⁡p(x)\log p(x), and that the distance between them is KL(q(z∣x) ∥ p(z∣x))\mathrm{KL}(q(z \mid x) \,\|\, p(z \mid x)). Try it before you read the proof.

    Interactive figure: loading…

    Drag the observation xx (yellow), then move the slider q(z=2)q(z = 2). The bottom panel shows the ELBO for every guess qq under the ceiling log⁡p(x)\log p(x). The yellow segment is the gap; the readout shows that it equals the KL divergence from qq to the exact posterior (the blue bars). The gap closes only at q=p(z∣x)q = p(z \mid x), the vertical blue line. The start is the hard assignment q(z=2)=1q(z = 2) = 1.

    Quick check

    Same model, but now you observe x=1x = 1. You use the hard assignment q(z=2)=1q(z = 2) = 1. How large is the gap log⁡p(x)−ELBO(q)\log p(x) - \mathrm{ELBO}(q)?

    3. Definitions and main results #

    Notation. pdatap_{\text{data}} is the data distribution; pθ(x)p_\theta(x) the model. In a latent variable model, pθ(x,z)=p(z) pθ(x∣z)p_\theta(x, z) = p(z)\,p_\theta(x \mid z). The KL divergence is KL(q ∥ p)=Eq[log⁡(q/p)]≥0\mathrm{KL}(q \,\|\, p) = \mathbb E_q[\log(q/p)] \ge 0, with equality only when q=pq = p (Gibbs' inequality, information theory, lesson 03). H(q)=−Eq[log⁡q]H(q) = -\mathbb E_q[\log q] is the entropy. All logarithms are natural, so the unit is the nat.

    Maximum likelihood is forward KL #

    Theorem (MLE = forward KL). For any model pθp_\theta,

    Ex∼pdata[−log⁡pθ(x)]=H(pdata)+KL(pdata ∥ pθ).\mathbb E_{x \sim p_{\text{data}}}\big[-\log p_\theta(x)\big] = H(p_{\text{data}}) + \mathrm{KL}(p_{\text{data}} \,\|\, p_\theta).

    H(pdata)H(p_{\text{data}}) does not depend on θ\theta. So maximizing the expected log-likelihood is the same as minimizing KL(pdata ∥ pθ)\mathrm{KL}(p_{\text{data}} \,\|\, p_\theta).

    Proof.

    1. KL(pdata ∥ pθ)=Epdata[log⁡pdata(x)]−Epdata[log⁡pθ(x)]\mathrm{KL}(p_{\text{data}} \,\|\, p_\theta) = \mathbb E_{p_{\text{data}}}[\log p_{\text{data}}(x)] - \mathbb E_{p_{\text{data}}}[\log p_\theta(x)].
    2. The first term is −H(pdata)-H(p_{\text{data}}) by the definition of entropy.
    3. Move it to the other side. ■\blacksquare

    With a finite training set, replace pdatap_{\text{data}} by the empirical distribution (equal weight 1/n1/n on each xix_i): the average negative log-likelihood −1n∑ilog⁡pθ(xi)-\frac1n\sum_i \log p_\theta(x_i) is then the cross-entropy between the empirical distribution and the model. For continuous data, HH is a differential entropy and can be negative, but it is still a constant in θ\theta.

    Corollary (a Gaussian fitted by MLE matches the moments). If q=N(μ,σ2)q = \mathcal N(\mu, \sigma^2) and pp has mean mm and variance vv, the forward KL KL(p ∥ q)\mathrm{KL}(p \,\|\, q) is smallest at μ=m\mu = m, σ2=v\sigma^2 = v.

    Proof of the corollary
    1. Ep[−log⁡q(x)]=12log⁡(2πσ2)+Ep[(x−μ)2]/(2σ2)\mathbb E_p[-\log q(x)] = \tfrac12\log(2\pi\sigma^2) + \mathbb E_p[(x - \mu)^2]/(2\sigma^2).
    2. Write x−μ=(x−m)+(m−μ)x - \mu = (x - m) + (m - \mu). The cross term has mean 0, so Ep[(x−μ)2]=v+(m−μ)2\mathbb E_p[(x - \mu)^2] = v + (m - \mu)^2.
    3. The term (m−μ)2(m - \mu)^2 is smallest at μ=m\mu = m.
    4. With μ=m\mu = m, the function 12log⁡σ2+v/(2σ2)\tfrac12\log\sigma^2 + v/(2\sigma^2) has derivative 12σ2−v2σ4\frac{1}{2\sigma^2} - \frac{v}{2\sigma^4} in σ2\sigma^2, which is 0 at σ2=v\sigma^2 = v; it is negative before and positive after, so this is the minimum.
    5. KL(p ∥ q)=Ep[−log⁡q]−H(p)\mathrm{KL}(p \,\|\, q) = \mathbb E_p[-\log q] - H(p), and H(p)H(p) does not depend on qq. ■\blacksquare

    For the two bumps at ±3\pm 3: m=0m = 0 and v=1+32=10v = 1 + 3^2 = 10, so the forward fit is N(0,10)\mathcal N(0, 10), as in the figure. The reverse KL has no such formula; it has a local minimum on each bump.

    Why a continuous latent is hard #

    With z∈Rdz \in \mathbb R^d and a neural network decoder, pθ(x)=∫p(z) pθ(x∣z) dzp_\theta(x) = \int p(z)\,p_\theta(x \mid z)\,dz has no closed form. A grid with nn points per axis needs ndn^d decoder calls. The posterior pθ(z∣x)=pθ(x,z)/pθ(x)p_\theta(z \mid x) = p_\theta(x, z)/p_\theta(x) is unknown too, because it needs pθ(x)p_\theta(x). Sampling is still easy (ancestral sampling). So evaluating and training are hard, while sampling is easy. The ELBO gives a quantity we can compute and train.

    Theorem 1: the evidence decomposition #

    Theorem 1. Let pθ(x)>0p_\theta(x) > 0. Let q(z∣x)q(z \mid x) be any distribution that puts mass only where pθ(z∣x)>0p_\theta(z \mid x) > 0 (it may put zero mass where the posterior is positive, as a hard assignment does). Then

    log⁡pθ(x)=Eq(z∣x)[log⁡pθ(x,z)−log⁡q(z∣x)]⏟ELBO(q)+KL(q(z∣x) ∥ pθ(z∣x)).\log p_\theta(x) = \underbrace{\mathbb E_{q(z \mid x)}\big[\log p_\theta(x, z) - \log q(z \mid x)\big]}_{\mathrm{ELBO}(q)} + \mathrm{KL}\big(q(z \mid x) \,\|\, p_\theta(z \mid x)\big).

    So ELBO(q)≤log⁡pθ(x)\mathrm{ELBO}(q) \le \log p_\theta(x), with equality exactly when q(z∣x)=pθ(z∣x)q(z \mid x) = p_\theta(z \mid x).

    Proof.

    1. log⁡p(x)\log p(x) does not depend on zz, so log⁡p(x)=Eq[log⁡p(x)]\log p(x) = \mathbb E_q[\log p(x)].
    2. Bayes' rule: p(x)=p(x,z)/p(z∣x)p(x) = p(x, z)/p(z \mid x) for every zz that qq can draw.
    3. Multiply and divide by qq inside the log: log⁡p(x,z)p(z∣x)=log⁡p(x,z)q(z∣x)+log⁡q(z∣x)p(z∣x)\log\frac{p(x, z)}{p(z \mid x)} = \log\frac{p(x, z)}{q(z \mid x)} + \log\frac{q(z \mid x)}{p(z \mid x)}.
    4. Take Eq\mathbb E_q of both sides: the first term gives the ELBO, the second gives the KL.
    5. KL≥0\mathrm{KL} \ge 0, with equality only when qq is the posterior. ■\blacksquare

    The Jensen route. Define the importance weight w(z)=p(x,z)/q(z∣x)w(z) = p(x, z)/q(z \mid x). Then Eq[w]=∑zq p(x,z)q=p(x)\mathbb E_q[w] = \sum_z q\,\frac{p(x, z)}{q} = p(x). The logarithm is concave, so Jensen's inequality gives log⁡p(x)=log⁡Eq[w]≥Eq[log⁡w]=ELBO(q)\log p(x) = \log \mathbb E_q[w] \ge \mathbb E_q[\log w] = \mathrm{ELBO}(q). This route is one line, but it does not give the size of the gap. Theorem 1 does: the gap is exactly a KL divergence.

    What each term rewards. Split log⁡p(x,z)=log⁡pθ(x∣z)+log⁡p(z)\log p(x, z) = \log p_\theta(x \mid z) + \log p(z):

    ELBO(q)=Eq[log⁡pθ(x∣z)]⏟reconstruction−KL(q(z∣x) ∥ p(z))⏟rate.\mathrm{ELBO}(q) = \underbrace{\mathbb E_q\big[\log p_\theta(x \mid z)\big]}_{\text{reconstruction}} - \underbrace{\mathrm{KL}\big(q(z \mid x) \,\|\, p(z)\big)}_{\text{rate}} .

    The reconstruction term rewards latents that explain xx well. The rate term charges nats for moving qq away from the prior, that is, for storing information about xx in zz. A second form is ELBO(q)=Eq[log⁡p(x,z)]+H(q)\mathrm{ELBO}(q) = \mathbb E_q[\log p(x, z)] + H(q): fit plus spread. Without the entropy H(q)H(q), the best qq would be a point mass on the most probable latent.

    What maximizing does. Over qq, the term log⁡p(x)\log p(x) is a constant. So maximizing the ELBO over qq is the same as minimizing KL(q ∥ p(z∣x))\mathrm{KL}(q \,\|\, p(z \mid x)): a reverse KL, so the best qq in a restricted family is mode seeking. Over θ\theta, a step can raise log⁡pθ(x)\log p_\theta(x) or shrink the gap. So the optimum is biased toward models whose posteriors are easy to fit with qq.

    Quick check

    The decoder θ\theta is fixed. You change only q(z∣x)q(z \mid x) for one data point xx. Which statement is true?

    Theorem 2: EM never decreases the log-likelihood #

    When the exact posterior is computable (mixtures, hidden Markov models, factor analysis), we can make the gap zero. Take a dataset x1,…,xnx_1, \dots, x_n with one distribution qiq_i per data point, and L(θ,q)=∑iELBO(xi;θ,qi)\mathcal L(\theta, q) = \sum_i \mathrm{ELBO}(x_i; \theta, q_i). The EM algorithm (expectation–maximization) alternates two steps:

    1. E-step: qi←pθt(z∣xi)q_i \leftarrow p_{\theta_t}(z \mid x_i) for every ii. By Theorem 1, every gap is 0.
    2. M-step: θt+1=arg⁡max⁡θL(θ,q)\theta_{t+1} = \arg\max_\theta \mathcal L(\theta, q). For a Gaussian mixture this has a closed form: weighted means, weighted variances and average responsibilities.

    Theorem 2. log⁡pθt+1(x1:n)≥log⁡pθt(x1:n)\log p_{\theta_{t+1}}(x_{1:n}) \ge \log p_{\theta_t}(x_{1:n}).

    Proof of Theorem 2
    1. After the E-step, L(θt,q)=log⁡pθt(x1:n)\mathcal L(\theta_t, q) = \log p_{\theta_t}(x_{1:n}) (all gaps are 0).
    2. The M-step gives L(θt+1,q)≥L(θt,q)\mathcal L(\theta_{t+1}, q) \ge \mathcal L(\theta_t, q).
    3. Theorem 1 at θt+1\theta_{t+1} gives log⁡pθt+1(x1:n)≥L(θt+1,q)\log p_{\theta_{t+1}}(x_{1:n}) \ge \mathcal L(\theta_{t+1}, q).
    4. Chain the three: log⁡pθt+1(x1:n)≥L(θt+1,q)≥L(θt,q)=log⁡pθt(x1:n)\log p_{\theta_{t+1}}(x_{1:n}) \ge \mathcal L(\theta_{t+1}, q) \ge \mathcal L(\theta_t, q) = \log p_{\theta_t}(x_{1:n}). ■\blacksquare

    EM is coordinate ascent on L\mathcal L: the E-step maximizes over qq, the M-step over θ\theta. It needs the exact posterior in the E-step. For a neural decoder this posterior is unknown, so a VAE cannot use EM.

    Amortized inference and the two gaps #

    A VAE chooses a family Q\mathcal Q (for example, Gaussians with diagonal covariance) and one encoder network qϕ(z∣x)q_\phi(z \mid x) with parameters ϕ\phi. For any xx, the encoder outputs a member of Q\mathcal Q. This is amortized inference: one forward pass replaces a separate optimization for each data point. The model and the encoder are trained together by stochastic gradient ascent on ∑iL(θ,ϕ;xi)\sum_i \mathcal L(\theta, \phi; x_i), where L(θ,ϕ;x)\mathcal L(\theta, \phi; x) is the ELBO with q=qϕ(⋅∣x)q = q_\phi(\cdot \mid x). The gap is not 0, so a step that raises the ELBO can lower log⁡pθ(x)\log p_\theta(x). There is no monotone guarantee as in EM.

    EM per-point VI amortized VI (VAE)
    qq for each xx exact posterior best member of Q\mathcal Q, optimized for this xx encoder output qϕ(⋅∣x)q_\phi(\cdot \mid x)
    gap 0 approximation gap approximation gap + amortization gap
    cost for a new xx one E-step (if tractable) an inner optimization loop one forward pass

    The decomposition (Cremer, Li and Duvenaud, 2018). Let qx∗q^*_x be the best member of Q\mathcal Q for this xx, the one with the largest ELBO. Then

    log⁡p(x)−ELBO(qϕ)=log⁡p(x)−ELBO(qx∗)⏟approximation gap+ELBO(qx∗)−ELBO(qϕ)⏟amortization gap.\log p(x) - \mathrm{ELBO}(q_\phi) = \underbrace{\log p(x) - \mathrm{ELBO}(q^*_x)}_{\text{approximation gap}} + \underbrace{\mathrm{ELBO}(q^*_x) - \mathrm{ELBO}(q_\phi)}_{\text{amortization gap}} .

    Both parts are ≥0\ge 0.

    • The approximation gap equals KL(qx∗ ∥ p(z∣x))\mathrm{KL}(q^*_x \,\|\, p(z \mid x)): the family Q\mathcal Q is too simple. Fixes: a richer family (full covariance, normalizing flows, hierarchical latents) or a tighter bound (IWAE, below).
    • The amortization gap means that the encoder does not output the best member for this xx. Fixes: a larger encoder, a few gradient steps on each qq after the encoder (semi-amortized inference), or more encoder updates per decoder update.
    Quick check

    Your VAE uses a diagonal Gaussian encoder. You replace the encoder by a network twice as large, with the same output family. Which gap can this reduce?

    Theorem 3: the IWAE bound #

    Draw KK samples from the encoder instead of one, and average the weights inside the logarithm.

    Theorem 3 (Burda, Grosse and Salakhutdinov 2016). Let q(z∣x)>0q(z \mid x) > 0 wherever p(x,z)>0p(x, z) > 0. Draw z1,…,zKz_1, \dots, z_K independently from q(z∣x)q(z \mid x), let wk=p(x,zk)/q(zk∣x)w_k = p(x, z_k)/q(z_k \mid x) and p^K=1K∑k=1Kwk\hat p_K = \frac1K\sum_{k=1}^K w_k. Define the IWAE bound (importance-weighted autoencoder bound)

    LK=E[log⁡p^K]=E[log⁡1K∑k=1Kp(x,zk)q(zk∣x)].\mathcal L_K = \mathbb E\big[\log \hat p_K\big] = \mathbb E\Big[\log \frac1K\sum_{k=1}^K \frac{p(x, z_k)}{q(z_k \mid x)}\Big].

    Then (i) L1=ELBO\mathcal L_1 = \mathrm{ELBO}; (ii) LK≤log⁡p(x)\mathcal L_K \le \log p(x); (iii) LK≤LK+1\mathcal L_K \le \mathcal L_{K+1}; (iv) if the weights are bounded, LK→log⁡p(x)\mathcal L_K \to \log p(x) as K→∞K \to \infty.

    Why this is true, in words. p^K\hat p_K is an unbiased estimate of p(x)p(x). The log of an unbiased estimate is biased downward (Jensen). Averaging more weights makes the estimate less noisy, so the downward bias shrinks.

    Proof of Theorem 3
    1. (i) For K=1K = 1, E[log⁡w1]=Eq[log⁡p(x,z)−log⁡q(z∣x)]\mathbb E[\log w_1] = \mathbb E_q[\log p(x, z) - \log q(z \mid x)], which is the ELBO.
    2. (ii) E[wk]=∫q(z∣x) p(x,z)q(z∣x) dz=p(x)\mathbb E[w_k] = \int q(z \mid x)\,\frac{p(x, z)}{q(z \mid x)}\,dz = p(x), so E[p^K]=p(x)\mathbb E[\hat p_K] = p(x). Jensen for the concave log: E[log⁡p^K]≤log⁡E[p^K]=log⁡p(x)\mathbb E[\log \hat p_K] \le \log \mathbb E[\hat p_K] = \log p(x).
    3. (iii) Take K+1K + 1 samples and a subset II of size KK, chosen uniformly at random. Each index is in II with probability K/(K+1)K/(K+1), so EI[1K∑k∈Iwk]=1K⋅KK+1∑k=1K+1wk=p^K+1\mathbb E_I\big[\frac1K\sum_{k \in I} w_k\big] = \frac1K \cdot \frac{K}{K+1}\sum_{k=1}^{K+1} w_k = \hat p_{K+1}.
    4. Jensen over II, with the samples fixed: log⁡p^K+1=log⁡EI[1K∑k∈Iwk]≥EI[log⁡1K∑k∈Iwk]\log \hat p_{K+1} = \log \mathbb E_I\big[\frac1K\sum_{k \in I} w_k\big] \ge \mathbb E_I\big[\log \frac1K\sum_{k \in I} w_k\big].
    5. Average over the samples. For each fixed II, the KK weights in II are independent draws, so the right side has expectation LK\mathcal L_K. Hence LK+1≥LK\mathcal L_{K+1} \ge \mathcal L_K.
    6. (iv) By the law of large numbers, p^K→p(x)\hat p_K \to p(x) with probability 1. If the weights are bounded, log⁡p^K\log \hat p_K is bounded too (between the log of the smallest and the largest weight), so the limit can be taken inside the expectation. ■\blacksquare
    Interactive figure: loading…

    Move the proposal qq (orange) and watch the bound. The model is z∼N(0,1)z \sim \mathcal N(0, 1), x∣z∼N(z,0.25)x \mid z \sim \mathcal N(z, 0.25), with the observation x=1.5x = 1.5; so log⁡p(x)=−1.931\log p(x) = -1.931 is known exactly (blue line), and the posterior is N(1.2,0.2)\mathcal N(1.2, 0.2). Each orange point is a Monte Carlo estimate of LK\mathcal L_K with ±2\pm 2 standard errors. With qq = the prior, the ELBO (K=1K = 1) is 4.84.8 nats too low, but L1000\mathcal L_{1000} is within 0.0020.002 nats. With qq = the posterior every weight equals p(x)p(x), and all LK\mathcal L_K are exact. Try "too narrow": the weights have infinite variance and the bound improves very slowly.

    How fast the IWAE gap closes, and its cost for training

    For large KK, expand log⁡p^K\log \hat p_K around p(x)p(x) to second order. With E[p^K]=p(x)\mathbb E[\hat p_K] = p(x) and Var⁡(p^K)=Var⁡q(w)/K\operatorname{Var}(\hat p_K) = \operatorname{Var}_q(w)/K:

    log⁡p(x)−LK≈Var⁡q(w)2K p(x)2.\log p(x) - \mathcal L_K \approx \frac{\operatorname{Var}_q(w)}{2K\,p(x)^2} .

    The gap shrinks like 1/K1/K, and it is small when qq makes the weights nearly equal. The dashed grey curve in the figure is this prediction. When qq is much narrower than the posterior, Var⁡q(w)=∞\operatorname{Var}_q(w) = \infty and the formula fails: the bound still rises, but slowly. (For the Gaussian example above, this happens when qq's variance is at most half of the posterior's variance.)

    The price is KK times the compute. For training, a second price appears: the encoder's gradient gets noisier relative to its size as KK grows; its signal-to-noise ratio falls like 1/K1/\sqrt K (Rainforth et al., 2018). For evaluation, large KK is standard: Burda et al. report test log-likelihoods with K=5000K = 5000.

    Quick check

    What is the IWAE bound LK\mathcal L_K for K=1K = 1?

    Answers to section 1. (1) It covers both bumps. MLE minimizes the forward KL, which is mode covering: for bumps at ±3\pm 3 the fit is N(0,10)\mathcal N(0, 10). (2) About 0.3 nats. A point mass has H(q)=0H(q) = 0, so its ELBO is log⁡p(x,z=2)\log p(x, z{=}2), and the gap is −log⁡p(z=2∣x)=−log⁡σ(1)=0.313-\log p(z{=}2 \mid x) = -\log\sigma(1) = 0.313 nats. (3) The ELBO can go up: the refinement removes part of the amortization gap. log⁡pθ(x)\log p_\theta(x) cannot change, because it does not depend on qq.

    4. Worked example #

    Same mixture, same x=0.5x = 0.5. The log-joints are log⁡p(x,z=1)=−2.7371\log p(x, z{=}1) = -2.7371 and log⁡p(x,z=2)=−1.7371\log p(x, z{=}2) = -1.7371. They differ by exactly the log-odds 2x=12x = 1.

    (a) The ELBO for three choices of q=(q1,q2)q = (q_1, q_2). Use ELBO=Eq[log⁡p(x,z)]+H(q)\mathrm{ELBO} = \mathbb E_q[\log p(x, z)] + H(q).

    qq Eq[log⁡p(x,z)]\mathbb E_q[\log p(x, z)] H(q)H(q) ELBO gap log⁡p(x)−ELBO\log p(x) - \mathrm{ELBO}
    uniform (0.5,0.5)(0.5, 0.5) −2.2371-2.2371 0.69310.6931 −1.5439-1.5439 0.12010.1201
    hard (0,1)(0, 1) −1.7371-1.7371 00 −1.7371-1.7371 0.31330.3133
    posterior (0.2689,0.7311)(0.2689, 0.7311) −2.0060-2.0060 0.58220.5822 −1.4238-1.4238 00

    Step by step for the first row: Eq[log⁡p(x,z)]=0.5⋅(−2.7371)+0.5⋅(−1.7371)=−2.2371\mathbb E_q[\log p(x, z)] = 0.5 \cdot (-2.7371) + 0.5 \cdot (-1.7371) = -2.2371; H(q)=−2⋅0.5log⁡0.5=log⁡2=0.6931H(q) = -2 \cdot 0.5 \log 0.5 = \log 2 = 0.6931; the sum is −1.5439-1.5439. Check it with Theorem 1: KL(q ∥ p(z∣x))=12log⁡0.50.2689+12log⁡0.50.7311=0.3101−0.1899=0.1201\mathrm{KL}(q \,\|\, p(z \mid x)) = \tfrac12\log\tfrac{0.5}{0.2689} + \tfrac12\log\tfrac{0.5}{0.7311} = 0.3101 - 0.1899 = 0.1201. ✓

    (b) The two gaps. If Q\mathcal Q = hard assignments (as in hard EM or k-means), the best member is z=2z = 2, so the approximation gap at x=0.5x = 0.5 is 0.31330.3133 nats, whatever the encoder. If Q\mathcal Q = all distributions on {1,2}\{1, 2\}, the approximation gap is 0, and only the encoder can be wrong. Take the encoder qϕ(z=2∣x)=σ(a+bx)q_\phi(z{=}2 \mid x) = \sigma(a + bx). The exact posterior is σ(2x)\sigma(2x), so (a,b)=(0,2)(a, b) = (0, 2) gives zero gap for every xx. A half-trained encoder (a,b)=(0,1)(a, b) = (0, 1) outputs q2=σ(0.5)=0.6225q_2 = \sigma(0.5) = 0.6225 at x=0.5x = 0.5, and its gap is KL((0.3775,0.6225) ∥ (0.2689,0.7311))=0.0280\mathrm{KL}((0.3775, 0.6225) \,\|\, (0.2689, 0.7311)) = 0.0280 nats: a pure amortization gap.

    A case where even the best encoder of this form has a gap: change the model to 12N(0,1)+12N(0,4)\tfrac12\mathcal N(0, 1) + \tfrac12\mathcal N(0, 4) (same mean, different variances). Its posterior logit is log⁡p(z=2∣x)p(z=1∣x)=−log⁡2+38x2\log\frac{p(z = 2 \mid x)}{p(z = 1 \mid x)} = -\log 2 + \tfrac38 x^2, which is symmetric in xx. A linear encoder σ(a+bx)\sigma(a + bx) cannot follow it; its best version is almost constant (a=0.244a = 0.244, b=0b = 0) and has an average gap of 0.1810.181 nats over the data. One more input feature, x2x^2, removes the gap: the family "all distributions on {1,2}\{1, 2\}" was never the problem, the encoder was.

    (c) IWAE with K=2K = 2, by exact enumeration. Take qq uniform. The weights are w(1)=0.0648/0.5=0.1295w(1) = 0.0648/0.5 = 0.1295 and w(2)=0.1760/0.5=0.3521w(2) = 0.1760/0.5 = 0.3521. The pair (z1,z2)(z_1, z_2) takes four equally likely values:

    • (1,1)(1, 1): log⁡w(1)=−2.0439\log w(1) = -2.0439;
    • (2,2)(2, 2): log⁡w(2)=−1.0439\log w(2) = -1.0439;
    • (1,2)(1, 2) or (2,1)(2, 1), probability 12\tfrac12: log⁡0.1295+0.35212=log⁡0.2408=−1.4238=log⁡p(x)\log\frac{0.1295 + 0.3521}{2} = \log 0.2408 = -1.4238 = \log p(x).

    So L2=14(−2.0439)+14(−1.0439)+12(−1.4238)=−1.4839\mathcal L_2 = \tfrac14(-2.0439) + \tfrac14(-1.0439) + \tfrac12(-1.4238) = -1.4839, and

    ELBO=−1.5439  <  L2=−1.4839  <  log⁡p(x)=−1.4238.\mathrm{ELBO} = -1.5439 \;<\; \mathcal L_2 = -1.4839 \;<\; \log p(x) = -1.4238 .

    The gap falls from 0.12010.1201 to 0.06010.0601, about half. The large-KK formula, with Var⁡q(w)/p(x)2=0.2136\operatorname{Var}_q(w)/p(x)^2 = 0.2136, predicts 0.2136/(2⋅2)=0.05340.2136/(2 \cdot 2) = 0.0534 for K=2K = 2. It becomes accurate by K=10K = 10: predicted 0.01070.0107, exact 0.01100.0110.

    5. In code #

    NumPy and SciPy check the numbers of section 4. The IWAE bound for a uniform qq is computed exactly, without Monte Carlo noise: the number of draws with z=2z = 2 is binomial.

    import numpy as np
    from scipy.stats import norm, binom
    from scipy.special import logsumexp, expit
    
    # The two-Gaussians model: p(z = k) = 1/2, x | z = k ~ N(mu_k, 1), mu = (-1, +1)
    mu, x = np.array([-1.0, 1.0]), 0.5
    log_joint = np.log(0.5) + norm.logpdf(x, mu, 1.0)      # log p(x, z = k)
    log_px = logsumexp(log_joint)                          # log p(x)
    post = np.exp(log_joint - log_px)                      # p(z | x)
    print(log_joint.round(4), round(log_px, 4), post.round(4), round(expit(2 * x), 4))
    # [-2.7371 -1.7371] -1.4238 [0.2689 0.7311] 0.7311
    
    def elbo(q):                                           # E_q[log p(x, z)] + H(q)
        q = np.asarray(q, float); m = q > 0
        return np.sum(q[m] * log_joint[m]) - np.sum(q[m] * np.log(q[m]))
    
    def kl(q, p):                                          # KL(q || p) on {1, 2}
        q = np.asarray(q, float); m = q > 0
        return np.sum(q[m] * np.log(q[m] / p[m]))
    
    for q in ([0.5, 0.5], [0.0, 1.0], post):
        print(round(elbo(q), 4), round(log_px - elbo(q), 4), round(kl(q, post), 4))
    # -1.5439 0.1201 0.1201      uniform q: gap = KL to the posterior
    # -1.7371 0.3133 0.3133      hard assignment
    # -1.4238 0.0 0.0            q = posterior: no gap
    
    # Exact IWAE bound for q uniform: the number m of draws with z = 2 is Binomial(K, 1/2)
    w = np.exp(log_joint) / 0.5                            # importance weights p(x, z)/q(z)
    for K in [1, 2, 10, 100, 1000]:
        m = np.arange(K + 1)
        L_K = np.sum(binom.pmf(m, K, 0.5) * np.log(((K - m) * w[0] + m * w[1]) / K))
        print(K, round(log_px - L_K, 5))
    # 1 0.12011 | 2 0.06006 | 10 0.01102 | 100 0.00107 | 1000 0.00011
    

    The gap halves from K=1K = 1 to K=2K = 2 and then falls like 1/K1/K. Numerics: in high dimensions the raw weights wkw_k underflow or overflow. Always compute log⁡p^K=logsumexp⁡(log⁡w)−log⁡K\log \hat p_K = \operatorname{logsumexp}(\log w) - \log K.

    6. Where it shows up #

    • VAEs (lesson 02). The loss is −ELBO-\mathrm{ELBO} with a Gaussian encoder and a neural decoder. Test log-likelihoods are reported as LK\mathcal L_K with large KK.
    • Diffusion models (lesson 07). DDPM is a latent variable model with latents x1,…,xTx_1, \dots, x_T and a fixed "encoder", the noising process. Its loss is a reweighted ELBO.
    • Latent diffusion (lesson 13). The first stage is an autoencoder trained with a reconstruction term and, in the KL-regularized version, a very small rate term. Latent diffusion models of weather fields and of seismic ground motion use the same two stages.
    • Mixtures in climate science. Gaussian mixtures fitted by EM to Northern Hemisphere geopotential height anomalies found three robust circulation regimes (Smyth, Ide and Ghil, J. Atmos. Sci., 1999). The posterior gives each day's regime probabilities.
    • Amortized inference in science. One encoder that outputs a posterior for any new observation replaces one optimization per seismogram or per field (simulation-based inference uses the same idea). The amortization gap is the accuracy you pay for that speed.
    • MLE vs other objectives. Likelihood-trained models (autoregressive, flows, VAEs, diffusion) cover all modes but may put mass where there is no data; GANs (lesson 05) do not minimize the forward KL and can drop modes ("mode collapse").

    7. Common mistakes #

    • Mixing up forward and reverse KL. MLE minimizes KL(pdata ∥ pθ)\mathrm{KL}(p_{\text{data}} \,\|\, p_\theta), the forward KL (mode covering). Variational inference over qq minimizes KL(q ∥ p(z∣x))\mathrm{KL}(q \,\|\, p(z \mid x)), a reverse KL (mode seeking).
    • Comparing models by the ELBO as if it were the likelihood. A model can win by having a smaller gap, not a higher log⁡p(x)\log p(x). Compare with LK\mathcal L_K for large KK.
    • Dropping −log⁡q-\log q in a Monte Carlo ELBO. Without the entropy, qq collapses to a point mass at the most probable latent.
    • Mixing up the two gaps. A bigger or better-trained encoder cannot fix the approximation gap: it is set by the family Q\mathcal Q. A richer family lowers the approximation gap, but does not remove the amortization gap by itself.
    • Expecting EM's guarantee from a VAE. EM's monotone guarantee comes from the exact posterior in every E-step (gap 0) and from coordinate ascent. A VAE has a restricted encoder and takes joint gradient steps in (θ,ϕ)(\theta, \phi), so log⁡pθ(x)\log p_\theta(x) can go down.
    • Ignoring the support condition of IWAE. If q(z∣x)=0q(z \mid x) = 0 where p(x,z)>0p(x, z) > 0, then p^K\hat p_K is no longer unbiased and LK\mathcal L_K does not reach log⁡p(x)\log p(x) (check yourself 5).

    8. Check yourself #

    1. Mixture with weights π=(0.2,0.8)\pi = (0.2, 0.8), means (−1,1)(-1, 1), unit variances. What is p(z=2∣x=0)p(z{=}2 \mid x{=}0)?
      AnswerThe log-odds are log⁡0.80.2+2⋅0=log⁡4\log\frac{0.8}{0.2} + 2 \cdot 0 = \log 4, so p(z=2∣x=0)=4/5=0.8p(z{=}2 \mid x{=}0) = 4/5 = 0.8. At x=0x = 0 both likelihoods are equal, so the posterior equals the prior.
    2. In the lesson's mixture, what is the gap of a hard assignment at x=0x = 0?
      AnswerThe posterior is (12,12)(\frac12, \frac12), so the gap is −log⁡12=log⁡2=0.693-\log\frac12 = \log 2 = 0.693 nats. With two components, this is the largest gap that a hard assignment to the more likely component can have.
    3. Why does the EM E-step make the bound tight, and why can a VAE not do this step?
      AnswerSetting qi=pθt(z∣xi)q_i = p_{\theta_t}(z \mid x_i) makes KL(qi ∥ p(z∣xi))=0\mathrm{KL}(q_i \,\|\, p(z \mid x_i)) = 0, so the ELBO equals log⁡pθt(xi)\log p_{\theta_t}(x_i) (Theorem 1). For a neural decoder, pθ(z∣x)p_\theta(z \mid x) needs pθ(x)=∫p(z)pθ(x∣z) dzp_\theta(x) = \int p(z)p_\theta(x \mid z)\,dz, which has no closed form. So the VAE uses a parametric encoder and keeps a gap.
    4. A VAE gives test values L1=−95.2\mathcal L_1 = -95.2, L10=−93.8\mathcal L_{10} = -93.8, L1000=−93.1\mathcal L_{1000} = -93.1 nats. What do you know about log⁡p(x)\log p(x) and about the ELBO gap?
      Answerlog⁡p(x)≥L1000≈−93.1\log p(x) \ge \mathcal L_{1000} \approx -93.1 (up to Monte Carlo noise). The ELBO gap log⁡p(x)−L1\log p(x) - \mathcal L_1 is at least 95.2−93.1=2.195.2 - 93.1 = 2.1 nats. There is no upper limit from these numbers: log⁡p(x)\log p(x) can be above −93.1-93.1.
    5. In the lesson's mixture at x=0.5x = 0.5, use the hard q=(0,1)q = (0, 1) as the IWAE proposal. What is LK\mathcal L_K for every KK, and why does it not approach log⁡p(x)\log p(x)?
      AnswerEvery sample is z=2z = 2 with weight p(x,z=2)/1=0.1760p(x, z{=}2)/1 = 0.1760, so LK=log⁡0.1760=−1.7371\mathcal L_K = \log 0.1760 = -1.7371 for all KK. The support condition fails: q(z=1)=0q(z{=}1) = 0 while p(x,z=1)>0p(x, z{=}1) > 0, so E[p^K]=p(x,z=2)<p(x)\mathbb E[\hat p_K] = p(x, z{=}2) < p(x).
    6. You fit q=N(μ,σ2)q = \mathcal N(\mu, \sigma^2) to p=12N(−2,1)+12N(2,1)p = \tfrac12\mathcal N(-2, 1) + \tfrac12\mathcal N(2, 1) by forward KL. What are μ\mu and σ2\sigma^2?
      AnswerMoment matching: μ=0\mu = 0 and σ2=Var⁡p(x)=1+22=5\sigma^2 = \operatorname{Var}_p(x) = 1 + 2^2 = 5. (The variance of a mixture is the average within-component variance, 1, plus the variance of the means, 4.)
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Which KL divergence does maximum likelihood minimize?

    2. Why is the forward KL mode covering?

    3. Define the ELBO for a latent variable model.

    4. What is the gap log⁡p(x)−ELBO(q)\log p(x) - \mathrm{ELBO}(q) exactly?

    5. In the mixture 12N(−1,1)+12N(1,1)\tfrac12\mathcal N(-1, 1) + \tfrac12\mathcal N(1, 1), what is p(z=2∣x)p(z = 2 \mid x)?

    6. Why does EM never decrease log⁡p(x)\log p(x)?

    7. What is the amortization gap?

    8. Write the IWAE bound.

    9. Why is LK≤log⁡p(x)\mathcal L_K \le \log p(x)?

    Open the review →

    9. Interview angle #

    • "Why do we train with maximum likelihood, and what does it optimize?" — It minimizes the forward KL to the data distribution. It is consistent and needs only samples of the data, but it is mode covering: a model that is too simple puts mass between the modes.
    • "Derive the ELBO. Which derivation tells you the gap?" — Jensen on log⁡Eq[w]\log\mathbb E_q[w] gives the bound; inserting q/qq/q into log⁡p(x,z)p(z∣x)\log\frac{p(x, z)}{p(z \mid x)} gives ELBO + KL, so the gap is KL(q ∥ p(z∣x))\mathrm{KL}(q \,\|\, p(z \mid x)).
    • "Why not maximize log⁡p(x)\log p(x) of a VAE directly?" — The integral over zz has no closed form, and the log of a Monte Carlo average is biased downward. The ELBO is a bound we can estimate without bias and differentiate.
    • "How would you measure the amortization gap?" — Compare the ELBO of the encoder output, the ELBO after optimizing qq for each test point (same family), and LK\mathcal L_K with large KK as an estimate of log⁡p(x)\log p(x) (Cremer et al., 2018).
    • "Is a tighter bound always better for training?" — No. IWAE costs KK times more, and the encoder's gradient signal-to-noise ratio falls like 1/K1/\sqrt K.

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. The marginal and the posterior of a 1D Gaussian mixture; check Bayes' rule numerically.
    2. The ELBO as a function of q(z=2)q(z = 2); find its maximum and check that the gap equals the KL.
    3. EM for a 2D Gaussian mixture on 8-Gaussians data; check that log⁡p\log p never decreases.
    4. The IWAE bound LK\mathcal L_K for K=1,…,100K = 1, \dots, 100 on a linear-Gaussian model with a closed-form p(x)p(x); check that it rises with KK and stays below log⁡p(x)\log p(x).
    5. Forward vs reverse KL fits by grid search; compare with the figure in section 2.

    11. Watch and read #

    What a generative model is and the map of model families used in this track.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A short refresher on maximum likelihood before the KL view of section 3.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The ELBO as a floor under the log-evidence, with plots of the gap.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The E-step and M-step for a Gaussian mixture, step by step.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play