4.5.3Generative Models

Variational Autoencoders (VAE) theory

3,267 words15 min readdifficulty · medium6 backlinks

#ai-ml/generative-models #unsupervised-learning #probabilistic-models #latent-variables

Overview

Variational Autoencoders (VAEs) are generative models that learn to encode data into a latent space and decode it back, while ensuring the latent space follows a known distribution (typically Gaussian). Unlike standard autoencoders, VAEs are probabilistic and enable sampling of new data.


Core Intuition

Why do we need the probabilistic formulation?

  • Deterministic autoencoders can "memorize" and create disconnected regions in latent space
  • We want to generate new samples by sampling from latent space
  • Probabilistic interpretation gives us a principled way to balance reconstruction and regularization

Mathematical Foundation

The Generative Story

Why Gaussian prior? It's mathematically convenient, has infinite support, and the central limit theorem suggests many natural processes converge to it.

The Problem: Intractable Marginal Likelihood

We want to maximize: pθ(x)=pθ(xz)p(z)dzp_\theta(\mathbf{x}) = \int p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z}) d\mathbf{z}

Why is this hard? For each data point x\mathbf{x}, we'd need to integrate over ALL possible latent codes z\mathbf{z} to see which ones could have generated it. With high-dimensional z\mathbf{z}, this integral is computationally intractable.

The Solution: Variational Inference

Introduce an inference network (encoder) qϕ(zx)q_\phi(\mathbf{z}|\mathbf{x}) that approximates the true posterior pθ(zx)p_\theta(\mathbf{z}|\mathbf{x}).

Deriving the ELBO from scratch:

Start with log-likelihood: logpθ(x)=logpθ(xz)p(z)dz\log p_\theta(\mathbf{x}) = \log \int p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z}) d\mathbf{z}

Multiply inside by qϕ(zx)qϕ(zx)=1\frac{q_\phi(\mathbf{z}|\mathbf{x})}{q_\phi(\mathbf{z}|\mathbf{x})} = 1: logpθ(x)=logqϕ(zx)pθ(xz)p(z)qϕ(zx)dz\log p_\theta(\mathbf{x}) = \log \int q_\phi(\mathbf{z}|\mathbf{x}) \frac{p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z})}{q_\phi(\mathbf{z}|\mathbf{x})} d\mathbf{z}

This is expectation over qϕq_\phi: logpθ(x)=logEqϕ(zx)[pθ(xz)p(z)qϕ(zx)]\log p_\theta(\mathbf{x}) = \log \mathbb{E}_{q_\phi(\mathbf{z}|\mathbf{x})} \left[ \frac{p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z})}{q_\phi(\mathbf{z}|\mathbf{x})} \right]

Why this step? Jensen's inequality states logE[X]E[logX]\log \mathbb{E}[X] \geq \mathbb{E}[\log X] for any random variable XX (log is concave). Apply it:

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

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

The second term is negative KL divergence: Eqϕ(zx)[logp(z)qϕ(zx)]=DKL(qϕ(zx)p(z))\mathbb{E}_{q_\phi(\mathbf{z}|\mathbf{x})} \left[ \log \frac{p(\mathbf{z})}{q_\phi(\mathbf{z}|\mathbf{x})} \right] = -D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z}))

Why "lower bound"? The inequality from Jensen guarantees logpθ(x)L\log p_\theta(\mathbf{x}) \geq \mathcal{L}. Maximizing the ELBO pushes up a lower bound on the log-likelihood.

The Gap: KL Between Approximate and True Posterior

We can show: logpθ(x)=L(θ,ϕ;x)+DKL(qϕ(zx)pθ(zx))\log p_\theta(\mathbf{x}) = \mathcal{L}(\theta, \phi; \mathbf{x}) + D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}) \| p_\theta(\mathbf{z}|\mathbf{x}))

Why? Start from: DKL(qϕpθ(zx))=Eqϕ[logqϕ(zx)pθ(zx)]D_{KL}(q_\phi \| p_\theta(\mathbf{z}|\mathbf{x})) = \mathbb{E}_{q_\phi} \left[ \log \frac{q_\phi(\mathbf{z}|\mathbf{x})}{p_\theta(\mathbf{z}|\mathbf{x})} \right]

Use Bayes rule: pθ(zx)=pθ(xz)p(z)pθ(x)p_\theta(\mathbf{z}|\mathbf{x}) = \frac{p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z})}{p_\theta(\mathbf{x})}:

