Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 20: Generative Models: VAEs, GANs and Diffusion

Open in Colab

What I cannot create, I do not understand.

Richard Feynman (on his blackboard, 1988)

20.1 Learning to Generate

A classifier learns p(y∣x)p(y \mid x): given an image, which digit is it? A generative model learns about p(x)p(x) itself, well enough to draw new samples that look like the training data: new faces, new sentences, new molecules. Three families dominate:

  • Variational autoencoders (VAEs): an autoencoder whose code space is made regular enough to sample from.

  • Generative adversarial networks (GANs): a generator trained against a discriminator that tries to tell its output from real data.

  • Diffusion models: a network that learns to remove noise, step by step, starting from pure noise.

We use two datasets: scikit-learn’s digits (8×8 images), and a two-dimensional toy distribution, eight Gaussian clusters on a ring, where we can see every sample and count how many clusters a model covers.

1797 digits of 64 pixels in [0, 1]

20.2 Variational Autoencoders

An autoencoder (Chapter 18) compresses an input xx into a code zz and rebuilds it. Its code space has no reason to be regular: codes of training images may be scattered with gaps, and decoding a random point gives garbage. A VAE (Kingma and Welling, 2014) fixes that in two ways:

  1. The encoder outputs a distribution for each input, a mean μ(x)\mu(x) and a variance σ2(x)\sigma^2(x), and zz is sampled from it. Nearby codes must then decode to similar images.

  2. The loss adds a term that pulls every such distribution towards the standard normal N(0,I)\mathcal{N}(0, I):

L=−log⁡p(x∣z)⏟reconstruction+KL(N(μ,σ2) ∥ N(0,I))⏟regularisation,KL=−12∑(1+log⁡σ2−μ2−σ2)\mathcal{L} = \underbrace{-\log p(x \mid z)}_{\text{reconstruction}} + \underbrace{\mathrm{KL}\big(\mathcal{N}(\mu, \sigma^2) \,\|\, \mathcal{N}(0, I)\big)}_{\text{regularisation}}, \qquad \mathrm{KL} = -\tfrac12 \sum \big(1 + \log \sigma^2 - \mu^2 - \sigma^2\big)

The sum is (minus) the evidence lower bound (ELBO) on log⁡p(x)\log p(x). To generate, sample z∼N(0,I)z \sim \mathcal{N}(0, I) and decode it.

The reparameterisation trick. Backpropagation cannot go through a random draw. Write the draw as z=μ+σ⊙εz = \mu + \sigma \odot \varepsilon with ε∼N(0,I)\varepsilon \sim \mathcal{N}(0, I): the randomness is now an input, and zz is a differentiable function of μ\mu and σ\sigma.

VAE with a 2-D code: reconstruction 21.9, KL 2.47 (nats per digit)
VAE with a 8-D code: reconstruction 20.7, KL 3.37 (nats per digit)
71 s

With a two-dimensional code, the whole space of digits can be drawn: each training digit placed at its mean code μ(x)\mu(x), coloured by its label; and, on the right, the decoder’s output on a regular grid of codes.

Source
<Figure size 1200x540 with 3 Axes>
<Figure size 1100x140 with 10 Axes>

The digits of each class gather in their own region of the code plane, and the regions touch: there are no large empty gaps, because the KL term keeps every code close to N(0,I)\mathcal{N}(0, I). Decoding a grid of codes, one digit turns smoothly into its neighbours. The price of that regularity is in the numbers: the KL term costs 2.47 nats per digit with a 2-D code (3.37 with 8), and the reconstruction is worse than a plain autoencoder’s. New digits sampled from N(0,I)\mathcal{N}(0, I) and decoded by the 8-D VAE are recognisable but blurry: a VAE is rewarded for the average of the images an uncertain code could stand for, a known weakness of the family.

20.3 Generative Adversarial Networks

A GAN (Goodfellow et al., 2014) has no encoder and no explicit likelihood. A generator GG turns random noise zz into a sample; a discriminator DD outputs the probability that its input is real. They play a game:

min⁡Gmax⁡D  Ex∼data[log⁡D(x)]+Ez[log⁡(1−D(G(z)))]\min_G \max_D \; \mathbb{E}_{x \sim \text{data}}[\log D(x)] + \mathbb{E}_{z}[\log(1 - D(G(z)))]

