Simple Algorithm
Artificial Intelligence · Deep Layer · 30 min

Variational Autoencoders & the ELBO

Latent variables and variational inference.

The ELBO is one inequality, log⁡pθ(x)≥Eq[log⁡pθ(x,z)−log⁡q(z)]\log p_\theta(\mathbf x)\ge\E_q[\log p_\theta(\mathbf x,\mathbf z)-\log q(\mathbf z)]. Behind it hide two different gaps, two competing gradient estimators, a family of ever tighter bounds, and a theorem saying that the bound is maximized by a model that ignores its latent code. This lesson makes each of them precise.

What you’ll learn

  • Split the gap between log⁡pθ(x)\log p_\theta(\mathbf x) and an amortized ELBO into approximation and amortization gaps.
  • Prove that the reparameterization and score-function estimators are unbiased, compare their variances, and prove that the importance-weighted bound tightens monotonically.
  • Derive the rate–distortion decomposition −ELBO=D+R-\mathrm{ELBO}=D+R with H−D≤Iq(X;Z)≤RH-D\le I_q(X;Z)\le R, and prove that posterior collapse is optimal for expressive decoders.
  • Place the β\beta-VAE, free bits, VQ-VAE and hierarchical VAEs in this picture.

Amortized inference and its two gaps

log⁡pθ(x)−ELBO(θ,qϕ;x)=[log⁡pθ(x)−sup⁡q∈QELBO(θ,q;x)]⏟approximation gap+[sup⁡q∈QELBO(θ,q;x)−ELBO(θ,qϕ(⋅∣x);x)]⏟amortization gap\log p_\theta(\mathbf x)-\mathrm{ELBO}\big(\theta,q_\phi;\mathbf x\big)=\underbrace{\Big[\log p_\theta(\mathbf x)-\sup_{q\in\mathcal Q}\mathrm{ELBO}(\theta,q;\mathbf x)\Big]}_{\text{approximation gap}}+\underbrace{\Big[\sup_{q\in\mathcal Q}\mathrm{ELBO}(\theta,q;\mathbf x)-\mathrm{ELBO}\big(\theta,q_\phi(\cdot\mid\mathbf x);\mathbf x\big)\Big]}_{\text{amortization gap}}
The first gap is what the best member of Q\mathcal Q misses, inf⁡q∈QDKL(q ∥ pθ(⋅∣x))\inf_{q\in\mathcal Q}\KL\big(q\,\|\,p_\theta(\cdot\mid\mathbf x)\big). The second is what one shared encoder loses relative to optimizing qq separately for each x\mathbf x.

Cremer, Li & Duvenaud (2018) measured both gaps and found that suboptimal inference was often due more to the encoder than to the Gaussian family. They also observed a subtler effect: because the objective subtracts DKL(q ∥ pθ(⋅∣x))\KL\big(q\,\|\,p_\theta(\cdot\mid\mathbf x)\big), training pushes the decoder toward models whose true posteriors are easy to approximate. The ELBO does not just evaluate a model; it shapes it.

Each gap has its own remedies. Richer families such as normalizing-flow posteriors (Rezende & Mohamed, 2015) attack the approximation gap. Iterative refinement, a few steps of per-example gradient ascent started from the encoder's output (semi-amortized VAEs), attacks the amortization gap.

Check your understanding

At test time you keep a trained diagonal-Gaussian encoder, but for each x\mathbf x you run 50 steps of gradient ascent on the ELBO over that x\mathbf x's Gaussian parameters, starting from the encoder's output. Which gap can this reduce?

  1. Only the approximation gap
  2. Only the amortization gap
  3. Both gaps
  4. Neither: the ELBO cannot be improved after training
Show the answer

B. Only the amortization gap

The family stays diagonal Gaussian, so the best achievable ELBO, sup⁡q∈QELBO\sup_{q\in\mathcal Q}\mathrm{ELBO}, is unchanged, and so is the approximation gap. Per-example optimization only moves qq toward that supremum, shrinking the amortization gap.

Gradient estimators and tighter bounds

