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 — Implementation

Open in Colab
  1. The β-VAE trade-off: reconstruction against regularity

  2. Walking through the code space: interpolation

  3. A conditional VAE: choose the digit

  4. A Wasserstein GAN with gradient penalty

  5. Faster diffusion sampling with fewer steps (DDIM)

  6. Conditional diffusion with classifier-free guidance

  7. Judging samples with a classifier

1797 digits; the judge classifies its own training digits with accuracy 0.985

1. The β-VAE Trade-off

Weighting the KL term by β\beta trades reconstruction for regularity: β<1\beta < 1 rebuilds better but leaves a less regular code space; β>1\beta > 1 pushes the codes towards N(0,I)\mathcal{N}(0, I) harder and tends to separate independent factors of variation (Higgins et al., 2017).

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

β=0.25\beta = 0.25 rebuilds best (17.6 nats) but its codes stray far from N(0,I)\mathcal{N}(0, I) (KL 9.45). With β=4\beta = 4 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.

<Figure size 1050x145 with 10 Axes>

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.

<Figure size 1050x605 with 50 Axes>
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 ff 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 E[f(real)]−E[f(fake)]\mathbb{E}[f(\text{real})] - \mathbb{E}[f(\text{fake})], the generator maximises E[f(fake)]\mathbb{E}[f(\text{fake})]. The critic must have a bounded slope; the gradient penalty (Gulrajani et al., 2017) enforces it by pushing ∥∇f∥→1\|\nabla f\| \to 1 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 β=(0.5,0.9)\beta = (0.5, 0.9), five critic steps per generator step), for two seeds:

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 TT steps does not have to be sampled with all TT. DDIM (Song et al., 2021) makes the reverse process deterministic and lets it jump: from the predicted noise ε^\hat\varepsilon at step tt, estimate the clean data x^0=(xt−1−αˉt ε^)/αˉt\hat x_0 = (x_t - \sqrt{1-\bar\alpha_t}\,\hat\varepsilon)/\sqrt{\bar\alpha_t}, then move straight to an earlier step ss: xs=αˉs x^0+1−αˉs ε^x_s = \sqrt{\bar\alpha_s}\,\hat x_0 + \sqrt{1-\bar\alpha_s}\,\hat\varepsilon.

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:

ε~=(1+w) εθ(xt,t,c)−w εθ(xt,t,∅)\tilde\varepsilon = (1 + w)\, \varepsilon_\theta(x_t, t, c) - w\, \varepsilon_\theta(x_t, t, \varnothing)

A larger guidance weight ww 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 cc.

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
<Figure size 1050x145 with 10 Axes>

Without guidance (w=0w = 0), 89% of the samples are read as the requested digit; with w=1w = 1 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.

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.