4.5.5Generative Models

ELBO objective and KL term

2,967 words13 min readdifficulty · medium

Overview

The Evidence Lower BOund (ELBO) is the central optimization objective in variational inference and the training loss for Variational Autoencoders (VAEs). It provides a tractable way to approximate intractable posterior distributions by maximizing a lower bound on the log-likelihood, while simultaneously including a KL divergence term that regularizes the approximate posterior.

Figure — ELBO objective and KL term

Derivation from First Principles

Step 1: Start with the intractable log-likelihood

We want to maximize logpθ(x)\log p_\theta(x) for observed data xx, where the generative model is: pθ(x)=pθ(xz)p(z)dzp_\theta(x) = \int p_\theta(x|z) p(z) dz

Why this is hard: For most choices of pθ(xz)p_\theta(x|z) (like a neural network decoder), this integral has no closed form and is exponentially expensive in the dimension of zz.

Step 2: Introduce the approximate posterior

Since we can't compute pθ(zx)p_\theta(z|x) directly, we introduce an approximate posterior qϕ(zx)q_\phi(z|x) (the encoder network in VAEs). This is our variational distribution—we'll optimize ϕ\phi to make qϕ(zx)q_\phi(z|x) close to pθ(zx)p_\theta(z|x).

Step 3: Derive the ELBO using Jensen's inequality

Start with the log-likelihood: logpθ(x)=logpθ(x,z)dz\log p_\theta(x) = \log \int p_\theta(x, z) dz

Multiply and divide by qϕ(zx)q_\phi(z|x): =logqϕ(zx)qϕ(zx)pθ(x,z)dz=logEqϕ(zx)[pθ(x,z)qϕ(zx)]= \log \int \frac{q_\phi(z|x)}{q_\phi(z|x)} p_\theta(x, z) dz = \log \mathbb{E}_{q_\phi(z|x)} \left[ \frac{p_\theta(x, z)}{q_\phi(z|x)} \right]

Key insight: log()\log(\cdot) is a concave function, so by Jensen's inequality (which for concave functions gives f(E[X])E[f(X)]f(\mathbb{E}[X]) \geq \mathbb{E}[f(X)]): logEq[f(z)]Eq[logf(z)]\log \mathbb{E}_{q} [f(z)] \geq \mathbb{E}_{q} [\log f(z)]

Applying this: logpθ(x)Eqϕ(zx)[logpθ(x,z)qϕ(zx)]\log p_\theta(x) \geq \mathbb{E}_{q_\phi(z|x)} \left[ \log \frac{p_\theta(x, z)}{q_\phi(z|x)} \right]

Why this step? Jensen's inequality lets us move the log\log inside the expectation at the cost of introducing an inequality. Because log\log is concave, the inequality points the right way (log\log of an average \geq average of log\logs), giving us a valid lower bound. This makes the expression computable via Monte Carlo sampling.

Step 4: Rewrite using conditional and prior

Using pθ(x,z)=pθ(xz)p(z)p_\theta(x, z) = p_\theta(x|z) p(z): L=Eqϕ(zx)[logpθ(xz)+logp(z)logqϕ(zx)]\mathcal{L} = \mathbb{E}_{q_\phi(z|x)} [\log p_\theta(x|z) + \log p(z) - \log q_\phi(z|x)]

Rearrange: =Eqϕ(zx)[logpθ(xz)]+Eqϕ(zx)[logp(z)qϕ(zx)]= \mathbb{E}_{q_\phi(z|x)} [\log p_\theta(x|z)] + \mathbb{E}_{q_\phi(z|x)} \left[ \log \frac{p(z)}{q_\phi(z|x)} \right]

Why this form?

  • The first term rewards the model for reconstructing xx from latent codes sampled from the encoder.
  • The second term penalizes the encoder distribution for deviating from the prior p(z)p(z), preventing it from collapsing or overfitting.

Understanding the KL Term

