Simple Algorithm
Deep Learning · Activation · 18 min

Deep Generative Models

Networks that create: learning a distribution well enough to sample from it.

Show a network ten thousand faces and ask it for a new one: a face that appears nowhere in the data but could have. To do that it must learn the distribution the faces came from, not just a boundary between classes. Four families of networks have found four very different ways to do it, and you will run three of them here.

What you’ll learn

  • Explain the difference between a discriminative model p(y∣x)p(y\mid\mathbf x) and a generative model p(x)p(\mathbf x), and what it means to sample from a learned distribution.
  • Describe the four main families (autoregressive models, VAEs, GANs, and diffusion and flow models) by how each one turns randomness into data.
  • Train a toy GAN and recognize mode collapse; run a diffusion model and a flow and see why fewer steps cost quality.
  • Explain how latent spaces and conditioning steer generation, and why likelihood, sample quality and diversity must be measured separately.

Telling apart versus making

Almost every network in this course so far has been discriminative. Shown an input x\mathbf x, say a photo, it outputs a label yy, or more precisely a probability distribution p(y∣x)p(y\mid\mathbf x) over labels. To tell cats from dogs it only needs whatever separates them: the shape of the ears, the snout. Everything else in the picture can be ignored.

A generative model learns the distribution of the data itself, p(x)p(\mathbf x), well enough to sample from it: to produce new examples that look as if they came from the same source as the training data, without copying any one of them. Often you want a conditional version p(x∣c)p(\mathbf x\mid c), where the condition cc is a class label, a sketch or a sentence of text.

p(y∣x)⏟discriminative: a label given the inputversusp(x)  or  p(x∣c)⏟generative: the data itself\underbrace{p(y\mid\mathbf x)}_{\text{discriminative: a label given the input}}\qquad\text{versus}\qquad\underbrace{p(\mathbf x)\ \text{ or }\ p(\mathbf x\mid c)}_{\text{generative: the data itself}}
A classifier may ignore everything that does not affect the label. A generative model must account for every pixel, every word, every audio sample.

Why is this hard? A small 64×6464\times64 color image is a list of 64×64×3=12,28864\times64\times3=12{,}288 numbers: one point in a 12,288-dimensional space. Pick a point at random and you get colored static. Natural images fill a vanishingly small, strangely shaped region of that space, and a good model must put its probability on that region and spread it over all of it: every breed, every pose, every kind of lighting.

What are generative models for?

  • Media: images and video from text prompts, speech synthesis, music.
  • Text: every large language model is a generative model of text that samples one token after another.
  • Science: candidate molecules, proteins and materials, sampled from models trained on known ones.
  • Data: synthetic data and augmentation for training other models, and filling in missing parts of an image.
  • Compression and anomaly detection: a model that gives typical data high probability can encode it in few bits, and can flag inputs it finds improbable.
Check your understanding

Which of these tasks needs a generative model, rather than only a classifier or a regressor?

  1. Flag incoming emails as spam or not spam
  2. Estimate a house's price from its size and location
  3. Fill a missing rectangle of a photo with content that matches its surroundings
  4. Name the objects visible in a photo
Show the answer

C. Fill a missing rectangle of a photo with content that matches its surroundings

Filling the hole means producing pixels. Many completions are plausible, and the model must sample one that fits, which takes a distribution over images, p(missing part∣rest of the photo)p(\text{missing part}\mid\text{rest of the photo}). The other three tasks map an input to a label or a number.

One piece at a time

The first family rests on a fact about probability. Any distribution over a sequence x=(x1,…,xd)\mathbf x=(x_1,\dots,x_d) factors, by the chain rule of probability, into a product of one-step predictions:

p(x)=p(x1) p(x2∣x1) p(x3∣x1,x2)⋯p(xd∣x1,…,xd−1)=∏i=1dp(xi∣x<i)p(\mathbf x)=p(x_1)\,p(x_2\mid x_1)\,p(x_3\mid x_1,x_2)\cdots p(x_d\mid x_1,\dots,x_{d-1})=\prod_{i=1}^{d}p(x_i\mid x_{<i})
This holds for every distribution: no approximation has been made yet. The modeling starts when one network is asked to predict each piece from the pieces before it.