DerivationProof
  1. Eqϕ[f(z)]=Er[f(gϕ(ε))]\E_{q_\phi}[f(\mathbf z)]=\E_{r}\big[f(g_\phi(\boldsymbol\varepsilon))\big]

    (a) The law of the unconscious statistician rewrites the expectation over a fixed distribution:

  2. ∂ϕiEr[h(ϕ,ε)]=lim⁡s→0Er[h(ϕ+sei,ε)−h(ϕ,ε)s]=Er[∂ϕih(ϕ,ε)]\partial_{\phi_i}\E_r[h(\phi,\boldsymbol\varepsilon)]=\lim_{s\to0}\E_r\Big[\tfrac{h(\phi+s\mathbf e_i,\boldsymbol\varepsilon)-h(\phi,\boldsymbol\varepsilon)}{s}\Big]=\E_r\big[\partial_{\phi_i}h(\phi,\boldsymbol\varepsilon)\big]

    By the mean value theorem, each difference quotient of h(ϕ,ε)=f(gϕ(ε))h(\phi,\boldsymbol\varepsilon)=f(g_\phi(\boldsymbol\varepsilon)) in a coordinate direction is bounded by G(ε)G(\boldsymbol\varepsilon), so dominated convergence moves the limit inside:

  3. ∇ϕ∫qϕ(z)f(z) dz=∫f(z) ∇ϕqϕ(z) dz=Eqϕ[f(z)∇ϕlog⁡qϕ(z)]■\nabla_\phi\int q_\phi(\mathbf z)f(\mathbf z)\,d\mathbf z=\int f(\mathbf z)\,\nabla_\phi q_\phi(\mathbf z)\,d\mathbf z=\E_{q_\phi}\big[f(\mathbf z)\nabla_\phi\log q_\phi(\mathbf z)\big]\qquad\blacksquare

    (b) Differentiate the density instead of the integrand, and use ∇q=q ∇log⁡q\nabla q=q\,\nabla\log q:

Estimator (b) is fully general (discrete z\mathbf z, black-box ff) but uses only values of ff, so its variance grows with f2f^2; it needs baselines and control variates in practice, as in policy gradients. Estimator (a) uses the slope of ff. For discrete latents, continuous relaxations such as the Gumbel-softmax (Concrete) distribution and straight-through estimators trade a little bias for estimator (a)'s low variance.

Predict before you look

Take qμ=N(μ,1)q_\mu=\mathcal N(\mu,1) and f(z)=zf(z)=z, so ∇μE[f]=1\nabla_\mu\E[f]=1. The reparameterization estimator is exactly 11 (variance 00). What is the variance of the single-sample score-function estimator f(z) (z−μ)f(z)\,(z-\mu) at μ=3\mu=3?

Show the answer

11

With z=μ+εz=\mu+\varepsilon the estimator is με+ε2\mu\varepsilon+\varepsilon^2, with mean 11 and second moment μ2Eε2+2μEε3+Eε4=μ2+3\mu^2\E\varepsilon^2+2\mu\E\varepsilon^3+\E\varepsilon^4=\mu^2+3. The variance is μ2+2=11\mu^2+2=11, and it grows without bound as the mean moves away from 00. A baseline bb, giving (f(z)−b)(z−μ)(f(z)-b)(z-\mu), removes most of it.

DerivationProof of the bound and its monotonicity
  1. LK≤log⁡E[1K∑kwk]=log⁡pθ(x)\mathcal L_K\le\log\E\Big[\tfrac1K\textstyle\sum_kw_k\Big]=\log p_\theta(\mathbf x)

    Each weight has mean Eq[wk]=∫pθ(x,z) dz=pθ(x)\E_q[w_k]=\int p_\theta(\mathbf x,\mathbf z)\,d\mathbf z=p_\theta(\mathbf x). Jensen's inequality for the concave log gives the upper bound:

  2. 1K∑k=1Kwk=EI[1m∑k∈Iwk]\frac1K\sum_{k=1}^Kw_k=\E_I\Big[\frac1m\sum_{k\in I}w_k\Big]

    For m<Km<K, let II be a uniformly random mm-subset of {1,…,K}\{1,\dots,K\}. Each index lands in II with probability m/Km/K, so the full average is an average over subsets:

  3. LK=E log⁡EI[1m∑k∈Iwk] ≥ E EIlog⁡[1m∑k∈Iwk]=Lm\mathcal L_K=\E\,\log\E_I\Big[\tfrac1m\textstyle\sum_{k\in I}w_k\Big]\ \ge\ \E\,\E_I\log\Big[\tfrac1m\textstyle\sum_{k\in I}w_k\Big]=\mathcal L_m

    Apply Jensen again, this time to EI\E_I, then take expectations over the samples. Every subset average has the law of an mm-sample average:

  4. Elog⁡p^K≈log⁡pθ(x)−Var⁡[p^K]2pθ(x)2=log⁡pθ(x)−Var⁡q[w]2K pθ(x)2\E\log\hat p_K\approx\log p_\theta(\mathbf x)-\frac{\Var[\hat p_K]}{2p_\theta(\mathbf x)^2}=\log p_\theta(\mathbf x)-\frac{\Var_q[w]}{2K\,p_\theta(\mathbf x)^2}

    For the limit, the strong law gives 1K∑kwk→pθ(x)\frac1K\sum_kw_k\to p_\theta(\mathbf x) almost surely, and bounded convergence passes the log and the expectation through. The rate comes from a second-order Taylor expansion of log⁡\log around pθ(x)p_\theta(\mathbf x), using Var⁡q[w]/pθ(x)2=χ2(pθ(⋅∣x) ∥ q)\Var_q[w]/p_\theta(\mathbf x)^2=\chi^2\big(p_\theta(\cdot\mid\mathbf x)\,\|\,q\big).