Why we need it:

  1. Prevents posterior collapse: Without the KL term, the encoder could learn to map each xx to a deterministic, wildly different zz, making the latent space discontinuous and unusable for generation.
  2. Enables sampling: By keeping qϕ(zx)p(z)q_\phi(z|x) \approx p(z), we can generate new samples by drawing zp(z)z \sim p(z) and decoding, even for xx we've never seen.
  3. Regularization: Acts like a complexity penalty—simpler, more "prior-like" encodings are preferred.

Mathematical Properties

Key properties:

  • DKL(qp)0D_{KL}(q \| p) \geq 0 always (Gibbs' inequality)
  • DKL(qp)=0D_{KL}(q \| p) = 0 iff q=pq = p almost everywhere
  • Not symmetric: DKL(qp)DKL(pq)D_{KL}(q \| p) \neq D_{KL}(p \| q) in general

Why this direction? We use DKL(qp)D_{KL}(q \| p) not DKL(pq)D_{KL}(p \| q) because:

  • qq is the distribution we control (encoder)
  • Expectations are taken w.r.t. qq, which we can sample from
  • This is called reverse KL or exclusive KL—it makes qq underestimate the support of pp (zero-forcing behavior)

The Gap: ELBO vs True Log-Likelihood

Step 5: Quantifying the gap

Start from Bayes' rule: pθ(zx)=pθ(xz)p(z)pθ(x)p_\theta(z|x) = \frac{p_\theta(x|z) p(z)}{p_\theta(x)}

Taking logs: logpθ(x)=logpθ(xz)+logp(z)logpθ(zx)\log p_\theta(x) = \log p_\theta(x|z) + \log p(z) - \log p_\theta(z|x)

Take expectation over qϕ(zx)q_\phi(z|x): logpθ(x)=Eqϕ[logpθ(xz)]+Eqϕ[logp(z)]Eqϕ[logpθ(zx)]\log p_\theta(x) = \mathbb{E}_{q_\phi} [\log p_\theta(x|z)] + \mathbb{E}_{q_\phi} [\log p(z)] - \mathbb{E}_{q_\phi} [\log p_\theta(z|x)]

Add and subtract Eqϕ[logqϕ(zx)]\mathbb{E}_{q_\phi} [\log q_\phi(z|x)]: =Eqϕ[logpθ(xz)]DKL(qϕ(zx)p(z))L(θ,ϕ;x)+DKL(qϕ(zx)pθ(zx))Gap= \underbrace{\mathbb{E}_{q_\phi} [\log p_\theta(x|z)] - D_{KL}(q_\phi(z|x) \| p(z))}_{\mathcal{L}(\theta, \phi; x)} + \underbrace{D_{KL}(q_\phi(z|x) \| p_\theta(z|x))}_{\text{Gap}}

Why this matters:

  • The gap between ELBO and true log-likelihood is exactly the KL divergence between our approximation and the true posterior
  • As we maximize ELBO, we simultaneously improve the generative model (θ\theta) and the approximation quality (ϕ\phi)
  • When qϕ(zx)=pθ(zx)q_\phi(z|x) = p_\theta(z|x), ELBO equals log-likelihood

Worked Examples

ELBO: L=Ezqϕ[12xμθ(z)2]DKL(qϕ(zx)N(0,I))\mathcal{L} = \mathbb{E}_{z \sim q_\phi} [-\frac{1}{2} \|x - \mu_\theta(z)\|^2] - D_{KL}(q_\phi(z|x) \| \mathcal{N}(0, I))

Why this step? The reconstruction term becomes negative squared error because logN(x;μ,I)=12xμ2+const\log \mathcal{N}(x; \mu, I) = -\frac{1}{2}\|x - \mu\|^2 + \text{const}.

Closed-form KL for diagonal Gaussians: DKL(qϕp)=12j=1d(μj2+σj2logσj21)D_{KL}(q_\phi \| p) = \frac{1}{2} \sum_{j=1}^{d} \left( \mu_j^2 + \sigma_j^2 - \log \sigma_j^2 -1 \right)

Derivation of this formula: Starting from definition: DKL=Eq[logq(z)logp(z)]D_{KL} = \mathbb{E}_q [\log q(z) - \log p(z)] =Eq[12j(zjμj)2σj212logσj2+12jzj2]+const= \mathbb{E}_q \left[ -\frac{1}{2} \sum_j \frac{(z_j - \mu_j)^2}{\sigma_j^2} - \frac{1}{2}\log \sigma_j^2 + \frac{1}{2} \sum_j z_j^2 \right] + \text{const}

Using Eq[zj2]=μj2+σj2\mathbb{E}_q[z_j^2] = \mu_j^2 + \sigma_j^2 and Eq[(zjμj)2]=σj2\mathbb{E}_q[(z_j - \mu_j)^2] = \sigma_j^2: =12j(1logσj2+μj2+σj2)= \frac{1}{2} \sum_j \left( -1 - \log \sigma_j^2 + \mu_j^2 + \sigma_j^2 \right)

Why this matters: This closed form makes VAE training efficient—no Monte Carlo estimation needed for the KL term.

Step 1: Reconstruction term logpθ(xz)=12(0.2,0.8)(0.19,0.79)2=12(0.012+0.012)=0.0001\log p_\theta(x|z) = -\frac{1}{2} \|(0.2, 0.8) - (0.19, 0.79)\|^2 = -\frac{1}{2}(0.01^2 + 0.01^2) = -0.0001

Why this step? We evaluate how well the decoder reconstructed the original xx from the sampled latent code.

Step 2: KL term (using logσj2=2logσj-\log \sigma_j^2 = -2\log\sigma_j, so log(0.82)0.446-\log(0.8^2) \approx 0.446 and log(1.22)0.365-\log(1.2^2) \approx -0.365) DKL=12[(0.52+0.82log(0.82)1)+((0.3)2+1.22log(1.22)1)]D_{KL} = \frac{1}{2} [(0.5^2 + 0.8^2 - \log(0.8^2) - 1) + ((-0.3)^2 + 1.2^2 - \log(1.2^2) - 1)] =12[(0.25+0.64+0.4461)+(0.09+1.440.3651)]= \frac{1}{2} [(0.25 + 0.64 + 0.446 - 1) + (0.09 + 1.44 - 0.365 - 1)] =12[0.336+0.165]=0.2505= \frac{1}{2} [0.336 + 0.165] = 0.2505

ELBO: L=0.00010.2505=0.2506\mathcal{L} = -0.0001 - 0.2505 = -0.2506

Why this step? We penalize the encoder for producing a distribution that deviates from the standard normal prior. Note the crucial detail: the KL formula uses logσj2=2logσj\log \sigma_j^2 = 2\log\sigma_j, not logσj\log \sigma_j—forgetting the factor of 2 is a common error.

What happens:

  • β<1\beta < 1: Prioritizes reconstruction, KL can grow large → better reconstructions, entangled latents
  • β=1\beta = 1: Standard ELBO, balanced trade-off
  • β>1\beta > 1: Prioritizes matching prior → more disentangled latents, worse reconstructions

Why this works: The KL term's strength controls the information bottleneck. Higher β\beta forces the encoder to use fewer, more independent dimensions of zz, leading to disentanglement.


Common Mistakes and Misconceptions

The truth: The KL term isn't ad-hoc regularization; it arises naturally from the variational inference framework. It's the gap between your approximate posterior and the true posterior. Removing it doesn't give you a "less regularized" VAE—it breaks the mathematical justification for why you're optimizing this objective at all.

How to fix it: Remember the derivation: ELBO + KL gap = log-likelihood. The KL term is part of the bound, not an add-on.

The nuance: Maximizing ELBO w.r.t. θ\theta does improve logpθ(x)\log p_\theta(x). But when we also optimize ϕ\phi, we're tightening the bound by reducing the KL gap. The log-likelihood only increases if the ELBO increase exceeds the gap reduction. In practice, we jointly optimize, so both happen together.

How to fix it: ELBO is a lower bound for fixed ϕ\phi. When ϕ\phi changes, the bound itself moves. The guarantee is: Llogp(x)\mathcal{L} \leq \log p(x) always, but improving L\mathcal{L} improves the model.

The truth: KL is asymmetric. DKL(qp)D_{KL}(q \| p) (reverse KL, used in ELBO) is zero-forcing: it makes q(z)0q(z) \approx 0 wherever p(z)0p(z) \approx 0, leading to underestimation of the true posterior's support. DKL(pq)D_{KL}(p \| q) (forward KL) is zero-avoiding: it makes q(z)>0q(z) > 0 wherever p(z)>0p(z) > 0, leading to overestimation of support.

Why it matters for VAEs: Reverse KL can cause posterior collapse where the encoder ignores certain modes of the true posterior. Forward KL would make the approximate posterior overly broad and diffuse.

How to fix it: Remember the direction: we want expectations w.r.t. qq (what we can sample), so we use DKL(qp)D_{KL}(q \| p).

The truth: ELBO is a lower bound on log-probability, which can be negative (probabilities can be < 1). What matters is that ELBO increases during training, not its absolute value. A typical ELBO value might be -1000 or -10000 depending on data dimensionality.

How to fix it: Track ELBO improvement, not absolute value. Compare ELBO across architectures on the same data for meaningful comparisons.


Active Recall Practice

Recall Explain ELBO to a 12-year-old

Imagine you have a magic box that can create pictures. But you want to understand what secret codes the box uses to make each picture. The problem is, you can't peek inside the box directly.

So you build a guesser machine that looks at picture and guesses what secret code created it. Now you play a game:

  1. Show your guesser a picture → it guesses a code
  2. Feed that code to the magic box → see if you get the same picture back
  3. You get points if the picture comes out right

But there's a catch! Your guesser can't just make up any random codes—it has to use codes that are similar to the ones the magic box naturally uses (like numbers between 0 and 1, not crazy numbers like 999).

ELBO is your score in this game: You get points for recreating pictures correctly (reconstruction term), but you lose points if your guesser uses weird, un-natural codes (KL term). Maximizing ELBO means getting better at both guessing codes and recreating pictures while keeping your guesses reasonable.


For KL direction: "Queen Prefers Priors"DKL(QϕP)D_{KL}(\mathbf{Q}_\phi \| \mathbf{P}), we measure how far our Queen (encoder) is from the Prior.


Connections

  • Variational Inference: ELBO is the fundamental objective in VI; VAEs are a deep learning application
  • KL Divergence: Deep dive into properties, forward vs reverse, f-divergences
  • VAE Architecture: How ELBO is implemented in neural networks with reparameterization trick
  • Expectation Maximization: ELBO appears in EM algorithm for latent variable models
  • Information Bottleneck: β-VAE connects to IB principle via weighted KL term
  • Posterior Collapse: What happens when KL → 0 and the model ignores latent variables
  • Importance Weighted Autoencoders: Tighter bounds than ELBO using multiple samples
  • Normalizing Flows: Alternative to diagonal Gaussian encoder for more expressive qϕq_\phi

Summary

The ELBO objective L=Eqϕ(zx)[logpθ(xz)]DKL(qϕ(zx)p(z))\mathcal{L} = \mathbb{E}_{q_\phi(z|x)} [\log p_\theta(x|z)] - D_{KL}(q_\phi(z|x) \| p(z)) is a tractable lower bound on the intractable log-likelihood logpθ(x)\log p_\theta(x). It decomposes into:

  1. Reconstruction term: Reward accurate decoding
  2. KL regularization: Keep encoder close to prior

The gap between ELBO and log-likelihood is exactly DKL(qϕ(zx)pθ(zx))D_{KL}(q_\phi(z|x) \| p_\theta(z|x))—the approximation error of the variational posterior. Maximizing ELBO jointly improves the generative model and reduces the approximation gap. The KL term is not ad-hoc regularization but a fundamental consequence of the variational framework that enables sampling, prevents collapse, and provides a principled training objective for VAEs.


#flashcards/ai-ml

What is the ELBO objective in variational inference?
The Evidence Lower BOund, L(θ,ϕ;x)=Eqϕ(zx)[logpθ(xz)]DKL(qϕ(zx)p(z))\mathcal{L}(\theta, \phi; x) = \mathbb{E}_{q_\phi(z|x)} [\log p_\theta(x|z)] - D_{KL}(q_\phi(z|x) \| p(z)), a tractable lower bound on logpθ(x)\log p_\theta(x) that decomposes into a reconstruction term and a KL regularization term.
Why is ELBO called a "lower bound"?
Because by Jensen's inequality (log is concave), L(θ,ϕ;x)logpθ(x)\mathcal{L}(\theta, \phi; x) \leq \log p_\theta(x) always holds. Maximizing ELBO pushes up the log-likelihood from below.
What are the two components of the ELBO?
1) Reconstruction term: Eqϕ(zx)[logpθ(xz)]\mathbb{E}_{q_\phi(z|x)} [\log p_\theta(x|z)] (reward accurate decoding), 2) KL divergence: DKL(qϕ(zx)p(z))-D_{KL}(q_\phi(z|x) \| p(z)) (penalize deviation from prior).
What is the gap between ELBO and true log-likelihood?
The gap is DKL(qϕ(zx)pθ(zx))D_{KL}(q_\phi(z|x) \| p_\theta(z|x)), the KL divergence between the approximate posterior and the true posterior. When this is zero, ELBO equals log-likelihood.
Why do we use DKL(qp)D_{KL}(q \| p) instead of DKL(pq)D_{KL}(p \| q) in ELBO?
Because we need expectations w.r.t. qϕq_\phi, which we can sample from