DKL(qϕpθ(zx))=Eqϕ[logqϕ(zx)logpθ(xz)logp(z)+logpθ(x)]D_{KL}(q_\phi \| p_\theta(\mathbf{z}|\mathbf{x})) = \mathbb{E}_{q_\phi} \left[ \log q_\phi(\mathbf{z}|\mathbf{x}) - \log p_\theta(\mathbf{x}|\mathbf{z}) - \log p(\mathbf{z}) + \log p_\theta(\mathbf{x}) \right]

Since logpθ(x)\log p_\theta(\mathbf{x}) doesn't depend on z\mathbf{z}: DKL(qϕpθ(zx))=logpθ(x)L(θ,ϕ;x)D_{KL}(q_\phi \| p_\theta(\mathbf{z}|\mathbf{x})) = \log p_\theta(\mathbf{x}) - \mathcal{L}(\theta, \phi; \mathbf{x})

Since KL divergence is always 0\geq 0, this confirms the ELBO is a lower bound.


The Reparameterization Trick

Problem: We need to compute gradients through Eqϕ(zx)[]\mathbb{E}_{q_\phi(\mathbf{z}|\mathbf{x})}[\cdot], but sampling is not differentiable.

Assume qϕ(zx)=N(μϕ(x),σϕ2(x))q_\phi(\mathbf{z}|\mathbf{x}) = \mathcal{N}(\boldsymbol{\mu}_\phi(\mathbf{x}), \boldsymbol{\sigma}_\phi^2(\mathbf{x})).

Standard sampling (non-differentiable): zN(μϕ(x),σϕ2(x))\mathbf{z} \sim \mathcal{N}(\boldsymbol{\mu}_\phi(\mathbf{x}), \boldsymbol{\sigma}_\phi^2(\mathbf{x}))

Intuition: Think of it like separating the "decision" (mean and variance, which depend on parameters) from the "randomness" (epsilon, which doesn't). Now gradients can flow through the decision part.


Practical VAE Architecture

Why predict log variance? Ensures positivity (σ2=exp(logσ2)>0\sigma^2 = \exp(\log \sigma^2) > 0) and numerical stability.

The Loss Function in Practice

For a dataset D={x(i)}i=1N\mathcal{D} = \{\mathbf{x}^{(i)}\}_{i=1}^N:

L(θ,ϕ)=1Ni=1N[Eqϕ(zx(i))[logpθ(x(i)z)]DKL(qϕ(zx(i))p(z))]\mathcal{L}(\theta, \phi) = \frac{1}{N} \sum_{i=1}^N \left[ \mathbb{E}_{q_\phi(\mathbf{z}|\mathbf{x}^{(i)})} [\log p_\theta(\mathbf{x}^{(i)}|\mathbf{z})] - D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}^{(i)}) \| p(\mathbf{z})) \right]

Monte Carlo estimate (typically 1 sample per data point): L1Ni=1N[logpθ(x(i)z(i))DKL(qϕ(zx(i))N(0,I))]\mathcal{L} \approx \frac{1}{N} \sum_{i=1}^N \left[ \log p_\theta(\mathbf{x}^{(i)}|\mathbf{z}^{(i)}) - D_{KL}(q_\phi(\mathbf{z}|\mathbf{x}^{(i)}) \| \mathcal{N}(\mathbf{0}, \mathbf{I})) \right]

where z(i)=μϕ(x(i))+σϕ(x(i))ϵ(i)\mathbf{z}^{(i)} = \boldsymbol{\mu}_\phi(\mathbf{x}^{(i)}) + \boldsymbol{\sigma}_\phi(\mathbf{x}^{(i)}) \odot \boldsymbol{\epsilon}^{(i)}.

KL Divergence for Gaussians (Closed Form)

For q=N(μ,σ2I)q = \mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\sigma}^2\mathbf{I}) and p=N(0,I)p = \mathcal{N}(\mathbf{0}, \mathbf{I}):

Derivation: DKL(qp)=Eq[logq(z)]Eq[logp(z)]D_{KL}(q \| p) = \mathbb{E}_q[\log q(\mathbf{z})] - \mathbb{E}_q[\log p(\mathbf{z})]

For multivariate Gaussian (dimension dd): logq(z)=d2log(2π)j=1dlogσj12j=1d(zjμj)2σj2\log q(\mathbf{z}) = -\frac{d}{2}\log(2\pi) - \sum_{j=1}^d \log \sigma_j - \frac{1}{2}\sum_{j=1}^d \frac{(z_j - \mu_j)^2}{\sigma_j^2}

logp(z)=d2log(2π)12j=1dzj2\log p(\mathbf{z}) = -\frac{d}{2}\log(2\pi) - \frac{1}{2}\sum_{j=1}^d z_j^2

