Generative models, one map: what each family can compute
The opener of a series that ends at one-step generators. What it means to learn a distribution; maximum likelihood as a KL divergence; change of variables and normalising flows; VAEs; GANs and their divergences, including MMD; energy-based models, the score and Langevin dynamics; autoregressive models. Every result derived step by step, and a flow, a VAE and a GAN trained on the same data to show how each one fails.
Contents
- Notation
- 1. What it means to learn a distribution
- Three things a model can be asked to do
- Maximum likelihood is a KL divergence
- Forward and reverse KL make different mistakes
- When the model cannot be evaluated
- 2. Pushing noise forward: change of variables
- 3. Normalising flows: exact likelihood, invertible maps
- 4. Latent variables and VAEs
- 5. GANs: learning a sampler with a classifier
- Divergences that see distance: Wasserstein and MMD
- 6. Energy-based models and the score
- 7. Autoregressive models
- 8. Same data, three families
- 9. The map, and where this series goes
- Questions
- References
A generative model turns noise into data. Below, Gaussian noise on the left is pushed through an invertible map into the plane on the right. Slide from 0 to 1 to apply the map, and hover over the right panel to see the density at a point computed from the formula this post derives:
What to try. At the map is the identity and the two panels agree. As grows, the grid on the right is stretched outwards, swirled and bent, and the two colours let you follow the upper and lower halves of the noise. The heat map is the density of , computed from the change-of-variables formula: it stays high where the grid cells stay small and thins out where they grow. At the circled point, and the map expands area there by , so . Hover elsewhere to see the same bookkeeping.
This is the first post of a series on deep generative models: this map, then diffusion models, flow matching, and finally the one-step generators that are the newest part of the field. Each later post builds on what is set up here, so this one answers the questions that the others take for granted:
- What does it mean to learn a distribution, and how do you measure success when all you have is samples? (Section 1.)
- What can each family compute, a density, samples or the score, and at what cost? (Sections 2 to 7.)
- Why does each family fail the way it does? I trained a flow, a VAE and a GAN on the same data to show it. (Section 8.)
- Where do diffusion, flow matching and one-step generators fit? (Section 9.)
Every result has a folded proof in numbered steps. The shared example of the series is a ring of eight Gaussians in the plane, simple enough to see everything and hard enough that every family gets something wrong.
Notation
Plain italic letters are scalars, bold italic lower case are vectors, bold upright capitals are matrices.
| Symbol | Meaning |
|---|---|
| , | a data point and the data distribution |
| , | noise or a latent variable, usually |
| the model distribution, with parameters | |
| , | an invertible map (flow); a generator (sampler) |
| the Jacobian matrix of | |
| an encoder: an approximate posterior over | |
| a GAN discriminator | |
| , | an energy and its normalising constant |
| the score | |
| , , | Kullback–Leibler, Jensen–Shannon, maximum mean discrepancy |
Later posts add time: with data at and noise at , a score and a velocity .
1. What it means to learn a distribution
Three things a model can be asked to do
We have samples from an unknown , and nothing else. A model can be asked for three different things:
- Sample: produce new . Image and audio generation need only this.
- Evaluate: compute at a given point. Compression, anomaly detection and model comparison need this.
- Score: compute , the direction in which the density grows fastest. Diffusion models are built on it.
No family does all three cheaply. That single fact organises the whole field, and this post.
Maximum likelihood is a KL divergence
The standard way to fit is to maximise the average log-likelihood of the data. It has a precise meaning.
Definition 1 (Kullback–Leibler divergence)
. It is non-negative and zero only when (Gibbs’ inequality, proved in the sparse GP post, Section 2).
Proposition 1 (Maximum likelihood minimises the forward KL)
and the average is an unbiased estimate of the expectation on the left.
Proof
Step 1. Expand the KL. .
Step 2. The first term does not depend on . It is minus the entropy of the data, a constant. So minimising the KL over is the same as maximising the second expectation.
Step 3. The sample average. Each is drawn from , so equals the expectation, and so does the expectation of their average.
Two consequences matter for everything that follows. Maximum likelihood needs , so it needs a model that can evaluate. And it minimises the KL in one particular direction, which decides what kind of mistakes the model prefers.
Forward and reverse KL make different mistakes
averages over . Wherever the data have mass and the model has almost none, is huge, so the fit spreads over all the data, even where that means putting mass between modes. The reverse divergence averages over the model instead: it punishes the model for putting mass where the data have none, so it prefers to sit inside one mode. Fit a single Gaussian to two modes and watch both:
With the modes close together (separation ), both fits are almost the same wide Gaussian. Pull them apart. At the maximum-likelihood fit has mean and standard deviation : it covers both modes, and puts most of its mass in the empty middle. The reverse-KL fit sits exactly on the larger mode (mean , standard deviation ) and ignores the other one.
Proposition 2 (The forward-KL Gaussian matches moments)
Among Gaussians , is minimised by the mean and variance of : and .
Proof
Step 1. Only the cross term depends on . .
Step 2. Write out the Gaussian log-density. .
Step 3. Split the square. With and , , because the cross term is zero.
Step 4. Minimise over . Only depends on , so .
Step 5. Minimise over . The objective is now . Its derivative in is , which is zero at , and the second derivative there is .
This is the root of a theme that runs through the series. Likelihood-based models (flows, VAEs, and diffusion models, whose training is a bound on the likelihood) are mass-covering: they rarely drop a mode, but they can put mass where there are no data. Models trained by other divergences can be mode-seeking: sharp, but liable to miss modes.
When the model cannot be evaluated
If the model is only a sampler, is unavailable and maximum likelihood is impossible. Then the two distributions must be compared from samples alone. Three ways are standard, and Section 5 derives them: train a classifier to tell them apart (the Jensen–Shannon divergence of GANs), measure how far mass must move (the Wasserstein distance), or compare averages of kernel features (the maximum mean discrepancy).
2. Pushing noise forward: change of variables
The simplest way to build a sampler is to transform noise: draw and set . The distribution of is the pushforward of through . Sampling is one evaluation of . Evaluating the density of is possible when is invertible, and the formula is the most-used identity in generative modelling.
Theorem 1 (Change of variables in one dimension)
Let be differentiable and strictly increasing, and . Then
For strictly decreasing , replace by .
Proof
Step 1. The CDF. For increasing , exactly when . So , with the CDF of .
Step 2. Differentiate in . The density is the derivative of the CDF. By the chain rule, .
Step 3. The derivative of the inverse. Differentiating gives .
Step 4. Decreasing . Then exactly when , so . Differentiating gives the same formula with .
Where is steep, an interval of is stretched over a long interval of , so the same probability is spread thinner, and the density falls. Where is flat, it piles up. In more dimensions, “steepness” becomes the factor by which changes volume, which is the absolute determinant of its Jacobian.
Theorem 2 (Change of variables)
Let be invertible and differentiable with a differentiable inverse, and . Then
or, in logs, .
Proof
Step 1. Probabilities of sets. For any region , exactly when , so .
Step 2. Substitute . The multivariate substitution rule of calculus says . So .
Step 3. Read off the density. This holds for every region , so the integrand is the density of .
Step 4. Jacobian of the inverse. Differentiating with the chain rule gives , so and .
Corollary 1 (Compositions add their log-determinants)
For with and ,
Proof
Step 1. Chain rule. .
Step 2. Determinants multiply. , so the log of the absolute determinant of the product is the sum of the logs. Substitute into the theorem.
The figure at the top is this formula, live. The map there is a radial stretch, a swirl and a shear. The swirl and the shear preserve area (determinant 1), so the density changes only through the stretch. The formula’s readout is exact, and the heat map on the right is computed from it; I checked that it integrates to 1 and that the log-determinant matches a numerical Jacobian to ten decimal places.
3. Normalising flows: exact likelihood, invertible maps
A normalising flow makes the invertible map learnable: with , each a small invertible network. The corollary gives exactly, so the flow trains by maximum likelihood and samples in one pass (Rezende and Mohamed, 2015; Dinh, Sohl-Dickstein and Bengio, 2017).
The difficulty is cost. The determinant of a general Jacobian costs , and for an image is in the hundreds of thousands. So flows are built from layers whose Jacobians are triangular, whose determinant is the product of the diagonal.
Proposition 3 (The affine coupling layer)
Split and let and be any networks. The map
is invertible in closed form, and , at cost .
Proof
Step 1. The inverse. , and then . Nothing needs inverting except an exponential, because and are only ever evaluated at , which is known.
Step 2. The Jacobian’s blocks. and . . The block is complicated, but it sits below the diagonal.
Step 3. The determinant. The Jacobian is block lower-triangular, so its determinant is the product of the diagonal blocks’ determinants: .
Step 4. Stacking. One layer leaves unchanged, so consecutive layers swap the roles of the two halves.
Flows have one limitation that no amount of training removes.
Proposition 4 (A flow cannot separate modes)
If is continuous and has a positive density on all of , then the flow’s density is positive on the connected set . If the data’s modes are separated by regions of zero density, the flow must still put positive density on paths between them.
Proof
Step 1. The support. for every in the image , since both factors are positive.
Step 2. The image is connected. is connected, and the continuous image of a connected set is connected.
Step 3. Conclusion. Any two modes lie in one connected set on which the density is positive, so there is a path between them along which the density never vanishes.
On the ring of eight Gaussians (Section 8) the trained flow does exactly this: it draws thin bridges from mode to mode, and a quarter of its samples land on them. Continuous-time flows, which define by an ordinary differential equation , share the limitation, and they are the starting point of the flow-matching post.
4. Latent variables and VAEs
A latent-variable model does not need to be invertible. It draws a latent and then from a decoder , for example . Sampling is easy, but the likelihood
has no closed form once the decoder is a neural network. Variational inference supplies a bound. The sparse GP post, Section 2, derives it in general; here it is for one data point.
Proposition 5 (The VAE bound (Kingma and Welling, 2014; Rezende, Mohamed and Wierstra, 2014))
For any distribution ,
Proof
Step 1. Bayes’ rule, pointwise in . .
Step 2. Add and subtract and group:
Step 3. Average over . The left side does not depend on . The three averages on the right are the reconstruction term and the two KL divergences.
The last KL is non-negative, so the ELBO is a lower bound, and maximising it over makes the encoder approximate the true posterior. Two choices make it trainable at scale. The encoder is amortised: one network outputs for every , instead of separate parameters per data point. And the expectation is estimated by reparameterisation, , proved in the deep GP post, Section 5. The KL term is in closed form:
Proposition 6 (KL to a standard Gaussian)
Proof
Step 1. The general formula for is (proved in the Gaussian toolkit).
Step 2. Substitute , , , : the trace is , the quadratic form is , and .
Why VAE samples look the way they do follows from the model, not from bad training:
- The decoder adds isotropic noise. A sample is the decoder mean plus , which blurs every output by the same amount in every direction.
- The prior has holes. The encoder maps the data to a set of codes, but the prior also covers codes that no data point maps to. Those decode to points between the modes.
- The bound has a gap. Training maximises the ELBO, not the likelihood, and a decoder that ignores can make the KL term zero. When this posterior collapse happens, the model explains the data as noise.
5. GANs: learning a sampler with a classifier
A generative adversarial network (Goodfellow et al., 2014) keeps only the sampler, , with no density at all. To compare its samples with the data, it trains a classifier to tell real from generated, and trains to fool it:
What is the generator really minimising? Write for the distribution of .
Proposition 7 (The optimal discriminator)
For fixed , is maximised by .
Proof
Step 1. One integral. , writing the second expectation over .
Step 2. Maximise pointwise. can be chosen separately at each , so maximise over , with and .
Step 3. Set the derivative to zero. gives . The second derivative, , is negative, so it is a maximum.
Proposition 8 (GANs minimise the Jensen–Shannon divergence)
At the optimal discriminator, , where with .
Proof
Step 1. Substitute .
Step 2. Bring in the mixture . , so each logarithm is .
Step 3. Recognise the KLs. .
So the ideal generator minimises the Jensen–Shannon divergence, which is zero only when . In practice the ideal is far away, for two reasons:
Proposition 9 (No gradient when the supports are disjoint)
If and are positive on disjoint sets, then , however close or far apart the sets are.
Proof
Step 1. On the support of , , so and . Hence .
Step 2. Symmetrically, , so .
Step 3. Consequence. Moving a little closer to the data, without overlapping it, does not change the divergence: its gradient is zero. Early in training, and for data on thin sets such as images, this is the usual situation.
The second reason is mode collapse: the generator can fool the current discriminator by producing a few convincing kinds of sample, then move on when the discriminator catches up. Its behaviour resembles the reverse KL of Section 1, sharp and mode-seeking.
Divergences that see distance: Wasserstein and MMD
The fixes replace the Jensen–Shannon divergence with one that changes smoothly as the generated distribution moves towards the data, even without overlap. The Wasserstein-1 distance is the least average distance mass must travel to turn into ; it is estimated through its dual form with a constrained critic network (Arjovsky, Chintala and Bottou, 2017). The other fix comes from kernel methods, and returns in the post on one-step generators.
Definition 2 (Kernel mean embedding and MMD (Gretton et al., 2012))
For a positive-definite kernel with reproducing kernel Hilbert space , the mean embedding of is , and the maximum mean discrepancy is .
Proposition 10 (MMD from samples)
with and , all independent. Each term can be estimated by averaging the kernel over pairs of samples.
Proof
Step 1. Expand the squared norm. .
Step 2. The reproducing property. .
Step 3. Move the expectations out of the inner products (the inner product is linear in each argument, and the expectations are finite for a bounded kernel): , and likewise for the other two terms.
For a characteristic kernel such as the squared-exponential, only when (Sriperumbudur et al., 2010), so the MMD is a genuine discrepancy that needs only samples. Generators trained to minimise it directly, without an adversary, were among the first alternatives to GANs (Li, Swersky and Zemel, 2015; Dziugaite, Roy and Ghahramani, 2015).
6. Energy-based models and the score
An energy-based model writes down an unnormalised density, , where is any network and . Any shape is allowed, but is an integral over all of and is intractable. It enters the likelihood gradient:
Proposition 11 (The likelihood gradient of an energy-based model)
Proof
Step 1. .
Step 2. Differentiate . .
Step 3. Combine. Subtracting gives the stated form: push the energy down at the data, and up at samples from the model.
So training needs samples from the model at every step, which is expensive. The way out is a quantity that does not involve at all.
Proposition 12 (The score does not need the normalising constant)
.
Proof
Step 1. .
Step 2. depends on but not on , so its gradient in is zero.
The score points uphill in density. Remarkably, it is enough to sample.
Proposition 13 (Langevin dynamics leaves p invariant)
The stochastic differential equation has as a stationary distribution. Its discretisation , , samples approximately from for small and many steps.
Proof
We check the one-dimensional case with the Fokker–Planck equation, which the diffusion post derives. For , the density of evolves by .
Step 1. Put in and . Then .
Step 2. The right-hand side. .
Step 3. Conclusion. : if is distributed as , it stays distributed as . The drift pushes mass uphill exactly as fast as the noise spreads it out.
What remains is to learn the score from data, without knowing . Hyvärinen (2005) showed that the obvious objective can be rewritten without the unknown score.
Proposition 14 (Score matching (Hyvärinen, 2005))
In one dimension, for a model score and data density that vanish fast enough at infinity,
In dimensions the derivative becomes the divergence, .
Proof
Step 1. Expand the square. . The last term does not depend on .
Step 2. Simplify the cross term. , so .
Step 3. Integrate by parts. , because the boundary term vanishes.
Step 4. Substitute. The cross term becomes , which depends only on the model and the data samples.
In high dimensions the divergence costs one backward pass per dimension, and the score is learned badly in regions with no data, where Langevin dynamics starts. Both problems disappear if the data are first blurred with Gaussian noise of several sizes, and the score of each blurred distribution is learned instead (Vincent, 2011; Song and Ermon, 2019). That step is the beginning of diffusion models, and of the next post.
7. Autoregressive models
The last family evaluates exactly and samples slowly. Order the coordinates of , and use the chain rule of probability:
It holds for every distribution, by repeated use of , so nothing is approximated. A network outputs each conditional, for example a softmax over pixel values, so the likelihood is exact and training is maximum likelihood (van den Oord et al., 2016). Sampling must generate , then given , and so on: sequential network passes. For text that is natural, and large language models are exactly this. For an image with hundreds of thousands of values it is slow, and the ordering of pixels is arbitrary.
8. Same data, three families
Here is the ring of eight Gaussians (radius 2, standard deviation 0.1), and three models trained on it: a normalising flow (eight affine coupling layers), a VAE (two-dimensional latent, learned decoder noise) and a GAN. All three use the same small networks, one training run each with a fixed seed. Below each panel: how many of the eight modes receive at least 2% of the samples, the share of samples within three standard deviations of a mode (99% for the data), and the likelihood where the model has one.
Each family fails in the way its mathematics predicts:
- The flow covers all eight modes and draws bridges between them. A quarter of its samples lie off the modes, on the connecting paths that Section 3 proved it cannot avoid. Its likelihood is exact: 0.90 nats per point, against 0.32 for the true distribution.
- The VAE covers all eight modes and fills the space between them. Only 53% of its samples are on a mode. The decoder noise blurs, and codes from the prior’s holes decode to points between the modes. Its of 1.71 is an upper bound on its negative log-likelihood, not the value itself.
- The GAN’s samples are sharp but smear along the ring, and it drops one mode entirely. It covers 7 of 8. It has no likelihood to report at all.
With more tuning each model improves, and these small networks are far from the state of the art. But the characters are the ones reported throughout the literature: likelihood training covers the data and leaks between modes, adversarial training is sharp and drops modes.
9. The map, and where this series goes
Side by side:
| family | evaluate | network passes per sample | typical failure | training |
|---|---|---|---|---|
| autoregressive | exact | (one per coordinate) | slow sampling | stable, maximum likelihood |
| normalising flow | exact | 1 | bridges between modes; restricted layers | stable, maximum likelihood |
| VAE | lower bound | 1 | blur, holes, posterior collapse | stable, ELBO |
| GAN | none | 1 | missing modes | unstable minimax game |
| energy-based | up to | many (MCMC) | slow, hard to train | needs model samples |
| diffusion and flow matching | through an ODE, costly | tens to hundreds | slow sampling | stable, simple regression |
Xiao, Kreis and Vahdat (2022) summarised the tension as a trilemma: high sample quality, coverage of all modes, and fast sampling. GANs had quality and speed but not coverage. VAEs and flows had speed and coverage but lower quality. Diffusion models, which learn the score of the data blurred at every noise level and then follow a dynamics like Langevin’s, achieve quality and coverage and pay in speed.
The rest of the series follows that route and then removes its cost:
- Diffusion models (next): add noise until the data are Gaussian, learn to undo it, and see why denoising is score matching in disguise.
- Flow matching: replace the noisy dynamics by a deterministic flow, learned by plain regression on a velocity field, and make its paths straighter.
- One-step generators: learn to jump along the whole flow in a single network pass. This brings back the GAN’s speed with the diffusion model’s coverage: consistency models, flow maps, MeanFlow, and drifting models, where the kernel discrepancies of Section 5 return.
Questions
Question 1
A model can produce samples but not evaluate its density. Which of the divergences in this post can you still use to train it, and why not maximum likelihood?
Answer
Maximum likelihood needs at the data points, which a sampler cannot provide. Divergences that need only samples remain: the Jensen–Shannon divergence through a trained classifier (a GAN), the Wasserstein distance through a constrained critic, and the MMD, whose three terms are averages of a kernel over pairs of samples.
Question 2
Why is the density of a flow’s output low where the map stretches space, and high where it compresses it?
Answer
By change of variables, , and is the factor by which multiplies small volumes. The probability in a small region is preserved, so if the region’s volume is multiplied by 3, its density is divided by 3.
Question 3
In the GAN proof, what does the discriminator output at the optimum when the generator is perfect, and what does that tell you about training dynamics?
Answer
With , everywhere: the best classifier can only guess. The value is , the minimum. During training the discriminator is never optimal and the generator never perfect, and the two chase each other; nothing in the game guarantees that this chase converges.
Question 4
Why can score matching be computed from data, although its definition contains the unknown ?
Answer
Integration by parts moves the derivative from the data density onto the model’s score (Step 3 of the proof), turning into . What remains are expectations under of quantities that depend only on the model, which sample averages estimate.
Question 5
The VAE in Section 8 reports and the flow an exact negative log-likelihood of . Can you conclude that the flow fits the data better?
Answer
Not quite. The is only an upper bound on the VAE’s negative log-likelihood; its true value lies somewhere below 1.71. An importance-weighted estimate would tighten it. The sample statistics (53% against 75% on a mode) point the same way as the numbers, so the conclusion is probably right, but the comparison of a bound with an exact value is not by itself a proof.
References
- I. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D. Warde-Farley, S. Ozair, A. Courville, Y. Bengio. Generative adversarial nets. NeurIPS, 2014.
- D. P. Kingma, M. Welling. Auto-encoding variational Bayes. ICLR, 2014. arXiv:1312.6114
- D. J. Rezende, S. Mohamed, D. Wierstra. Stochastic backpropagation and approximate inference in deep generative models. ICML, 2014.
- D. J. Rezende, S. Mohamed. Variational inference with normalizing flows. ICML, 2015.
- L. Dinh, J. Sohl-Dickstein, S. Bengio. Density estimation using Real NVP. ICLR, 2017. arXiv:1605.08803
- G. Papamakarios, E. Nalisnick, D. J. Rezende, S. Mohamed, B. Lakshminarayanan. Normalizing flows for probabilistic modeling and inference. JMLR, 2021.
- A. Hyvärinen. Estimation of non-normalized statistical models by score matching. JMLR, 2005.
- P. Vincent. A connection between score matching and denoising autoencoders. Neural Computation, 2011.
- Y. Song, S. Ermon. Generative modeling by estimating gradients of the data distribution. NeurIPS, 2019.
- A. Gretton, K. M. Borgwardt, M. J. Rasch, B. Schölkopf, A. Smola. A kernel two-sample test. JMLR, 2012.
- B. K. Sriperumbudur, A. Gretton, K. Fukumizu, B. Schölkopf, G. R. G. Lanckriet. Hilbert space embeddings and metrics on probability measures. JMLR, 2010.
- Y. Li, K. Swersky, R. Zemel. Generative moment matching networks. ICML, 2015.
- G. K. Dziugaite, D. M. Roy, Z. Ghahramani. Training generative neural networks via maximum mean discrepancy optimization. UAI, 2015.
- M. Arjovsky, S. Chintala, L. Bottou. Wasserstein generative adversarial networks. ICML, 2017.
- A. van den Oord, N. Kalchbrenner, K. Kavukcuoglu. Pixel recurrent neural networks. ICML, 2016.
- Z. Xiao, K. Kreis, A. Vahdat. Tackling the generative learning trilemma with denoising diffusion GANs. ICLR, 2022.
- S. Bond-Taylor, A. Leach, Y. Long, C. G. Willcocks. Deep generative modelling: a comparative review of VAEs, GANs, normalizing flows, energy-based and autoregressive models. IEEE TPAMI, 2022.
Was this useful?
Thanks, that helps me decide what to write next.