Concept Map

intractable integral

cannot compute

variational distribution

apply Jensens inequality

used in

lower bounds

splits into

splits into

regularizes

uses

pulls q toward

maximized to train

Log-likelihood log p x

Marginal over latent z

Introduce approx posterior q phi

VAE Encoder

ELBO lower bound

Reconstruction term

KL divergence term

VAE Decoder p theta x given z

Prior p z

Variational Autoencoder

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, yaha core baat ye hai ki generative models me hum chahte hain ki apne data xx ka log-likelihood logp(x)\log p(x) maximize karein, taaki model realistic samples generate kar sake. Lekin problem ye hai ki p(x)p(x) compute karna hai to sabhi possible latent codes zz ke upar integrate karna padta hai, jo practically impossible hai — ek exponentially bada integral. To hum seedha wo cheez maximize hi nahi kar sakte jo hume chahiye. Isiliye ELBO aata hai: ye ek aisi quantity hai jo hum actually compute kar sakte hain, aur jo hamesha logp(x)\log p(x) se chhoti ya barabar rehti hai. Iska matlab agar hum ELBO ko upar push karein, to woh niche se hamare unreachable ceiling ko bhi upar dhakelta hai. Bilkul jaise ek tower banake ceiling ki minimum height ka guarantee dena.

