Quiz 2

Variational Autoencoders: ELBO, Reparameterization, and KL Divergence

1009 words
5 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Variational Autoencoders: ELBO, Reparameterization, and KL Divergence ## 🎯 Learning Objectives - Understand the motivation for variational inference in latent variable models - Derive the ELBO (Evidence Lower Bound) from KL divergence - Implement the reparameterization trick for differentiable sampling - Compare...

Variational Autoencoders: ELBO, Reparameterization, and KL Divergence

🎯 Learning Objectives

  • Understand the motivation for variational inference in latent variable models
  • Derive the ELBO (Evidence Lower Bound) from KL divergence
  • Implement the reparameterization trick for differentiable sampling
  • Compare VAE with AE and understand the regularization effect of KL

📋 Prerequisites

  • Bayesian inference basics
  • KL divergence and entropy
  • Autoencoder architecture

1. 📖 Core Content

1.1 The Generative Modeling Problem

We want to learn p(x)p(x) — the probability distribution of data. Latent variable models introduce a hidden variable zz:
p(x)=p(xz)p(z)dzp(x) = \int p(x|z) p(z) dz
The problem: this integral is intractable for complex models (we'd need to integrate over all possible latent codes).

1.2 The ELBO Derivation

Starting from the log-likelihood:
logp(x)=logp(xz)p(z)dz\log p(x) = \log \int p(x|z) p(z) dz
Introduce an approximate posterior qϕ(zx)q_\phi(z|x):
logp(x)=DKL(qϕ(zx)p(zx))+L(x;θ,ϕ)\log p(x) = D_{KL}(q_\phi(z|x) || p(z|x)) + \mathcal{L}(x; \theta, \phi)
Since DKL0D_{KL} \geq 0:
logp(x)L(x;θ,ϕ)=Eqϕ(zx)[logpθ(xz)]DKL(qϕ(zx)p(z))\log p(x) \geq \mathcal{L}(x; \theta, \phi) = \mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)] - D_{KL}(q_\phi(z|x) || p(z))
Where:
  • Eqϕ(zx)[logpθ(xz)]\mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)]: Reconstruction loss (log-likelihood of data given latent)
  • DKL(qϕ(zx)p(z))D_{KL}(q_\phi(z|x) || p(z)): KL regularization (encourages latent distribution to match prior)

1.3 The Reparameterization Trick

The sampling operation zqϕ(zx)=N(μ,σ2)z \sim q_\phi(z|x) = \mathcal{N}(\mu, \sigma^2) is not differentiable. The reparameterization trick makes it differentiable:
z=μ+σϵ,ϵN(0,I)z = \mu + \sigma \odot \epsilon, \quad \epsilon \sim \mathcal{N}(0, I)
Now gradients can flow through μ\mu and σ\sigma:
python
# runnable
import torch
import torch.nn as nn
import torch.nn.functional as F
class VAE(nn.Module):
    def __init__(self, input_dim=784, latent_dim=20, hidden_dim=400):
        super().__init__()
        # Encoder
        self.encoder = nn.Sequential(
            nn.Linear(input_dim, hidden_dim),
            nn.ReLU()
        )
        self.mu_layer = nn.Linear(hidden_dim, latent_dim)
        self.logvar_layer = nn.Linear(hidden_dim, latent_dim)
        # Decoder
        self.decoder = nn.Sequential(
            nn.Linear(latent_dim, hidden_dim),
            nn.ReLU(),
            nn.Linear(hidden_dim, input_dim),
            nn.Sigmoid()
        )
    def encode(self, x):
        h = self.encoder(x)
        return self.mu_layer(h), self.logvar_layer(h)
    def reparameterize(self, mu, logvar):
        """Reparameterization trick: z = μ + σ * ε"""
        if self.training:
            std = torch.exp(0.5 * logvar)
            eps = torch.randn_like(std)
            return mu + eps * std
        return mu  # Deterministic at inference
    def decode(self, z):
        return self.decoder(z)
    def forward(self, x):
        mu, logvar = self.encode(x)
        z = self.reparameterize(mu, logvar)
        recon = self.decode(z)
        return recon, mu, logvar
def vae_loss(recon, x, mu, logvar):
    """VAE loss = reconstruction + KL divergence"""
    # Reconstruction loss (binary cross-entropy)
    recon_loss = F.binary_cross_entropy(recon, x, reduction='sum')
    # KL divergence: KL(q(z|x) || p(z)) where p(z) = N(0, I)
    # Formula: -0.5 * sum(1 + log(σ²) - μ² - σ²)
    kl_loss = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
    return recon_loss + kl_loss

1.4 Interpreting the KL Term

The KL divergence KL(qϕ(zx)N(0,I))KL(q_\phi(z|x) || \mathcal{N}(0, I)) has two effects:
  1. Posterior collapse prevention: Prevents the encoder from mapping different inputs to distant latent codes
  2. Latent space regularization: Encourages the latent space to be smooth and continuous
