Loading learning content...
Read aloud is unavailable in this browser.
Variational Autoencoders (VAEs) represent one of the most elegant intersections of probabilistic reasoning and deep learning. Introduced by Kingma and Welling in 2013, VAEs solved a fundamental problem: how do we learn meaningful latent representations while simultaneously building generative models that can synthesize new data?
Before VAEs, autoencoders could compress data but lacked probabilistic structure. Generative models like GMMs could model distributions but struggled with high-dimensional data like images. VAEs unified these worlds—creating a principled framework where neural networks learn to encode observations into structured latent spaces, and then decode from those spaces to generate new samples.
This page develops the complete mathematical formulation of VAEs from first principles. We'll see how the Evidence Lower Bound (ELBO) emerges naturally from variational inference, why it provides a tractable objective for deep learning, and how this formulation enables both generation and representation learning.
By the end of this page, you will understand the probabilistic foundations of VAEs, derive the ELBO objective from variational inference principles, see how intractable posteriors necessitate the VAE architecture, and appreciate why VAEs became foundational to modern generative modeling. This isn't just about formulas—it's about understanding why VAEs work.
At its core, generative modeling asks: given a dataset of observations ${x^{(1)}, x^{(2)}, ..., x^{(N)}}$, can we learn the underlying distribution $p(x)$ that generated them?
If we could model $p(x)$ accurately, we could:
The challenge is that real-world data—images, audio, text—lives in extremely high-dimensional spaces with complex dependencies. A 256×256 color image has 196,608 dimensions. Modeling the joint distribution over all pixels directly is intractable.
High-dimensional data like images doesn't fill the entire pixel space uniformly. Real images occupy a tiny, lower-dimensional manifold within that space. A random collection of pixel values almost never looks like a real image. This suggests that underlying low-dimensional latent factors generate the observed high-dimensional data.
VAEs embrace this intuition by introducing latent variables $z$ that capture the underlying factors of variation. The generative process becomes:
This defines the generative model:
$$p_\theta(x) = \int p(z) \cdot p_\theta(x|z) , dz$$
Here:
The elegance of this setup: we use a simple prior $p(z)$ (easy to sample) combined with a powerful, learnable decoder $p_\theta(x|z)$ (neural network) to model arbitrarily complex $p_\theta(x)$.
| Component | Mathematical Form | Role | Implementation |
|---|---|---|---|
| Prior $p(z)$ | $\mathcal{N}(0, I)$ | Regularizes latent space | Fixed distribution (no parameters) |
| Likelihood $p_\theta(x|z)$ | Neural network decoder | Maps latent code to observation | Deep network outputting distribution params |
| Marginal $p_\theta(x)$ | $\int p(z) p_\theta(x|z) dz$ | The actual data distribution | Intractable integral |
| Posterior $p_\theta(z|x)$ | $\frac{p(z) p_\theta(x|z)}{p_\theta(x)}$ | Infers latent code from data | Intractable (requires marginal) |
The marginal likelihood $p_\theta(x) = \int p(z) p_\theta(x|z) dz$ requires integrating over all possible latent codes—intractable for complex decoders. Similarly, the posterior $p_\theta(z|x)$ (what latent code explains observation $x$?) depends on this intractable marginal via Bayes' rule. We cannot directly maximize log-likelihood or compute the true posterior.
Given a dataset $\mathcal{D} = {x^{(1)}, ..., x^{(N)}}$, the natural objective is maximum likelihood estimation:
$$\theta^* = \arg\max_\theta \sum_{i=1}^{N} \log p_\theta(x^{(i)})$$
Maximizing log-likelihood finds parameters $\theta$ that make the observed data most probable under our model. This is principled, asymptotically consistent, and well-understood.
The problem: Computing $\log p_\theta(x)$ requires:
$$\log p_\theta(x) = \log \int p(z) \cdot p_\theta(x|z) , dz$$
This integral has no closed form when $p_\theta(x|z)$ is a deep neural network. We cannot evaluate the objective, let alone optimize it.
One might try estimating the integral by sampling: draw $z^{(j)} \sim p(z)$ and approximate $p_\theta(x) \approx \frac{1}{M}\sum_j p_\theta(x|z^{(j)})$. This fails catastrophically because most samples from the prior give near-zero likelihood $p_\theta(x|z^{(j)})$—random latent codes rarely explain any particular observation. The variance is astronomical.
Suppose we had access to the true posterior $p_\theta(z|x)$—the distribution over latent codes that could have generated observation $x$. Then we could:
But the posterior is also intractable:
$$p_\theta(z|x) = \frac{p(z) \cdot p_\theta(x|z)}{p_\theta(x)} = \frac{p(z) \cdot p_\theta(x|z)}{\int p(z') \cdot p_\theta(x|z') , dz'}$$
The denominator is exactly the intractable marginal likelihood. We're stuck in a loop: we need the posterior to estimate the marginal, but we need the marginal to compute the posterior.
This is precisely where variational inference comes to the rescue.
Variational inference sidesteps intractable posteriors by introducing a tractable approximation. Since we cannot compute $p_\theta(z|x)$, we'll learn a simpler distribution $q_\phi(z|x)$ that approximates it.
This inference network or encoder takes an observation $x$ and outputs parameters of a distribution over latent codes. Typically:
$$q_\phi(z|x) = \mathcal{N}(z; \mu_\phi(x), \text{diag}(\sigma^2_\phi(x)))$$
Where $\mu_\phi(x)$ and $\sigma_\phi(x)$ are neural network outputs, and $\phi$ are the network parameters.
The key insight: Instead of computing the intractable posterior, we optimize $q_\phi(z|x)$ to be as close as possible to $p_\theta(z|x)$. Closeness is measured by KL divergence:
$$D_{\text{KL}}(q_\phi(z|x) | p_\theta(z|x)) = \mathbb{E}{q\phi(z|x)}\left[\log \frac{q_\phi(z|x)}{p_\theta(z|x)}\right]$$
KL divergence measures how much one distribution differs from another, in units of nats (or bits). $D_{\text{KL}}(q | p) = 0$ if and only if $q = p$ almost everywhere. It's asymmetric and non-negative. We use $D_{\text{KL}}(q | p_\theta)$ rather than the reverse because this form leads to tractable optimization—we sample from $q$ which we control.
Let's manipulate the log-marginal likelihood to reveal a tractable objective. Starting with any observation $x$:
$$\log p_\theta(x) = \log \int p(z) \cdot p_\theta(x|z) , dz$$
We introduce $q_\phi(z|x)$ via an importance-weighting identity:
$$\log p_\theta(x) = \log \int q_\phi(z|x) \cdot \frac{p(z) \cdot p_\theta(x|z)}{q_\phi(z|x)} , dz$$
Since $\log$ is concave, Jensen's inequality gives:
$$\log p_\theta(x) \geq \int q_\phi(z|x) \log \frac{p(z) \cdot p_\theta(x|z)}{q_\phi(z|x)} , dz$$
$$= \mathbb{E}{q\phi(z|x)}\left[\log p_\theta(x|z) + \log p(z) - \log q_\phi(z|x)\right]$$
This is the Evidence Lower Bound (ELBO):
$$\text{ELBO}(\theta, \phi; x) = \mathbb{E}{q\phi(z|x)}[\log p_\theta(x|z)] - D_{\text{KL}}(q_\phi(z|x) | p(z))$$
| Term | Mathematical Expression | Interpretation | Effect on Training |
|---|---|---|---|
| Reconstruction | $\mathbb{E}{q\phi(z|x)}[\log p_\theta(x|z)]$ | Expected log-likelihood of data given latent | Trains decoder to reconstruct inputs |
| KL Regularization | $D_{\text{KL}}(q_\phi(z|x) | p(z))$ | Divergence from prior | Regularizes encoder toward prior |
| Full ELBO | Reconstruction $-$ KL | Lower bound on log evidence | Joint objective for encoder + decoder |
Maximizing the ELBO simultaneously: (1) trains the decoder to reconstruct data from latent codes, (2) trains the encoder to produce latent codes that explain the data, and (3) regularizes the latent space toward the prior. All from one principled objective derived from variational inference!
The ELBO admits multiple equivalent decompositions, each illuminating different aspects of what VAE training accomplishes.
$$\text{ELBO} = \underbrace{\mathbb{E}{q\phi(z|x)}[\log p_\theta(x|z)]}{\text{Reconstruction term}} - \underbrace{D{\text{KL}}(q_\phi(z|x) | p(z))}_{\text{KL regularizer}}$$
Reconstruction term: The expected log-probability of observation $x$ under the decoder, given latent codes sampled from the encoder. Maximizing this trains the decoder to accurately reconstruct inputs from their latent codes.
KL regularizer: How much the approximate posterior $q_\phi(z|x)$ deviates from the prior $p(z)$. Minimizing this prevents the encoder from learning arbitrarily complex posteriors—it must stay "close" to the simple prior.
Alternatively, we can show:
$$\log p_\theta(x) = \text{ELBO}(\theta, \phi; x) + D_{\text{KL}}(q_\phi(z|x) | p_\theta(z|x))$$
Since KL divergence is non-negative, ELBO ≤ log p(x), confirming it's a lower bound. The gap between ELBO and true log-likelihood is exactly the KL divergence between approximate and true posteriors.
Crucial insight: Maximizing ELBO simultaneously:
The ELBO equals log p(x) if and only if $q_\phi(z|x) = p_\theta(z|x)$—the approximate posterior equals the true posterior. More flexible variational families (e.g., normalizing flows) tighten the bound by better approximating the true posterior.
VAEs have a clean interpretation as probabilistic graphical models, connecting them to the broader literature on Bayesian modeling.
The generative process defines a directed graphical model:
$$z \rightarrow x$$
Where:
This factorizes the joint:
$$p_\theta(x, z) = p(z) \cdot p_\theta(x|z)$$
The encoder $q_\phi(z|x)$ represents amortized inference—a single neural network that outputs approximate posteriors for any input, rather than optimizing per-datapoint variational parameters.
This "runs the generative model in reverse":
$$x \rightarrow z$$
Mapping observations back to their likely latent codes.
| Direction | Model Component | Distribution | Parameters |
|---|---|---|---|
| $z \to x$ | Generative (Decoder) | $p_\theta(x|z)$ | $\theta$ (decoder weights) |
| $x \to z$ | Inference (Encoder) | $q_\phi(z|x)$ | $\phi$ (encoder weights) |
| Prior | Latent prior | $p(z) = \mathcal{N}(0, I)$ | None (fixed) |
| Joint | Full generative | $p_\theta(x, z) = p(z)p_\theta(x|z)$ | $\theta$ |
Traditional variational inference optimizes separate variational parameters for each datapoint—computationally expensive and doesn't generalize to new data.
Amortization uses a single encoder network that learns to perform inference for any input:
This is sometimes called variational autoencoding because the encoder "encodes" data into approximate posterior distributions over latent codes.
Classical autoencoders learn deterministic mappings $x \to z \to x$. VAEs extend this to probabilistic mappings: the encoder outputs a distribution $q_\phi(z|x)$, we sample $z$ from it, and the decoder defines a distribution $p_\theta(x|z)$. This probabilistic structure is what enables principled generation and uncertainty quantification.
The VAE formulation is agnostic to specific distributional choices, but standard implementations use carefully chosen forms that balance expressiveness with tractability.
$$p(z) = \mathcal{N}(z; 0, I) = \prod_{j=1}^{d} \mathcal{N}(z_j; 0, 1)$$
Why this choice?
The decoder $p_\theta(x|z)$ should match the data type:
Continuous data (images, audio): $$p_\theta(x|z) = \mathcal{N}(x; \mu_\theta(z), \sigma^2 I)$$
The decoder network outputs the mean $\mu_\theta(z)$, with fixed or learned variance. This yields a mean squared error reconstruction loss when $\sigma^2 = 1$:
$$\log p_\theta(x|z) \propto -|x - \mu_\theta(z)|^2$$
Binary data: $$p_\theta(x|z) = \prod_i \text{Bernoulli}(x_i; \pi_\theta(z)_i)$$
The decoder outputs probabilities $\pi_\theta(z) \in [0,1]^D$ (via sigmoid). This yields binary cross-entropy loss:
$$\log p_\theta(x|z) = \sum_i [x_i \log \pi_i + (1-x_i) \log(1-\pi_i)]$$
| Data Type | Likelihood | Decoder Output | Effective Loss |
|---|---|---|---|
| Continuous (normalized) | $\mathcal{N}(x; \mu_\theta(z), \sigma^2 I)$ | Mean $\mu_\theta(z)$ | MSE reconstruction |
| Binary / Binarized images | Bernoulli$(x; \pi_\theta(z))$ | Probabilities $\pi \in [0,1]$ | Binary cross-entropy |
| Count data | Poisson$(x; \lambda_\theta(z))$ | Rate $\lambda > 0$ | Poisson log-likelihood |
| Categorical / discrete | Categorical$(x; p_\theta(z))$ | Softmax probabilities | Cross-entropy |
| Mixture (complex) | Mixture of Gaussians | Means, variances, weights | Log-sum-exp of components |
Using MSE loss (Gaussian likelihood with fixed variance) on normalized images in [0,1] is common but technically incorrect—Gaussian likelihood assigns non-zero probability to values outside [0,1]. In practice it works reasonably well, but Bernoulli likelihood is more principled for binary/normalized pixel values.
For the standard VAE with Gaussian encoder and prior, the KL divergence has a beautiful closed-form solution. Let:
Where $\mu = \mu_\phi(x)$ and $\sigma = \sigma_\phi(x)$ are encoder outputs.
$$D_{\text{KL}}(q_\phi(z|x) | p(z)) = \frac{1}{2} \sum_{j=1}^{d} \left( \mu_j^2 + \sigma_j^2 - \log \sigma_j^2 - 1 \right)$$
This decomposes into per-dimension contributions:
Minimizing KL divergence pushes each latent dimension toward $\mathcal{N}(0, 1)$.
1234567891011121314151617181920212223242526272829303132
import torch def kl_divergence_gaussian(mu: torch.Tensor, log_var: torch.Tensor) -> torch.Tensor: """ Compute KL divergence between N(mu, sigma^2) and N(0, I). Args: mu: Encoder mean output, shape (batch_size, latent_dim) log_var: Encoder log-variance output, shape (batch_size, latent_dim) Returns: KL divergence summed over latent dimensions, shape (batch_size,) Derivation: D_KL(q || p) = 0.5 * sum(mu^2 + sigma^2 - log(sigma^2) - 1) = 0.5 * sum(mu^2 + exp(log_var) - log_var - 1) """ # Element-wise computation kl_per_dim = 0.5 * (mu.pow(2) + log_var.exp() - log_var - 1) # Sum over latent dimensions kl_per_sample = kl_per_dim.sum(dim=1) return kl_per_sample # Example usagebatch_size, latent_dim = 32, 64mu = torch.randn(batch_size, latent_dim)log_var = torch.randn(batch_size, latent_dim) kl = kl_divergence_gaussian(mu, log_var)print(f"KL per sample: {kl.mean().item():.4f}") # Expect positive valueThe encoder outputs log σ² rather than σ or σ² directly. This ensures numerical stability: (1) log-variance can be any real number, while variance must be positive, (2) computing σ² = exp(log σ²) is numerically stable, (3) prevents division by zero and maintains gradient flow for small variances.
The KL term acts as a regularizer on the latent space:
The tension: Reconstruction wants informative, distinctive codes; KL wants codes near the prior. This tension is fundamental to VAE learning—balancing data fidelity with latent space structure.
We've derived the complete mathematical foundation of Variational Autoencoders from first principles. Let's consolidate the key ideas:
What's next:
We've established what VAEs optimize (the ELBO) and why (variational inference). The next page explores how: the encoder-decoder neural network architecture that implements these distributions, translating mathematical abstraction into trainable models.
You now understand the probabilistic foundation of VAEs: how intractable inference leads to the ELBO objective, why the reconstruction-regularization decomposition matters, and how latent variable models connect to deep learning. Next, we'll see how encoder and decoder networks bring this formulation to life.