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

    Information Theory · Lesson 9 · Information-theoretic objectives in ML

    The ELBO: variational inference, VAEs and importance-weighted bounds

    Advanced 80 min 4 interactive figures 4 videos Colab notebook

    Before this lesson: lesson 03 (Jensen's inequality, KL divergence, Gibbs' inequality), lesson 04 (cross-entropy as a loss), lesson 06 (differential entropy, the Gaussian KL, forward and reverse KL). Bayes' rule and posteriors from probability lesson 01; importance sampling from the probability track; gradient estimators from calculus lesson 12. Time: about 80 minutes, plus the notebook.


    Why this matters #

    Bayesian inference needs the posterior p(z∣x)=p(x,z)/p(x)p(z \mid x) = p(x, z)/p(x). The numerator is easy: prior times likelihood. The denominator p(x)=∫p(x,z) dzp(x) = \int p(x, z)\,dz is an integral over all latent values, and in most models it has no closed form. The ELBO turns this integral into an optimization problem.

    The same bound appears in many places:

    • VAEs are trained by maximizing the ELBO (Kingma and Welling, 2013).
    • Diffusion models: the DDPM loss is a reweighted ELBO over many noising steps (generative models track).
    • EM for mixture models climbs the ELBO (ML fundamentals track, in preparation).
    • Variational Bayesian neural networks put a distribution qq on the weights and maximize the ELBO.
    • Science: fast approximate posteriors for inverse problems, such as seismic tomography, and latent-variable models of single-cell gene expression.

    Two facts matter most in practice: how far the bound is from log⁡p(x)\log p(x), and in which direction qq is wrong when its family is too simple. This lesson answers both.

    In this lesson log⁡\log is the natural logarithm, so all values are in nats; divide by ln⁡2\ln 2 to get bits. This is also what PyTorch and NumPy compute.

    1. Predict first #

    2. The picture #

    The model. A latent-variable model is a joint distribution p(x,z)=p(z) p(x∣z)p(x, z) = p(z)\,p(x \mid z). The prior p(z)p(z) says which latent values are likely before we see data. The likelihood p(x∣z)p(x \mid z) says how the observation xx is produced from zz. We observe one xx and keep it fixed.

    • The evidence (or marginal likelihood) is p(x)=∫p(x,z) dzp(x) = \int p(x, z)\,dz, a sum for discrete zz.
    • The posterior is p(z∣x)=p(x,z)/p(x)p(z \mid x) = p(x, z)/p(x), by Bayes' rule.
    • A variational distribution q(z)q(z) is any distribution over zz that we choose. It is our approximation of the posterior.

    The simplest case: zz has two values. Suppose the model gives, for our observed xx,

    p(x,z=0)=0.02,p(x,z=1)=0.18.p(x, z{=}0) = 0.02, \qquad p(x, z{=}1) = 0.18 .

    Then p(x)=0.02+0.18=0.2p(x) = 0.02 + 0.18 = 0.2, so log⁡p(x)=log⁡0.2=−1.609\log p(x) = \log 0.2 = -1.609. The posterior is p(z∣x)=(0.02/0.2, 0.18/0.2)=(0.1, 0.9)p(z \mid x) = (0.02/0.2,\ 0.18/0.2) = (0.1,\ 0.9). A distribution qq on {0,1}\{0, 1\} is one number t=q(z=1)t = q(z{=}1). Define

    ELBO(q)=Ez∼q[log⁡p(x,z)q(z)]=(1−t)log⁡0.021−t+tlog⁡0.18t\mathrm{ELBO}(q) = \mathbb{E}_{z \sim q}\Big[\log \frac{p(x, z)}{q(z)}\Big] = (1 - t)\log\frac{0.02}{1 - t} + t \log\frac{0.18}{t}

    (with 0log⁡0=00 \log 0 = 0 at t=0t = 0 and t=1t = 1). Four values of tt:

    t=q(z=1)t = q(z{=}1) 0 0.5 0.9 1
    ELBO(q)\mathrm{ELBO}(q) −3.912 −2.120 −1.609 −1.715
    gap log⁡p(x)−ELBO(q)\log p(x) - \mathrm{ELBO}(q) 2.303 0.511 0 0.105
    Interactive figure: loading…

    Move t=q(z=1)t = q(z{=}1) and watch the magenta ELBO curve under the dashed ceiling log⁡p(x)\log p(x). The aqua gap is 0 only at the blue posterior value t=0.9t = 0.9. The side panel shows that the gap equals KL(q ∥ p(z∣x))\mathrm{KL}(q\,\|\,p(z \mid x)), computed separately. Try the other joints, and the end points t=0t = 0 and t=1t = 1.

    Three things to see:

    1. The ELBO is never above log⁡p(x)\log p(x). It is a floor under a fixed ceiling: the ceiling does not depend on qq.
    2. It touches the ceiling at one qq only: t=0.9t = 0.9, the posterior.
    3. At t=1t = 1, qq is a point mass on the most probable latent (the MAP latent). The ELBO is then log⁡p(x,z=1)=log⁡0.18=−1.715\log p(x, z{=}1) = \log 0.18 = -1.715. That is below the maximum. The ELBO rewards qq for spreading over every zz that explains xx, not only the best one.

    The weights picture. Write

    w(z)=p(x,z)q(z),w(z) = \frac{p(x, z)}{q(z)},

    the importance weight of zz (as in importance sampling). If q(z)>0q(z) > 0 wherever p(x,z)>0p(x, z) > 0, then:

    • Eq[w]=∑zq(z)p(x,z)q(z)=∑zp(x,z)=p(x)\mathbb{E}_q[w] = \sum_z q(z)\frac{p(x, z)}{q(z)} = \sum_z p(x, z) = p(x). The arithmetic mean of the weights is the evidence.
    • ELBO(q)=Eq[log⁡w]\mathrm{ELBO}(q) = \mathbb{E}_q[\log w]. So eELBOe^{\mathrm{ELBO}} is the geometric mean of the weights.

    A geometric mean is never larger than the arithmetic mean, and the two are equal only when all values are equal. If qq is the posterior, then w(z)=p(x,z)/p(z∣x)=p(x)w(z) = p(x, z)/p(z \mid x) = p(x) for every zz: all weights are equal and the gap is 0. The more the weights spread, the larger the gap. At t=0.5t = 0.5 the weights are 0.02/0.5=0.040.02/0.5 = 0.04 and 0.18/0.5=0.360.18/0.5 = 0.36. Their arithmetic mean is 0.2=p(x)0.2 = p(x); their geometric mean is 0.04⋅0.36=0.12=e−2.120\sqrt{0.04 \cdot 0.36} = 0.12 = e^{-2.120}.

    Quick check

    In the two-value example, qq is uniform (t=0.5t = 0.5) and the ELBO is −2.120-2.120 while log⁡p(x)=−1.609\log p(x) = -1.609. The gap 0.5110.511 nats equals which quantity?

    Quick check

    zz is discrete and qq puts all its mass on one value z0z_0. What is the ELBO?

    3. Definitions and main results #

    Notation. 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, lesson 03). H(q)=−Eq[log⁡q(z)]H(q) = -\mathbb{E}_q[\log q(z)] is the entropy of qq; for a continuous zz it is the differential entropy of lesson 06.

    Definition. For a fixed observation xx and a distribution qq over zz, the evidence lower bound is

    ELBO(q)=Ez∼q[log⁡p(x,z)−log⁡q(z)].\mathrm{ELBO}(q) = \mathbb{E}_{z \sim q}\big[\log p(x, z) - \log q(z)\big].

    Physicists call −ELBO-\mathrm{ELBO} the variational free energy.

    Theorem 1 (the evidence decomposition) #

    Let qq be a distribution with q(z)=0q(z) = 0 wherever p(z∣x)=0p(z \mid x) = 0. Then

    log⁡p(x)=ELBO(q)+KL(q(z) ∥ p(z∣x)).\log p(x) = \htmlClass{c5}{\mathrm{ELBO}(q)} + \htmlClass{c3}{\mathrm{KL}\big(q(z)\,\|\,p(z \mid x)\big)} .

    Hence ELBO(q)≤log⁡p(x)\mathrm{ELBO}(q) \le \log p(x), with equality if and only if q(z)=p(z∣x)q(z) = p(z \mid x).

    The condition is needed for a finite KL. If qq puts mass where the posterior has none, then log⁡w=−∞\log w = -\infty there: the ELBO is −∞-\infty and the KL is +∞+\infty.

    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 with p(z∣x)>0p(z \mid x) > 0. This includes every zz that qq can draw. So log⁡p(x)=Eq[log⁡p(x,z)p(z∣x)]\log p(x) = \mathbb{E}_q\Big[\log \frac{p(x, z)}{p(z \mid x)}\Big].
    3. Multiply and divide by q(z)q(z) inside the log: log⁡p(x,z)p(z∣x)=log⁡p(x,z)q(z)+log⁡q(z)p(z∣x)\log\frac{p(x, z)}{p(z \mid x)} = \log\frac{p(x, z)}{q(z)} + \log\frac{q(z)}{p(z \mid x)}.
    4. Take Eq\mathbb{E}_q of both terms. The first gives ELBO(q)\mathrm{ELBO}(q). The second gives KL(q ∥ p(z∣x))\mathrm{KL}(q\,\|\,p(z \mid x)).
    5. KL≥0\mathrm{KL} \ge 0, with equality if and only if q=p(z∣x)q = p(z \mid x) (Gibbs). So ELBO(q)≤log⁡p(x)\mathrm{ELBO}(q) \le \log p(x), with the same equality case. ■\blacksquare

    Check with the toy. At t=0.5t = 0.5 the gap is 0.5110.511, and KL((0.5,0.5) ∥ (0.1,0.9))=0.511\mathrm{KL}((0.5, 0.5)\,\|\,(0.1, 0.9)) = 0.511 (the first quiz above).

    The Jensen route (lesson 03). If q(z)>0q(z) > 0 wherever p(x,z)>0p(x, z) > 0, then p(x)=Eq[w]p(x) = \mathbb{E}_q[w]. The log 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 gives the bound in one line, but not the size of the gap. Theorem 1 says the gap is exactly a KL divergence.

    A consequence for Monte Carlo. Step 2 says log⁡w(z)=log⁡p(x)\log w(z) = \log p(x) for every zz when qq is the posterior. So the Monte Carlo estimate 1S∑s=1Slog⁡w(zs)\frac1S \sum_{s=1}^S \log w(z_s) of the ELBO has zero variance at the posterior, for any number of samples SS.

    The two standard forms #

    Split log⁡p(x,z)\log p(x, z) in two ways. Each split gives a form of the ELBO that is used in practice.

    Form 1: energy + entropy.

    ELBO(q)=Eq[log⁡p(x,z)]+H(q).\mathrm{ELBO}(q) = \mathbb{E}_q[\log p(x, z)] + H(q).

    The first term (the negative energy) pulls qq toward latents with a high joint density, as MAP does. The entropy term pays qq for being spread out. Without it, the best qq would be a point mass at the MAP latent. In the toy at t=0.5t = 0.5: Eq[log⁡p(x,z)]=12(log⁡0.02+log⁡0.18)=−2.813\mathbb{E}_q[\log p(x, z)] = \frac12(\log 0.02 + \log 0.18) = -2.813 and H(q)=log⁡2=0.693H(q) = \log 2 = 0.693. The sum is −2.120-2.120, as in the table.

    Form 2: reconstruction − KL to the prior. Use log⁡p(x,z)=log⁡p(x∣z)+log⁡p(z)\log p(x, z) = \log p(x \mid z) + \log p(z):

    ELBO(q)=Eq[log⁡p(x∣z)]⏟reconstruction−KL(q(z) ∥ p(z))⏟KL to the prior.\mathrm{ELBO}(q) = \underbrace{\mathbb{E}_q[\log p(x \mid z)]}_{\text{reconstruction}} - \underbrace{\mathrm{KL}\big(q(z)\,\|\,p(z)\big)}_{\text{KL to the prior}} .

    The reconstruction term rewards latents that explain xx well. The KL to the prior keeps qq close to the prior: moving qq away from p(z)p(z), so that zz can store information about this particular xx, costs nats. This is the VAE form. Lesson 10 reads it as a trade-off between distortion and rate.

    The three expressions, log⁡p(x)−KL(q ∥ p(z∣x))\log p(x) - \mathrm{KL}(q\,\|\,p(z \mid x)), energy + entropy, and reconstruction − KL, are the same number. Use the one whose terms you can compute.

    A continuous example. Let z∼N(0,1)z \sim \mathcal{N}(0, 1) and x∣z∼N(z,1)x \mid z \sim \mathcal{N}(z, 1), and observe x=2x = 2. Section 4 computes everything by hand: log⁡p(x)=−2.2655\log p(x) = -2.2655 and the posterior is N(1,12)\mathcal{N}(1, \frac12). For q=N(m,s2)q = \mathcal{N}(m, s^2) both forms have closed forms.

    Interactive figure: loading…

    Move the mean and the variance of qq and compare it with the posterior. The posterior lies between the prior (dashed grey, centred at 0) and the likelihood p(x=2∣z)p(x{=}2 \mid z) (thin dark line, centred at 2). The two number lines show the same ELBO in two ways: log⁡p(x)\log p(x) minus the gap, and the reconstruction term minus the KL to the prior. Notice that N(2,12)\mathcal{N}(2, \frac12) has the best reconstruction but pays a large KL to the prior.

    What maximizing the ELBO does #

    Over qq, with the model fixed. log⁡p(x)\log p(x) does not depend on qq. So by Theorem 1,

    arg⁡max⁡qELBO(q)=arg⁡min⁡qKL(q ∥ p(z∣x)).\arg\max_q \mathrm{ELBO}(q) = \arg\min_q \mathrm{KL}\big(q\,\|\,p(z \mid x)\big).

    This is the reverse KL of lesson 06. It is the direction we can work with. It needs only expectations under qq (we can sample from qq) and values of p(x,z)p(x, z); the unknown log⁡p(x)\log p(x) is a constant. The forward KL KL(p(z∣x) ∥ q)\mathrm{KL}(p(z \mid x)\,\|\,q) needs expectations under the posterior, which is the thing we cannot compute. Fitting qq in this way is called variational inference (VI).

    The reverse KL Eq[log⁡(q/p(z∣x))]\mathbb{E}_q[\log(q/p(z \mid x))] is large when qq puts mass where the posterior is small. So qq avoids low-posterior regions. Two consequences:

    • Mode seeking. For a posterior with well-separated modes, a single Gaussian qq locks onto one mode. Each mode gives a local maximum of the ELBO; the starting point decides which one you find.
    • Variances that are too small. Let the posterior be N(μ,Σ)\mathcal{N}(\mu, \Sigma) and let qq be a factorized (mean-field) Gaussian ∏iN(mi,si2)\prod_i \mathcal{N}(m_i, s_i^2). The reverse-KL optimum is m=μm = \mu and si2=1/(Σ−1)iis_i^2 = 1/(\Sigma^{-1})_{ii}. This is the variance of ziz_i given all other coordinates, and it is never larger than the marginal variance Σii\Sigma_{ii}. With unit variances and correlation ρ=0.9\rho = 0.9,
    Σ=(1ρρ1),Σ−1=11−ρ2(1−ρ−ρ1),\Sigma = \begin{pmatrix} 1 & \rho \\ \rho & 1\end{pmatrix}, \qquad \Sigma^{-1} = \frac{1}{1-\rho^2}\begin{pmatrix} 1 & -\rho \\ -\rho & 1\end{pmatrix},

    so (Σ−1)ii=1/(1−ρ2)(\Sigma^{-1})_{ii} = 1/(1 - \rho^2) and si2=1−ρ2=0.19s_i^2 = 1 - \rho^2 = 0.19 instead of 1. (The forward KL would give si2=Σii=1s_i^2 = \Sigma_{ii} = 1.)

    Over the model parameters θ\theta. Write the model as pθp_\theta. Theorem 1 gives

    ELBO(q,θ)=log⁡pθ(x)−KL(q ∥ pθ(z∣x)).\mathrm{ELBO}(q, \theta) = \log p_\theta(x) - \mathrm{KL}\big(q\,\|\,p_\theta(z \mid x)\big).

    A step in θ\theta that raises the ELBO raises the log-likelihood, or moves the model's posterior toward qq, or both. So it is approximate maximum likelihood with a bias: it prefers models whose posteriors are easy to fit with the chosen family. For a dataset, the sum of the per-example ELBOs is a lower bound on the log-likelihood of the data.

    If we set qq to the exact posterior before each θ\theta step, the gap is 0 at the current θ\theta. This is EM (expectation–maximization): the E-step sets q=pθ(z∣x)q = p_{\theta}(z \mid x), the M-step maximizes the ELBO in θ\theta. Then log⁡pθ(x)\log p_\theta(x) never decreases.

    Quick check

    The model p(x,z)p(x, z) is fixed. You maximize the ELBO over a family of distributions qq. Which quantity are you minimizing?

    Amortized inference, two gaps, and posterior collapse #

    A dataset has many observations x1,…,xnx_1, \dots, x_n, and each has its own posterior. Fitting a separate qq for each xx is slow. A VAE uses one network, the encoder, that outputs qϕ(z∣x)q_\phi(z \mid x) for every xx. This is amortized inference: the cost of learning to infer is shared by all xx.

    Let qx∗q^*_x be the best member of the family for this xx (for example, the best diagonal Gaussian). The gap splits in two (Cremer, Li and Duvenaud, 2018):

    log⁡p(x)−ELBO(qϕ)=log⁡p(x)−ELBO(qx∗)⏟approximation gap+ELBO(qx∗)−ELBO(qϕ)⏟amortization gap.\begin{aligned} \log p(x) - \mathrm{ELBO}(q_\phi) &= \underbrace{\log p(x) - \mathrm{ELBO}(q^*_x)}_{\text{approximation gap}} \\ &\quad + \underbrace{\mathrm{ELBO}(q^*_x) - \mathrm{ELBO}(q_\phi)}_{\text{amortization gap}} . \end{aligned}
    • The approximation gap is KL(qx∗ ∥ p(z∣x))\mathrm{KL}(q^*_x\,\|\,p(z \mid x)): the family is too simple.
    • The amortization gap is the price of one shared encoder instead of a separate optimization for each xx.

    A different failure is posterior collapse. The decoder models xx well without using zz. Then the best encoder outputs qϕ(z∣x)=p(z)q_\phi(z \mid x) = p(z) for every xx, and the KL term is 0. The ELBO can still be good, but zz carries no information about xx.

    Posterior collapse can happen at the optimum, not only because of bad training (Lucas et al., 2019). The smallest example is a linear VAE. Data x∼N(0,1)x \sim \mathcal{N}(0, 1). Decoder p(x∣z)=N(az,σ2)p(x \mid z) = \mathcal{N}(a z, \sigma^2) with prior z∼N(0,1)z \sim \mathcal{N}(0, 1). Then the model gives x∼N(0,a2+σ2)x \sim \mathcal{N}(0, a^2 + \sigma^2). Keep σ2\sigma^2 fixed and learn aa: the best fit makes a2+σ2=1a^2 + \sigma^2 = 1 when it can. If the decoder noise σ2\sigma^2 is 1 or more, the noise alone already explains the data, and the best aa is 0.

    Interactive figure: loading…

    Change the decoder noise σ2\sigma^2 and the decoder weight aa. The encoder is always the exact posterior, so the ELBO equals the average log-likelihood. It is the reconstruction term (dark line) minus the KL to the prior. The yellow line marks the best aa. Push σ2\sigma^2 to 1 or above: the best aa becomes 0, the KL term becomes 0, and the latent is unused.

    In this example the decoder noise σ2\sigma^2 acts as a weight. A Gaussian decoder gives log⁡p(x∣z)=−∥x−x^(z)∥22σ2+const\log p(x \mid z) = -\frac{\|x - \hat x(z)\|^2}{2\sigma^2} + \text{const}, so a large σ2\sigma^2 makes the reconstruction term cheap compared with the KL term. Common remedies for collapse in real VAEs are KL annealing (the weight of the KL term grows from 0 to 1 during training) and "free bits" (no KL penalty below a few nats per latent group); see Kingma and Welling (2019), §2.8.

    The VAE loss #

    A VAE has an encoder qϕ(z∣x)q_\phi(z \mid x) and a decoder pθ(x∣z)p_\theta(x \mid z), both neural networks, and a prior p(z)=N(0,I)p(z) = \mathcal{N}(0, I). It maximizes the average ELBO in Form 2 over both ϕ\phi and θ\theta. The generative-models track covers the architecture and training practice. Here are the three pieces of the loss.

    1. Gaussian encoder. The encoder outputs a mean vector μϕ(x)\mu_\phi(x) and a log-variance vector log⁡σϕ2(x)\log \sigma^2_\phi(x), both of length dd (the latent dimension): qϕ(z∣x)=N(μϕ(x),diag⁡(σϕ2(x)))q_\phi(z \mid x) = \mathcal{N}\big(\mu_\phi(x), \operatorname{diag}(\sigma_\phi^2(x))\big).

    2. The KL term in closed form. For one dimension,

    KL(N(μ,σ2) ∥ N(0,1))=12(μ2+σ2−1−log⁡σ2),\mathrm{KL}\big(\mathcal{N}(\mu, \sigma^2)\,\|\,\mathcal{N}(0, 1)\big) = \tfrac12\big(\mu^2 + \sigma^2 - 1 - \log \sigma^2\big),

    and for a diagonal Gaussian the KL is the sum of this over the dd dimensions.

    Derivation of the Gaussian KL to N(0,1)\mathcal{N}(0, 1)
    1. log⁡q(z)=−12log⁡(2πσ2)−(z−μ)22σ2\log q(z) = -\frac12\log(2\pi\sigma^2) - \frac{(z - \mu)^2}{2\sigma^2} and log⁡p(z)=−12log⁡(2π)−z22\log p(z) = -\frac12\log(2\pi) - \frac{z^2}{2}.
    2. Under qq: Eq[(z−μ)2]=σ2\mathbb{E}_q[(z - \mu)^2] = \sigma^2 and Eq[z2]=μ2+σ2\mathbb{E}_q[z^2] = \mu^2 + \sigma^2.
    3. So Eq[log⁡q]=−12log⁡(2πσ2)−12\mathbb{E}_q[\log q] = -\frac12\log(2\pi\sigma^2) - \frac12 and Eq[log⁡p]=−12log⁡(2π)−12(μ2+σ2)\mathbb{E}_q[\log p] = -\frac12\log(2\pi) - \frac12(\mu^2 + \sigma^2).
    4. Subtract: KL=Eq[log⁡q]−Eq[log⁡p]=−12log⁡σ2−12+12(μ2+σ2)\mathrm{KL} = \mathbb{E}_q[\log q] - \mathbb{E}_q[\log p] = -\frac12\log\sigma^2 - \frac12 + \frac12(\mu^2 + \sigma^2). ■\blacksquare

    The KL is 0 only at μ=0\mu = 0, σ2=1\sigma^2 = 1: the function σ2−1−log⁡σ2\sigma^2 - 1 - \log\sigma^2 is ≥0\ge 0 with its minimum at σ2=1\sigma^2 = 1.

    3. The reconstruction term with the reparameterization trick. The term Eqϕ[log⁡pθ(x∣z)]\mathbb{E}_{q_\phi}[\log p_\theta(x \mid z)] has no closed form for a neural decoder, so we estimate it with one (or a few) samples of zz. But we also need its gradient with respect to ϕ\phi, and ϕ\phi is inside the distribution we sample from. The reparameterization trick writes the sample as a deterministic function of ϕ\phi and a fixed noise:

    z=μϕ(x)+σϕ(x)⊙ε,ε∼N(0,I).z = \mu_\phi(x) + \sigma_\phi(x) \odot \varepsilon, \qquad \varepsilon \sim \mathcal{N}(0, I).

    Now ε\varepsilon does not depend on ϕ\phi, and backpropagation goes through zz to μϕ\mu_\phi and σϕ\sigma_\phi. This gradient estimator has much lower variance than the score-function (REINFORCE) estimator (calculus lesson 12).

    What log⁡pθ(x∣z)\log p_\theta(x \mid z) is. It depends on the decoder's output distribution:

    • Bernoulli decoder (binary or [0,1][0, 1] pixels): the decoder outputs logits ℓ\ell, and
    log⁡pθ(x∣z)=∑j[xjlog⁡σ(ℓj)+(1−xj)log⁡(1−σ(ℓj))],\log p_\theta(x \mid z) = \sum_j \big[x_j \log \sigma(\ell_j) + (1 - x_j)\log(1 - \sigma(\ell_j))\big],

    where σ\sigma is the sigmoid. This is minus the binary cross-entropy (lesson 04).

    • Gaussian decoder with a fixed variance σx2\sigma_x^2: log⁡pθ(x∣z)=−∥x−x^∥22σx2−D2log⁡(2πσx2)\log p_\theta(x \mid z) = -\frac{\|x - \hat x\|^2}{2\sigma_x^2} - \frac{D}{2}\log(2\pi\sigma_x^2), where x^\hat x is the decoder output and DD the data dimension. Up to a constant, this is a scaled squared error.

    In PyTorch the loss for a batch is a few lines (the encoder and decoder are any networks):

    import torch
    import torch.nn.functional as F
    
    def vae_loss(x, encoder, decoder):
        mu, logvar = encoder(x)                     # q(z | x) = N(mu, diag(exp(logvar)))
        eps = torch.randn_like(mu)
        z = mu + torch.exp(0.5 * logvar) * eps      # reparameterization
        logits = decoder(z)                         # Bernoulli decoder p(x | z)
        rec = -F.binary_cross_entropy_with_logits(logits, x, reduction="none").sum(dim=1)
        kl = 0.5 * (mu**2 + logvar.exp() - 1 - logvar).sum(dim=1)
        elbo = rec - kl                             # one-sample ELBO estimate per example
        return -elbo.mean()                         # loss = -ELBO, in nats per example
    

    Two details matter. Sum over the data dimensions and the latent dimensions (not a mean), or the two terms get the wrong relative weight. And the loss is in nats per example; divide by Dln⁡2D \ln 2 to report bits per dimension, the usual unit for images.

    Quick check

    The encoder outputs μ=(1,0)\mu = (1, 0) and σ2=(1,1)\sigma^2 = (1, 1) for a 2-D latent. What is the KL term KL(q ∥ N(0,I))\mathrm{KL}(q\,\|\,\mathcal{N}(0, I))?

    Theorem 2 (the importance-weighted bound; Burda, Grosse and Salakhutdinov, 2015) #

    The ELBO is the log of a geometric mean of weights. If we average several weights before taking the log, the average spreads less, and Jensen's inequality loses less. This is the IWAE (importance weighted autoencoder) bound.

    Let q(z)>0q(z) > 0 wherever p(x,z)>0p(x, z) > 0. Draw z1,…,zKz_1, \dots, z_K independently from qq, write wk=w(zk)=p(x,zk)/q(zk)w_k = w(z_k) = p(x, z_k)/q(z_k), and let p^K=1K∑k=1Kwk\hat p_K = \frac1K \sum_{k=1}^K w_k. Define

    LK=E[log⁡p^K]=Ez1,…,zK∼q[log⁡1K∑k=1Kp(x,zk)q(zk)].\mathcal{L}_K = \mathbb{E}\big[\log \hat p_K\big] = \mathbb{E}_{z_1, \dots, z_K \sim q}\Big[\log \frac1K \sum_{k=1}^K \frac{p(x, z_k)}{q(z_k)}\Big].

    Then:

    1. L1=ELBO(q)\mathcal{L}_1 = \mathrm{ELBO}(q);
    2. LK≤LK+1≤log⁡p(x)\mathcal{L}_K \le \mathcal{L}_{K+1} \le \log p(x) for every KK;
    3. if ww is bounded and the ELBO is finite, LK→log⁡p(x)\mathcal{L}_K \to \log p(x) as K→∞K \to \infty.

    (Burda et al. state part 3 with bounded ww only; the finite ELBO is the extra assumption that the short proof below uses.)

    Toy check. In the two-value example with uniform qq, the weights are 0.040.04 and 0.360.36, each with probability 12\frac12. For K=2K = 2: both draws are 0.040.04 with probability 14\frac14, both 0.360.36 with probability 14\frac14, and one of each with probability 12\frac12. So

    L2=14log⁡0.04+14log⁡0.36+12log⁡0.2=−1.865,\mathcal{L}_2 = \tfrac14\log 0.04 + \tfrac14\log 0.36 + \tfrac12\log 0.2 = -1.865 ,

    between L1=−2.120\mathcal{L}_1 = -2.120 and log⁡p(x)=−1.609\log p(x) = -1.609. The gap falls from 0.511 to 0.255.

    Proof of Theorem 2
    1. Part 1. For K=1K = 1, p^1=w1\hat p_1 = w_1, and E[log⁡w1]\mathbb{E}[\log w_1] is the ELBO.
    2. Upper bound. Each weight has mean Eq[w]=∫p(x,z) dz=p(x)\mathbb{E}_q[w] = \int p(x, z)\,dz = p(x). So E[p^K]=p(x)\mathbb{E}[\hat p_K] = p(x): p^K\hat p_K is an unbiased estimate of p(x)p(x). Jensen for the concave log: LK=E[log⁡p^K]≤log⁡E[p^K]=log⁡p(x)\mathcal{L}_K = \mathbb{E}[\log \hat p_K] \le \log \mathbb{E}[\hat p_K] = \log p(x).
    3. Monotonicity, setup. Take K+1K + 1 samples. Let II be a uniformly random subset of {1,…,K+1}\{1, \dots, K + 1\} of size KK, independent of the samples. 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, 1K∑k∈Iwk\frac1K\sum_{k \in I} w_k is an average of KK independent weights, so its expected log is LK\mathcal{L}_K. Hence LK+1≥LK\mathcal{L}_{K+1} \ge \mathcal{L}_K.
    6. Limit. By the strong law of large numbers, p^K→p(x)\hat p_K \to p(x) with probability 1. If w≤Bw \le B, then 1K∑klog⁡wk≤log⁡p^K≤log⁡B\frac1K\sum_k \log w_k \le \log \hat p_K \le \log B (the left inequality is "geometric mean ≤ arithmetic mean"). The left side is an average of independent integrable variables when the ELBO is finite. This sandwich lets the limit move inside the expectation (uniform integrability), so LK→log⁡p(x)\mathcal{L}_K \to \log p(x). ■\blacksquare

    Why the gap shrinks like 1/K1/K. Both the ELBO and LK\mathcal{L}_K have the form E[log⁡(an unbiased estimate of p(x))]\mathbb{E}[\log(\text{an unbiased estimate of } p(x))]. The Jensen gap of the log grows with the spread of the estimate. The average of KK weights has variance Var⁡q(w)/K\operatorname{Var}_q(w)/K. For large KK, a second-order Taylor expansion of log⁡\log around p(x)p(x) (the delta method) gives

    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}.

    So the gap shrinks like 1/K1/K, and it is small when qq makes the weights nearly equal.

    Interactive figure: loading…

    Increase KK and watch two things. Top: the orange histogram of 1000 estimates log⁡p^K\log \hat p_K becomes narrow, and its average (≈ LK\mathcal{L}_K) moves up toward the dashed ceiling log⁡p(x)\log p(x). Some single estimates land above the ceiling. Bottom: the gap against KK on log-log axes approaches the dashed 1/K1/K line. Change the proposal qq: the gap is 0 for every KK when qq is the posterior N(1,12)\mathcal{N}(1, \frac12).

    The price.

    • Compute. KK times the work per example.
    • High dimensions. Importance weights degrade when zz has many dimensions: one weight tends to dominate the sum.
    • Training signal. A tighter bound is not always better for training. Average MM independent estimates of the gradient of LK\mathcal{L}_K. The signal-to-noise ratio of the encoder's gradient is of order M/K\sqrt{M/K}, while the decoder's is of order MK\sqrt{MK} (Rainforth et al., 2018). So a large KK helps the decoder and hurts the encoder.
    • Evaluation. For evaluation, a large KK is standard: Burda et al. report test log-likelihoods with K=5000K = 5000.
    Another view: IWAE is an ELBO with a richer approximation

    Draw KK samples from qq and keep one of them with probability proportional to its weight. The kept sample has an implicit distribution qEWq_{\mathrm{EW}}, which is closer to the posterior than qq. One can show ELBO(q)≤LK≤ELBO(qEW)≤log⁡p(x)\mathrm{ELBO}(q) \le \mathcal{L}_K \le \mathrm{ELBO}(q_{\mathrm{EW}}) \le \log p(x) (Cremer, Morris and Duvenaud, 2017; Kingma and Welling, 2019, §2.6). So IWAE does not change the model; it fits a better approximate posterior that is built from KK samples of the simple one.

    Quick check

    For a fixed qq you compute L1\mathcal{L}_1, L10\mathcal{L}_{10} and L100\mathcal{L}_{100} exactly (not by sampling). Which ordering is guaranteed?

    Answers to section 1. (1) The maximum over all qq is log⁡p(x)\log p(x), reached only by the posterior q=p(z∣x)q = p(z \mid x), where the KL gap is 0 (Theorem 1). (2) Tighter, or equal: L10≥L1\mathcal{L}_{10} \ge \mathcal{L}_1. And LK≤log⁡p(x)\mathcal{L}_K \le \log p(x) always, as an expectation (Theorem 2). A single estimate can land above log⁡p(x)\log p(x) by noise. (3) On one mode, with a variance that is too small for the whole posterior: the reverse KL is mode seeking. (If the modes overlap strongly, qq can sit between them.)

    4. Worked example #

    Model. z∼N(0,1)z \sim \mathcal{N}(0, 1), x∣z∼N(z,1)x \mid z \sim \mathcal{N}(z, 1), observed x=2x = 2. Everything is in closed form, so every claim can be checked.

    (a) Exact answers. x=z+noisex = z + \text{noise} with independent unit-variance noise, so x∼N(0,2)x \sim \mathcal{N}(0, 2) and

    log⁡p(2)=−12log⁡(2π⋅2)−222⋅2=−1.2655−1=−2.2655.\log p(2) = -\tfrac12\log(2\pi \cdot 2) - \frac{2^2}{2 \cdot 2} = -1.2655 - 1 = -2.2655 .

    Posterior: p(z∣x)∝exp⁡(−z22−(x−z)22)p(z \mid x) \propto \exp\big(-\frac{z^2}{2} - \frac{(x - z)^2}{2}\big). The exponent is a quadratic in zz with coefficient −12⋅2-\frac12 \cdot 2 on z2z^2, so the precision is 1+1=21 + 1 = 2. The linear coefficient is xx, so the mean is x/2=1x/2 = 1. Hence p(z∣x)=N(1,12)p(z \mid x) = \mathcal{N}(1, \frac12).

    (b) The ELBO for q=N(m,s2)q = \mathcal{N}(m, s^2), in the reconstruction − KL form:

    • Reconstruction: log⁡p(x∣z)=−12log⁡2π−12(x−z)2\log p(x \mid z) = -\frac12\log 2\pi - \frac12(x - z)^2, and Eq[(x−z)2]=(x−m)2+s2\mathbb{E}_q[(x - z)^2] = (x - m)^2 + s^2 (squared bias plus variance). So
    Eq[log⁡p(x∣z)]=−12log⁡2π−12((x−m)2+s2).\mathbb{E}_q[\log p(x \mid z)] = -\tfrac12\log 2\pi - \tfrac12\big((x - m)^2 + s^2\big).
    • KL to the prior (the VAE formula above):
    KL(N(m,s2) ∥ N(0,1))=12(m2+s2−1−log⁡s2).\mathrm{KL}(\mathcal{N}(m, s^2)\,\|\,\mathcal{N}(0, 1)) = \tfrac12(m^2 + s^2 - 1 - \log s^2).
    qq reconstruction KL to prior ELBO log⁡p(x)−ELBO\log p(x) - \mathrm{ELBO} KL(q ∥ N(1,12))\mathrm{KL}(q\,\|\,\mathcal{N}(1, \frac12))
    N(1,1)\mathcal{N}(1, 1) −1.9189 0.5000 −2.4189 0.1534 0.1534
    N(2,12)\mathcal{N}(2, \frac12) −1.1689 2.0966 −3.2655 1.0000 1.0000
    N(1,12)\mathcal{N}(1, \frac12) −1.6689 0.5966 −2.2655 0 0

    Read the rows step by step.

    • N(2,12)\mathcal{N}(2, \frac12) explains the data best (the highest reconstruction term), but pays 2.10 nats to move away from the prior.
    • N(1,1)\mathcal{N}(1, 1) has the right mean but is too wide.
    • The last column is computed separately, with the Gaussian KL formula of lesson 06:
    KL(N(m,s2) ∥ N(1,12))=12(log⁡1/2s2+s2+(m−1)21/2−1).\mathrm{KL}\big(\mathcal{N}(m, s^2)\,\|\,\mathcal{N}(1, \tfrac12)\big) = \tfrac12\Big(\log\frac{1/2}{s^2} + \frac{s^2 + (m - 1)^2}{1/2} - 1\Big).

    It equals the gap in every row, as Theorem 1 says. For N(2,12)\mathcal{N}(2, \frac12): 12(0+0.5+10.5−1)=12(3−1)=1\frac12(0 + \frac{0.5 + 1}{0.5} - 1) = \frac12(3 - 1) = 1 exactly.

    • Check of Form 1 for N(1,1)\mathcal{N}(1, 1): Eq[log⁡p(x,z)]=−3.8379\mathbb{E}_q[\log p(x, z)] = -3.8379 and H(q)=12log⁡(2πe)=1.4189H(q) = \frac12\log(2\pi e) = 1.4189. The sum is −2.4189-2.4189. ✓

    (c) Maximize over qq. Write the ELBO as a function of mm and s2s^2:

    ELBO(m,s2)=−12log⁡2π−12(2−m)2−12s2−12(m2+s2−1−log⁡s2).\mathrm{ELBO}(m, s^2) = -\tfrac12\log 2\pi - \tfrac12(2 - m)^2 - \tfrac12 s^2 - \tfrac12\big(m^2 + s^2 - 1 - \log s^2\big).
    • ∂/∂m\partial/\partial m: (2−m)−m=0(2 - m) - m = 0, so m=1m = 1.
    • ∂/∂s2\partial/\partial s^2: −12−12+12s2=0-\frac12 - \frac12 + \frac{1}{2s^2} = 0, so s2=12s^2 = \frac12.

    The optimum is exactly the posterior. The Gaussian family contains it, so the approximation gap is 0 and the bound is tight.

    (d) IWAE for q=N(2,12)q = \mathcal{N}(2, \frac12). Both qq and the posterior have variance 12\frac12, so the normalizing constants cancel and

    log⁡w(z)=log⁡p(x)+log⁡p(z∣x)−log⁡q(z)=log⁡p(x)+(z−2)2−(z−1)2=log⁡p(x)+3−2z.\begin{aligned} \log w(z) &= \log p(x) + \log p(z \mid x) - \log q(z) \\ &= \log p(x) + (z - 2)^2 - (z - 1)^2 \\ &= \log p(x) + 3 - 2z . \end{aligned}

    Under qq, z∼N(2,12)z \sim \mathcal{N}(2, \frac12), so 3−2z∼N(3−4, 4⋅12)=N(−1,2)3 - 2z \sim \mathcal{N}(3 - 4,\ 4 \cdot \frac12) = \mathcal{N}(-1, 2). So log⁡w−log⁡p(x)\log w - \log p(x) is Gaussian with mean −1-1 and variance 2. The ELBO gap is −E[log⁡w−log⁡p(x)]=1-\mathbb{E}[\log w - \log p(x)] = 1, as in the table. Section 5 estimates the IWAE gaps by sampling:

    KK 1 10 100
    log⁡p(x)−LK\log p(x) - \mathcal{L}_K 1.00 0.19 0.03

    Compare with the large-KK formula. Here w/p(x)=eYw/p(x) = e^{Y} with Y∼N(−1,2)Y \sim \mathcal{N}(-1, 2), and E[e2Y]=e2(−1)+12⋅4⋅2=e2\mathbb{E}[e^{2Y}] = e^{2(-1) + \frac12 \cdot 4 \cdot 2} = e^{2} (the mean of a log-normal variable), so

    Var⁡q(w)p(x)2=E[e2Y]−(E[eY])2=e2−1=6.39.\frac{\operatorname{Var}_q(w)}{p(x)^2} = \mathbb{E}[e^{2Y}] - \big(\mathbb{E}[e^{Y}]\big)^2 = e^2 - 1 = 6.39 .

    Here E[eY]=e−1+12⋅2=1\mathbb{E}[e^{Y}] = e^{-1 + \frac12 \cdot 2} = 1, as it must be, because Eq[w]=p(x)\mathbb{E}_q[w] = p(x). The formula gives 6.39/(2K)=0.0326.39/(2K) = 0.032 at K=100K = 100 (close to 0.028) and 0.320.32 at K=10K = 10 (too large: K=10K = 10 is not yet "large").

    5. In code #

    NumPy and SciPy check the numbers of section 4 by other routes: numerical integration for the ELBO, the law of the log-weights for IWAE, and a numerical optimizer for the mean-field example. The notebook has these cells and the exercises.

    import numpy as np
    from scipy.stats import norm
    from scipy.special import logsumexp
    from scipy.optimize import minimize
    
    # Model: z ~ N(0, 1), x | z ~ N(z, 1). Observed x = 2, so x ~ N(0, 2) and p(z | x) = N(1, 1/2).
    x = 2.0
    log_px = norm(0, np.sqrt(2)).logpdf(x)
    print(round(log_px, 4))                                  # -2.2655
    
    def kl_gauss(m1, v1, m2, v2):                            # KL(N(m1, v1) || N(m2, v2)), 1-D
        return 0.5 * (np.log(v2 / v1) + (v1 + (m1 - m2) ** 2) / v2 - 1)
    
    # (a) ELBO by numerical integration on a grid; the gap equals KL(q || posterior).
    z = np.linspace(-10, 12, 200_001)
    log_joint = norm(0, 1).logpdf(z) + norm(z, 1).logpdf(x)  # log p(z) + log p(x | z)
    for m, s2 in [(1.0, 1.0), (2.0, 0.5), (1.0, 0.5)]:
        q = norm(m, np.sqrt(s2))
        elbo = np.trapezoid(q.pdf(z) * (log_joint - q.logpdf(z)), z)
        print(m, s2, round(elbo, 4), round(log_px - elbo, 4), round(kl_gauss(m, s2, 1.0, 0.5), 4))
    # 1.0 1.0 -2.4189 0.1534 0.1534
    # 2.0 0.5 -3.2655 1.0 1.0
    # 1.0 0.5 -2.2655 0.0 0.0
    
    # (b) IWAE gap for q = N(2, 1/2): log w - log p(x) = 3 - 2z ~ N(-1, 2) under q.
    #     Never average the weights directly: use logsumexp(log w) - log K.
    rng = np.random.default_rng(1)
    for K, n in [(1, 1_000_000), (10, 200_000), (100, 40_000)]:
        Y = rng.normal(-1.0, np.sqrt(2.0), size=(n, K))
        print(K, round(-np.mean(logsumexp(Y, axis=1) - np.log(K)), 2))
    # 1 1.0
    # 10 0.19
    # 100 0.03
    
    # (c) Reverse KL with a factorized q underestimates the marginal variances.
    rho = 0.9
    S = np.array([[1.0, rho], [rho, 1.0]])
    P = np.linalg.inv(S)
    def reverse_kl(log_var):                                 # KL(N(0, diag) || N(0, S))
        D = np.diag(np.exp(log_var))
        return 0.5 * (np.trace(P @ D) - 2 + np.log(np.linalg.det(S) / np.linalg.det(D)))
    res = minimize(reverse_kl, x0=np.zeros(2), method="Nelder-Mead", options={"xatol": 1e-8, "fatol": 1e-12})
    print(np.exp(res.x).round(3))      # [0.19 0.19] = 1 - rho^2; the true marginal variances are 1
    

    The grid integral in (a) is a route that does not use the closed forms of section 4. In (b) the log of an average of weights must be computed in log space: the weights themselves overflow or underflow for real models.

    6. Where it shows up #

    • VAEs. The loss is −ELBO-\mathrm{ELBO} with an encoder qϕ(z∣x)q_\phi(z \mid x) and a decoder pθ(x∣z)p_\theta(x \mid z), trained jointly by stochastic gradients with the reparameterization trick. The IWAE objective replaces L1\mathcal{L}_1 by LK\mathcal{L}_K. The generative-models track covers architectures, β-VAEs and VQ-VAEs.
    • Diffusion models. The DDPM loss is a reweighted ELBO in which the "encoder" is the fixed noising process (generative models track). The first stage of latent diffusion (Stable Diffusion) is an autoencoder trained with a reconstruction loss (plus perceptual and adversarial terms) and a very small KL-to-prior penalty: Form 2 with a strongly down-weighted KL term.
    • EM and variational Bayes. EM is coordinate ascent on the ELBO with an exact E-step. Variational Bayesian neural networks ("Bayes by Backprop") put a Gaussian qq on the weights and maximize the ELBO; the KL to the prior acts as a regularizer.
    • Topic models and probabilistic programming. Latent Dirichlet allocation was fitted with mean-field VI. Pyro and NumPyro fit user-written models by stochastic VI ("SVI") on the ELBO.
    • ML for science: inverse problems. Variational inference gives approximate posteriors for seismic tomography at a fraction of the cost of Monte Carlo sampling (Zhang and Curtis, 2020). The mean-field result of section 3 is the warning: a factorized qq reports too little uncertainty when the parameters are correlated, as neighbouring velocity cells are.
    • ML for science: single-cell biology. scVI (Lopez et al., 2018) is a VAE for single-cell RNA counts; its latent space is used for clustering, batch correction and differential expression.
    • Simulation-based inference: the other KL. If you can simulate pairs (z,x)(z, x) from the model, you can train qϕ(z∣x)q_\phi(z \mid x) by maximizing Ep(z,x)[log⁡qϕ(z∣x)]\mathbb{E}_{p(z, x)}[\log q_\phi(z \mid x)] (neural posterior estimation). This minimizes the forward KL from the posterior, averaged over xx, so qϕq_\phi tends to cover all modes.

    7. Common mistakes #

    • Reading the ELBO as log⁡p(x)\log p(x). It is log⁡p(x)\log p(x) minus a gap. A model can win on the ELBO by having a smaller gap, not a higher likelihood. Compare models with LK\mathcal{L}_K for a large KK.
    • The wrong KL direction. Maximizing the ELBO minimizes KL(q ∥ p(z∣x))\mathrm{KL}(q\,\|\,p(z \mid x)), not KL(p(z∣x) ∥ q)\mathrm{KL}(p(z \mid x)\,\|\,q). This is why VI underestimates uncertainty.
    • Confusing the two KL terms. The gap is the KL to the posterior. The term inside Form 2 is the KL to the prior. Making the KL to the prior small does not make the bound tight.
    • Dropping the entropy term. Without H(q)H(q) (or the −log⁡q-\log q part of a Monte Carlo estimate), the optimum collapses to a point mass at the MAP latent.
    • Mean instead of sum in the VAE loss. Averaging the reconstruction over pixels but summing the KL over latents changes the weight of the two terms (like a large β). The ELBO sums both.
    • "Larger KK is always better." The bound is tighter, but the cost grows like KK and the encoder's gradient becomes noisier.
    • Treating one estimate as a guaranteed bound. LK≤log⁡p(x)\mathcal{L}_K \le \log p(x) holds in expectation; a single Monte Carlo estimate can land above log⁡p(x)\log p(x).

    8. Check yourself #

    1. Two latent values with p(x,z=0)=0.1p(x, z{=}0) = 0.1 and p(x,z=1)=0.3p(x, z{=}1) = 0.3, and qq uniform. Compute log⁡p(x)\log p(x), the ELBO, the gap and KL(q ∥ p(z∣x))\mathrm{KL}(q\,\|\,p(z \mid x)).
      Answerp(x)=0.4p(x) = 0.4, so log⁡p(x)=−0.916\log p(x) = -0.916. The weights are w=(0.1/0.5, 0.3/0.5)=(0.2,0.6)w = (0.1/0.5,\ 0.3/0.5) = (0.2, 0.6), so ELBO =12(log⁡0.2+log⁡0.6)=12log⁡0.12=−1.060= \frac12(\log 0.2 + \log 0.6) = \frac12\log 0.12 = -1.060. Gap =−0.916+1.060=0.144= -0.916 + 1.060 = 0.144. The posterior is (0.25,0.75)(0.25, 0.75), so KL=12log⁡0.50.25+12log⁡0.50.75=12log⁡43=0.144\mathrm{KL} = \frac12\log\frac{0.5}{0.25} + \frac12\log\frac{0.5}{0.75} = \frac12\log\frac43 = 0.144. ✓
    2. Why does variational inference minimize KL(q ∥ p(z∣x))\mathrm{KL}(q\,\|\,p(z \mid x)) and not KL(p(z∣x) ∥ q)\mathrm{KL}(p(z \mid x)\,\|\,q)?
      AnswerThe reverse KL needs only expectations under qq (which we can sample) and values of log⁡p(x,z)\log p(x, z). The unknown log⁡p(x)\log p(x) is a constant, so maximizing the ELBO minimizes the reverse KL. The forward KL needs expectations under the posterior, which we cannot compute or sample.
    3. In the worked example, restrict qq to the family N(m,1)\mathcal{N}(m, 1). What is the best mm, and what is the remaining gap called?
      Answer∂/∂m\partial/\partial m: (2−m)−m=0(2 - m) - m = 0, so m=1m = 1. ELBO =−2.4189= -2.4189, gap =0.1534=KL(N(1,1) ∥ N(1,12))= 0.1534 = \mathrm{KL}(\mathcal{N}(1, 1)\,\|\,\mathcal{N}(1, \frac12)). It is the approximation gap of this family: no member does better.
    4. The posterior is a 2-D Gaussian with unit variances and correlation ρ=0.5\rho = 0.5. What variances does a mean-field qq get from the reverse KL? From the forward KL?
      AnswerReverse KL: 1/(Σ−1)ii=1−ρ2=0.751/(\Sigma^{-1})_{ii} = 1 - \rho^2 = 0.75. Forward KL: the marginal variances, 1.
    5. If qq is the exact posterior, what is LK\mathcal{L}_K for each KK, and what is the variance of its Monte Carlo estimate?
      AnswerEvery weight equals p(x)p(x), so log⁡p^K=log⁡p(x)\log \hat p_K = \log p(x) for every draw. Hence LK=log⁡p(x)\mathcal{L}_K = \log p(x) for all KK, and the estimate has zero variance.
    6. A VAE has a 3-D latent. For every input xx the encoder outputs μ=(0,0,0)\mu = (0, 0, 0) and σ2=(1,1,1)\sigma^2 = (1, 1, 1). What is the KL term, and what does this tell you about the model?
      AnswerThe KL term is 00: qϕ(z∣x)=N(0,I)=p(z)q_\phi(z \mid x) = \mathcal{N}(0, I) = p(z). Since this holds for every xx, the encoder ignores the input and zz carries no information about xx. This is posterior collapse: the decoder models xx without zz.
    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. Write the evidence decomposition for a latent-variable model.

    2. Derive the ELBO with Jensen's inequality in one line.

    3. Write the ELBO as reconstruction minus a KL. Which KL is it?

    4. Write the ELBO as energy plus entropy.

    5. Maximizing the ELBO over qq minimizes which divergence, and what follows?

    6. Give KL(N(μ,σ2) ∥ N(0,1))\mathrm{KL}(\mathcal{N}(\mu, \sigma^2)\,\|\,\mathcal{N}(0, 1)).

    7. What is the reparameterization trick, and why is it used?

    8. Define the IWAE bound LK\mathcal{L}_K.

    9. How does the IWAE gap log⁡p(x)−LK\log p(x) - \mathcal{L}_K behave for large KK?

    10. What are the approximation gap and the amortization gap?

    Open the review →

    9. Interview angle #

    • "Derive the ELBO." — Two ways: insert q(z)/q(z)q(z)/q(z) into log⁡p(x,z)p(z∣x)\log\frac{p(x, z)}{p(z \mid x)} to get ELBO + KL (this also gives the gap); or Jensen on log⁡Eq[p(x,z)/q(z)]\log \mathbb{E}_q[p(x, z)/q(z)].
    • "What does each term of the VAE loss do?" — The reconstruction term rewards latents that explain xx. The KL to the prior limits the information in zz and keeps qq close to the prior, so that samples from the prior decode to realistic data.
    • "Why can't we just maximize log⁡p(x)\log p(x)?" — It needs ∫p(x∣z) p(z) dz\int p(x \mid z)\,p(z)\,dz, which has no closed form for a neural decoder, and naive Monte Carlo with samples from the prior has a huge variance.
    • "Why is VI mode seeking? Why does it underestimate variance?" — The reverse KL punishes qq for mass where the posterior is small. A mean-field Gaussian gets the conditional variances 1/(Σ−1)ii1/(\Sigma^{-1})_{ii}.
    • "Why the reparameterization trick?" — To backpropagate through sampling: z=μ+σεz = \mu + \sigma\varepsilon moves the randomness into ε\varepsilon, which does not depend on the parameters.
    • "Why is IWAE tighter, and why not train with K=1000K = 1000?" — The average of KK weights spreads less, so the Jensen gap shrinks like 1/K1/K. But the cost is KK times larger, and the encoder's gradient signal-to-noise ratio falls like 1/K1/\sqrt{K}.
    • "What is posterior collapse? How do you detect and reduce it?" — The KL term goes to 0 and the encoder outputs the prior for every xx. Watch the KL per latent dimension; use KL annealing, free bits, or a weaker decoder.

    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 ELBO of the two-value example as a function of tt; check that the gap equals the KL to the posterior.
    2. The closed-form ELBO of the linear-Gaussian model against a Monte Carlo estimate with reparameterized samples.
    3. iwae_bound with logsumexp, for K=1,10,100K = 1, 10, 100, and the 1/K1/K behaviour of the gap.
    4. Fit q=N(m,s2)q = \mathcal{N}(m, s^2) by gradient ascent on the ELBO with reparameterization gradients, and recover the exact posterior N(1,12)\mathcal{N}(1, \frac12).
    5. A mean-field qq for a correlated 2-D Gaussian posterior: the variances 1−ρ21 - \rho^2 of section 3.

    11. Watch and read #

    A step-by-step derivation of the ELBO and its KL gap, as in Theorem 1.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The ELBO under the fixed log-evidence, with an interactive plot like the figures of section 2.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The VAE architecture, the reparameterization trick and β-VAEs.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A full university lecture: evidence lower bounds, mean-field factorization, and VI for a Gaussian mixture.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play