KL(N(μ,σ2)N(0,1))=12(1+logσ2μ2σ2)KL(\mathcal{N}(\mu, \sigma^2) || \mathcal{N}(0, 1)) = -\frac{1}{2}(1 + \log \sigma^2 - \mu^2 - \sigma^2)
μσ²KLEffect
010Perfect match to prior
0.510.125Slight deviation
212.0Large deviation (penalized)
00.11.2Underconfident (too certain)
030.39Overconfident (too uncertain)

1.5 Beta-VAE

Beta-VAE introduces a weight β\beta on the KL term:
LβVAE=E[logpθ(xz)]βKL(qϕ(zx)p(z))\mathcal{L}_{\beta-VAE} = \mathbb{E}[\log p_\theta(x|z)] - \beta \cdot KL(q_\phi(z|x) || p(z))
β>1\beta > 1: Encourages disentangled representations (each latent dimension captures a separate factor of variation) β=0\beta = 0: Standard autoencoder (no regularization)

📝 Practice Questions

Q1
<strong>Q1</strong>: Show that the ELBO is a lower bound on the log-likelihood.
Start with log-likelihood: logp(x)=logp(x,z)dz\log p(x) = \log \int p(x,z) dz =logq(zx)p(x,z)q(zx)dz= \log \int q(z|x) \frac{p(x,z)}{q(z|x)} dz q(zx)logp(x,z)q(zx)dz\geq \int q(z|x) \log \frac{p(x,z)}{q(z|x)} dz (by Jensen's inequality: log(E[X]) ≥ E[log(X)]) =q(zx)logp(xz)p(z)q(zx)dz= \int q(z|x) \log \frac{p(x|z)p(z)}{q(z|x)} dz =q(zx)logp(xz)dz+q(zx)logp(z)q(zx)dz= \int q(z|x) \log p(x|z) dz + \int q(z|x) \log \frac{p(z)}{q(z|x)} dz =Eq(zx)[logp(xz)]KL(q(zx)p(z))= \mathbb{E}_{q(z|x)}[\log p(x|z)] - KL(q(z|x) || p(z))
This lower bound is the ELBO. Maximizing it improves the model's log-likelihood. Q2
<strong>Q2
<strong>Q2</strong>: In the reparameterization trick, why can't we directly sample z ~ N(μ, σ²) and backpropagate?
Direct sampling: z = sample(N(μ, σ²))
The gradient ∂z/∂μ and ∂z/∂σ doesn't exist — sampling is a stochastic operation with no defined gradient. The "sampling node" breaks the computation graph.
Reparameterization: z = μ + σ·ε, ε ~ N(0,1)
Now z is a deterministic function of μ, σ, and ε. Gradients ∂z/∂μ = 1 and ∂z/∂σ = ε exist and can be computed. The randomness comes from ε (external), which doesn't need gradients.
This seemingly simple trick is what makes VAEs trainable with SGD. Q3
<strong>Q3
<strong>Q3
<strong>Q3
<strong>Q3</strong>: What is posterior collapse in VAEs, and how can it be detected?
Posterior collapse: The KL term dominates the loss, and the encoder learns to map all inputs to the prior distribution: q(zx)p(z)=N(0,I)q(z|x) \approx p(z) = N(0, I).
Symptoms:
  1. Ignored latent code: The decoder ignores z (produces same output regardless of input)
  2. KL divergence approaches 0: μ → 0, σ² → 1 for all inputs
  3. Reconstruction is blurry/mean: Decoder averages over all possibilities
  4. No latent structure: Interpolating in latent space doesn't change output
Causes: Powerful decoder (e.g., expressive autoregressive), weak latent, high β value.
Fixes: Reduce β, use KL annealing, use a weaker decoder, increase latent dimensionality. Q4
<strong>Q4
<strong>Q4
<strong>Q4
<strong>Q4
<strong>Q4</strong>: Compare VAEs and GANs on sample quality, latent space structure, and training stability.
AspectVAEGAN
Sample qualityBlurry, less sharpSharp, high quality
Latent spaceSmooth, continuous (KL regularized)Often less structured
Training stabilityStable (ELBO optimization)Unstable (min-max game)
LikelihoodTractable lower boundNo likelihood available
Mode coverageGood (covers all modes)Poor (mode collapse)
Mathematical frameworkVariational inferenceGame theory
DiversityHighLow to moderate
VAEs excel at structured latent spaces (useful for interpolation, semi-supervised learning) while GANs excel at sample quality. Diffusion models (covered in Week 4-5) combine benefits of both.
</details> * * * ## 🔗 Cross-References - **Next**: [Diffusion Models](/notes/04-degree-electives-bsda5002-genai-foundations-week04-04-diffusion-models) - **Previous**: [GANs](/notes/04-degree-electives-bsda5002-genai-foundations-week02-02-gans) - **Video**: BSDA5002 Week 4-5 transcripts [Join Discord](https://discord.gg/gE2m4Qrdqv) [Previous**GANs**](/notes/04-degree-electives-bsda5002-genai-foundations-week02-02-gans)[Next**Diffusion Models (DDPM)**](/notes/04-degree-electives-bsda5002-genai-foundations-week04-04-diffusion-models)
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.