Chapter 20: Generative Models — Implementation
The β-VAE trade-off: reconstruction against regularity
Walking through the code space: interpolation
A conditional VAE: choose the digit
A Wasserstein GAN with gradient penalty
Faster diffusion sampling with fewer steps (DDIM)
Conditional diffusion with classifier-free guidance
Judging samples with a classifier
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
from sklearn.linear_model import LogisticRegression
torch.set_num_threads(4)
X, y = load_digits(return_X_y=True)
Xt, yt = torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y)
judge = LogisticRegression(max_iter=3000).fit(X / 16, y) # a classifier used to judge generated digits (Section 7)
print(f'{len(Xt)} digits; the judge classifies its own training digits with accuracy {judge.score(X / 16, y):.3f}')
def show(imgs, title, n=10, rows=1):
fig, axes = plt.subplots(rows, n, figsize=(n * 1.05, rows * 1.15 + .3))
for ax, im in zip(np.ravel(axes), imgs[:n * rows]):
ax.imshow(np.asarray(im).reshape(8, 8), cmap='gray_r', vmin=0, vmax=1); ax.axis('off')
fig.suptitle(title, fontsize=10); plt.show()1797 digits; the judge classifies its own training digits with accuracy 0.985
1. The β-VAE Trade-off¶
Weighting the KL term by trades reconstruction for regularity: rebuilds better but leaves a less regular code space; pushes the codes towards harder and tends to separate independent factors of variation (Higgins et al., 2017).
class VAE(nn.Module):
def __init__(self, z=8, cond=0):
super().__init__(); self.cond = cond
self.enc = nn.Sequential(nn.Linear(64 + cond, 128), nn.ReLU(), nn.Linear(128, 2 * z))
self.dec = nn.Sequential(nn.Linear(z + cond, 128), nn.ReLU(), nn.Linear(128, 64))
def forward(self, x, c=None):
h = x if c is None else torch.cat([x, c], 1)
mu, logvar = self.enc(h).chunk(2, 1)
z = mu + torch.randn_like(mu) * (0.5 * logvar).exp()
return self.decode(z, c), mu, logvar
def decode(self, z, c=None):
return self.dec(z if c is None else torch.cat([z, c], 1))
def train_vae(beta=1.0, z=8, cond=False, epochs=120):
torch.manual_seed(0); vae = VAE(z, 10 if cond else 0); opt = torch.optim.Adam(vae.parameters(), 1e-3); g = torch.Generator().manual_seed(0)
onehot = F.one_hot(yt, 10).float()
for ep in range(epochs):
for idx in torch.randperm(len(Xt), generator=g).split(64):
logits, mu, logvar = vae(Xt[idx], onehot[idx] if cond else None)
rec = F.binary_cross_entropy_with_logits(logits, Xt[idx], reduction='sum') / len(idx)
kl = -0.5 * (1 + logvar - mu ** 2 - logvar.exp()).sum() / len(idx)
opt.zero_grad(); (rec + beta * kl).backward(); opt.step()
with torch.no_grad():
logits, mu, logvar = vae(Xt, onehot if cond else None)
rec = float(F.binary_cross_entropy_with_logits(logits, Xt, reduction='sum') / len(Xt)); kl = float(-0.5 * (1 + logvar - mu ** 2 - logvar.exp()).sum() / len(Xt))
return vae, rec, kl
t0 = time.time(); vaes = {}
for beta in [0.25, 1.0, 4.0]:
vaes[beta], rec, kl = train_vae(beta)
with torch.no_grad(): s = torch.sigmoid(vaes[beta].decode(torch.randn(500, 8, generator=torch.Generator().manual_seed(1)))).numpy()
print(f'beta {beta:<4}: reconstruction {rec:5.1f}, KL {kl:5.2f}; samples the judge finds confidently (> 0.9) a digit: {(judge.predict_proba(s).max(1) > .9).mean():.2f}')
print(f'{time.time() - t0:.0f} s')beta 0.25: reconstruction 17.6, KL 9.45; samples the judge finds confidently (> 0.9) a digit: 0.24
beta 1.0 : reconstruction 20.9, KL 3.33; samples the judge finds confidently (> 0.9) a digit: 0.24
beta 4.0 : reconstruction 27.1, KL 0.00; samples the judge finds confidently (> 0.9) a digit: 0.00
34 s
rebuilds best (17.6 nats) but its codes stray far from (KL 9.45). With the KL term falls to 0.00: the encoder gives up and outputs the prior for every digit, the decoder learns to draw one average blur, and no sample is a confident digit. This is posterior collapse, a common failure of VAEs with a strong decoder or a heavy KL weight. Only about a quarter of the samples of the other two are confidently classified: unconditional samples from a small VAE are often ambiguous.
2. Interpolation¶
A regular code space can be walked: encode two digits, move in a straight line between their codes, and decode each point.
vae = vaes[1.0]
a, b = Xt[y == 0][0], Xt[y == 6][3]
with torch.no_grad():
za, zb = vae.enc(a[None]).chunk(2, 1)[0], vae.enc(b[None]).chunk(2, 1)[0]
path = torch.sigmoid(vae.decode(torch.cat([za + (zb - za) * t for t in torch.linspace(0, 1, 10)])))
show(path, 'from a 0 to a 6, decoded along a straight line in the code space')
3. A Conditional VAE¶
Giving the label to both the encoder and the decoder (one-hot) lets the code describe only the style (slant, thickness), and lets us choose which digit to generate.
cvae, rec, kl = train_vae(1.0, cond=True)
with torch.no_grad():
z = torch.randn(10, 8, generator=torch.Generator().manual_seed(2))
rows = [torch.sigmoid(cvae.decode(z, F.one_hot(torch.full((10,), d), 10).float())) for d in range(10)]
show(torch.cat(rows[:5]), 'conditional VAE: each row one digit, each column one style code z', n=10, rows=5)
with torch.no_grad():
lab = torch.arange(10).repeat(50); s = torch.sigmoid(cvae.decode(torch.randn(500, 8, generator=torch.Generator().manual_seed(4)), F.one_hot(lab, 10).float())).numpy()
print(f'the judge reads the requested digit in {(judge.predict(s) == lab.numpy()).mean():.2f} of 500 conditional samples')
the judge reads the requested digit in 1.00 of 500 conditional samples
Every column keeps one style code: the same slant and thickness across all ten digits. And the separate classifier reads the requested digit in all 500 conditional samples: conditioning turns a vague generator into a precise one.
4. A Wasserstein GAN With Gradient Penalty¶
The Wasserstein GAN (Arjovsky et al., 2017) replaces the discriminator by a critic that outputs a score, not a probability, and minimises an estimate of the Wasserstein (“earth mover’s”) distance between the real and generated distributions: the critic maximises , the generator maximises . The critic must have a bounded slope; the gradient penalty (Gulrajani et al., 2017) enforces it by pushing on points between real and fake samples. Its critic’s estimate is meant to track sample quality, which a standard GAN’s losses do not. On the ring of eight clusters, with the settings usually recommended for it (Adam with , five critic steps per generator step), for two seeds:
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): return CENTRES[torch.randint(0, 8, (n,), generator=g)] + 0.05 * torch.randn(n, 2, generator=g)
def coverage(s):
d = torch.cdist(s, CENTRES); near = d.min(1).values < 0.3
return int(torch.unique(d.argmin(1)[near]).numel()), float(near.float().mean())
def train_wgan_gp(steps=3000, lr=1e-3, seed=0, n_critic=5, lam=10.0):
torch.manual_seed(seed)
G = nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 2))
f = nn.Sequential(nn.Linear(2, 64), nn.LeakyReLU(.2), nn.Linear(64, 64), nn.LeakyReLU(.2), nn.Linear(64, 1))
oG, of = torch.optim.Adam(G.parameters(), lr, betas=(.5, .9)), torch.optim.Adam(f.parameters(), lr, betas=(.5, .9))
g, hist = torch.Generator().manual_seed(seed), []
for s in range(1, steps + 1):
for _ in range(n_critic):
real, fake = ring(128, g), G(torch.randn(128, 2, generator=g)).detach()
e = torch.rand(128, 1, generator=g); mid = (e * real + (1 - e) * fake).requires_grad_(True)
grad = torch.autograd.grad(f(mid).sum(), mid, create_graph=True)[0]
loss_f = f(fake).mean() - f(real).mean() + lam * ((grad.norm(dim=1) - 1) ** 2).mean()
of.zero_grad(); loss_f.backward(); of.step()
loss_g = -f(G(torch.randn(128, 2, generator=g))).mean()
oG.zero_grad(); loss_g.backward(); oG.step()
if s % 1000 == 0:
with torch.no_grad(): hist.append((s, *coverage(G(torch.randn(2000, 2, generator=torch.Generator().manual_seed(1)))), -float(loss_f)))
return G, hist
t0 = time.time()
for seed in [0, 1]:
_, hist = train_wgan_gp(seed=seed)
print(f'seed {seed}: ' + '; '.join(f'step {s}: {k} clusters, {share:.2f} near, estimate {w:.3f}' for s, k, share, w in hist))
print(f'{time.time() - t0:.0f} s')seed 0: step 1000: 8 clusters, 0.36 near, estimate 0.192; step 2000: 8 clusters, 0.70 near, estimate 0.055; step 3000: 8 clusters, 0.82 near, estimate 0.045
seed 1: step 1000: 8 clusters, 0.26 near, estimate -0.120; step 2000: 8 clusters, 0.59 near, estimate 0.179; step 3000: 8 clusters, 0.74 near, estimate 0.129
142 s
Both seeds cover all eight clusters, and end with 82% and 74% of the samples near one. (The standard GAN of the theory chapter used other settings, so this is not a fair race.) The critic’s distance estimate is noisy from one batch to the next: for seed 0 it falls as the samples improve (0.192, 0.055, 0.045), for seed 1 it does not. In practice it is averaged over many batches before being read.
5. Faster Diffusion Sampling¶
A diffusion model trained with steps does not have to be sampled with all . DDIM (Song et al., 2021) makes the reverse process deterministic and lets it jump: from the predicted noise at step , estimate the clean data , then move straight to an earlier step : .
T = 100
betas = torch.linspace(1e-4, 0.1, T); abar = torch.cumprod(1 - betas, 0)
def train_diffusion(sampler, dim, steps, hidden=128, cond=False, seed=0, p_drop=0.1):
"""With cond=True, the label (one-hot, or all zeros for 'no label' with probability p_drop) is a second input."""
torch.manual_seed(seed); g = torch.Generator().manual_seed(seed)
net = nn.Sequential(nn.Linear(dim + 1 + (10 if cond else 0), 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, lab = 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
inp = [xt, t[:, None] / T]
if cond:
c = F.one_hot(lab, 10).float() * (torch.rand(len(x0), 1, generator=g) > p_drop) # drop the label 10% of the time
inp.append(c)
loss = F.mse_loss(net(torch.cat(inp, 1)), eps); opt.zero_grad(); loss.backward(); opt.step()
return net
ring_sampler = lambda n, g: (ring(n, g), None)
t0 = time.time(); dnet = train_diffusion(ring_sampler, 2, 4000)
print(f'trained in {time.time() - t0:.0f} s')
@torch.no_grad()
def ddim(net, n, dim, steps, seed=1, extra=None):
ts = torch.linspace(T - 1, 0, steps).round().long().tolist()
x = torch.randn(n, dim, generator=torch.Generator().manual_seed(seed))
for i, t in enumerate(ts):
e = net(torch.cat([x, torch.full((n, 1), t / T)] + ([extra] if extra is not None else []), 1))
x0 = (x - (1 - abar[t]).sqrt() * e) / abar[t].sqrt()
a_prev = abar[ts[i + 1]] if i + 1 < len(ts) else torch.tensor(1.0)
x = a_prev.sqrt() * x0 + (1 - a_prev).sqrt() * e
return x
for steps in [100, 20, 5]:
t0 = time.time(); k, share = coverage(ddim(dnet, 2000, 2, steps))
print(f'DDIM with {steps:>3} steps: {k} of 8 clusters, {share:.2f} near a cluster ({1000 * (time.time() - t0):.0f} ms)')trained in 11 s
DDIM with 100 steps: 8 of 8 clusters, 0.89 near a cluster (126 ms)
DDIM with 20 steps: 8 of 8 clusters, 0.84 near a cluster (53 ms)
DDIM with 5 steps: 8 of 8 clusters, 0.49 near a cluster (11 ms)
Twenty deterministic steps instead of one hundred keep all eight clusters with 84% of the samples near one, in a fraction of the time; with five steps only 49% are. Image models sample in 20 to 50 steps this way instead of 1 000.
6. Conditional Diffusion and Classifier-Free Guidance¶
To ask for a particular digit, the denoiser also receives the label. Classifier-free guidance (Ho and Salimans, 2022) trains one network both with the label and, 10% of the time, without it; at sampling time it extrapolates away from the unconditional prediction:
A larger guidance weight gives samples that match the condition more clearly, at the cost of diversity. Text-to-image models do exactly this, with a sentence’s embedding as .
digit_sampler = lambda n, g: (lambda i: (Xt[i] * 2 - 1, yt[i]))(torch.randint(0, len(Xt), (n,), generator=g))
t0 = time.time(); cnet = train_diffusion(digit_sampler, 64, 10000, hidden=256, cond=True)
print(f'trained in {time.time() - t0:.0f} s')
@torch.no_grad()
def guided(net, labels, w, steps=50, seed=5):
n = len(labels); c = F.one_hot(labels, 10).float(); empty = torch.zeros_like(c)
ts = torch.linspace(T - 1, 0, steps).round().long().tolist()
x = torch.randn(n, 64, generator=torch.Generator().manual_seed(seed))
for i, t in enumerate(ts):
tt = torch.full((n, 1), t / T)
e = (1 + w) * net(torch.cat([x, tt, c], 1)) - w * net(torch.cat([x, tt, empty], 1))
x0 = (x - (1 - abar[t]).sqrt() * e) / abar[t].sqrt()
a_prev = abar[ts[i + 1]] if i + 1 < len(ts) else torch.tensor(1.0)
x = a_prev.sqrt() * x0 + (1 - a_prev).sqrt() * e
return ((x.clamp(-1, 1) + 1) / 2).numpy()
labels = torch.arange(10).repeat(50)
for w in [0.0, 1.0, 3.0]:
s = guided(cnet, labels, w)
print(f'guidance w = {w}: the judge reads the requested digit in {(judge.predict(s) == labels.numpy()).mean():.2f} of 500 samples; pixel spread within a digit {s.reshape(50, 10, 64).std(0).mean():.3f}')
show(guided(cnet, torch.arange(10), 3.0, seed=7), 'conditional diffusion, w = 3: the digits 0 to 9, on request')trained in 61 s
guidance w = 0.0: the judge reads the requested digit in 0.89 of 500 samples; pixel spread within a digit 0.164
guidance w = 1.0: the judge reads the requested digit in 1.00 of 500 samples; pixel spread within a digit 0.142
guidance w = 3.0: the judge reads the requested digit in 1.00 of 500 samples; pixel spread within a digit 0.122

Without guidance (), 89% of the samples are read as the requested digit; with or 3, all of them. The pixel spread between samples of the same digit falls from 0.164 to 0.122: guidance buys fidelity with diversity.
7. Judging Samples¶
Generative models are hard to evaluate: there is no single right output. The checks used above are simple versions of the standard ones:
Is it recognisable? A separate classifier’s confidence on the samples (the idea behind the Inception Score).
Does it match the request? The share of conditional samples classified as the requested label.
Is it diverse? The spread between samples of the same class; for images, the Fréchet Inception Distance compares the mean and covariance of a pretrained network’s features on real and generated sets, catching both poor quality and missing variety.
Is it copied? The nearest training example to each sample: a model that memorises can score well on everything else.
s = guided(cnet, torch.arange(10).repeat(5), 3.0, seed=9)
d = ((s[:, None, :] - (X / 16)[None, :, :]) ** 2).sum(2)
print(f'distance from each of 50 samples to its nearest training digit: median {np.median(d.min(1)):.2f}; '
f'typical distance between two training digits of the same class: {np.median([((X[y == c][0] / 16 - X[y == c][1:] / 16) ** 2).sum(1).min() for c in range(10)]):.2f}')distance from each of 50 samples to its nearest training digit: median 1.70; typical distance between two training digits of the same class: 1.26
The samples are further from their nearest training digit (median 1.70) than two training digits of the same class typically are from each other (1.26): the model is not simply returning training images.
Summary¶
β weighs a VAE’s KL term: lower rebuilds better, higher regularises more.
A regular code space can be interpolated; a conditional VAE separates the digit from its style.
A WGAN-GP’s critic gives a loss that tracks quality and trains more reliably than the standard GAN.
DDIM samples a diffusion model in a few deterministic steps.
Classifier-free guidance trades diversity for fidelity to the condition: the mechanism behind text-to-image models.
Generated samples are judged on recognisability, fidelity, diversity and novelty.