An autoregressive model learns all of these conditionals with one network. A language model is exactly this, with tokens as the pieces: it is trained on next-token prediction, and it generates text by sampling a token, appending it and predicting again. The same recipe works for images read pixel by pixel in raster order (PixelCNN; van den Oord, Kalchbrenner & Kavukcuoglu, 2016) and for raw audio, one sample at a time (WaveNet; van den Oord et al., 2016).

Two strengths follow. Training is plain maximum likelihood: make each true next piece probable. And the model gives the exact probability of any example, the product above, so you can compare models by how probable they find held-out data. The weakness is speed: sampling is sequential, one network evaluation per piece.

Predict before you look

A PixelCNN-style model generates a 64×6464\times64 grayscale image one pixel at a time, in raster order. How many sequential network evaluations does one sample take?

Show the answer

4096 evaluations

One per pixel: 64×64=4,09664\times64=4{,}096, each waiting for the pixel before it. A color image predicted one channel value at a time takes three times as many. Training is different: all the true pixels are known in advance, so masking lets a single forward pass compute every conditional at once.

Squeeze through a bottleneck

An autoencoder is a pair of networks trained to copy their input through a narrow channel. The encoder compresses x\mathbf x into a short vector z\mathbf z, its code or latent variable (hidden, never observed), and the decoder is trained to rebuild x\mathbf x from z\mathbf z alone. Training minimizes the reconstruction error. With, say, 32 numbers to describe a whole face, the code cannot store pixels: it is forced to keep what matters most, such as pose, hair and expression.

Think first You trained an autoencoder on faces and it reconstructs them well. Why not generate new faces by feeding random codes to its decoder?

Nothing in training told the decoder what to do with codes it never saw. The codes of the training faces form a scattered, oddly shaped cloud in latent space, with gaps and holes, and a random code usually lands in a gap and decodes to a smear. To generate, you must know which codes are valid and how to sample them.

The variational autoencoder (VAE; Kingma & Welling, 2014; Rezende, Mohamed & Wierstra, 2014) fixes exactly that. Its encoder outputs a small cloud of codes for each input, a mean and a spread, instead of a single point, and a penalty pulls every cloud toward one fixed distribution, the standard bell curve N(0,I)\mathcal N(\mathbf 0,I). The clouds overlap and fill the space, so after training you can draw z∼N(0,I)\mathbf z\sim\mathcal N(\mathbf 0,I), decode it, and get a plausible new face. One sample costs one pass through the decoder.

The latent space is useful in its own right. Moving a code smoothly morphs one output into another. Gómez-Bombarelli et al. (2018) trained a VAE on molecules written as text strings, then searched its continuous latent space for molecules with better predicted properties, guided by a model trained to predict those properties from the code: a smooth search that discrete molecular structures do not allow directly.

A cousin, the VQ-VAE, snaps each code to the nearest entry of a learned codebook, so that an image becomes a grid of discrete tokens that a transformer can model like text. The first DALL·E (Ramesh et al., 2021) used a closely related discrete autoencoder to represent each 256×256256\times256 image as a 32×3232\times32 grid of tokens, each taking one of 8,192 values.

A forger and a critic

The third family drops likelihood altogether. A generative adversarial network (GAN; Goodfellow et al., 2014) trains two networks against each other. The generator GG turns a random vector z\mathbf z into a sample G(z)G(\mathbf z). The discriminator DD sees a mix of real examples and the generator's fakes and outputs the probability that its input is real. DD is trained to tell them apart; GG is trained to fool DD.

If both played perfectly, the fakes would become indistinguishable from real data, and the best DD could do would be to answer 12\tfrac12 for everything. A GAN never computes p(x)p(\mathbf x), but its generator samples in a single forward pass, and the samples can be strikingly sharp: in 2019 StyleGAN (Karras, Laine & Aila) produced 1024×10241024\times1024 portraits of people who do not exist.

Check your understanding

A GAN trained on photos of ten dog breeds produces only beautiful, realistic golden retrievers. What has happened?

  1. Overfitting: it has memorized the training photos
  2. Mode collapse: the generator found a few kinds of output that fool the discriminator and stopped covering the rest of the data
  3. The discriminator has won: it rejects every sample
  4. Nothing is wrong: realistic samples show that it learned the distribution
Show the answer

B. Mode collapse: the generator found a few kinds of output that fool the discriminator and stopped covering the rest of the data

