Generative Models
VAEs, GANs and diffusion: learning to create.
A classifier only has to learn what separates a cat from a dog. A model that can draw a new cat must capture the whole distribution of cat images, down to the last pixel. Four families do this in different ways: autoregressive models, VAEs, GANs and diffusion models. Each one buys something (exact likelihoods, a latent space, one-shot sampling, stable training) by giving something else up.
What you’ll learn
- Compare the generative families by what they offer: exact or bounded likelihood, sampling cost, and a latent space.
- Explain how masked convolutions make a PixelCNN's exact likelihood trainable in one pass while sampling stays sequential.
- Derive the VAE's reparameterized gradient and the optimal GAN discriminator.
- Derive the closed form of the diffusion forward process, write DDPM training and sampling as pseudocode, and relate noise prediction to the score.
- Compute FID for Gaussian features and state its main caveats.
Three jobs: density, sampling, latents
A generative model is fitted to samples from an unknown . You might want three different things from it:
- Density: evaluate for a given , for compression, anomaly detection or comparing models on held-out data.
- Sampling: draw new quickly.
- Latents: a code to interpolate, edit or condition on, which makes the model useful as a representation.
No family does all three well, and the trade-offs organize the field.
The default way to fit a density is maximum likelihood: maximize . In expectation that is the same as minimizing the forward KL divergence , a mass-covering objective that punishes any data the model misses (Information Theory for AI). It requires computing . The families differ in how they deal with that: they make the likelihood tractable (autoregressive models, flows), bound it (VAEs, diffusion), or give it up (GANs).
| Family | Cost of one sample | Latent code | Typical weakness | |
|---|---|---|---|---|
| Autoregressive (PixelCNN, language models) | exact | sequential network passes | none | slow sampling; a fixed ordering |
| Normalizing flow | exact | one pass | of the same dimension as | invertible architectures only |
| VAE | lower bound (ELBO) | one pass | low-dimensional with an encoder | blurry samples |
| GAN | none | one pass | , but no encoder | unstable training, mode collapse |
| Diffusion | lower bound; exact through an ODE | tens to a thousand passes | noise of the same dimension (through the ODE) | slow sampling, much reduced by better samplers |
You need to rank several trained models by the probability they assign to a held-out test image. Which model cannot report that number, even approximately?
- A PixelCNN
- A normalizing flow
- A VAE
- A GAN
Show the answer
D. A GAN
A GAN's generator pushes noise through a network and defines no density at all; typically its samples even lie on a low-dimensional surface, where a density does not exist. PixelCNNs and flows give exact log-likelihoods, and a VAE gives a lower bound that importance sampling can tighten.
Autoregressive models: exact likelihood, one pixel at a time
The chain rule of probability holds for every distribution and every ordering of the coordinates. Model each conditional with a network and the log-likelihood is exact: a sum of cross-entropies, as in a language model (From N-grams to Embeddings).
PixelCNN (van den Oord, Kalchbrenner & Kavukcuoglu, 2016) orders the pixels in raster order and the color channels R, G, B within each pixel, and predicts each subpixel with a 256-way softmax. The trick that makes training fast is the masked convolution: every kernel weight at or after the current position in that order is zeroed. Mask A, in the first layer, also hides the current subpixel; mask B, in later layers, lets a position see its own features. No output can see its own value or any later one, so a single forward pass over a real image computes all conditionals at once.
Stacked masked convolutions leave a "blind spot" of pixels above and to the right that never reach the output; the gated PixelCNN (van den Oord et al., 2016) removed it with separate vertical and horizontal stacks.
PIXELCNN-SAMPLE(network f, height H, width W)
x ← array of zeros, shape H × W × 3
for i = 1..H:
for j = 1..W:
for c in (R, G, B):
probs ← softmax(f(x)[i, j, c]) // 256 values; depends only on earlier subpixels
x[i, j, c] ← a draw from probs
return xTraining runs once per image, because the real image supplies every input. Sampling runs it once per subpixel, because each input is generated by the previous step. Caching activations reduces the cost of each step but not the number of sequential steps.
How many sequential network evaluations does PIXELCNN-SAMPLE need for one RGB image?
Show the answer
3072
One per subpixel: . Training on the same image takes a single parallel pass. The same asymmetry, parallel training and sequential sampling, holds for WaveNet audio (Speech & Audio) and for every autoregressive language model.
Latent variables: the variational autoencoder
A latent-variable model draws a code first and then the data: , then , with a neural decoder. Its likelihood is an intractable integral. The variational autoencoder (Kingma & Welling, 2014; Rezende, Mohamed & Wierstra, 2014) adds an encoder and maximizes the evidence lower bound, derived with Jensen's inequality in Information Theory for AI:
The reconstruction term is an expectation over a distribution that depends on , so you cannot simply backpropagate through "draw ". Write the draw as a deterministic function of and parameter-free noise:
Now the distribution being averaged over no longer depends on , and the gradient moves inside the expectation (under mild regularity conditions):
A single draw of gives an unbiased estimate, computed by ordinary backpropagation through , and . Its variance is usually far lower than that of the score-function (REINFORCE) estimator , which uses only the value of and not its slope.
def vae_loss(x, encoder, decoder):
mu, log_var = encoder(x) # parameters of q(z | x)
eps = torch.randn_like(mu)
z = mu + torch.exp(0.5 * log_var) * eps # reparameterized draw
x_hat = decoder(z) # mean of a Gaussian p(x | z)
recon = ((x - x_hat) ** 2).sum(dim=1) # -log p(x | z) up to scale and a constant
kl = 0.5 * (mu**2 + log_var.exp() - 1 - log_var).sum(dim=1)
return (recon + kl).mean() # negative ELBO, averaged over the batchWith a fixed-variance Gaussian decoder the reconstruction term is a squared error. That is why VAE samples tend to be blurry: under squared error the best output is the average of all images consistent with . The Deep Layer lesson treats posterior collapse and the -VAE.
GANs: a generator, a critic and a game
A generative adversarial network (Goodfellow et al., 2014) gives up the likelihood altogether. A generator maps noise to a sample , which defines a distribution only implicitly. A discriminator is trained to tell real samples from generated ones, and the generator is trained to fool it. The two play a zero-sum game:
Fix and write both expectations as integrals over , with the distribution of :
can be chosen separately at each . For , the function is concave on with derivative , which vanishes at :
Substituting back gives the generator's objective. The Generative Adversarial Networks lesson proves that it is a Jensen–Shannon divergence, so its unique minimum is , where :
In practice and are networks updated in alternation by stochastic gradient steps, and the generator usually minimizes instead of . Both reward fooling , but early in training, when easily rejects fakes, the original loss gives almost no gradient. GANs sample in one forward pass and produce sharp images: StyleGAN (Karras, Laine & Aila, 2019) generated photorealistic faces. But training can oscillate instead of converging, and the generator can suffer mode collapse, covering a few modes of the data and ignoring the rest.
Write the discriminator's output on a fake as with logit . Early in training, . How many times larger is the gradient magnitude of the non-saturating loss than that of the original loss ?
Show the answer
99
, while : a ratio of . The original loss saturates exactly when the generator is worst, which is when it most needs a signal.
Diffusion: learning to undo noise
A diffusion model (Sohl-Dickstein et al., 2015; Ho, Jain & Abbeel, 2020) fixes a forward process that destroys data gradually: a Markov chain that adds a little Gaussian noise at each of steps. DDPM used , with rising linearly from to .
Nothing in the forward process is learned. The model learns the reverse: how to remove one step of noise.
Write one step with fresh noise , and unroll two steps:
A sum of independent zero-mean Gaussians is Gaussian, and the variances add:
So two steps act like one step with . By induction on :
Training never has to simulate the chain: pick a random and noise the data in one shot. As , forgets ; with DDPM's schedule, .
A network is trained to predict the noise that was added, with a plain squared error. Why that is the right target: the best possible noise predictor is , a rescaled score of the noised data distribution . That is Tweedie's formula, proved in Autoencoders & Latent Spaces: denoising and score estimation are the same problem. Training and sampling, as in Ho et al.'s Algorithms 1 and 2:
DDPM-TRAIN
repeat
x0 ← a training example; t ← uniform on {1, …, T}; ε ← N(0, I)
take a gradient step on ‖ε − ε_θ(√ᾱ_t · x0 + √(1 − ᾱ_t) · ε, t)‖²
until converged
DDPM-SAMPLE
x ← a draw from N(0, I) // x_T
for t = T, T − 1, …, 1:
z ← a draw from N(0, I) if t > 1, else 0
x ← (x − β_t / √(1 − ᾱ_t) · ε_θ(x, t)) / √α_t + σ_t · z
return x // x_0is set to or to ; Ho et al. found the two gave similar results. Sampling costs network evaluations, the price of diffusion. The last step adds no noise.
Think first Why not train one network to map pure noise to data in a single step, , with the same squared-error loss?
Trained with squared error, a one-step denoiser outputs . Since carries almost no information about , that is close to the mean of the whole dataset: one blurry average for every input. Small steps keep each reverse conditional close to a Gaussian, so a Gaussian step with a learned mean is accurate. Large steps make the true conditional broad and multimodal, which is what the 5-step samples suffered from. Better samplers and distillation cut the number of steps to tens or even one or two (Diffusion Models).
Measuring quality, and open questions
How good is a generative model? Held-out likelihood (bits per dimension) is principled but available only for some families, and it can disagree with sample quality in both directions (Theis, van den Oord & Bethge, 2016). The standard sample-based score for images is the Fréchet Inception Distance (FID; Heusel et al., 2017). Embed real and generated images with an ImageNet-trained Inception-v3 network (2,048 features each), fit a Gaussian to each set of features, and compute
In one dimension FID reduces to . Real features are ; a generator's features are , centered correctly but with half the standard deviation. What is the FID?
Show the answer
C.
, so FID . A generator that output the same feature every time () would score : FID penalizes missing diversity, not only wrong averages.
Key takeaways
- Generative models trade exact or bounded likelihood, sampling cost and latent structure against each other: autoregressive models and flows give exact likelihoods, VAEs and diffusion models give bounds, GANs give none.
- Autoregressive models factor ; masked convolutions make PixelCNN's training one parallel pass, but sampling takes sequential steps.
- VAEs maximize the ELBO with an encoder, the reparameterization and a closed-form Gaussian KL. GANs play a minimax game whose optimal discriminator is .
- Diffusion noises data with and learns to predict the noise, which amounts to learning the score; sampling reverses the chain in many small steps.
- FID is the 2-Wasserstein distance between Gaussian fits to Inception features. It depends on the number of samples and on implementation details, and mixes fidelity with diversity.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In a DDPM, at step . How is generated from a data point and fresh noise ?
Show the answer
C.
, so the coefficients are and . Their squares add to , which keeps the variance at for unit-variance data: the process is variance preserving.
At some point , the data density is three times the generator's: . What does the optimal discriminator output there?
Show the answer
B.
: it is the posterior probability that is real when real and fake samples are equally common.
Why does the VAE write instead of drawing directly?
- It makes the encoder deterministic, so no sampling happens during training
- It turns the sample into a differentiable function of , so backpropagation yields an unbiased, low-variance gradient of the ELBO
- It makes the KL term vanish
- It is needed to evaluate exactly
Show the answer
B. It turns the sample into a differentiable function of , so backpropagation yields an unbiased, low-variance gradient of the ELBO
The randomness moves into , whose distribution does not depend on , so , which one sample estimates without bias.
A PixelCNN evaluates the likelihood of a RGB training image in one forward pass, yet needs 3,072 passes to sample one. What makes training parallel?
- Training uses a smaller network
- The masked convolutions make each output depend only on earlier subpixels, and during training all of those are available from the real image
- Training ignores the dependence between pixels
- The softmax over 256 values is computed in closed form
Show the answer
B. The masked convolutions make each output depend only on earlier subpixels, and during training all of those are available from the real image
Every conditional needs only earlier subpixels, which the training image supplies, so the masks let one pass compute all of them (teacher forcing). At sampling time each earlier subpixel must be generated first.
Paper A reports FID 12 computed from 5,000 samples; paper B reports FID 10 from 50,000 samples, on the same dataset. What can you conclude?
- Model B is better, because its FID is lower
- Model A is better, because it reached a good score with fewer samples
- Little: FID's finite-sample bias depends on the number of samples (fewer samples inflate it), so the numbers are not comparable
- The models are equivalent, since the scores differ by less than 20%
Show the answer
C. Little: FID's finite-sample bias depends on the number of samples (fewer samples inflate it), so the numbers are not comparable
Estimating means and covariances from samples biases FID upward by an amount that shrinks with , and preprocessing details also shift scores. Comparisons need the same , the same reference statistics and the same implementation.
Go deeper
- Variational Autoencoders & the ELBO · Latent variables and variational inference.
- Generative Adversarial Networks · A two-player game with a forger and a critic.
- Diffusion Models · Learning to reverse a noising process.
Further reading
- I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, ch. 20 "Deep Generative Models" (MIT Press, 2016).
- A. van den Oord, N. Kalchbrenner & K. Kavukcuoglu, "Pixel recurrent neural networks," ICML (2016).
- M. Heusel, H. Ramsauer, T. Unterthiner, B. Nessler & S. Hochreiter, "GANs trained by a two time-scale update rule converge to a local Nash equilibrium," NeurIPS (2017).
- K. P. Murphy, Probabilistic Machine Learning: Advanced Topics, part IV "Generation" (MIT Press, 2023).