A tighter bound is not automatically a better training signal. Rainforth et al. (2018) showed that the signal-to-noise ratio of the IWAE gradient decays like O(1/K)\order{1/\sqrt K} for the encoder's parameters while it grows like O(K)\order{\sqrt K} for the decoder's, so large KK improves the model but starves the encoder. Doubly reparameterized estimators (Tucker et al., 2019) repair the encoder's gradient.

Rate, distortion and posterior collapse

DerivationBounds on the information in the code
  1. R=Eq(x,z)[log⁡qϕ(z∣x)q(z)+log⁡q(z)p(z)]=Iq(X;Z)+DKL(q(z) ∥ p(z)) ≥ Iq(X;Z)R=\E_{q(\mathbf x,\mathbf z)}\Big[\log\frac{q_\phi(\mathbf z\mid\mathbf x)}{q(\mathbf z)}+\log\frac{q(\mathbf z)}{p(\mathbf z)}\Big]=I_q(X;Z)+\KL\big(q(\mathbf z)\,\|\,p(\mathbf z)\big)\ \ge\ I_q(X;Z)

    Insert q(z)q(\mathbf z) into the rate ("ELBO surgery", Hoffman & Johnson, 2016):

  2. Iq(X;Z)=H−Hq(X∣Z) ≥ H−Eq[−log⁡pθ(x∣z)]=H−DI_q(X;Z)=H-H_q(X\mid Z)\ \ge\ H-\E_q\big[-\log p_\theta(\mathbf x\mid\mathbf z)\big]=H-D

    The decoder gives the matching lower bound, since a conditional entropy is at most the cross-entropy of any model of the same conditional (Gibbs' inequality):

  3. H−D ≤ Iq(X;Z) ≤ R,D+R ≥ HH-D\ \le\ I_q(X;Z)\ \le\ R,\qquad D+R\ \ge\ H

    And the ELBO never exceeds Elog⁡pθ(x)≤Elog⁡pdata(x)=−H\E\log p_\theta(\mathbf x)\le\E\log p_{\text{data}}(\mathbf x)=-H. Together (Alemi et al., 2018):

Every model on the line D+R=HD+R=H, from (R,D)=(0,H)(R,D)=(0,H) to (H,0)(H,0), has the same, optimal, ELBO, and there the two bounds pinch: Iq=RI_q=R. At one end the code carries no information about x\mathbf x; at the other it carries all of it and reconstruction is perfect. The objective cannot tell them apart. Where a trained model lands depends on the model class and on optimization.

To move a model off the R=0R=0 end, change the objective or the model class. The β\beta-VAE (Higgins et al., 2017) maximizes Eqlog⁡pθ(x∣z)−β DKL\E_q\log p_\theta(\mathbf x\mid\mathbf z)-\beta\,\KL: β<1\beta<1 buys rate, β>1\beta>1 penalizes it, and sweeping β\beta traces the rate–distortion curve of the model family. With a Gaussian decoder of fixed variance σ2\sigma^2, β\beta is a noise level in disguise:

−E∥x−μθ(z)∥22σ2−β DKL=β(−E∥x−μθ(z)∥22βσ2−DKL)-\frac{\E\norm{\mathbf x-\boldsymbol\mu_\theta(\mathbf z)}^2}{2\sigma^2}-\beta\,\KL=\beta\left(-\frac{\E\norm{\mathbf x-\boldsymbol\mu_\theta(\mathbf z)}^2}{2\beta\sigma^2}-\KL\right)
So a β\beta-VAE has the same optimal parameters as an ordinary VAE whose decoder variance is βσ2\beta\sigma^2. Other remedies: KL annealing, which ramps β\beta from 0 to 1 (Bowman et al., 2016); free bits, which replace each latent group's KL by max⁡(λ,DKL)\max(\lambda,\KL) and so guarantee λ\lambda nats of rate (Kingma et al., 2016); and decoders with limited receptive fields, which leave work for z\mathbf z.
Think first In a text VAE with an LSTM decoder, the KL term falls to almost zero early in training and never recovers. Annealing β\beta from 0 to 1 often prevents this, although the final objective is the same ELBO. Why can annealing help at all?

It changes which optimum gradient descent finds, not which optima exist. At initialization the decoder cannot yet use a code, so encoding information costs rate at once and pays off only later; with β=1\beta=1 from the start, the cheapest move is to shut the code off, and the model may never leave that region. With β≈0\beta\approx0 early, encoder and decoder first build a useful code, which the rate penalty then compresses. When the decoder is expressive enough, the theorem says the collapsed solution is still a global optimum.

Discrete codes, deep hierarchies and the frontier

The VQ-VAE (van den Oord, Vinyals & Kavukcuoglu, 2017) makes the code discrete. Each encoder output vector ze(x)\mathbf z_e(\mathbf x) is snapped to its nearest codebook entry, zq=ek\mathbf z_q=\mathbf e_k with k=arg min⁡j∥ze(x)−ej∥k=\argmin_j\norm{\mathbf z_e(\mathbf x)-\mathbf e_j}. The posterior is one-hot, so with a uniform prior over KK codes the KL is the constant log⁡K\log K per position and drops out. The argmin has no gradient, so the decoder's gradient with respect to zq\mathbf z_q is copied onto ze\mathbf z_e (the straight-through estimator), and two extra terms pull codebook and encoder together:

L=−log⁡pθ(x∣zq(x))+∥sg⁡[ze(x)]−ek∥2+β∥ze(x)−sg⁡[ek]∥2\loss=-\log p_\theta\big(\mathbf x\mid\mathbf z_q(\mathbf x)\big)+\norm{\operatorname{sg}[\mathbf z_e(\mathbf x)]-\mathbf e_k}^2+\beta\norm{\mathbf z_e(\mathbf x)-\operatorname{sg}[\mathbf e_k]}^2
sg⁡\operatorname{sg} is stop-gradient. The codebook term moves ek\mathbf e_k toward the encoder outputs assigned to it, as in kk-means (moving averages are a common alternative), and the commitment term (β=0.25\beta=0.25 in the paper) keeps the encoder near its codes. A prior over the code indices is fitted afterward, originally by a PixelCNN.

This two-stage recipe, compress to discrete tokens and then model the tokens, became a backbone of generative modeling. VQ-VAE-2 (Razavi, van den Oord & Vinyals, 2019) used a hierarchy of codes. VQGAN (Esser, Rombach & Ommer, 2021) added perceptual and adversarial losses so that a transformer could model the tokens. The autoencoders of latent diffusion (Diffusion Models) and the residual-vector-quantized neural audio codecs of Speech Synthesis descend from the same line. A recurring failure is codebook collapse, in which only a few codes are ever used; kk-means initialization and re-seeding dead codes help.

Continuous latents scale by depth instead. Hierarchical VAEs with top-down inference, from the Ladder VAE (Sønderby et al., 2016) to NVAE (Vahdat & Kautz, 2020) and Very Deep VAEs (Child, 2021), stack dozens of latent layers. Child argued that a deep enough hierarchical VAE can represent an autoregressive model, and showed such VAEs matching or beating autoregressive likelihoods on images while sampling far faster. A diffusion model is formally a hierarchical VAE with TT latent layers of the data's dimension and a fixed, non-learned encoder (Kingma et al., 2021).

Key takeaways

  • The amortized ELBO's gap is an approximation gap (the family) plus an amortization gap (the shared encoder), and training also bends the decoder toward posteriors that are easy to approximate.
  • The reparameterization and score-function estimators are both unbiased. The first differentiates through the sample and needs a differentiable ff; the second uses only values of ff and has high variance without baselines.
  • Importance-weighted bounds LK\mathcal L_K increase monotonically to log⁡pθ(x)\log p_\theta(\mathbf x), with a gap of about χ2(pθ(⋅∣x) ∥ q)/(2K)\chi^2(p_\theta(\cdot\mid\mathbf x)\,\|\,q)/(2K), but the encoder's gradient signal-to-noise ratio decays like 1/K1/\sqrt K.
  • −ELBO=D+R-\mathrm{ELBO}=D+R with H−D≤Iq(X;Z)≤RH-D\le I_q(X;Z)\le R. Every model on D+R=HD+R=H is ELBO-optimal, so collapse is optimal whenever the decoder alone can model the data; β\beta (a disguised decoder variance), free bits and annealing move models along or off that line.
  • VQ-VAEs use discrete codes, a constant KL and straight-through gradients. The "tokenize, then model the tokens" pipelines of VQGAN, latent diffusion and audio codecs grew from them, while hierarchical VAEs and diffusion models deepen the latent hierarchy.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Two VAEs trained on the same discrete dataset, of entropy HH, both reach the best possible average ELBO, −H-H. Model A has rate R=0R=0; model B has rate R=40R=40 nats. How much information about x\mathbf x do their codes carry?

  1. The same amount, since their ELBOs are equal
  2. B carries at most 40 nats, possibly none at all
  3. A carries none; B carries exactly 40 nats
  4. A carries HH nats, because its decoder reproduces the data distribution
Show the answer

C. A carries none; B carries exactly 40 nats

On the optimal line D+R=HD+R=H the bounds H−D≤Iq≤RH-D\le I_q\le R pinch, so Iq=RI_q=R: 00 for A and 4040 nats for B. Equal ELBOs, very different use of the latent; that is the rate–distortion critique of the ELBO.

Question 2

A β\beta-VAE uses β=4\beta=4 and a Gaussian decoder with fixed variance σ2=0.01\sigma^2=0.01. Which standard VAE (β=1\beta=1) has the same optimal parameters?

  1. Decoder variance 0.00250.0025
  2. Decoder variance 0.160.16
  3. Decoder variance 0.010.01, KL weight 1/41/4
  4. Decoder variance 0.040.04
Show the answer

D. Decoder variance 0.040.04

−∥x−μ∥22σ2−βDKL=β(−∥x−μ∥22βσ2−DKL)-\frac{\norm{\mathbf x-\boldsymbol\mu}^2}{2\sigma^2}-\beta\KL=\beta\Big(-\frac{\norm{\mathbf x-\boldsymbol\mu}^2}{2\beta\sigma^2}-\KL\Big), and the positive factor β\beta does not move the maximizer. So β=4\beta=4 at σ2=0.01\sigma^2=0.01 behaves like β=1\beta=1 at βσ2=0.04\beta\sigma^2=0.04: penalizing rate is the same as assuming noisier data.

Question 3

As the number of importance samples KK grows, which statement about the IWAE objective LK\mathcal L_K is true?

  1. The bound tightens monotonically toward log⁡pθ(x)\log p_\theta(\mathbf x), but the signal-to-noise ratio of the encoder's gradient decays like 1/K1/\sqrt K
  2. The bound can get looser for some KK, so KK must be tuned on validation data
  3. For large KK the bound exceeds log⁡pθ(x)\log p_\theta(\mathbf x)
  4. Encoder and decoder gradients both become less noisy, so larger KK is always better for training
Show the answer

A. The bound tightens monotonically toward log⁡pθ(x)\log p_\theta(\mathbf x), but the signal-to-noise ratio of the encoder's gradient decays like 1/K1/\sqrt K

The random-subset argument gives Lm≤LK≤log⁡pθ(x)\mathcal L_m\le\mathcal L_K\le\log p_\theta(\mathbf x) for m<Km<K, with a gap of about χ2/(2K)\chi^2/(2K). Rainforth et al. (2018) showed that the decoder's gradient SNR grows like K\sqrt K while the encoder's decays like 1/K1/\sqrt K.

Question 4

Why does the VQ-VAE training loss contain no KL term?

  1. The commitment term is exactly the KL divergence, written differently
  2. The posterior is one-hot and the prior uniform over KK codes, so the KL is the constant log⁡K\log K
  3. KL divergence is undefined for discrete distributions
  4. The straight-through estimator cancels the KL's gradient
Show the answer

B. The posterior is one-hot and the prior uniform over KK codes, so the KL is the constant log⁡K\log K

DKL(δk ∥ Uniform(K))=log⁡K\KL\big(\delta_k\,\|\,\mathrm{Uniform}(K)\big)=\log K whatever kk is chosen, so it has no gradient and can be dropped. The rate is fixed by the codebook size; the prior is learned in a second stage.

Further reading

  • D. P. Kingma & M. Welling, "Auto-encoding variational Bayes," ICLR (2014).
  • D. J. Rezende, S. Mohamed & D. Wierstra, "Stochastic backpropagation and approximate inference in deep generative models," ICML (2014).
  • Y. Burda, R. Grosse & R. Salakhutdinov, "Importance weighted autoencoders," ICLR (2016).
  • A. A. Alemi, B. Poole, I. Fischer, J. V. Dillon, R. A. Saurous & K. Murphy, "Fixing a broken ELBO," ICML (2018).
  • D. P. Kingma & M. Welling, "An introduction to variational autoencoders," Foundations and Trends in Machine Learning (2019).