Each sample can look perfect while the set of samples misses most of the data: that is mode collapse. The generator is rewarded only for fooling the current discriminator, and a few convincing kinds of output can do that. Quality and coverage are different properties, which is why evaluating generative models needs more than one number.

Noise into data, one small step at a time

The fourth family is behind most image, video and audio generators as of the mid-2020s. A diffusion model (Sohl-Dickstein et al., 2015; Ho, Jain & Abbeel, 2020) starts from a simple observation: destroying data is easy. Add a little Gaussian noise to an image, then a little more, hundreds of times over, and you are left with pure noise. This is the forward process, and it involves no learning at all.

The network learns to run the film backward. Given a noisy image and its noise level, it predicts the noise that was added, which is the same as predicting a slightly cleaner image. To generate, start from pure noise and apply the denoiser step after step: the reverse process. Each step only has to remove a little noise, a far easier job than producing an image in one shot.

A close relative replaces the noisy walk with a smooth one. Picture every point of noise carried along by a velocity field, like a leaf on a stream, until it arrives at a data point: generating means solving an ordinary differential equation from time 00 (noise) to time 11 (data). Flow matching and rectified flow (Lipman et al., 2023; Liu, Gong & Liu, 2023) train the field by plain regression, using straight lines drawn between noise samples and data samples, and large text-to-image models have been built this way (Esser et al., 2024).

Steering what comes out

A generator is only useful if you can steer it. Two tools recur across the families.

Latent spaces. A VAE, a GAN or a flow turns a latent vector z\mathbf z into a sample, and nearby vectors give similar samples. Walk along a path between two latents and the output morphs from one face into another; move along a direction the model associates with an attribute, such as a smile or age, and you edit that attribute. Radford, Metz & Chintala (2016) found that even arithmetic works: average the latents of a few generated smiling women, subtract the average for neutral women, add the one for neutral men, and the result decodes to smiling men.

Conditioning. Give the network the condition cc as an extra input (a class label, a sketch, or a sentence turned into vectors by a text encoder) and train on pairs (x,c)(\mathbf x, c), so that it learns p(x∣c)p(\mathbf x\mid c). Image-to-image models condition on a whole picture: a map becomes a satellite photo, a sketch becomes a shoe.

Think first Latents are drawn from N(0,I)\mathcal N(\mathbf 0,I) in, say, d=512d=512 dimensions. Why might the straight-line midpoint of two such latents decode to a dull, washed-out image?

In high dimensions almost all of a Gaussian's samples lie near a sphere of radius about d\sqrt d, here about 22.6. The midpoint of two independent samples has length only about d/2\sqrt{d/2}, about 16, a radius at which the decoder almost never saw a latent during training. Interpolating along the sphere (slerp) keeps the latents typical; the Emergence lesson Latent Spaces for Generative Models derives this.

Is it any good?

Grading a classifier is easy: count its mistakes on held-out data. Grading a generative model is not, because there are at least three different things to want, and they can disagree:

  • Likelihood: how probable the model finds held-out real data. Autoregressive models and flows give it exactly, VAEs and diffusion models through a bound or at extra cost, GANs not at all.
  • Fidelity: does each sample look real?
  • Diversity, or coverage: do the samples, taken together, cover all of the data rather than a corner of it?

A model can have excellent likelihood and poor samples, or great samples and poor likelihood (Theis, van den Oord & Bethge, 2016), and a model that copies its training images looks perfect on fidelity while having learned nothing new. The most widely used image score, the Fréchet inception distance (FID; Heusel et al., 2017), compares statistics of a pretrained network's features on real and generated images, folding fidelity and diversity into one number. The Emergence lesson Evaluating Generative Models pulls them apart and shows how to detect memorization.

FamilyHow it samplesLikelihoodNetwork passes per sampleLatent code
Autoregressiveone piece at a time, each conditioned on the ones beforeexactone per piecenone
VAEdecode a random latenta lower boundoneyes, low-dimensional
GANpush a random latent through the generatornoneoneyes
Normalizing flowinvert a learned invertible map applied to noiseexactoneyes, as large as the data
Diffusion, flow matchingdenoise or integrate step by step from noisea bound, or exact but costlytens to hundreds (fewer after distillation)the starting noise
Each row is a different bargain between likelihood, speed and control, and real systems combine them: latent diffusion is an autoencoder plus diffusion, and image and audio tokenizers are autoencoders that feed autoregressive transformers.