DD is trained like a classifier (real = 1, generated = 0); GG is trained to make DD say 1 on its samples. In practice GG maximises log⁡D(G(z))\log D(G(z)) (the non-saturating loss), because early on, when DD easily rejects GG’s samples, log⁡(1−D(G(z)))\log(1 - D(G(z))) is flat and gives almost no gradient. At the game’s equilibrium, GG’s samples have the data’s distribution and DD outputs 12\tfrac12 everywhere.

On the ring of eight clusters, with Adam (β1=0.5\beta_1 = 0.5, as is usual for GANs):

step  500: 8 of 8 clusters covered, 0.18 of the samples near a cluster
step 1000: 8 of 8 clusters covered, 0.51 of the samples near a cluster
step 1500: 8 of 8 clusters covered, 0.75 of the samples near a cluster
step 2000: 8 of 8 clusters covered, 0.83 of the samples near a cluster
step 2500: 8 of 8 clusters covered, 0.86 of the samples near a cluster
step 3000: 8 of 8 clusters covered, 0.88 of the samples near a cluster
35 s
Source
<Figure size 1400x360 with 4 Axes>

From step 500 the generator already reaches all eight clusters, but only 18% of its samples lie near one; by step 3 000, 88% do. The samples tighten onto the clusters as the discriminator learns where real data are, and the generator follows.

20.4 Training GANs

GANs are notoriously hard to train. The two networks chase each other, and nothing guarantees that this game converges: the losses do not tell you how good the samples are, and small changes of settings change the outcome. The classic failure is mode collapse: the generator finds a few outputs that fool the discriminator and produces only those. The same GAN, with Adam’s default β1=0.9\beta_1 = 0.9 and a learning rate of 2×10−32 \times 10^{-3}, and two seeds:

seed 0: step 500: 2 clusters, 0.08; step 1000: 2 clusters, 0.08; step 1500: 1 clusters, 0.02; step 2000: 6 clusters, 0.07; step 2500: 8 clusters, 0.47; step 3000: 8 clusters, 0.63
seed 1: step 500: 1 clusters, 0.00; step 1000: 8 clusters, 0.17; step 1500: 8 clusters, 0.37; step 2000: 8 clusters, 0.64; step 2500: 8 clusters, 0.78; step 3000: 8 clusters, 0.88
Source
<Figure size 1050x360 with 3 Axes>

With seed 0, training goes wrong: from step 500 to step 1 500 the samples bunch together and reach only one or two of the eight clusters, with at most 8% of them near a cluster. The generator escapes only after step 2 000, and ends at 63%. With seed 1, the same settings recover by step 1 000 and end at 88%. Same data, same networks, same settings, different random start: GAN training is a dynamical system, not a minimisation, and a run can stall or collapse without warning.

What helps, from experience and theory:

  • Adam with β1=0.5\beta_1 = 0.5 and equal, small learning rates for both networks (Radford et al., 2016, DCGAN).

  • Batch normalisation in the generator, LeakyReLU in the discriminator, no pooling (strided convolutions instead) for images.

  • Label smoothing (real labels 0.9 instead of 1) so the discriminator does not become over-confident.

  • Losses that give useful gradients even when the discriminator wins: the Wasserstein GAN (Arjovsky et al., 2017) replaces the classifier by a critic with bounded slope, and its loss tracks sample quality.

  • Watch the samples, not the losses, and measure quality and diversity: the Fréchet Inception Distance (FID) compares the statistics of Inception-network features of real and generated images (lower is better).

GANs on images use convolutions (DCGAN, StyleGAN); the principle is the same. A small fully connected GAN on the digits:

<Figure size 1100x140 with 10 Axes>
23 s

The samples are sharper than the VAE’s, but noisier, and several look alike: even on this small problem, the generator favours a few shapes.

20.5 Diffusion Models

Diffusion models (Sohl-Dickstein et al., 2015; Ho et al., 2020, DDPM) generate by denoising. The idea in two processes:

Forward (fixed). Add a little Gaussian noise to a data point, TT times, with a schedule β1,…,βT\beta_1, \dots, \beta_T. After enough steps nothing of the data is left: xTx_T is pure noise. With αˉt=∏s≤t(1−βs)\bar\alpha_t = \prod_{s \le t}(1 - \beta_s), any step can be reached directly:

xt=αˉt x0+1−αˉt ε,ε∼N(0,I)x_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\, \varepsilon, \qquad \varepsilon \sim \mathcal{N}(0, I)

Reverse (learned). Train a network εθ(xt,t)\varepsilon_\theta(x_t, t) to predict the noise ε\varepsilon that was added, with a plain mean squared error. To generate, start from pure noise xTx_T and remove the predicted noise one step at a time:

xt−1=11−βt(xt−βt1−αˉt εθ(xt,t))+βt zx_{t-1} = \frac{1}{\sqrt{1-\beta_t}}\Big(x_t - \frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\, \varepsilon_\theta(x_t, t)\Big) + \sqrt{\beta_t}\, z

Training is as stable as regression: no adversary, no game. The price is sampling: TT network evaluations per sample instead of one.

T = 100; after the last step, sqrt(abar) = 0.075 of the data remains
diffusion on the ring: 8 of 8 clusters covered, 0.87 of the samples near a cluster (11 s)
Source
<Figure size 1600x340 with 5 Axes>

All eight clusters, with 87% of the samples near one, on the first attempt, with default settings and no adversary. The pictures show the reverse process: the cloud of noise stays shapeless for most of the steps, and the clusters form in the last quarter.

The same recipe on the digits (each image a 64-dimensional point, scaled to [−1,1][-1, 1]):

<Figure size 1100x140 with 10 Axes>
44 s

Recognisable digits, among them 0s, 6s and 9s, from a three-layer network trained only to predict noise. They are less blurry than the VAE’s, and more varied than the GAN’s.

Real image diffusion models use a U-Net (a convolutional network with skip connections) or a Transformer as εθ\varepsilon_\theta, about 1 000 steps, and guidance to steer sampling, for example by a text prompt encoded by a language model (Stable Diffusion, DALL·E). Faster samplers (DDIM) skip most steps, and latent diffusion runs the process in an autoencoder’s compact code space instead of on pixels.

20.6 Comparing the Three Families

VAEGANDiffusion
How it learnsmaximise a lower bound on log⁡p(x)\log p(x)a game against a discriminatorregress the added noise
Trainingstableunstable; mode collapsestable
Sample qualityblurrysharpsharp
Diversitygoodcan miss modesgood
Sampling speedone passone passmany passes (tens to 1 000)
Has an encoderyesnono (a fixed noising process)
Typical usecompression, latent spaces, anomaly detectionfast high-resolution images, style transfertoday’s text-to-image and video models

Generative models raise questions classifiers do not: realistic fake images and voices, the copyright of training data, and memorised training examples appearing in outputs (Chapter 12).

20.7 Summary

  • A generative model learns the data’s distribution well enough to sample from it.

  • A VAE encodes each input as a distribution, regularises it towards N(0,I)\mathcal{N}(0, I) with a KL term, and decodes samples from it; the reparameterisation trick makes it trainable.

  • A GAN trains a generator against a discriminator; it gives sharp samples but is unstable and can collapse onto a few modes.

  • A diffusion model learns to predict the noise added to data, and generates by denoising pure noise step by step: stable training, excellent samples, slow sampling.

Exercises

  1. For a VAE with μ=0.5\mu = 0.5 and log⁡σ2=0\log\sigma^2 = 0 for a one-dimensional code, compute the KL term. What values minimise it?

  2. Why can backpropagation not go through z∼N(μ,σ2)z \sim \mathcal{N}(\mu, \sigma^2), and how does z=μ+σεz = \mu + \sigma\varepsilon fix it?

  3. At the equilibrium of a GAN, what does the discriminator output for any input? Why?

  4. Explain why the generator’s loss log⁡(1−D(G(z)))\log(1 - D(G(z))) gives almost no gradient early in training, and what the non-saturating loss changes.

  5. A GAN’s samples all look like 1s and 7s. Name the failure, and two things you would try.

  6. With αˉt=0.25\bar\alpha_t = 0.25, write xtx_t in terms of x0x_0 and ε\varepsilon. How much of the signal is left?

  7. Why is training a diffusion model more stable than training a GAN? What does it cost in exchange?

Further Reading

  • D. Kingma, M. Welling, “Auto-encoding variational Bayes”, ICLR, 2014.

  • I. Goodfellow et al., “Generative adversarial nets”, NeurIPS, 2014.

  • A. Radford, L. Metz, S. Chintala, “Unsupervised representation learning with deep convolutional GANs” (DCGAN), ICLR, 2016.

  • M. Arjovsky, S. Chintala, L. Bottou, “Wasserstein GAN”, ICML, 2017.

  • J. Ho, A. Jain, P. Abbeel, “Denoising diffusion probabilistic models”, NeurIPS, 2020.

  • R. Rombach et al., “High-resolution image synthesis with latent diffusion models”, CVPR, 2022.