Taking expectations over qq (using Eq[zj]=μj\mathbb{E}_q[z_j] = \mu_j, Eq[zj2]=μj2+σj2\mathbb{E}_q[z_j^2] = \mu_j^2 + \sigma_j^2):

Eq[logq(z)]=d2log(2π)j=1dlogσjd2\mathbb{E}_q[\log q(\mathbf{z})] = -\frac{d}{2}\log(2\pi) - \sum_{j=1}^d \log \sigma_j - \frac{d}{2}

Eq[logp(z)]=d2log(2π)12j=1d(μj2+σj2)\mathbb{E}_q[\log p(\mathbf{z})] = -\frac{d}{2}\log(2\pi) - \frac{1}{2}\sum_{j=1}^d (\mu_j^2 + \sigma_j^2)

Subtract: DKL(qp)=j=1dlogσjd2+12j=1d(μj2+σj2)D_{KL}(q \| p) = -\sum_{j=1}^d \log \sigma_j - \frac{d}{2} + \frac{1}{2}\sum_{j=1}^d (\mu_j^2 + \sigma_j^2)

=12j=1d(μj2+σj2logσj21)= \frac{1}{2}\sum_{j=1}^d \left( \mu_j^2 + \sigma_j^2 - \log \sigma_j^2 - 1 \right)


Worked Examples


Common Mistakes


Active Recall Checks

Recall Explain VAEs to a 12-Year-Old

Imagine you have a magic box that can compress photos of cats into secret codes (just a few numbers), and another magic box that can turn those codes back into cat photos.

A regular magic box might be mesy—some codes are far apart, some codes don't work at all. If you try a random code, you might get garbage.

A VAE is a smarter magic box that:

  1. Makes sure all the secret codes follow a pattern (like a bell curve)
  2. Makes sure nearby codes give similar cats
  3. Has no empty spots—every code you try gives you a cat!

The trick: While learning to compress and uncompress photos, the boxes also learn to organize codes nicely. Now you can:

  • Give any random code → get a new cat photo that looks real
  • Take two cat photos, mix their codes, get a cat that's in-between The "variational" part means we're using probability and smart math to make sure the organization happens automatically!

Memory Aids

Reparameterization: "Separate the random from the learnable"

  • Random: ϵ\epsilon (standard normal, no parameters)
  • Learnable: μ\mu and σ\sigma (encoder outputs)

KL Divergence Terms: "My Variance Logically Matters"

  • Mean squared: μ2\mu^2 (penalty for mean away from zero)
  • Variance: σ2\sigma^2 (penalty for too much spread)
  • Log variance: logσ2-\log \sigma^2 (penalty for too little spread)
  • Minus one: 1-1 (normalization)

Connections

  • Autoencoders: VAEs extend autoencoders with probabilistic formulation
  • Kullback-Leibler Divergence: Core to measuring distribution mismatch
  • Bayesian Inference: VAEs use variational inference for approximate posteriors
  • Latent Variable Models: VAEs are latent variable models with amortized inference
  • Evidence Lower Bound (ELBO): Fundamental objective function
  • Reparameterization Trick: Enables gradient-based learning
  • Generative Adversarial Networks (GANs): Alternative generative model approach
  • Normalizing Flows: Another probabilistic generative model family
  • Posterior Collapse: Common training pathology in VAEs
  • Disentangled Representations: Beta-VAE and other variants for interpretability
  • Conditional VAE: Extension for conditional generation
  • Importance-Weighted Autoencoders: Tighter ELBO bounds

#flashcards/ai-ml

What is the fundamental difference between autoencoders and VAEs? :: VAEs are probabilistic (encode/decode distributions not points), have a regularized latent space (KL term enforces prior), and enable generation by sampling from the prior distribution.

What does ELBO stand for and what are its two components?
Evidence Lower Bound. Components: (1) Reconstruction term - expected log-likelihood of data given latent code, (2) KL divergence term - regularization that keeps posterior close to prior.
Why do we need the reparameterization trick?
Standard sampling from encoder distribution is non-differentiable, blocking gradient flow to encoder parameters. Reparameterization separates random component (ε) from learnable parameters (μ, σ), making the sampling process differentiable.

Write the reparameterization trick formula :: z = μ_φ(x) + σ_φ(x) ⊙ ε, where ε ~ N(0, I). The randomness is in ε (independent of φ), allowing gradients to flow through μ and σ.

What is posterior collapse and why does it happen? :: When KL term goes to zero, encoder ignores input and outputs the prior distribution for all inputs. Happens when decoder is too powerful and can model p(x) from prior alone without needing information in z.