Key takeaways

  • A discriminative model learns p(y∣x)p(y\mid\mathbf x); a generative model learns p(x)p(\mathbf x) or p(x∣c)p(\mathbf x\mid c) well enough to sample new data.
  • Autoregressive models multiply one-step predictions: exact likelihood, sequential sampling. Every language model is one.
  • Autoencoders compress data to a latent code; VAEs make the codes follow a known distribution so that decoding random codes generates data, at the price of some blur.
  • GANs train a generator against a discriminator: sharp one-pass samples and no likelihood, with unstable training prone to mode collapse.
  • Diffusion and flow models turn noise into data in many small steps; fewer steps are faster but cruder. Latents, conditioning and guidance steer all of the families.
  • Likelihood, fidelity and diversity are different goals, and no single number measures all three.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which of these models can report the exact probability it assigns to a test image?

  1. A GAN
  2. A VAE
  3. A PixelCNN-style autoregressive model
  4. A plain autoencoder
Show the answer

C. A PixelCNN-style autoregressive model

An autoregressive model's probability is the product of its one-step predictions, each a distribution over the next pixel value, so it can be computed exactly in one pass. A VAE gives only a lower bound, a GAN gives no probability at all, and a plain autoencoder is not a probabilistic model.

Question 2

Why does a VAE's encoder output a mean and a spread, with a penalty that pulls them toward N(0,I)\mathcal N(\mathbf 0,I)?

  1. To make training faster
  2. So that the codes fill a known distribution you can sample from, and random codes decode to plausible data
  3. To make reconstructions sharper than a plain autoencoder's
  4. To make the latent space discrete
Show the answer

B. So that the codes fill a known distribution you can sample from, and random codes decode to plausible data

After training, codes drawn from N(0,I)\mathcal N(\mathbf 0,I) land where the decoder has seen codes before, so decoding them generates new data. A plain autoencoder's codes form an unknown, gappy cloud that cannot be sampled.

Question 3

A GAN has reached the ideal end of training: its samples are distributed exactly like the data. What does the best possible discriminator output?

  1. 11 for every real image and 00 for every fake
  2. 00 for every input, since half the inputs are fakes
  3. A random 00 or 11
  4. 12\tfrac12 for every input
Show the answer

D. 12\tfrac12 for every input

When real and generated data have the same distribution, nothing distinguishes them, and the output that minimizes the discriminator's loss is 12\tfrac12 everywhere. The Representation lesson derives the optimal discriminator for any generator.

Question 4

You cut a diffusion model's sampler from 50 denoising steps to 5. What should you expect?

  1. Faster sampling but worse samples, because a few large steps approximate the reverse process crudely
  2. Exactly the same samples, ten times faster
  3. Better samples, because fewer steps add less noise
  4. Nothing at all until the model is retrained for 5 steps
Show the answer

A. Faster sampling but worse samples, because a few large steps approximate the reverse process crudely

Each denoising step is only accurate for a small change in noise level. With 5 steps each jump is large, and samples land off the data, as the widget showed on the rings. Distillation and better solvers recover quality at few steps: see the Emergence lesson on few-step generation.

Question 5

A "model" simply outputs random images from its training set. Which statement is true?

  1. Its FID will be poor, because copied images are easy to detect
  2. It shows mode collapse, since it only repeats old images
  3. Its samples look real and cover the data, yet it has learned nothing beyond the training set: good-looking samples alone cannot certify a model
  4. Its likelihood on held-out test images will be excellent
Show the answer

C. Its samples look real and cover the data, yet it has learned nothing beyond the training set: good-looking samples alone cannot certify a model

A lookup table scores well on fidelity and even on many diversity measures, but it cannot produce anything new and gives zero probability to unseen test images. Detecting memorization takes dedicated tests, a theme of the Emergence lesson on evaluation.

Go deeper

Further reading

  • S. J. D. Prince, Understanding Deep Learning, ch. 14–18 (MIT Press, 2023), free at udlbook.github.io.
  • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, ch. 20 "Deep Generative Models" (MIT Press, 2016), free at deeplearningbook.org.