Chapter 20: Generative Models: VAEs, GANs and Diffusion
20.1 Learning to Generate¶
A classifier learns : given an image, which digit is it? A generative model learns about 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.
import math
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
torch.set_num_threads(4)
X, y = load_digits(return_X_y=True)
X = torch.tensor(X / 16, dtype=torch.float32)
print(f'{len(X)} digits of 64 pixels in [0, 1]')
CENTRES = torch.stack([2 * torch.cos(torch.arange(8) * 2 * math.pi / 8), 2 * torch.sin(torch.arange(8) * 2 * math.pi / 8)], 1)
def ring(n, g):
"""n points from 8 Gaussian clusters (std 0.05) on a circle of radius 2."""
c = torch.randint(0, 8, (n,), generator=g)
return CENTRES[c] + 0.05 * torch.randn(n, 2, generator=g)
def coverage(samples):
"""How many of the 8 clusters receive samples (within 0.3 of a centre), and the share of samples near any centre."""
d = torch.cdist(samples, CENTRES); near = d.min(1).values < 0.3
return int(torch.unique(d.argmin(1)[near]).numel()), float(near.float().mean())
def show_digits(imgs, title, n=10):
fig, axes = plt.subplots(1, n, figsize=(n * 1.1, 1.4))
for ax, im in zip(axes, imgs[:n]):
ax.imshow(im.reshape(8, 8), cmap='gray_r', vmin=0, vmax=1); ax.axis('off')
fig.suptitle(title, fontsize=10); plt.show()1797 digits of 64 pixels in [0, 1]
20.2 Variational Autoencoders¶
An autoencoder (Chapter 18) compresses an input into a code 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:
The encoder outputs a distribution for each input, a mean and a variance , and is sampled from it. Nearby codes must then decode to similar images.
The loss adds a term that pulls every such distribution towards the standard normal :
The sum is (minus) the evidence lower bound (ELBO) on . To generate, sample and decode it.
The reparameterisation trick. Backpropagation cannot go through a random draw. Write the draw as with : the randomness is now an input, and is a differentiable function of and .
class VAE(nn.Module):
def __init__(self, z=2):
super().__init__()
self.enc = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 2 * z)) # mean and log-variance
self.dec = nn.Sequential(nn.Linear(z, 128), nn.ReLU(), nn.Linear(128, 64)) # logits of the 64 pixels
def forward(self, x):
mu, logvar = self.enc(x).chunk(2, dim=1)
z = mu + torch.randn_like(mu) * (0.5 * logvar).exp() # reparameterisation
return self.dec(z), mu, logvar
def vae_loss(logits, x, mu, logvar):
rec = F.binary_cross_entropy_with_logits(logits, x, reduction='sum') / len(x)
kl = -0.5 * (1 + logvar - mu ** 2 - logvar.exp()).sum() / len(x)
return rec + kl, rec, kl
def train_vae(z, epochs=150):
torch.manual_seed(0); vae = VAE(z); opt = torch.optim.Adam(vae.parameters(), 1e-3); g = torch.Generator().manual_seed(0)
for ep in range(epochs):
for idx in torch.randperm(len(X), generator=g).split(64):
logits, mu, logvar = vae(X[idx]); loss, _, _ = vae_loss(logits, X[idx], mu, logvar)
opt.zero_grad(); loss.backward(); opt.step()
return vae
t0 = time.time(); vae2 = train_vae(2); vae8 = train_vae(8)
for name, v in [('2-D code', vae2), ('8-D code', vae8)]:
with torch.no_grad(): logits, mu, logvar = v(X); _, rec, kl = vae_loss(logits, X, mu, logvar)
print(f'VAE with a {name}: reconstruction {rec:.1f}, KL {kl:.2f} (nats per digit)')
print(f'{time.time() - t0:.0f} s')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 , coloured by its label; and, on the right, the decoder’s output on a regular grid of codes.
Source
with torch.no_grad(): mu = vae2.enc(X).chunk(2, 1)[0].numpy()
fig, axes = plt.subplots(1, 2, figsize=(12, 5.4))
sc = axes[0].scatter(mu[:, 0], mu[:, 1], c=y, cmap='tab10', s=6); axes[0].set_title('codes of the training digits'); fig.colorbar(sc, ax=axes[0], ticks=range(10))
grid = np.linspace(-2.2, 2.2, 15); canvas = np.zeros((15 * 8, 15 * 8))
with torch.no_grad():
for i, b in enumerate(grid[::-1]):
for j, a in enumerate(grid):
canvas[i * 8:(i + 1) * 8, j * 8:(j + 1) * 8] = torch.sigmoid(vae2.dec(torch.tensor([[a, b]], dtype=torch.float32))).reshape(8, 8).numpy()
axes[1].imshow(canvas, cmap='gray_r', extent=[-2.2, 2.2, -2.2, 2.2]); axes[1].set_title('decoded from a grid of codes')
plt.tight_layout(); plt.show()
with torch.no_grad():
show_digits(torch.sigmoid(vae8.dec(torch.randn(10, 8, generator=torch.Generator().manual_seed(3)))), 'new digits: z ~ N(0, I), decoded by the 8-D VAE')

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 . 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 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 turns random noise into a sample; a discriminator outputs the probability that its input is real. They play a game:
is trained like a classifier (real = 1, generated = 0); is trained to make say 1 on its samples. In practice maximises (the non-saturating loss), because early on, when easily rejects ’s samples, is flat and gives almost no gradient. At the game’s equilibrium, ’s samples have the data’s distribution and outputs everywhere.
On the ring of eight clusters, with Adam (, as is usual for GANs):
def train_gan(steps=3000, lr=1e-3, b1=0.5, seed=0, zdim=2, every=500):
torch.manual_seed(seed)
G = nn.Sequential(nn.Linear(zdim, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 2))
D = nn.Sequential(nn.Linear(2, 64), nn.LeakyReLU(.2), nn.Linear(64, 64), nn.LeakyReLU(.2), nn.Linear(64, 1))
oG = torch.optim.Adam(G.parameters(), lr, betas=(b1, .999)); oD = torch.optim.Adam(D.parameters(), lr, betas=(b1, .999))
g, bce, hist, snaps = torch.Generator().manual_seed(seed), nn.BCEWithLogitsLoss(), [], {}
for s in range(1, steps + 1):
real, fake = ring(128, g), G(torch.randn(128, zdim, generator=g))
lD = bce(D(real), torch.ones(128, 1)) + bce(D(fake.detach()), torch.zeros(128, 1))
oD.zero_grad(); lD.backward(); oD.step()
lG = bce(D(fake), torch.ones(128, 1)) # non-saturating: make D say "real"
oG.zero_grad(); lG.backward(); oG.step()
if s % every == 0:
with torch.no_grad(): smp = G(torch.randn(2000, zdim, generator=torch.Generator().manual_seed(1)))
hist.append((s, *coverage(smp))); snaps[s] = smp
return G, hist, snaps
t0 = time.time(); G, hist, snaps = train_gan()
for s, k, share in hist: print(f'step {s:>4}: {k} of 8 clusters covered, {share:.2f} of the samples near a cluster')
print(f'{time.time() - t0:.0f} s')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
fig, axes = plt.subplots(1, 4, figsize=(14, 3.6))
data = ring(2000, torch.Generator().manual_seed(9))
for ax, (title, pts) in zip(axes, [('data', data), ('GAN, step 500', snaps[500]), ('step 1500', snaps[1500]), ('step 3000', snaps[3000])]):
ax.scatter(pts[:, 0], pts[:, 1], s=2, alpha=.5); ax.set_title(title); ax.set_xlim(-3, 3); ax.set_ylim(-3, 3); ax.set_aspect('equal'); ax.set_xticks([]); ax.set_yticks([])
plt.tight_layout(); plt.show()
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 and a learning rate of , and two seeds:
for seed in [0, 1]:
_, h, sn = train_gan(lr=2e-3, b1=0.9, seed=seed)
print(f'seed {seed}: ' + '; '.join(f'step {s}: {k} clusters, {share:.2f}' for s, k, share in h))
if seed == 0: collapsed = snseed 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
fig, axes = plt.subplots(1, 3, figsize=(10.5, 3.6))
for ax, s in zip(axes, [1000, 1500, 3000]):
pts = collapsed[s]; ax.scatter(pts[:, 0], pts[:, 1], s=2, alpha=.5); ax.scatter(CENTRES[:, 0], CENTRES[:, 1], marker='x', c='k')
ax.set_title(f'β1 = 0.9, seed 0, step {s}'); ax.set_xlim(-3, 3); ax.set_ylim(-3, 3); ax.set_aspect('equal'); ax.set_xticks([]); ax.set_yticks([])
plt.tight_layout(); plt.show()
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 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:
def train_digit_gan(steps=4000, seed=0):
torch.manual_seed(seed)
G = nn.Sequential(nn.Linear(16, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 64), nn.Sigmoid())
D = nn.Sequential(nn.Linear(64, 128), nn.LeakyReLU(.2), nn.Linear(128, 128), nn.LeakyReLU(.2), nn.Linear(128, 1))
oG = torch.optim.Adam(G.parameters(), 2e-4, betas=(.5, .999)); oD = torch.optim.Adam(D.parameters(), 2e-4, betas=(.5, .999))
g, bce = torch.Generator().manual_seed(seed), nn.BCEWithLogitsLoss()
for s in range(steps):
real = X[torch.randint(0, len(X), (64,), generator=g)]; fake = G(torch.randn(64, 16, generator=g))
lD = bce(D(real), torch.full((64, 1), 0.9)) + bce(D(fake.detach()), torch.zeros(64, 1)) # label smoothing
oD.zero_grad(); lD.backward(); oD.step()
lG = bce(D(fake), torch.ones(64, 1)); oG.zero_grad(); lG.backward(); oG.step()
return G
t0 = time.time(); Gd = train_digit_gan()
with torch.no_grad(): show_digits(Gd(torch.randn(10, 16, generator=torch.Generator().manual_seed(3))), 'new digits from a small GAN')
print(f'{time.time() - t0:.0f} s')
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, times, with a schedule . After enough steps nothing of the data is left: is pure noise. With , any step can be reached directly:
Reverse (learned). Train a network to predict the noise that was added, with a plain mean squared error. To generate, start from pure noise and remove the predicted noise one step at a time:
Training is as stable as regression: no adversary, no game. The price is sampling: network evaluations per sample instead of one.
T = 100
betas = torch.linspace(1e-4, 0.1, T)
abar = torch.cumprod(1 - betas, 0)
print(f'T = {T}; after the last step, sqrt(abar) = {abar[-1].sqrt():.3f} of the data remains')
def train_diffusion(sampler, dim, steps, hidden=128, seed=0):
torch.manual_seed(seed); g = torch.Generator().manual_seed(seed)
net = nn.Sequential(nn.Linear(dim + 1, hidden), nn.ReLU(), nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, dim))
opt = torch.optim.Adam(net.parameters(), 1e-3)
for s in range(steps):
x0 = sampler(256, g); t = torch.randint(0, T, (len(x0),), generator=g); eps = torch.randn(x0.shape, generator=g)
xt = abar[t].sqrt()[:, None] * x0 + (1 - abar[t]).sqrt()[:, None] * eps
loss = F.mse_loss(net(torch.cat([xt, t[:, None] / T], 1)), eps)
opt.zero_grad(); loss.backward(); opt.step()
return net
@torch.no_grad()
def sample(net, n, dim, seed=1, keep=()):
g = torch.Generator().manual_seed(seed); x = torch.randn(n, dim, generator=g); kept = {T: x.clone()}
for t in reversed(range(T)):
eps = net(torch.cat([x, torch.full((n, 1), t / T)], 1))
x = (x - betas[t] / (1 - abar[t]).sqrt() * eps) / (1 - betas[t]).sqrt()
if t > 0: x = x + betas[t].sqrt() * torch.randn(n, dim, generator=g)
if t in keep: kept[t] = x.clone()
return x, kept
t0 = time.time(); dnet = train_diffusion(ring, 2, 4000)
pts, kept = sample(dnet, 2000, 2, keep=(75, 50, 25))
k, share = coverage(pts)
print(f'diffusion on the ring: {k} of 8 clusters covered, {share:.2f} of the samples near a cluster ({time.time() - t0:.0f} s)')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
fig, axes = plt.subplots(1, 5, figsize=(16, 3.4))
for ax, t in zip(axes, [T, 75, 50, 25, 0]):
p = kept[t] if t else pts
ax.scatter(p[:, 0], p[:, 1], s=2, alpha=.5); ax.set_title(f't = {t}' + (' (pure noise)' if t == T else '')); ax.set_xlim(-3.5, 3.5); ax.set_ylim(-3.5, 3.5); ax.set_aspect('equal'); ax.set_xticks([]); ax.set_yticks([])
fig.suptitle('sampling: from noise to data, by removing the predicted noise step by step'); plt.tight_layout(); plt.show()
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 ):
t0 = time.time()
digits_sampler = lambda n, g: X[torch.randint(0, len(X), (n,), generator=g)] * 2 - 1
dnet_digits = train_diffusion(digits_sampler, 64, 8000, hidden=256)
new, _ = sample(dnet_digits, 10, 64, seed=3)
show_digits((new.clamp(-1, 1) + 1) / 2, 'new digits from a small diffusion model')
print(f'{time.time() - t0:.0f} s')
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 , 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¶
| VAE | GAN | Diffusion | |
|---|---|---|---|
| How it learns | maximise a lower bound on | a game against a discriminator | regress the added noise |
| Training | stable | unstable; mode collapse | stable |
| Sample quality | blurry | sharp | sharp |
| Diversity | good | can miss modes | good |
| Sampling speed | one pass | one pass | many passes (tens to 1 000) |
| Has an encoder | yes | no | no (a fixed noising process) |
| Typical use | compression, latent spaces, anomaly detection | fast high-resolution images, style transfer | today’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 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¶
For a VAE with and for a one-dimensional code, compute the KL term. What values minimise it?
Why can backpropagation not go through , and how does fix it?
At the equilibrium of a GAN, what does the discriminator output for any input? Why?
Explain why the generator’s loss gives almost no gradient early in training, and what the non-saturating loss changes.
A GAN’s samples all look like 1s and 7s. Name the failure, and two things you would try.
With , write in terms of and . How much of the signal is left?
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.