Write the closed-form KL divergence between diagonal Gaussian and standard normal
D_KL(N(μ, σ²I) || N(0, I)) = (1/2) Σⱼ (μⱼ² + σ - log σⱼ² - 1)
Why is the ELBO called a "lower bound"?
Due to Jensen's inequality (log E[X] ≥ E[log X]), the ELBO is guaranteed to be ≤ log p_θ(x). Maximizing ELBO pushes up a lower bound on the data log-likelihood.
What does the μ² term in the KL divergence penalize?
Means that are far from zero (the prior mean). Forces encoder to organize codes around the origin of latent space.
What does the -log σ² term in the KL divergence encourage?
Encourages having enough variance (penalty for too little spread). Balances with σ² term which penalizes too much variance.
How do you generate new samples from a trained VAE?
(1) Sample z ~ N(0, I) from prior, (2) Pass z through decoder network p_θ(x|z), (3) Sample x from the output distribution (e.g., Bernoulli for binary images).
What is the relationship between ELBO and the KL to true posterior?
log p_θ(x) = ELBO + D_KL(q_φ(z|x) || p_θ(z|x). Since KL ≥ 0, ELBO ≤ log p_θ(x). Tighter ELBO means better posterior approximation.
Why do we typically predict log σ² instead of σ² directly?
Ensures positivity (σ² = exp(log σ²) > 0 always) and numerical stability (avoids very small values during optimization).
What is KL annealing and why is it used?
Gradually increasing the KL weight from β < 1 to β = 1 during training. Helps prevent posterior collapse by allowing reconstruction to be learned first before enforcing prior constraint.
In VAE objective, what happens if you remove the KL term entirely?
Model becomes standard autoencoder: latent space can be arbitrary/discontinuous, codes far apart, holes in space, cannot generate by sampling from prior, tends to overfit.
What is the generative story of a VAE?
(1) Sample latent code z ~ p(z) = N(0, I), (2) Generate data x ~ p_θ(x|z) via decoder network. Goal:

Concept Map

is a

uses

uses

maps x to

regularized to

reconstructs from

goal maximize

is

derives

approximates

enables

generates

Variational Autoencoder

Generative Model

Encoder q_phi z given x

Decoder p_theta x given z

Latent Space z

Gaussian Prior N 0 I

Intractable Marginal Likelihood

Variational Inference

ELBO Objective

Sample New Data

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, VAE ki asli baat samajhne ke liye ek image ko "meaning space" mein compress karne ka socho — jahan similar images paas-paas hoti hain. Simple autoencoder is space mein gaps aur weird clusters bana deta hai, jisse tum us space se random point uthakar valid image nahi bana sakte. VAE isko solve karta hai do tareeke se: pehla, woh compressed codes ko ek normal (Gaussian) distribution follow karne pe majboor karta hai taaki space smooth ho aur gaps na rahein; doosra, model ko probabilistic banata hai — matlab single point nahi, balki ek distribution output karta hai. Isse tum latent space se koi bhi point sample karke usse ek realistic naya image generate kar sakte ho. Yahi generative power hai jo VAE ko special banati hai.

Ab maths side pe — hum chahte hain ki pθ(x)p_\theta(\mathbf{x}) maximize ho, lekin uske liye humein saare possible latent codes z\mathbf{z} pe integrate karna padta hai, jo high dimensions mein computationally impossible hai (intractable). Isliye ek smart trick lagate hain: ek encoder network qϕ(zx)q_\phi(\mathbf{z}|\mathbf{x}) introduce karte hain jo true posterior ko approximate karta hai. Fir Jensen's inequality use karke hum ek lower bound nikalte hain jise ELBO kehte hain. ELBO ke do parts hote hain — pehla reconstruction quality (image kitni achhi wapas banti hai) aur doosra KL divergence (latent space kitna organized hai, prior ke kitna kareeb hai). In dono ke beech balance banana hi VAE training ka core hai.

Yeh cheez isliye important hai kyunki VAE tumhe ek principled, mathematically sound tareeka deta hai naya data generate karne ka — na ki sirf memorize karke copy paste karna. Real world mein iska use hota hai image generation, anomaly detection, aur data compression jaise applications mein. Aur sabse badi baat, ELBO derivation samajhne se tumhe variational inference ka foundation clear ho jaata hai, jo modern deep generative models — jaise diffusion models tak — mein baar-baar aata hai. Toh yeh concept ek building block hai jispe aage bahut kuch khada hai.

Go deeper — visual, from zero

Test yourself — Generative Models

Connections