Ab ELBO ke andar do parts hote hain, aur yahi samajhna sabse zaroori hai. Pehla hai reconstruction term — ye reward karta hai jab model latent code zz se wapas original xx ko sahi se bana pata hai. Doosra hai KL divergence term, jo encoder ki distribution qϕ(zx)q_\phi(z|x) ko prior p(z)p(z) (usually simple Gaussian) ke paas rehne pe force karta hai. Jensen's inequality ki wajah se — kyunki log\log ek concave function hai — hum log\log ko expectation ke andar la paate hain, aur bound sahi direction me point karta hai, matlab valid lower bound milta hai jise hum Monte Carlo sampling se estimate kar sakte hain.

Ye why-matters isliye hai ki ye poora balance hi VAE ki jaan hai. Agar sirf reconstruction pe focus karein, to model overfit ho jayega aur latent space bekhar (messy) ho jayega — smooth samples generate nahi honge. KL term isko regularize karke ensure karta hai ki latent space organized aur continuous rahe, taaki tum us space se naye points sample karke fresh, meaningful data generate kar sako. To samajh lo, ELBO ek clever trick hai jo intractable problem ko tractable bana deta hai, aur ye hi variational inference aur modern generative modeling ki foundation hai.

Go deeper — visual, from zero

Test yourself — Generative Models

Connections