From Reconstruction to Generation: VAEs and GANs
Bridge deterministic autoencoders to probabilistic generative models: examine Variational Autoencoders (VAEs) with the reparameterization trick and KL divergence, and Generative Adversarial Networks (GANs) with minimax game theory, mode collapse, and Wasserstein stabilization.
Contentsand lesson path
On this page
Lessons of Autoencoders & Generative Models
- Squeeze and Rebuild: What Autoencoders Learn Concept · 20 min
- Lab: Denoising and Anomaly Detection with an Autoencoder Lab · 30 min
- From Reconstruction to Generation: VAEs and GANs Concept · 25 min
- Diffusion Models: Learning to Undo Noise Concept · 25 min
- Lab: Generate, Adapt with LoRA and Evaluate a Diffusion Model Lab · 30 min
- Check: Choosing and Judging a Generative Model Knowledge check · 8 questions
What you will learn
- Explain how a variational autoencoder (latent prior, reparameterization trick, reconstruction plus KL loss) and a GAN (generator against discriminator) turn learned representations into generators, and recognize posterior collapse, mode collapse and unstable adversarial training.
Prerequisites: Deep Learning Fundamentals
01. Probabilistic Formulation and Adversarial Dynamics
While deterministic autoencoders excel at dimensionality reduction and reconstruction, transforming representation learners into true generative models requires defining a continuous, well-behaved probability distribution over the latent space. If any arbitrary sample drawn from a standard prior $p(z) = \mathcal{N}(0, I)$ can be decoded into a realistic, plausible data point, the model becomes genuinely generative. Two breakthrough paradigms solved this challenge in fundamentally different ways: Variational Autoencoders (VAEs) via variational Bayesian inference, and Generative Adversarial Networks (GANs) via game-theoretic adversarial competition.
-
Variational Autoencoders (VAEs): Learning Latent Probability Distributions: Introduced by Kingma & Welling (2013), a VAE replaces the deterministic encoder with a probabilistic encoder that outputs the parameters of a conditional Gaussian distribution: mean vector $\mu_\phi(x)$ and log-variance vector $\log \sigma^2_\phi(x)$. Instead of mapping an image to a single fixed point in $\mathbb{R}^d$, the encoder maps it to an elliptical probability cloud in latent space.
-
The Evidence Lower Bound (ELBO): Because the true marginal data log-likelihood $\log p_\theta(x) = \log \int p_\theta(x, z) dz$ is intractable, VAEs maximize the Evidence Lower Bound (ELBO), or equivalently minimize its negative:
$$\mathcal{L}{\text{VAE}}(\theta, \phi; x) = -\mathbb{E}{q_\phi(z \mid x)}[\log p_\theta(x \mid z)] + D_{\text{KL}}(q_\phi(z \mid x) \parallel p(z))$$
-
1. Reconstruction Term ($-\mathbb{E}[\log p_\theta(x \mid z)]$): Penalizes differences between the reconstructed output $\hat{x}$ and the input $x$ (evaluated via MSE or binary cross-entropy), ensuring high reconstruction fidelity.
-
2. Regularization Term ($D_{\text{KL}}$): The Kullback-Leibler divergence measures the statistical distance between the encoder's posterior distribution $q_\phi(z \mid x)$ and the standard Gaussian prior $p(z) = \mathcal{N}(0, I)$. It forces all latent clusters toward the origin and penalizes variance deviations. This regularization guarantees that the latent space remains smooth, continuous, and free of empty gaps, allowing users to sample $z \sim \mathcal{N}(0, I)$ at inference time and generate novel instances.
-
The Reparameterization Trick: If a network samples $z \sim \mathcal{N}(\mu, \sigma^2 I)$ directly, the stochastic sampling operation breaks backpropagation because random number generation is non-differentiable. The reparameterization trick isolates the stochasticity into an auxiliary independent noise variable $\epsilon \sim \mathcal{N}(0, I)$:
$$z = \mu_\phi(x) + \sigma_\phi(x) \odot \epsilon, \quad \text{where } \epsilon \sim \mathcal{N}(0, I)$$
Now, gradients $\frac{\partial \mathcal{L}}{\partial \mu}$ and $\frac{\partial \mathcal{L}}{\partial \sigma}$ can flow cleanly through deterministic arithmetic operations back into the encoder neural network.
- Generative Adversarial Networks (GANs): Minimax Two-Player Games:
Proposed by Goodfellow et al. (2014), GANs discard the explicit probability density estimation of VAEs in favor of an implicit generative process governed by a two-player zero-sum game:
- Generator ($G_\theta$): Takes a random noise vector $z \sim p_z(z)$ and attempts to map it to a synthetic sample $G(z)$ that mimics the true data distribution $p_{\text{data}}$.
- Discriminator ($D_\phi$): Takes either a real sample $x$ or a generated sample $G(z)$ and outputs a scalar probability $D(x) \in [0, 1]$ indicating whether the input is genuine.
- Minimax Objective Function:
$$\min_G \max_D V(D, G) = \mathbb{E}{x \sim p{\text{data}}}[\log D(x)] + \mathbb{E}_{z \sim p_z}[\log(1 - D(G(z)))]$$
-
GAN Failure Modes and Wasserstein Stabilization:
- Mode Collapse: The generator discovers a single realistic output (e.g., generating only one specific handwritten digit "8") that consistently fools the discriminator, ignoring the full diversity of the target distribution.
- Vanishing Gradients: When the discriminator achieves near-perfection ($D(x) \approx 1, D(G(z)) \approx 0$), the $\log(1 - D(G(z)))$ loss saturates, providing zero gradient signal to update the generator.
- Wasserstein GAN with Gradient Penalty (WGAN-GP): Arjovsky et al. (2017) reformulated GAN training by replacing the Jensen-Shannon divergence with the Earth Mover's (Wasserstein-1) Distance. The discriminator becomes a "Critic" $D_w(x)$ constrained to be 1-Lipschitz continuous by penalizing the norm of its gradient $(|\nabla_{\hat{x}} D_w(\hat{x})|_2 - 1)^2$. WGAN provides smooth, monotonically meaningful loss curves that correlate directly with generated sample quality, eliminating mode collapse and gradient vanishing.
-
Trade-Offs Between VAEs and GANs: VAEs offer stable training, explicit likelihood lower bounds, and well-structured continuous latent spaces ideal for smooth interpolation; however, their pixel-space reconstruction loss often causes generated images to appear overly smooth or blurry. Conversely, GANs produce remarkably sharp, photorealistic high-frequency details, but suffer from brittle training dynamics, hyperparameter sensitivity, and lack of an explicit latent density formulation.
-
The $\beta$-VAE Formulation and Representation Disentanglement: Standard VAEs frequently fail to isolate independent factors of variation (such as 3D object rotation, illumination angle, and object scale). Higgins et al. (2017) introduced $\beta$-VAE, modulating the KL divergence penalty with hyperparameter $\beta > 1$:
$$\mathcal{L}{\beta}(\theta, \phi; x) = -\mathbb{E}{q_\phi(z \mid x)}[\log p_\theta(x \mid z)] + \beta D_{\text{KL}}(q_\phi(z \mid x) \parallel p(z))$$
Elevating $\beta$ forces the diagonal covariance prior to impose statistical independence across latent channels, producing disentangled representations where traversing single latent coordinates corresponds to intuitive physical transformations.
-
Game-Theoretic Limit Cycles and Spectral Normalization in GANs: Simultaneous gradient descent in zero-sum minimax games does not guarantee convergence to Nash equilibria; instead, optimizer trajectories can enter rotational limit cycles where Generator and Critic oscillate indefinitely. To enforce the 1-Lipschitz continuity required by Wasserstein theory, Miyato et al. introduced Spectral Normalization, dividing the weight matrix of every Critic layer by its largest singular value (spectral norm $\sigma(W)$ computed via fast power iteration). Combined with the Two Time-Scale Update Rule (TTUR, updating Critic at a higher learning rate than Generator), Spectral Normalization stabilizes adversarial dynamics without requiring extensive hyperparameter sweeps.
-
Precision and Recall Trade-Offs in Generative Modeling: Evaluating generative distributions requires distinguishing between sample quality and sample diversity. Sajjadi et al. (2018) formalized Precision and Recall for Distributions: Precision measures what fraction of generated samples reside within the true data manifold (photorealism without visual artifacts), while Recall measures what fraction of the true data manifold is covered by generated samples (absence of mode dropping). Practitioners recognize that GANs historically prioritized Precision at the expense of Recall, whereas VAEs provided broad Recall while compromising on local Precision.
import torch
import torch.nn as nn
class VariationalEncoder(nn.Module):
def __init__(self, in_dim=64, latent_dim=8):
super().__init__()
self.shared = nn.Linear(in_dim, 32)
self.fc_mu = nn.Linear(32, latent_dim)
self.fc_logvar = nn.Linear(32, latent_dim)
def forward(self, x):
h = torch.relu(self.shared(x))
mu = self.fc_mu(h)
logvar = self.fc_logvar(h)
# Reparameterization trick
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
z = mu + std * eps
return z, mu, logvar
def compute_elbo_loss(recon_x, x, mu, logvar):
recon_loss = nn.functional.mse_loss(recon_x, x, reduction="sum")
# Analytical KL divergence between N(mu, sigma^2) and N(0, I)
kl_div = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return recon_loss + kl_div
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.