Generative models I: VAEs and GANs
Learning p(x): latent variables, the ELBO, and the adversarial game
Everything in this phase so far generates text one token at a time. Images, audio and molecules need other ways to learn a distribution and sample from it. Variational autoencoders introduce the latent-variable view and the ELBO — the same bound that reappears in diffusion (8.9 Generative models II: Diffusion and flow matching) — and GANs introduce adversarial training, which survives today in distillation and perceptual losses. The derivations lean on Bayes and MLE from 1.7 Probability II: Bayes, independence, MLE and MAP, KL from 1.9 Information theory: entropy, cross-entropy and KL divergence, and the encoder–decoder vocabulary from 4.10 Autoencoders, embeddings and representation learning.
You'll be able to
- Explain the latent-variable formulation of generative modeling and why the likelihood is intractable
- Derive the ELBO with Jensen's inequality and interpret its two terms
- Implement the reparameterization trick and the closed-form Gaussian KL
- Write the GAN minimax objective, derive the optimal discriminator and connect it to JS divergence
- Describe mode collapse, WGAN, and where VAEs and GANs are still used in 2026
Key ideas
- Generative models learn p(x) to sample, score and represent data; families trade off quality, diversity, likelihood and speed.
- VAEs posit z ~ N(0, I) and a decoder p_θ(x|z); the marginal likelihood is intractable, so an encoder q_φ(z|x) approximates the posterior.
- ELBO = E_q[log p_θ(x|z)] − KL(q_φ(z|x) ‖ p(z)); the gap to log p(x) is KL(q ‖ true posterior), so maximizing the ELBO tightens both.
Show 4 more key ideas
- The reparameterization z = μ + σ ⊙ ε makes sampling differentiable; the Gaussian-to-standard-normal KL has a closed form.
- GANs play min_G max_D E[log D(x)] + E[log(1 − D(G(z)))]; D* = p_data/(p_data + p_g), so at optimum G minimizes JS divergence.
- Mode collapse and vanishing gradients plague GANs; WGAN's Wasserstein critic, spectral norm and StyleGAN's design were the main fixes.
- Today VAEs compress latents for diffusion models and tokenize images/audio; adversarial losses persist in distillation and perceptual training.
Suggested path through this lesson
Generative modeling: learn
A discriminative model learns ; a generative model learns the data distribution itself, so it can sample new data, score how likely an input is, and often represent data in a useful latent space. The main families: autoregressive models (7.6 Decoder-only: GPT and autoregressive generation — exact likelihood, slow sampling), latent-variable models (VAEs), adversarial models (GANs), and diffusion/flow models (8.9 Generative models II: Diffusion and flow matching). Each trades off sample quality, diversity/coverage, likelihood evaluation and sampling speed.
Latent variables and the intractable integral
Assume data is produced by first drawing a latent code from a simple prior , then decoding it with a neural network: . The marginal likelihood is
an integral over all codes — intractable for a nonlinear decoder, as is the posterior we would need to infer codes. Variational inference replaces the true posterior with a learned encoder , typically a diagonal Gaussian .
The ELBO, derived
Multiply and divide by inside the log and apply Jensen's inequality ( is concave, so ):
This is the evidence lower bound (ELBO). The gap is exactly — you can verify by expanding the posterior with Bayes' rule (1.7 Probability II: Bayes, independence, MLE and MAP). Maximizing the ELBO therefore raises the likelihood and pulls the encoder toward the true posterior.
The two terms have plain meanings. With a Gaussian decoder of fixed variance, the reconstruction term is a negative squared error; with a Bernoulli decoder it is a negative binary cross-entropy (4.3 Loss functions catalog). The KL between the diagonal-Gaussian encoder and the standard-normal prior has a closed form:
which is zero only when the encoder outputs the prior exactly — it keeps the latent space smooth and centered so that sampling at test time lands on codes the decoder understands.
The reparameterization trick
The reconstruction term needs gradients through a random sample . Write the sample as a deterministic function of the parameters and fresh noise:
Now the randomness is in , which does not depend on , and gradients flow through and with far lower variance than score-function (REINFORCE, 4.11 Reinforcement learning essentials) estimators. The whole model trains end to end with a single Monte Carlo sample per example.
mu, logvar = encoder(x)
z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu) # reparameterize
x_hat = decoder(z)
recon = F.binary_cross_entropy_with_logits(x_hat, x, reduction="sum")
kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
loss = recon + kl # negative ELBO
VAE pathologies and variants
- Blurry samples: a pixel-wise Gaussian likelihood rewards averaging over plausible outputs.
- Posterior collapse: a powerful decoder ignores , the KL term goes to zero and the latent space carries nothing; remedies include KL annealing and weaker decoders.
- β-VAE weights the KL term by to encourage disentangled factors at the cost of reconstruction.
- VQ-VAE replaces the Gaussian latent with a learned codebook of discrete codes, giving tokens that autoregressive models can predict — the route taken by DALL·E 1, modern image tokenizers and neural audio codecs (8.10 Multimodal models).
- Most importantly, VAEs are the compressors inside latent diffusion (8.9 Generative models II: Diffusion and flow matching): Stable Diffusion's VAE maps a 512×512 image to a 64×64×4 latent and back.
GANs: a two-player game
A generator maps noise to a sample; a discriminator outputs the probability that an input is real. They play
Optimal discriminator. For a fixed with sample distribution , maximize pointwise with , ; setting the derivative to zero gives
Substituting back, the generator's objective becomes : at the discriminator's optimum, the generator minimizes the Jensen–Shannon divergence to the data, with global minimum . In practice maximizes instead of minimizing — the non-saturating loss — because the original saturates when confidently rejects early samples.
Why GANs are hard, and the fixes
- Mode collapse: produces a few convincing modes and ignores the rest of the data.
- Vanishing gradients: when real and generated distributions have disjoint support, JS divergence saturates and gives no useful signal. WGAN replaces it with the Wasserstein (earth-mover) distance, estimated by a critic constrained to be 1-Lipschitz (via gradient penalty or spectral normalization), restoring smooth gradients.
- Architecture and tricks: DCGAN's convolutional guidelines, two-time-scale updates, feature matching; StyleGAN's mapping network and per-layer style modulation gave photorealistic faces and a controllable latent space; CycleGAN learned unpaired image-to-image translation with cycle-consistency losses.
- Evaluation: Fréchet Inception Distance (FID) compares Gaussian fits of Inception features of real and generated images; precision/recall metrics separate quality from coverage.
2026: where VAEs and GANs live now
Diffusion and flow models (8.9 Generative models II: Diffusion and flow matching) won image and video generation on stability, diversity and scalability. But VAEs are everywhere as latent compressors and tokenizers, and adversarial losses survive as perceptual/adversarial terms in those compressors, in super-resolution, and in adversarial diffusion distillation that turns 50-step samplers into 1–4 step generators. Knowing both families is still essential.
Where this shows up later
- The ELBO and the KL-to-prior reappear, term by term, in diffusion models — 8.9 Generative models II: Diffusion and flow matching.
- VQ-VAE codes become the image and audio tokens of multimodal LLMs — 8.10 Multimodal models.
- Encoder/decoder vocabulary and autoencoders — 4.10 Autoencoders, embeddings and representation learning; the same KL divergence regularizes RLHF — 8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI.
Common pitfalls (4)
- Forgetting the KL term and training a plain autoencoder, then wondering why random z decodes to garbage.
- Sampling z inside the encoder without reparameterization — gradients cannot flow through torch.randn.
- Judging a GAN by sample quality alone while it has collapsed to a few modes; check coverage (recall) too.
- Assuming GANs are obsolete; adversarial losses are still inside the compressors and distillers of current image models.
Recap: all 7 key points
- Generative models learn p(x) to sample, score and represent data; families trade off quality, diversity, likelihood and speed.
- VAEs posit z ~ N(0, I) and a decoder p_θ(x|z); the marginal likelihood is intractable, so an encoder q_φ(z|x) approximates the posterior.
- ELBO = E_q[log p_θ(x|z)] − KL(q_φ(z|x) ‖ p(z)); the gap to log p(x) is KL(q ‖ true posterior), so maximizing the ELBO tightens both.
- The reparameterization z = μ + σ ⊙ ε makes sampling differentiable; the Gaussian-to-standard-normal KL has a closed form.
- GANs play min_G max_D E[log D(x)] + E[log(1 − D(G(z)))]; D* = p_data/(p_data + p_g), so at optimum G minimizes JS divergence.
- Mode collapse and vanishing gradients plague GANs; WGAN's Wasserstein critic, spectral norm and StyleGAN's design were the main fixes.
- Today VAEs compress latents for diffusion models and tokenize images/audio; adversarial losses persist in distillation and perceptual training.
Watch
The ELBO derivation and the reparameterization trick, slowly and precisely.
Read
Exercises
- Derive the ELBO gap
Show that by writing inside the expectation. Then derive the closed-form KL between and in one dimension.
- Train a VAE on MNIST
Implement a 2-D latent VAE in PyTorch, train 10 epochs, and plot (a) the latent space colored by digit and (b) a grid of decoded samples over a grid of codes. Expected: digits arranged in a continuous map; blurry but recognizable samples. Then set the KL weight to 0 and watch sampling break.
- Optimal discriminator numerically
On 1-D data with and , compute on a grid and verify by numerical integration. Expected: exactly.
- Observe mode collapse
Train a small GAN on a mixture of eight 2-D Gaussians arranged in a ring. Plot generated points every 500 steps. Expected: at some point the generator covers only a subset of modes; then add a gradient penalty (WGAN-GP) and compare coverage.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →