Contents
- 0. Where This Note Comes From and How to Read It
- 0.1 Origin
- 0.2 Notation
- 0.3 Index of Derivations
- 0.4 How to Read
- 1. The Shared Framework: What Generative Modeling Is Actually Doing
- 1.1 Problem Definition: Given Only Samples, Ask for a Density
- 1.2 Four Routes, Two Camps
- 1.3 Three “Distances”: KL, JS, and Wasserstein
- 1.4 Evaluation Metrics: High Likelihood Does Not Mean Good-Looking Images
- 1.5 Structural Analogy with Reinforcement Learning
- 1.6 Quick Overview of the Four Models
- 2. Variational Autoencoder (VAE)
- 2.1 Why It Is Needed: An Autoencoder Lacks the “Can Sample” Half
- 2.2 Principles and Formulas
- 2.3 The Evidence Lower Bound: Derived from logpθ(x)\log p_\theta(x)logpθ(x)
- 2.4 The KL Between Two Diagonal Gaussians
- 2.5 The Reparameterization Trick: Letting Gradients Pass Through Sampling
- 2.6 Training Details: KL Weight, Posterior Collapse, and Tighter Bounds
- 2.7 Pseudocode: VAE (Complete Version)
- 2.8 Section-by-Section Walkthrough of the Pseudocode
- 2.9 Per-Step Read/Write and State-Maintenance Checklist
- 2.10 Pitfall List
- 2.11 Scope of Application
- 3. Generative Adversarial Network (GAN)
- 3.1 Why It Is Needed: Likelihood Does Not Measure “Does It Look Right”
- 3.2 Principles and Formulas
- 3.3 The Optimal Discriminator and the JS Divergence
- 3.4 The Non-Saturating Loss: Straightening the Gradient Scale Back
- 3.5 The Fatal Weakness of JS: Zero Gradient When the Distributions Do Not Overlap
- 3.6 The Wasserstein Distance and the Kantorovich-Rubinstein Duality
- 3.7 Stabilization Techniques: From Structural Constraints to Spectral Normalization
- 3.8 Mode Collapse: An Inevitable Consequence of Reverse KL
- 3.9 Pseudocode: WGAN-GP (with a Note on the Difference from the BCE Version)
- 3.10 Section-by-Section Walkthrough of the Pseudocode
- 3.11 Per-Step Read/Write and State-Maintenance Checklist
- 3.12 Pitfall List
- 3.13 Scope of Applicability
- 4. Normalizing Flow
- 4.1 Why It Is Needed: A Density That Can Be Computed
- 4.2 The Change of Variables Formula
- 4.3 The Two Families of Invertible Structures
- 4.4 Affine Coupling Layer
- 4.5 Glow’s Invertible 1×11\times11×1 Convolution
- 4.6 Continuous Flow: Replacing “Layers” with “Time”
- 4.7 Engineering Details of Training and Sampling
- 4.8 Pseudocode: A RealNVP-Style Coupling Flow
- 4.9 Section-by-Section Walkthrough of the Pseudocode
- 4.10 Per-Step Read/Write and State-Maintenance Checklist
- 4.11 Pitfall List
- 4.12 Scope of Applicability
- 5. Diffusion Model
- 5.1 Why It Is Needed: Turning “One Giant Leap” into “A Thousand Small Shifts”
- 5.2 The Forward Chain and the Reverse Chain: Two Directions, Two Roles
- 5.3 Closed-Form Marginal of the Forward Process (Derivation 14)
- 5.4 The Evidence Lower Bound and the True Posterior (Derivation 15)
- 5.5 Four Parameterizations: Predict μ\muμ, x0x_0x0, ε\varepsilonε, or the Score
- 5.6 From the Term-by-Term KL to the Simplified Loss (Derivation 16)
- 5.7 The Score Viewpoint: the Tweedie Formula, Score Matching, and DDIM
- 5.8 Complete Pseudocode
- 5.9 Section-by-Section Walkthrough of the Pseudocode
- 5.10 Per-Step Read/Write and State-Maintenance Checklist
- 5.11 Pitfall List
- 5.12 Scope of Applicability
- 5.13 Relations with the Previous Three (One Table to Close)
- 6. Cross-Cutting Summary: Putting the Four Models in One Coordinate System
- 6.1 Master Table
- 6.2 The Six Key Divergences
- 6.3 The Six-Question Selection Decision Chain
- 6.4 The Four Most Easily Mismatched Combinations
- 6.5 One-Page Cheat Sheet
- 6.6 Five Universal Principles
- 6.7 The Concept Correspondence with Reinforcement Learning
- References
- Appendix: Abbreviation Quick-Reference
Notes on the Four Major AIGC Generative Models: Principles, Derivations, and Pseudocode for VAE, GAN, Normalizing Flow, and Diffusion Models
0. Where This Note Comes From and How to Read It
0.1 Origin
The writing of this note follows the site’s Deep Reinforcement Learning Core Algorithms Notes and Metaheuristic Optimization Notes. Both of those do the same thing: first give the shared framework, then unfold each algorithm along the same skeleton (why it is needed → principles and formulas → collapsible derivations → complete pseudocode → section-by-section walkthrough → per-step read/write and state-maintenance checklist → pitfall list → scope of application), and finally close with one master table, a few key disagreements, and one model-selection decision chain. This article moves that skeleton onto generative modeling.
The reason these four model families deserve to be discussed together is that they answer the same question, only entering it from four different angles:
| Model | One-sentence answer to “how is represented” |
|---|---|
| Variational Autoencoder (VAE) | Introduce a latent variable , approximate the posterior with an encoder and define the likelihood with a decoder, and optimize a lower bound on the log-likelihood |
| Generative Adversarial Network (GAN) | Write no density, only a sampler, and use a discriminator to turn “does it look real” into a training signal |
| Normalizing Flow | Carry a simple distribution onto a complex one with a chain of invertible transforms, with determinants guaranteeing that the likelihood is exactly computable |
| Diffusion Model | Split generation into tens to thousands of steps of “remove a little noise”, each step learning only one simple conditional distribution |
The relation among the four can be compressed into one sentence: VAE is “use a lower bound to bypass an integral that is hard to compute”, GAN is “use adversarial play to bypass a density that is hard to compute”, flow is “use invertible structure to make the integral computable”, diffusion is “use many small distributions to bypass one hard distribution”. These four sentences are the outline of the whole article; each later chapter expands one of them.
0.2 Notation
| Symbol | Meaning |
|---|---|
| a data sample (an image, audio, a sequence of text tokens, etc.), of dimension | |
| latent variable, of dimension , usually or | |
| the true data distribution, accessible only indirectly through training-set samples | |
| the model distribution defined by parameters | |
| the prior distribution of the latent variable, usually | |
| the variational posterior (encoder), defined by parameters | |
| the generative distribution (decoder / likelihood) | |
| discriminator output, interpreted as the probability that comes from data | |
| generator, mapping noise to a sample | |
| the sample distribution induced by the generator | |
| invertible transform (flow model), | |
| Jacobian matrix, with entries | |
| the noisy sample at step of the diffusion process, being clean data and pure noise | |
| the per-step noise variance of the forward diffusion process | |
| ; | |
| standard Gaussian noise, | |
| Kullback-Leibler divergence (KL divergence), | |
| Jensen-Shannon divergence (Jensen-Shannon divergence), the JS divergence | |
| first-order Wasserstein distance (Earth Mover’s Distance) | |
| Evidence Lower Bound, a lower bound on the log-likelihood | |
| Fréchet Inception Distance (a common metric for generation quality and diversity) | |
| Inception Score | |
| number of function evaluations, the core measure of sampling cost |
Note: the notation of the original literature of the four model families is mutually incompatible (VAE uses for encoder/decoder, GAN uses for the generator and for the discriminator, flow models use for the whole transform, diffusion uses for the noise network). This article unifies everything as in the table above: every “generative-side” parameter is written , every “inference-side / opponent-side” parameter is written . When reading a specific paper, translate its notation once according to that table; this is the place where cross-paper comparison most easily goes wrong.
0.3 Index of Derivations
The article contains 32 collapsible derivations, written in three batches: derivations 1–16 are the main-line derivations of each of the four models; derivations 17–24 are refinement derivations written for eight common gaps (the importance-weighted bound, the Lagrangian interpretation of free bits, the unified f-GAN framework, the Lipschitz argument behind WGAN-GP, the Jacobians of coupling layers and autoregressive flows, dequantization and bits per dimension, the implicit weights of the simplified loss, and classifier-free guidance); derivations 25–32 are a further round for eight places where “the main text mentions a concept but does not expand it” (the geometric difference between the minimax and the maximized lower bound, the closed-form Fréchet distance behind FID, the equivalence between the reconstruction term and the mean squared error, the quantitative condition for posterior collapse, the Lipschitz upper bound of spectral normalization and power iteration, a toy counterexample for mode collapse, the conversion among the four diffusion parameterizations, and the relation between the probability-flow ODE and DDIM). The numbering within each batch is continuous, but the positions are not strictly sorted by chapter, so use the table when looking things up:
| Number | Location | Derivation content |
|---|---|---|
| Derivation 1 | 1.2 | Why “computing the density in one step” is infeasible in general (the partition function is intractable) |
| Derivation 2 | 1.3 | The relations among the three distances: size and gradient behavior of KL, JS, and Wasserstein |
| Derivation 3 | 2.3 | The complete decomposition of the evidence lower bound (starting from , including the second way of writing the gap) |
| Derivation 4 | 2.4 | The closed form of the KL divergence between two diagonal Gaussians, and why it decomposes dimension by dimension |
| Derivation 5 | 2.5 | The validity of the reparameterization trick: why gradients can pass through sampling |
| Derivation 6 | 3.3 | The closed form of the optimal discriminator , and why the objective at the optimum equals |
| Derivation 7 | 3.4 | The gradient scale of the non-saturating loss, and why the original loss saturates |
| Derivation 8 | 3.5 | When the supports of the distributions do not overlap, the JS divergence is constant and the gradient is zero |
| Derivation 9 | 3.6 | The Kantorovich-Rubinstein duality of the Wasserstein distance (including the origin of the 1-Lipschitz constraint) |
| Derivation 10 | 4.2 | The change-of-variables formula: from one-dimensional density transformation to the high-dimensional Jacobian determinant |
| Derivation 11 | 4.4 | The Jacobian of an affine coupling layer is triangular, $\log\left |
| Derivation 12 | 4.5 | The $\log\left |
| Derivation 13 | 4.6 | The instantaneous change of variables for continuous flows and the Hutchinson trace estimate |
| Derivation 14 | 5.3 | The superposition-of-Gaussians proof of the closed-form forward marginal distribution |
| Derivation 15 | 5.4 | The term-by-term rearrangement of the evidence lower bound, and the closed form of the true posterior |
| Derivation 16 | 5.6 | The simplified loss: from per-term KL to noise regression, and where the coefficients went |
| Derivation 17 | 2.6 | Why the importance-weighted bound (IWAE) is tighter than the evidence lower bound, and its limit as |
| Derivation 18 | 2.6 | The Lagrangian interpretation of -VAE and free bits: why both are merely penalty formulations of a KL constraint |
| Derivation 19 | 3.3 | f-GAN: the variational lower bound of an arbitrary f-divergence, the Fenchel conjugate, and the optimal discriminator |
| Derivation 20 | 3.6 | Why the gradient penalty of WGAN-GP is equivalent to “gradient norm equal to one”, and why the penalty points are taken on the connecting line |
| Derivation 21 | 4.4 | The reciprocal determinants of the coupling-layer inverse transform, and the lower-triangular Jacobian of MAF/IAF |
| Derivation 22 | 4.7 | Why dequantization contributes to bits per dimension, and why skipping the noise is a cheating solution |
| Derivation 23 | 5.6 | The coefficient dropped by the simplified loss and the signal-to-noise-ratio weighting (including Min-SNR) |
| Derivation 24 | 5.7 | Where the score in classifier-free guidance comes from, why extrapolates, and what its geometric meaning is |
| Derivation 25 | 1.2 | The minimax of GAN versus the maximized lower bound of VAE: weak duality, the absence of a saddle point, and the rotation of the bilinear toy problem |
| Derivation 26 | 1.4 | The closed form of FID: the distance between two Gaussians in feature space, including the matrix square-root term |
| Derivation 27 | 2.2 | When the decoder is Gaussian, why the reconstruction term is the mean squared error, and how and become the same knob |
| Derivation 28 | 2.6 | The quantitative condition for posterior collapse: and the effective number of latents |
| Derivation 29 | 3.7 | The 1-Lipschitz upper bound of spectral normalization and the convergence rate of power iteration |
| Derivation 30 | 3.8 | The minimal counterexample for mode collapse: the forward KL diverges, the reverse KL is , and the JS divergence is always |
| Derivation 31 | 5.5 | The conversion among the four parameterizations (): is a 45° rotation and its error scale is independent of |
| Derivation 32 | 5.7 | Fokker-Planck equation → continuity equation → probability-flow ODE, and DDIM as its first-order Euler step |
In addition, Section 5.7 puts the Tweedie formula and the DDIM update into the body of the same derivation-style passage (without folding them separately), because they have already been fully expanded in the site’s Diffusion Model Notes; here only the main lines needed for the four-model comparison are kept.
0.4 How to Read
- Chapter 1 is the shared framework, making clear the problems shared by the four models, the four routes, the three distances, and the evaluation metrics. If you read only one chapter, read this one.
- Chapters 2 to 5 unfold in the order “VAE → GAN → Normalizing Flow → Diffusion”, each with the same skeleton. This order follows “density computability”: from being able to compute only a lower bound (VAE), to not being able to compute it at all (GAN), to being able to compute it exactly (flow), to not computing it directly but being able to bypass it (diffusion).
- Chapter 6 is the cross-cutting summary, containing one master table, six key disagreements, one model-selection decision chain, four most easily mismatched combinations, and a one-page cheat sheet. If you came only for “which family should I pick”, look at 6.1 first, then walk 6.3.
- All derivations are in collapsible blocks: look at the conclusion and the intuition first, and expand them only when you need to check the details. Every step inside a collapsible block writes out “which identity or which assumption was used”, so that you can check it yourself.
- Division of labor between this article and the site’s Diffusion Model Notes: that piece covers the full engineering detail of diffusion (U-Net, guidance, latent-space diffusion, flow matching, distillation, evaluation), whereas this article keeps only the four main lines needed for the four-model comparison (the forward closed form, the ELBO rearrangement, the equivalence of score and denoising, DDIM deterministic sampling). Consult it when you need more detail.
1. The Shared Framework: What Generative Modeling Is Actually Doing
1.1 Problem Definition: Given Only Samples, Ask for a Density
Given a training set whose samples are drawn independently and identically from some unknown distribution , generative modeling has two jobs:
- Estimate the density: construct so that it takes high values near the data and low values elsewhere;
- Sample: draw new samples from or from the distribution it induces, such that a new sample “looks like the data but not like any particular image in the training set”.
These two jobs are not equivalent. The first requires a normalizable density function; the second only requires a mapping that can carry noise onto the data manifold. GAN takes exactly the second road: it builds no density at all, only a mapping. This split (explicit density versus implicit density) is the starting point for understanding every difference among the four model families.
Maximum likelihood is the most natural objective:
It is equivalent to minimizing (up to an entropy term independent of ). This equivalence says: maximum likelihood is not “make the model memorize the training set”, but “make the model distribution approach the data distribution in the forward-KL sense”. Forward KL has an important property called support covering: whenever while , the integrand blows up, so the model is forced to leave probability for every possible data point. This property explains why the mode coverage of VAE and diffusion models is usually better than that of GAN, and also why GAN suffers from mode collapse (Section 3.8).
1.2 Four Routes, Two Camps
Split by “can the density be computed”, there are two camps and four representatives:
| Route | Density | Training signal | Sampling | Representative | Weakness in one sentence |
|---|---|---|---|---|---|
| Variational / latent variable | Only a lower bound | Reconstruction error + KL regularization | One decoding pass | VAE | The bound has a gap, the posterior approximation is biased, samples are rather blurry |
| Adversarial | Not computed at all | The discriminator’s classification signal | One forward pass | GAN | Unstable training, mode collapse, no likelihood |
| Invertible transform | Exactly computable | Exact log-likelihood | One inverse transform | Normalizing Flow, RealNVP, Glow | Strong structural constraints (must be invertible and dimension-preserving), many parameters |
| Diffusion / score | Not computed directly, but the score is estimable | Denoising regression (predicting noise or score) | Multi-step iteration | DDPM, DDIM, Flow Matching | Slow sampling, requiring tens to thousands of network evaluations |
There is also a “fifth route” not in the table: the autoregressive model (Autoregressive Model, AR: a model that predicts the next token item by item in order). It factorizes the joint density into a product of conditional densities, ; the density is exactly computable, and sampling must proceed in order. Today’s large language models are this route. This article does not expand autoregression, but mentions it in the cross-cutting summary, because the actual engineering choice for “AIGC” is often a mixture of autoregression (text) and diffusion (image/audio).
Derivation 1: Why "computing the density in one step" is infeasible in general
Step 1: write the normalized form. Any energy model can be written as
where is the energy function and is the partition function. can be computed arbitrarily easily by a neural network, but is an integral over the whole -dimensional space.
Step 2: explain why this integral cannot be computed. Numerical methods for high-dimensional integrals (grids, quadrature formulas) grow exponentially in cost with dimension: if points are taken per dimension, the total number of points is , and an image with is simply impossible. If Monte Carlo estimation is used, an unbiased estimate requires sampling from — and “sampling from ” is exactly the problem we set out to solve, which is a circular dependency.
Step 3: so only three escape routes remain. Either bypass the normalization constant (the score does not depend on — this is the theoretical fulcrum of diffusion models and score matching); or write no density and learn only a mapping (GAN); or design the structure so that the determinant is computable, turning in the change-of-variables formula into an sum (flow models). VAE takes the fourth route: instead of computing , it substitutes a computable lower bound.
Step 4: this explains why the technical routes of the four model families are so different. They are not four “styles” but four ways around the same difficulty (an intractable partition function). When reading any generative model, the first question to ask is which escape route it chose.
Derivation 25: Why GAN's minimax is a saddle-point problem while VAE's maximization of a lower bound is one-sided
Step 1: write both objectives in dual form. The VAE optimization is
The two maxima can be exchanged, because for every the inner maximization over is always defined; this is “raising the same lower bound with both the encoder and the decoder”, and there is no adversarial relation at all.
The GAN objective is
Here and generally cannot be exchanged.
Step 2: the weak duality inequality. For any we have ; taking the maximum over on both sides gives
The left side is “move the generator first, then the discriminator”; the right side is “move the discriminator first, then the generator”. Equality requires a saddle point to exist, and Sion’s minimax theorem requires to be convex in one variable and concave in the other; is neither convex nor concave in (because passes through a neural network), so equality generally fails.
Step 3: why alternating gradients just go around in circles. Take the bilinear toy objective , which captures the minimal structure of “the discriminator improving makes life harder for the generator, and the generator improving makes life harder for the discriminator”. The alternating gradients are
Along its solutions , so the trajectory is a closed circle: the parameters rotate forever instead of converging. This is the continuous-time explanation of “the GAN loss keeps moving while sample quality does not improve”. In real networks the generator Jacobian is asymmetric, which amplifies this rotation, hence the need for different learning rates on the two sides (two time-scale update rule, TTUR), Adam’s second moment, gradient penalties or spectral normalization to damp it.
Step 4: why the VAE does not have this problem. The maximization of over pushes in the same direction; there is no “one side wins, the other loses”. Its gradient is the variance-reduced policy-gradient form
The sign is determined by “the log ratio of the sample minus the current lower bound”, and no adversarial sign flip can occur. The price is that the bound may be loose (the gap is quantified in Derivation 3) and posterior collapse is common (Derivation 28).
Conclusion: “saddle point” and “one-sided maximization” are two different optimization geometries. To classify a new method, just check whether the objective has two groups of parameters performing opposite / ; if it does, be prepared for rotation and non-convergence.
1.3 Three “Distances”: KL, JS, and Wasserstein
Training a generative model is essentially pushing toward under some distribution distance. Which distance is chosen determines the nature of the training signal.
The key difference among the three distances is not their numerical magnitude but their behavior when the supports of the two distributions do not intersect:
- KL diverges outright when the supports do not intersect (wherever while , it is infinite);
- JS saturates at the constant when the supports do not intersect, and the gradient is zero — this is exactly the mathematical root of the training difficulty of the original GAN (Derivation 8);
- Wasserstein still gives a positive value proportional to “how far apart the two distributions are” when the supports do not intersect, and the gradient is not zero — this is the entire motivation for WGAN (Derivation 9).
Derivation 2: The relations among the three distances and their gradient behavior
Step 1: JS is the symmetrization of KL. Taking the midpoint distribution , we get
Both terms are non-negative (because the combination of and expectation is exactly the definition of KL), and both vanish when , so . The upper bound is attained when the supports do not intersect: on the support of we then have , making the first term ; on the support of we have , making the second term also , for a total of .
Step 2: JS can be written as a convex combination of KL terms, but the weights on the two sides are asymmetric. The expression above can also be written as
Expand the first term: . Note that requires evaluating on the support of , so JS simultaneously penalizes “p has mass where m has little” and “q has mass where m has little”, which is what makes it saturate instead of diverging when the supports do not intersect.
Step 3: Wasserstein is the minimum cost of “optimal transport”. is the set of all joint distributions (couplings) with marginals and ; picks one of these couplings so that the expected “transport distance” is minimal. It does not need the two distributions to share support: as long as mass can be moved from one place to another, the cost is a finite value proportional to the distance.
Step 4: the ordering among the three. In one dimension with bounded support, and hold (where is the total variation distance). These inequalities say that KL is the “strictest” (diverges fastest), JS is the “mildest” (it has an upper bound and therefore saturates), and Wasserstein is the “most geometric” (it grows linearly with distance).
Step 5: why gradient behavior matters more than numerical value. What training actually uses is the gradient, not the distance value. Let be a degenerate distribution taking a value at a single point, and let be away from it. Then the gradient of with respect to the parameter is — the discriminator is already perfect, and the generator receives no directional information; whereas , and the gradient points in the direction of “moving the point toward the data”. This is the full meaning of “JS saturates, W does not”.
1.4 Evaluation Metrics: High Likelihood Does Not Mean Good-Looking Images
This is the most counterintuitive point in generative modeling: high log-likelihood does not mean good visual quality of samples.
The reason is that likelihood is “comparing density point by point in pixel space”. As long as an image is shifted by one or two pixels, it is already far from the training sample in the sense of pixel space; yet the human eye cannot see the difference of one or two pixels. Conversely, a model that slightly shifts, duplicates, and blurs the training set may have a very high likelihood, yet its samples are a smear. Theis et al. and van den Oord et al. have both discussed this mismatch.
Engineering has therefore split into two sets of metrics:
| Metric | Based on | Explanation |
|---|---|---|
| Log-likelihood / bits per dimension (bpd) | exact or lower-bound density | suitable for comparing VAE and flow; GAN and diffusion are usually not directly comparable |
| Inception Score (IS) | the prediction distribution of a pretrained classifier over generated images | measures “whether a single image looks like some class” and “whether all classes are covered”; insensitive to mode collapse inside the same generator |
| Fréchet Inception Distance (FID) | Gaussian statistics of real and generated images in Inception feature space | the common primary metric; sensitive to missing modes, sensitive to sample count |
| Precision-recall | support overlap in feature space | reports “quality” and “coverage” separately, more interpretable than a single FID |
The closed form of FID:
where are the Gaussian moments of the real-image features and those of the generated-image features. Note that it assumes the features are Gaussian, an assumption that does not strictly hold, so absolute FID values cannot be compared across datasets — only within the same dataset, the same feature extractor, and the same sample count.
Reading advice: when reporting a generative model, give at least three things — FID (or IS) + the sample count and random seed + one coverage-type metric. With only a single FID number, it is almost impossible to judge where the model is actually strong.
Derivation 26: The closed-form Fréchet distance behind FID, and how the $W_2$ distance between two Gaussians in feature space is computed
Step 1: the one-dimensional closed form first. The 2-Wasserstein distance between two one-dimensional Gaussians and is
The idea of the derivation: in one dimension the optimal transport map is monotone, namely ; substituting it into yields the mean difference and the standard-deviation difference as the two terms.
Step 2: the multivariate generalization. With covariances ,
The optimal transport map is with
Expanding , the cross terms and simplify exactly to the matrix square root in the expression above. That square root comes from the construction that simultaneously diagonalizes two positive definite matrices: there exists an invertible with and .
Step 3: FID is exactly this. FID takes the second-to-last layer features of an Inception network, estimates means and covariances from real and generated samples respectively, and then computes
In other words, FID is “the distance between two Gaussians in feature space”, not any distance in pixel space.
Step 4: three limitations one must know. (i) It assumes the features are Gaussian, whereas real feature distributions are not, so FID is only a proxy metric; (ii) it has no upper bound, and its value depends on the Inception weights, the input resolution and the normalization, so it is incomparable once the preprocessing changes; (iii) with few samples the covariance estimate is biased, and FID is systematically too low, so reporting FID must always come with the sample count and a confidence interval. These three points explain why “FID gets better while human eyes see worse” can happen.
1.5 Structural Analogy with Reinforcement Learning
The training process of all four generative models can be written as a loop of “sample → evaluate → update”, which formally corresponds to the episode structure of reinforcement learning:
| Reinforcement learning concept | Counterpart in a generative model |
|---|---|
| Policy | Generator , decoder , reverse process |
| Environment transition | Forward noising process (fixed and known), true data distribution |
| Trajectory / episode | One sampling trajectory: in one step, or in many steps |
| Reward signal | Discriminator output, reconstruction error, log-likelihood, denoising residual |
| Value function / critic | The discriminator (GAN), the encoder (the VAE’s approximate posterior), the score implicit in the noise-prediction network |
| Policy collapse | Mode collapse |
| Entropy regularization | The VAE’s KL term, the diffusion noise schedule, the GAN’s diversity metric |
| On-policy / off-policy | Flow and VAE compute exact likelihood with the current model (on-policy); GAN evaluates current samples with a discriminator (approximately on-policy, but historical samples can be used) |
There are two places where this analogy is genuinely useful:
- It explains “why the generator needs entropy”. SAC’s maximum-entropy objective lets the policy keep multiple modes; the KL term, the noise schedule, and the diversity loss of generative models play exactly the same role — preventing the generator from staking all probability on one mode.
- It explains “why the discriminator becomes too strong”. In reinforcement learning, an overly strong critic makes the actor’s gradient vanish; in GAN, an overly strong discriminator makes JS saturate and the generator’s gradient zero. The root cause is the same in both places: when the evaluator is too good, the learner receives no signal.
1.6 Quick Overview of the Four Models
| Dimension | VAE | GAN | Normalizing Flow | Diffusion |
|---|---|---|---|---|
| Density | lower bound | none | exact | lower bound (but the score is exactly computable) |
| Latent space | yes, and continuous | yes (noise), no structural constraint | yes, of the same dimension as the data and invertible | yes (noisy samples at each noise level) |
| Sampling cost | 1 decoding pass | 1 forward pass | 1 inverse transform | passes (tens to thousands) |
| Training stability | high | low | high | high |
| Mode coverage | good (forward KL) | poor (prone to collapse) | good | good |
| Sample sharpness | rather low (rather blurry) | high | medium | high |
| Main cost | gap in the posterior approximation | tuning, stability | structural constraints, parameter count | slow sampling |
This table gives the conclusions first; the next four chapters explain the “why” of each row.
2. Variational Autoencoder (VAE)
2.1 Why It Is Needed: An Autoencoder Lacks the “Can Sample” Half
An ordinary Autoencoder (AE) compresses into with an encoder, then restores into with a decoder; the loss is the reconstruction error. It can compress and it can denoise, but it is not a generative model:
- The latent space has no probabilistic structure. After training you do not know from which distribution to draw ; drawing an arbitrary point and decoding it usually gives noise;
- The latent space may have “holes”. In the region between the encodings of two training samples, the decoder has never been trained, and its output is meaningless;
- The reconstruction error itself does not constitute a likelihood. “Reconstructing it convincingly” and “having a high density” are two different things.
VAE’s fix is very direct: put a prior distribution on the latent space, and force the posterior output by the encoder to stay close to it. The latent space is thereby “compacted” into a continuous, samplable region, and any drawn from the prior can be decoded into a reasonable sample. The price is that the encoder can no longer output a point; it must output a distribution — and the step “sampling from a distribution” is not differentiable, so reparameterization is needed.
VAE therefore has three components:
- Encoder (inference network) , usually taken as a diagonal Gaussian ;
- Decoder (generative network) , usually taken as a Gaussian or a Bernoulli;
- Prior .
2.2 Principles and Formulas
The objective VAE optimizes is the Evidence Lower Bound (ELBO):
The roles of the two terms are very clear:
- The first term, the reconstruction term: makes the decoded sample look like the input. It encourages to place where “the decoder can restore ”;
- The second term, the regularization term: makes the encoded distribution close to the prior. It encourages not to open up a small separate region for each sample, but to spread the codes over the whole prior.
These two terms are in conflict: the reconstruction term wants the variance of as small as possible (pinning to a single point, preserving information faithfully), whereas the regularization term wants to equal as closely as possible (variance 1, mean 0). The ELBO is the equilibrium point of these two forces, and is the knob that tunes this balance (Section 2.6).
Derivation 27: When the decoder is Gaussian, why the reconstruction term is the mean squared error, and how $\sigma$ and $\beta$ become the same knob
Step 1: assume a Gaussian decoder. For continuous data (pixels normalized to or ), it is standard to set
Step 2: take the negative log. The Gaussian log density is , hence
The second term depends on neither nor and is a constant during optimization. Therefore the reconstruction term is the mean squared error with coefficient : using the mean squared error in a VAE is not a design choice but a direct consequence of a Gaussian likelihood.
Step 3: and are the same knob. What the VAE actually optimizes is
Multiply the whole expression by the positive constant (this does not change the minimizer):
So “tuning ” and “tuning the assumed observation-noise standard deviation ” are the same operation: a large is equivalent to believing the data are noisy, hence trusting the reconstruction less and the prior more. This explains why -VAE can trade fidelity against disentanglement continuously with a single scalar (Derivation 18 reaches the same conclusion from the Lagrangian side).
Step 4: discrete data need cross-entropy instead. If is an 8-bit pixel, take ; the negative log-likelihood is then a per-pixel cross-entropy and there is no knob, so can only be adjusted explicitly. The form of the reconstruction loss must match the assumed data likelihood: treating images as continuous and using the mean squared error, or treating categories as Gaussian and using the mean squared error, both distort the meaning of .
2.3 The Evidence Lower Bound: Derived from
Derivation 3: The complete decomposition of the evidence lower bound, and the gap being exactly a KL divergence
Step 1: write “integrating over the latent variable” as “taking an expectation over some distribution”. By the law of total probability,
This integral becomes intractable once the dimension of is even moderately large (the same difficulty as Derivation 1 in Section 1.2). Introduce an arbitrary distribution (requiring it to have positive density on the support of , otherwise the KL diverges), and insert a “multiply by 1”:
Step 2: use Jensen’s inequality to push the inside the expectation. is concave, so for any positive random variable we have (this is Jensen’s inequality; equality holds if and only if is almost surely constant). Taking :
Step 3: split into the “reconstruction” and “KL” terms. Split the joint distribution as :
The second expectation is, word for word by the definition of KL, , and so the ELBO in the body text is obtained.
Step 4: how large the gap is — the second way of writing it. Write the ELBO as
Check: the right-hand side expands to , and the latter term is exactly minus the KL. Hence
Step 5: what this gap shows. It shows that the shortfall of the ELBO comes entirely from how good the posterior approximation is, and has nothing to do with the decoder. If happened to equal the true posterior , the ELBO would equal the log-likelihood exactly. This is where the name “variational inference” comes from: approximating a posterior that is hard to compute with a distribution that can be computed. The engineering implication is: to raise the VAE’s likelihood, either make the posterior family more flexible (e.g., importance weighting, flow-based posteriors), or make the true posterior simpler (e.g., limit the decoder’s capacity).
Step 6: the equality condition of Jensen and “why VAE samples are rather blurry”. Equality requires to be constant in almost everywhere, i.e., . In practice is a diagonal Gaussian while the true posterior usually is not, so equality cannot be attained and the ELBO systematically underestimates. The direct consequence of the underestimate: the model spreads the “uncertain part” onto the decoder’s variance, and the output becomes the average of several possible samples, which looks blurry. This is the first layer of the explanation for VAE’s blurriness (the second layer is posterior collapse, in Section 2.6).
The specific form of the decoding term. If with fixed, then
The second term does not depend on or and can be dropped. Hence “maximizing the reconstruction term” under a fixed variance is strictly equivalent to minimizing the mean squared error. This explains the first implementation trap of VAE: much code writes MSE while believing it is optimizing a likelihood; under a fixed variance the two really do coincide, but as soon as the decoder learns itself, the equivalence breaks (see the pitfall list in Section 2.10).
2.4 The KL Between Two Diagonal Gaussians
Derivation 4: The closed form of the KL divergence between two diagonal Gaussians, and why it decomposes dimension by dimension
Step 1: reduce to one dimension. Because both and are products of independent one-dimensional Gaussians, the KL of the joint distribution equals the sum of the one-dimensional KLs:
This follows from the definition of KL plus the product structure: and likewise for , and the expectation factorizes. So it suffices to look at one dimension.
Step 2: write out the log densities of that dimension. , :
Step 3: take the difference and the expectation. The constant term cancels:
Using the two second-moment identities and , substituting gives
Step 4: rearrange into the common form. Write as :
Summing over dimensions gives the formula in the body text. Two properties of this expression matter:
- It involves no sampling. The KL term is computed analytically, and the gradient passes straight to the encoder parameters without reparameterization;
- It is very sensitive to the shape of . When , , so the regularization term does not allow the encoder to squeeze the variance to 0; when it attains its minimum 0. These two properties are exactly the mathematical mechanism behind “the latent space is compacted onto the prior”.
2.5 The Reparameterization Trick: Letting Gradients Pass Through Sampling
The first term of the ELBO must be differentiated with respect to , and appears inside sampling: “draw a from ”. Sampling is a random operation, and gradients cannot pass through it directly.
Derivation 5: The validity of the reparameterization trick, and its variance comparison against the score function estimator
Step 1: move the randomness to a position that has no parameters. Let , where is independent of . Because a linear transform preserves Gaussianity,
i.e., the distribution of is exactly the same as before. But the way it is written has changed: the randomness comes only from , and appears only in the deterministic map .
Step 2: use a change of measure to write “the expectation over ” as “an expectation over a fixed distribution”.
This step is an equality, not an approximation: both expectations are taken over the same random variable , only with a different parameterization.
Step 3: push the gradient inside the expectation. Provided and satisfy integrability and local Lipschitz conditions (in engineering terms, “the network is an ordinary neural network”),
This is the reparameterized gradient. Written term by term: the partial derivative with respect to is (because ), and the partial derivative with respect to is .
Step 4: compare with the score function estimator. Without reparameterization, the only available unbiased estimator is
This is the REINFORCE-type estimator of reinforcement learning (also called the likelihood-ratio estimator or score function estimator). It is unbiased, but its variance is very large: it uses only the scalar value of to weight a high-dimensional gradient in a direction unrelated to , compressing the information “was this sample good” into a single number. The reparameterized version, in contrast, passes back dimension by dimension, carrying far more information.
Step 5: the cost and the boundary of applicability. Reparameterization requires to belong to a “reparameterizable” family (Gaussians, Laplace, Logistic, Gumbel-Softmax approximations, etc.) and requires to be differentiable with respect to . Discrete latent variables cannot be reparameterized directly (they need Gumbel-Softmax or REINFORCE). This is also why the latent variables of a VAE are almost always continuous Gaussians — not for aesthetics, but because of the gradient path.
Step 6: identity with reinforcement learning. The reparameterized policy gradient of SAC uses the same trick: rewriting “sample an action from the policy distribution” as “deterministic function + exogenous noise”, so that can pass through sampling. The mathematics is exactly the same in both places; only is replaced by the value.
2.6 Training Details: KL Weight, Posterior Collapse, and Tighter Bounds
The ELBO of a standard VAE has a structural weakness: the magnitudes of the reconstruction term and the KL term do not match. The reconstruction term sums over pixels, whereas the KL term sums over latent dimensions. In image tasks is often a hundred times , so the KL term is relatively negligible and the encoder “cannot be bothered” to use the latent variables — it squeezes onto the prior, turning into noise, and the decoder degenerates into an “unconditional generator”.
This phenomenon is called posterior collapse. Its criterion is very direct:
Once it appears, the latent space loses its information content, and the VAE degenerates into “a noisy autoencoder”. There are four common countermeasures:
| Countermeasure | Implementation | Mechanism |
|---|---|---|
| -VAE | Turn the KL weight down: , | Directly weaken the regularization term so that the encoder dares to use the latent variables; does the opposite and is used to learn disentangled representations |
| KL annealing | Set early in training and increase it linearly to the target value | Let the decoder learn to use first, then apply pressure gradually |
| Free bits | Penalize only the part of each dimension’s KL that exceeds the threshold : | Give each dimension a “free allowance” of nats, guaranteeing that at least some information is encoded |
| Limit decoder capacity | Use a weaker decoder (e.g., shallow, or add noise to the output) | Make it impossible for the reconstruction term to succeed on its own, forcing dependence on |
-VAE with has an additional by-product: disentangled representations. Increasing the KL penalty forces each latent dimension to independently take charge of a different factor of variation, and on data such as dSprites one obtains effects like “one dimension controls shape, one dimension controls rotation”. The price is a drop in reconstruction quality.
The other direction is to tighten the lower bound: the Importance Weighted Autoencoder (IWAE).
samples are averaged with weights and then passed through ; Jensen’s inequality still gives a lower bound, but a tighter one than (the larger is, the closer it is to the true log-likelihood). Note that the gradient of IWAE tends to “let a few good samples dominate”, so it is sensitive to , and the training objective is no longer exactly the same as the one-sample ELBO.
Derivation 17: Why the importance-weighted bound (IWAE) is tighter than the ELBO, and how tight it can get
Step 1: define the importance weights. Draw samples independently from , and define the importance weight of each sample as
Note that is a random variable (it depends on ), and that — this is exactly the fact ” is the expectation of ”, and it is the fulcrum of all the inequalities that follow.
Step 2: write out the -sample lower bound.
For it degenerates to .
Step 3: prove that it is a lower bound (Jensen, same direction as the ELBO). is concave, hence
The last step uses and the fact that the sum of terms equals . So is still a legitimate lower bound on the log-likelihood.
Step 4: prove that it is tighter than the ELBO (this step is the whole value of IWAE). For the same concave function , use once more “the log of an average is no smaller than the average of the logs”:
Taking expectations on both sides, the right-hand side is . Hence
Equality condition: holds if and only if all are equal, i.e., for every — that is, the posterior approximation is exact. This is the same condition as the Jensen equality condition of Derivation 3, except that now samples must satisfy it simultaneously, which has lower probability, and therefore in practice the larger is, the less likely equality is attained, and the tighter the bound becomes instead.
Step 5: monotonicity and consistency. Regard the weights of as a mixture of “the average of the first ” and “the -th one”:
Then, by the concavity of , , where the first term on the right is a combination of and the second term , and therefore
i.e., is monotonically non-decreasing in . As , by the law of large numbers almost surely, and is continuous, hence . So IWAE is a sequence of lower bounds that converges to the true likelihood as grows, which is the key difference from the ELBO (where is fixed and the gap is always the posterior KL).
Step 6: how tight it can get — a computable upper bound. From the sandwich of Step 4 we immediately obtain
That is, the gap of IWAE does not exceed the posterior KL. This conclusion is very practical: if the posterior approximation itself is good (small KL), between 8 and 64 suffices; if the posterior family is weak (a diagonal Gaussian fitting a multimodal posterior), then no matter how large is, the gap can only be pushed down to the magnitude of that KL, not to zero.
Step 7: the cost — gradient variance and “domination by a few samples”. Differentiating :
The factor inside the bracket is a softmax weight. When is large, the weights concentrate on the few largest (a heavy-tailed weight distribution), so the gradient is in effect determined by only those samples, and the variance rises instead. This is why IWAE in practice usually uses (rather than ), and it is the mathematical explanation of “for IWAE, larger is not always better”. If a large really is needed, it must be combined with gradient truncation (applying stop-gradient to ) or reweighting to keep the variance down.
Step 8: the connection with the VAE structure. IWAE changes only the training objective, not the model structure — it is still “encoder + decoder”, and sampling is still one decoding pass. This is important: it shows that the tightness of the ELBO is a question of the objective, not of the structure. To tighten the bound, besides increasing , one can also switch to a more flexible posterior family (flow-based posteriors, inverse autoregressive posteriors); the latter is a structural change, and the cost is a slower encoder.
Derivation 18: Both β-VAE and free bits are the Lagrangian solution of a constrained ELBO
Step 1: write “we want a small KL” as a constrained problem. The standard ELBO is
-VAE changes it to
On the surface it is merely “a different weight”, but as shown below: every corresponds to the optimal multiplier of some KL upper-bound constraint, so -VAE is not arbitrary weighting but the solution of a family of constrained problems.
Step 2: write the constrained form. Consider
Introducing the multiplier , the Lagrangian is
Maximize over and minimize over (a saddle point). Given , the subproblem in is exactly the objective of -VAE (the constant does not affect the gradient). So the objective of -VAE is the Lagrangian of the upper-bound constrained problem.
Step 3: KKT and “what means”. The complementary slackness condition is . Two cases:
- if the KL of the optimal solution is strictly smaller than (the constraint is inactive), then , and the problem degenerates into an ordinary autoencoder that “only reconstructs and ignores regularization”;
- if the KL exactly equals (the constraint is active), then , and is exactly “how much reconstruction one is willing to sacrifice in order to relax the KL constraint by one unit”.
Therefore is equivalent to relaxing (allowing a larger KL, hence stronger encoding), and is equivalent to tightening (forcing a smaller KL, hence forcing the dimensions to be independent and producing disentanglement). This translates “what is actually being done by turning up or down” into a constrained problem with units: is measured in nats (units of information), and is measured in “reconstruction cost per nat”.
Step 4: free bits are the Lagrangian solution of a “per-dimension lower bound constraint”. The motivation of free bits is the opposite: it wants to guarantee that every dimension encodes at least of information, i.e., the constraint
This is a “lower bound constraint”. Write it as a penalty function (penalizing the shortfall):
Step 5: look at the piecewise behavior of this dimension by dimension. For the -th dimension:
So when , this term produces no gradient at all — those nats are “free”, and the encoder may use them without being penalized; once the threshold is exceeded, the gradient immediately becomes 1 (the same coefficient as in the standard ELBO). This answers exactly “why free bits prevent posterior collapse”:
- the mechanism of posterior collapse is “the KL term presses toward the prior”, and in the region this pressure is explicitly set to zero;
- the encoder can therefore first write information into the latent variables “for free”, letting the decoder learn to depend on ; only after exceeds does the standard regularization take over.
Step 6: the contrast with -VAE. The two are in fact two directions of the same Lagrangian framework:
| Method | Constraint type | Penalty term | Gradient behavior | Problem addressed |
|---|---|---|---|---|
| -VAE () | KL upper bound | Global scaling (every dimension shrinks) | Posterior collapse, latent variables not used | |
| -VAE () | Tighter KL upper bound | Global amplification | Pursuing disentangled representations | |
| Free bits | Per-dimension lower bound | Piecewise: zero below the threshold | Posterior collapse, with a per-dimension floor |
The key difference lies in “per dimension”: is a global scalar, and it cannot prevent “one dimension being completely squeezed dead while another dimension carries all the information”; the of free bits is per dimension, guaranteeing that every dimension has a minimum amount of information, so it is more effective against the subtler failure of “a few dimensions collapsing”.
Step 7: a limitation that must be stated clearly. Both methods change only the objective, not the posterior family. If the true posterior is multimodal, a diagonal Gaussian cannot fit it no matter how it is weighted (Step 6 of Derivation 17 already gave the upper bound: the gap does not exceed the posterior KL) — in that case and free bits can only mitigate “not using the latent variables”, not solve “using the latent variables badly”. To solve the latter, the posterior family must be changed (flow-based posteriors, IWAE).
Derivation 28: The quantitative condition for posterior collapse, and why "the encoder ignores the input" is a free local optimum
Step 1: construct the collapsed solution. If the decoder has enough capacity to output, for any , a distribution close to , then the reconstruction term is almost independent of :
Then the only term still depending on is the KL, whose minimum is attained at with value zero. So the objective admits a solution: the encoder ignores completely, the KL is zero, and reconstruction is barely hurt. This is not a pathological special case but a common convergence point whenever “the decoder is strong and the latent capacity is small”.
Step 2: the quantitative criterion. Let ; the per-dimension KL (closed form from Derivation 4) is
As and , . In practice a dimension whose KL stays below a threshold (say 0.01 nat) for a long time is declared collapsed, and one counts the effective number of latent variables
This is more reliable than looking at the total KL alone, because the total can be carried by a few dimensions while the rest have already stopped working.
Step 3: why a larger makes collapse easier. In the objective the KL carries coefficient and the reconstruction term coefficient one. The collapsed solution pushes the KL from some positive value down to zero, a gain of , at the cost of raising the reconstruction term by . Whenever
the collapsed solution is actually better. And shrinks as the decoder capacity grows (the decoder can fit the data by itself), so the stronger the decoder and the larger the , the easier the collapse — the danger of “large decoder + high ”.
Step 4: the mechanism of the three remedies. (i) free bits: replace the KL with , so the first nats are free and the collapsed solution is no longer free (the Lagrangian interpretation is Derivation 18); (ii) KL annealing: ramp from zero to its target, letting the encoder learn information before the KL is squeezed; (iii) weaken the decoder (reduce capacity, add dropout, add noise) so that becomes larger and collapse is not worthwhile. All three change the relative cost of the collapsed solution versus the useful one.
2.7 Pseudocode: VAE (Complete Version)
Algorithm: VAE (diagonal Gaussian posterior + Gaussian decoder)
Input: training set D, latent dimension d, batch size B, learning rate η, KL weight β, reconstruction variance σ²
Output: encoder q_φ(z|x), decoder p_θ(x|z)
Initialize: encoder parameters φ, decoder parameters θ
for epoch = 1 .. E:
for each mini-batch {x^(i)}_{i=1..B}:
# ---------- Segment 1: encode, output mean and log variance ----------
μ_i, logσ²_i ← Enc_φ(x^(i)) # two d-dimensional vectors, logσ² guarantees positivity
logσ²_i ← clamp(logσ²_i, -20, 10) # numerical guard against exp overflow
# ---------- Segment 2: reparameterized sampling ----------
ε_i ~ N(0, I) # independent per sample and per dimension
σ_i ← exp(0.5 * logσ²_i)
z_i ← μ_i + σ_i ⊙ ε_i
# ---------- Segment 3: decode ----------
x̂_i ← Dec_θ(z_i) # Gaussian mean; or Bernoulli probability
# ---------- Segment 4: the two loss terms ----------
L_rec ← (1/B) Σ_i (1/(2σ²)) * ||x^(i) − x̂_i||²
L_kl ← (1/B) Σ_i 0.5 * Σ_j (μ_ij² + σ_ij² − 1 − logσ_ij²)
L ← L_rec + β * L_kl
# ---------- Segment 5: backward pass and update ----------
g ← ∇_{θ,φ} L
θ, φ ← Adam(θ, φ, g, η)
return Enc_φ, Dec_θ
Sampling (generation) phase:
Input: trained decoder Dec_θ, number of samples M
for m = 1 .. M:
z_m ~ N(0, I) # must use the prior, not the encoder output
x_m ← Dec_θ(z_m)
return {x_m}
2.8 Section-by-Section Walkthrough of the Pseudocode
Segment 1 ①: the encoder outputs rather than . If were output directly, an extra positivity constraint would be needed (such as softplus or taking the absolute value), and has poor gradients near 0; outputting lets the network work on the unconstrained real line, and is naturally positive. The KL formula already contains , so this parameterization also saves one .
Segment 1 ②: clamp is not optional. Early in training can run to , and blows up to , the decoder output becomes NaN, and the whole training collapses afterwards. Restricting to is what almost every open-source implementation does.
Segment 2 ③: must be redrawn per sample and per dimension. This is the same class of error as “the random numbers must be redrawn per dimension” in PSO: if the whole batch shares one , the direction of the random perturbation is identical for all samples, the variance estimate of reparameterization becomes invalid, and the training symptom is “the KL term fluctuates and the latent space does not spread out”.
Segment 3 ④: the decoder outputs a “mean”, not a “sample”. Under a Gaussian decoder, , and the reconstruction loss depends only on the mean; at generation time one may draw noise again if a random sample is wanted, but the common practice is to output the mean directly (this is one direct reason why VAE samples are rather “smooth”).
Segment 4 ⑤: the KL must be computed per sample and then averaged. The correct way is to first compute for each sample, then average over the batch. If one averages over the batch first and then plugs it into the formula, what is obtained is , which is not the same thing as “the average of the KLs”; the two differ by a term. This is one of the most hidden errors in implementations.
Segment 4 ⑥: what tunes is “whether the latent variables are used”. With a small the reconstruction dominates, the latent space carries more information but may be irregular; with a large the regularization dominates, the latent space is regular but may collapse. In engineering it is advisable to first get things running with , then decide which way to tune based on the two curves “reconstruction metric versus KL value”.
Segment 5 ⑦: the two networks must be updated simultaneously. The two losses of VAE share the same , and the gradients of the encoder and decoder depend on each other. If they are updated in two separate steps (first the encoder, then the decoder), the used in the second step is already stale, which is equivalent to differentiating with respect to the old parameters and introduces bias.
Sampling segment ⑧: generation must sample from the prior. Sampling from and then decoding gives “a reconstruction of a training sample”, not a new sample. This is the dividing line between VAE generation and AE reconstruction, and also the source of the common misunderstanding that “VAE can only interpolate and cannot truly generate” — the correct way is , or interpolating along the line connecting two encoded points.
2.9 Per-Step Read/Write and State-Maintenance Checklist
VAE has no complicated “gradient flow” problem (every term is differentiable), but it does have a checklist of “which quantities must be recomputed every step, which must be kept, and which must have their gradients cut”:
| Quantity | When read | When written | Kept across steps | Consequence of getting it wrong |
|---|---|---|---|---|
| Every step | Every step | No (discarded after the step) | Mistaking it for a reusable representation breaks batch independence | |
| Every step | Every step | No | Forgetting clamp leads to numerical explosion | |
| Every step | Newly drawn every step | No | Sharing within a batch invalidates the variance estimate | |
| At decoding | Every step | No | Reusing an old across steps makes the gradient mismatch the current parameters | |
| Every step | Every step | Kept | — | |
| Every step | Every step | Kept | — | |
| KL term | Every step | Every step | No | Omitting it leaves the latent space unconstrained, degenerating into an AE |
| Every step | Per schedule (during annealing) | Kept (may be increased) | Starting with a large causes collapse |
Three decision principles:
- “Randomness may come only from exogenous noise.” Sampling must be written as ; one must not call
.sample()on a distribution object and then cut the graph — the latter silently cuts the gradient to , and training looks normal while the encoder does not learn. - “The KL must be computed per sample.” Any formulation that aggregates statistics first and then plugs them into a formula must be double-checked, because KL is not a linear function.
- “Generation uses the prior, reconstruction uses the posterior.” These two paths must not be mixed: training uses the posterior (because must be seen), likelihood evaluation uses the posterior (importance weighting), and generation uses the prior.
2.10 Pitfall List
| Symptom | Possible cause | Fix |
|---|---|---|
| Generated samples are all blurry average images | Gaussian decoder + fixed large variance + posterior approximation gap | Reduce the decoding variance, switch to a discrete/mixture likelihood, or switch to diffusion |
| The KL term rapidly drops to 0 and the latent variables stop working | Posterior collapse | Lower , KL annealing, free bits, weaken the decoder |
| The training loss looks normal but the samples are highly similar to the training set | The encoder output was used at generation time | Generation must use |
| Some latent dimensions are always 0 | Excessive KL penalty ( too large) | Lower ; or let free bits give each dimension an allowance |
| The reconstruction term does not decrease | Insufficient decoder capacity / latent dimension too small | Widen the decoder, increase ; or check normalization |
| is learned close to 0 and training is unstable | Missing clamp or KL weight too small | clamp(logσ²); check whether the KL is really included in the loss |
| The KL differs enormously between two batches | Aggregating before computing the KL | Compute the KL per sample, then average |
| Non-numeric values appear when interpolating in the latent space | Prior and aggregated posterior do not match (prior hole) | Use , or regularize the aggregated posterior (VAMP prior) |
Among them, “prior hole” deserves a separate mention: a VAE guarantees only that each is close to the prior, not that the aggregated posterior fills the prior. As a result, in regions not covered by the training samples (holes), the decoder’s behavior is undefined, and interpolation collapses there. This is not a bug but a property of the ELBO objective itself; fixing it requires changing the objective (e.g., adding an aggregated-posterior regularizer, or switching to a model such as diffusion that is defined over the whole space).
2.11 Scope of Application
Suitable for:
- Tasks that need a continuous, interpretable latent space: representation learning, disentanglement, interpolation, attribute editing (-VAE, conditional VAE);
- Tasks that need a likelihood lower bound for model comparison: academic comparisons, density estimation;
- Tasks that need extremely fast sampling: a single decoding pass, two to three orders of magnitude faster than diffusion;
- Tasks that need it as a “compressor” rather than a generator: this is the real home ground of VAE today — latent diffusion uses a VAE to compress a image into a latent, and the diffusion runs in that latent space. In that case the reconstruction quality of the VAE matters far more than generation diversity, and the KL weight is usually set very small (close to an AE);
- Anomaly detection: reconstruction error plus likelihood can serve as an anomaly score;
- Discrete latent spaces for speech and music: VQ-VAE (Vector Quantized VAE) uses a codebook to discretize continuous latent variables, and is a common front end for audio codecs and autoregressive generators.
Not suitable for:
- Tasks that pursue extreme sample sharpness: the blurriness of VAE comes from the Gaussian likelihood and the posterior gap, and changing the loss can only mitigate it, not remove it; such tasks should use GAN or diffusion;
- Tasks that need an exact log-likelihood: only a lower bound can be given, and the bound varies with , so cross-model comparison is not rigorous; for an exact likelihood choose Normalizing Flow;
- Tasks where the latent variables need strong expressive power: a diagonal Gaussian posterior is too simple, and a complex multimodal posterior gets averaged away; use a flow-based posterior (VAE + Flow) or a diffusion posterior.
3. Generative Adversarial Network (GAN)
3.1 Why It Is Needed: Likelihood Does Not Measure “Does It Look Right”
The objective of VAE is likelihood, and Section 1.4 already showed that likelihood and visual quality are misaligned. GAN’s starting point is: drop likelihood altogether and directly learn a sampler that “can fool a judge”.
This idea turns generation into a game:
- Generator maps noise to a sample , and wants the distribution of its output to be indistinguishable from ;
- Discriminator takes a sample as input and outputs “the probability that it comes from real data”, and wants to judge real samples as real and fake samples as fake.
The two are trained alternately. What the discriminator provides is a learnable distance — it needs no density, only the ability to see the difference. This “distance” adapts as training proceeds, which is exactly where GAN’s sharp samples come from, and also where its instability comes from.
3.2 Principles and Formulas
The objective of the original GAN is a minimax game:
A few notes on how it is written:
- is the discriminator’s objective (push both terms up: real samples judged 1, fake samples judged 0);
- is the generator’s objective (push the second term up, i.e., make close to 1);
- the first term has no gradient with respect to ( comes from the data), so in practice it is dropped when updating the generator;
- this is a two-player zero-sum game, not single-objective optimization. Its solution is not a “minimum point” but a Nash equilibrium — a point at which neither side can improve unilaterally. This difference is the whole source of trouble in GAN training dynamics (Section 3.8).
3.3 The Optimal Discriminator and the JS Divergence
With the generator fixed, the optimal discriminator can be obtained in closed form, and this solution happens to turn the game objective into the JS divergence.
Derivation 6: The closed form of the optimal discriminator, and that at the optimum the objective equals $2\,\mathrm{JSD}-2\log 2$
Step 1: write the expectations as integrals and look at them pointwise. Let and :
The integrand at each depends only on the value of , so “maximizing over the function ” can be done pointwise: for each independently maximize
Step 2: differentiate pointwise and set to zero.
Step 3: since , this is the maximum point, and it is unique. Therefore
Note the condition under which this conclusion applies: and have densities with respect to the same measure (if is supported on a low-dimensional manifold, then strictly speaking the pointwise argument does not hold, which is exactly the problem to be dealt with in Section 3.5).
Step 4: substitute back into the objective. Denote the midpoint distribution , so :
Step 5: massage it into the form of KL. Split each term into “relative to the midpoint” plus a constant:
The second term is likewise . Both and equal 1 (probability normalization).
Step 6: combine.
Since , we have , and the global minimum is attained if and only if .
Step 7: three corollaries of this result.
- The generator’s optimal solution is , at which (the discriminator is completely unable to tell them apart and can only guess). This gives the theoretical convergence point of GAN;
- under the optimal discriminator the training objective is exactly the minimization of the JS divergence. So the answer to “which distance is GAN learning” is: JS (the original version), f-divergence (the f-GAN family), Wasserstein (WGAN);
- depends on the current value of , so the optimal discriminator changes after every generator update. must chase it: chasing too fast saturates it (Section 3.5), chasing too slowly gives the wrong gradient. This is the mathematical origin of “the discriminator and the generator must be balanced”, not an empirical rule of thumb.
Derivation 19: f-GAN — every f-divergence can be written as a "discriminator + generator" game
Derivation 6 handled only the JS divergence. In fact every f-divergence induces a GAN, and the role of the discriminator is to turn “a divergence” into “an estimable quantity”. This conclusion elevates the GAN family from “a trick” to “a class of frameworks”.
Step 1: the definition of an f-divergence. Let be a convex function with . The f-divergence of two distributions and (with densities and , and integrable where ) is
When it is ; when it is ; when it is the Pearson . Note that being convex with guarantees that and if and only if (Jensen: ).
Step 2: linearize with the Fenchel conjugate. The conjugate of a convex function is
By the definition of the conjugate, for all (simply drop the ). Take to be a function and , then multiply both sides by and integrate over :
i.e.,
Step 3: taking the supremum of this lower bound over gives the exact value. By the equality condition of the conjugate, (i.e., ), the optimal point is
Substituting it back makes the lower bound equal to . Hence
This is the complete origin of f-GAN: the discriminator is a function that “maps the density ratio to a real number”, training it maximizes this variational lower bound, and training the generator minimizes it.
Step 4: recover the three common losses. Substituting one by one:
| Name | Optimal | Corresponding discriminator output | ||
|---|---|---|---|---|
| KL | log density ratio (no activation) | |||
| (sigmoid output, off by a constant) | ||||
| Pearson | linear output (LSGAN) |
The second row is another way of writing Derivation 6: , hence , while — the two differ only by the constant , which does not affect how the supremum is taken, but after substituting back into the objective it produces a shift of , which is exactly the origin of that term in “the objective at the optimum equals ”. The third row shows that the Least Squares GAN (LSGAN) is not “trying a different loss” but “choosing the divergence”.
Step 5: the discriminator’s output layer is not chosen at random. The last column of the table above shows that the discriminator’s final activation must match . If JS is used (the original GAN), the range of is restricted by the domain of (), so a sigmoid must be applied to squeeze into ; if is used, is unbounded and a linear output is fine. A common mistake in practice is “changing the loss but not the activation”, which lets be evaluated outside its domain and makes the numerics diverge immediately.
Step 6: why this framework still does not solve the problem of Section 3.5. Apart from Wasserstein, all f-divergences (including JS, KL, ) degenerate into a constant when the supports of the two distributions do not intersect, and the gradient with respect to the parameters is zero. The unification of f-GAN happens only in the region “where the supports overlap”. It unifies “how a divergence becomes a game”, but not “what to do when the supports do not intersect” — the latter requires Integral Probability Metrics (IPM) and the 1-Lipschitz constraint, which are the topics of Derivation 9 and Derivation 20.
Step 7: one practical corollary. From Step 3 it is visible that the optimal depends only on the density ratio , not on the specific shapes of and individually. This explains an empirical phenomenon of GAN: what the discriminator learns is “the ratio of real to fake”, not “the distribution of real images”. The discriminator can therefore be reused, distilled, and used as a “density-ratio estimator” (for example in importance sampling and domain adaptation). This is also the mathematical justification for the statement “the discriminator of a GAN has independent value”.
3.4 The Non-Saturating Loss: Straightening the Gradient Scale Back
The original objective “saturates” in practice: early in training the generated samples are obviously fake, the discriminator outputs , and at that point the generator’s loss is already close to its minimum , so the gradient is nearly zero and the generator cannot learn. Goodfellow’s fix is to change the loss:
This is called the non-saturating loss. Note that it is not the original objective (it replaces with , and the two have completely different shapes when is small), so it no longer corresponds exactly to the JS divergence. But it gives a healthier gradient scale.
Derivation 7: The gradients of the two losses with respect to the logit are $-D$ and $-(1-D)$ respectively
Step 1: write the discriminator as sigmoid(logit). Let be the discriminator’s logit output and , where is the sigmoid function. Its derivative is
Step 2: compute the gradient of the original loss with respect to the logit. The generator minimizes
By the chain rule:
Step 3: compute the gradient of the non-saturating loss with respect to the logit.
Step 4: look at the behavior as . When the generated samples are obviously fake, :
- the original loss gradient : it vanishes. Moreover at this point, is already saturated, and also tends to 0, so multiplying the two layers gives a second-order small quantity;
- the non-saturating loss gradient : it does not vanish. The factor exactly cancels the inside .
Step 5: the behavior as (reverse check). When the generated samples are already good, the gradients of both losses tend to 0 (the original loss , the non-saturating one ). This is reasonable: the discriminator can no longer tell them apart, so there is naturally no information to learn. The difference lies in the early stage: the non-saturating loss has its largest gradient when “the judgment is wildly wrong”, whereas the original loss has its smallest gradient in exactly that case. The former is “hard examples first”, the latter is “easy examples first”, and the latter is clearly unsuitable for generation tasks.
Step 6: why many tutorials get this backwards. A common statement is “when approaches 1, saturates and the gradient vanishes”. That describes the case where the discriminator judges fake samples as real (as , , the gradient explodes rather than vanishes), which is not the same thing as “the generator cannot learn early on”. The real problem is at the end, and a careful computation shows that the original loss’s gradient there is “the outer layer does not vanish, the inner layer vanishes”, with the overall effect still vanishing. So the correct statement is: exactly when the generator most needs to learn, the original loss gives it no gradient from the discriminator.
3.5 The Fatal Weakness of JS: Zero Gradient When the Distributions Do Not Overlap
The conclusion of Section 3.3, “GAN minimizes the JS divergence”, sounds fine, but the JS divergence is constant in one common situation: when the supports of the two distributions do not overlap.
This almost inevitably happens in generation tasks. A image lives in a -dimensional space, and the real data occupy only a very low-dimensional manifold within it (the manifold of natural images), while the generator starts from noise and its initial output also lies on another low-dimensional manifold. The two manifolds almost certainly do not intersect.
Derivation 8: When the supports do not overlap, JS is constant and the generator's gradient is zero
Step 1: the setting. Assume there exists a measurable set such that all the mass of lies inside and all the mass of lies in the complement of (strictly: , ). This is “the supports do not intersect”.
Step 2: the optimal discriminator takes two extreme values inside and outside . From of Derivation 6: inside we have , hence ; inside we have , hence . That is,
Step 3: compute the optimal objective value. The first term is ; the second term is . So . Checking against the formula of Derivation 6: , consistent.
Step 4: differentiate with respect to the generator parameters — and get zero. The generator appears only in the second term: . On , and the integrand is , identically zero; on , . So this term is identically 0 and independent of , and the gradient is
Step 5: even without the optimal discriminator, saturation is enough. In practice does not take exactly 0/1, but it gets very close. At that point is already extremely small (Step 4 of Derivation 7), and the gradient the generator receives is likewise “numerically zero”. So “the discriminator is too strong” is not a tuning problem but a mathematical property of the JS objective: exactly when it should provide direction, it provides 0.
Step 6: this conclusion explains three phenomena in GAN training.
- Early on the discriminator must be “let off” (fewer update steps, added noise, label smoothing), otherwise it saturates right away;
- WGAN is not “another kind of GAN” but a switch to a distance that still has a gradient when the supports do not intersect (Derivation 9);
- diffusion models need no discriminator, because they change “crossing the manifold gap in one step” into “thousands of small displacements”, and at every step the two distributions overlap heavily — this directly sidesteps the problem of this section. This is the structural reason diffusion wins across the board on stability and coverage.
3.6 The Wasserstein Distance and the Kantorovich-Rubinstein Duality
The core replacement of WGAN is: change “minimize JS” into “minimize the Wasserstein-1 distance”. But itself is an optimization problem of “taking the infimum over all couplings”, which cannot be computed directly — its dual form is needed.
The form on the right replaces “take the infimum” with “take the supremum over the family of 1-Lipschitz functions”. It can be parameterized directly by a neural network: is the discriminator, except that now it outputs no probability and has no sigmoid, but a real-valued score (which is why it is called a critic rather than a discriminator). The “1-Lipschitz” constraint is implemented with spectral normalization or a gradient penalty.
Derivation 9: The upper bound, the lower bound, and the explicit one-dimensional construction of the Kantorovich-Rubinstein duality
Step 1: the upper bound (this step is elementary). Let be 1-Lipschitz, i.e., for all . For any coupling ,
The left-hand side depends only on the marginals: , . Hence for every such ,
Taking the supremum over all 1-Lipschitz gives .
Step 2: existence of the lower bound (the duality theorem). This is the content of strong duality in linear programming / the Kantorovich duality theorem: the optimal transport problem is a convex optimization with linear constraints, and the optimal value of its dual equals the optimal value of the primal. So the inequality above is an equality. The proof of the theorem is not repeated here; only its preconditions are emphasized: the cost function is continuous, and have compact support (or bounded moments). In engineering these preconditions all hold.
Step 3: the explicit construction in one dimension (the step most worth remembering). In one dimension, let be the cumulative distribution functions (CDFs) of . Take
Then , so is 1-Lipschitz. Compute the dual objective using integration by parts (or the density form , ):
And the one-dimensional happens to equal (this is the integral of the difference of the quantile functions, an equivalent form). So this attains the supremum, and the equality holds.
Step 4: what this construction shows. It shows that the shape of the “optimal critic” is exactly “the integral of the sign of ” — a function that climbs monotonically, rising where has more mass than and falling where has more mass than . In other words, the critic learns “the cumulative difference of which side has more mass”, which is geometrically completely different from “the discriminator learns pointwise realness”: the former looks at global transport, the latter at local authenticity.
Step 5: write the dual objective in trainable form. The objective of WGAN is
The gradient with respect to is “the score of real samples minus the score of fake samples”, and the gradient with respect to is “raise the score of fake samples”. Note that here there is no and no sigmoid, so there is no saturation; when the two distributions are apart, , and the gradient magnitude is of the same order as (Step 5 of Derivation 2).
Step 6: the cost. The 1-Lipschitz constraint is a hard constraint, and in implementation it can only be approximated: weight clipping (the original WGAN, crude but capacity-reducing), gradient penalty (WGAN-GP, a soft constraint), spectral normalization (an exact constraint per layer, with the whole network bounded by a product). These three approaches are expanded in Section 3.7.
Derivation 20: Why the gradient penalty of WGAN-GP is equivalent to "the gradient norm being exactly 1"
Derivation 9 gave the Kantorovich-Rubinstein duality , but did not explain “how the 1-Lipschitz constraint is realized in implementation”. This subsection makes the mathematical relations among the three realizations (weight clipping, gradient penalty, spectral normalization) clear.
Step 1: translate the “Lipschitz constant” into a gradient condition. Let be differentiable almost everywhere. The definition of being 1-Lipschitz is
Step 2: prove that ” 1-Lipschitz”. Along the straight line , by the fundamental theorem of calculus,
Taking absolute values and applying Cauchy-Schwarz:
So is enough for 1-Lipschitz.
Step 3: prove that the converse also holds (-Lipschitz ). Take ( a unit vector), then
Dividing both sides by and letting gives for every unit vector ; taking gives .
Step 4: so the constraint is an “upper bound on the gradient norm” — why is the penalty written as “equal to 1”. Strictly speaking the constraint is , whose penalty should be (one-sided). WGAN-GP uses a two-sided square:
It looks like a penalty for an equality constraint, and the reason it is still correct is that the constraint is active at the optimum: if somewhere, then can be “magnified” there (increasing the slope along that direction) without changing the sign constraint on , thereby continuing to raise the dual objective; therefore the optimal necessarily pushes the gradient norm up to 1 on the region connecting the data supports. In other words, is not “a relaxed version of the constraint” but the equality condition of the optimal solution.
Step 5: verify “the gradient norm is 1 at the optimum” with a one-dimensional example. Let , (), then . The dual problem under the 1-Lipschitz constraint has the optimal solution (linear, slope ), with everywhere. If is taken instead, the objective value is , only half of the optimum — this is a direct demonstration that “a gradient norm below 1 loses objective value”, and it also explains why the penalty pulls toward 1 rather than toward “less than 1”.
Step 6: why the penalty points lie only on the connecting line. WGAN-GP does not penalize over the whole space; it takes
The reason is that “the equality of the optimal 1-Lipschitz holds only along the paths that carry the mass of to ”. Forcing in regions far from the data support conflicts with the requirements in the data region and instead introduces bias (the WGAN-GP paper calls this “the penalty should not act off the manifold”). A related corollary: the distribution of depends on the coupling between and , and the easiest implementation is “random pairing within the same batch”, which corresponds to a particular coupling, not necessarily the optimal transport coupling between and ; thus GP is only “a local approximation to the optimal ”.
Step 7: why spectral normalization is the “hard constraint” version. Spectral Normalization (SN) replaces each layer’s linear map with ( being the largest singular value), so each layer’s Lipschitz constant is exactly 1; the Lipschitz constant of the whole network does not exceed the product of the layer constants, hence (provided the intermediate activations are 1-Lipschitz, such as ReLU and LeakyReLU). The difference from GP is:
| Approach | Constraint type | Cost | Side effect |
|---|---|---|---|
| Weight clipping (original WGAN) | Hard constraint, but it clips weights rather than gradients | Extremely cheap | Parameters squeezed into a small range, capacity loss, gradients vanish or explode |
| Gradient penalty (WGAN-GP) | Soft constraint, acting on interpolation points | One extra backward pass per step | Depends on the interpolation distribution, needs tuning |
| Spectral normalization (SN) | Hard constraint, acting on each layer’s weights | One power iteration per step | The global bound may be too tight, hurting expressiveness |
All three implement the single constraint “1-Lipschitz”; the only difference is “where the constraint is applied, and whether it is hard or soft”. This also explains why SN is often more stable than GP (no to tune, no dependence on interpolation), but in scenarios that need “an accurate Wasserstein value” GP is closer to the original definition.
3.7 Stabilization Techniques: From Structural Constraints to Spectral Normalization
GAN training instability does not have a single cause, so the stabilization techniques also come in layers:
| Technique | Level it acts on | Implementation | Side effect |
|---|---|---|---|
| DCGAN structural constraints | Architecture | Use strided convolution instead of pooling, BatchNorm, remove fully connected layers, LeakyReLU | Not enough for high resolution |
| Label smoothing | Objective | Real-sample labels set to 0.9 instead of 1 | Mitigates discriminator over-confidence |
| Input noise | Data | Add a small amount of Gaussian noise to ‘s input | Equivalent to regularizing |
| One-sided smoothing | Objective | Smooth only the real-sample side | More common than two-sided |
| TTUR | Optimization | ‘s learning rate higher than ‘s (e.g., 4 times) | Needs tuning |
| Gradient penalty (WGAN-GP) | Objective | See the formula below | One extra backward pass per step, slow |
| Spectral normalization | Layer | Normalize each layer’s weights by the largest singular value | Cheap to compute, constraint exact at the layer level |
| Exponential moving average (EMA) of generator weights | Evaluation | Sample with the moving-average parameters | Unrelated to the training loss, purely improves the metric |
| Historical sample buffer | Objective | Train with historical generated samples | Prevents from forgetting |
Gradient penalty (WGAN-GP):
where , , i.e., points are taken along the line between real and generated samples. The justification of this penalty term is: the gradient norm of the optimal critic should be 1 everywhere on the connecting line (in the one-dimensional construction, means exactly this). is usually taken as 10.
The mechanism of spectral normalization: for each layer’s weight matrix , estimate its largest singular value with power iteration, then set . Because , that layer’s Lipschitz constant does not exceed 1; the whole network is a composition of several layers, and its Lipschitz constant does not exceed the product of the layer constants, so the whole network is constrained as well. Its advantage is that the constraint is exact at each layer and the cost is only a few matrix-vector multiplications, which suits large models.
Derivation 29: Why spectral normalization forces the discriminator to be 1-Lipschitz, and what the power iteration actually estimates
Step 1: Lipschitz constant and operator norm. For a map , the Lipschitz constant is defined as
For the linear layer , this is exactly the spectral norm of the matrix:
This uses the equivalent definition of the spectral norm: , and the square root of the largest eigenvalue of is the largest singular value.
Step 2: the Lipschitz constant of a composition is at most the product of the layers. A network with layers is written
If the activation has Lipschitz constant at most one (ReLU is exactly one, LeakyReLU at most one, and the derivative bounds of tanh and sigmoid are one and ), then for any , repeatedly applying the triangle inequality gives
Hence . This is an upper bound, not an equality: the true Lipschitz constant is usually smaller, because the clipping of the activations and the cancellation between layers both lower it.
Step 3: layer-wise normalization pushes the bound to one. Spectral normalization replaces every layer with
Substituting into Step 2 gives . The only fact used is that dividing by the largest singular value leaves the singular vectors unchanged and scales all singular values uniformly, so the bound drops exactly to one.
Step 4: how is estimated at every step — power iteration. Computing exactly requires a singular value decomposition, which is too expensive at every step. Power iteration keeps a vector and alternates
Each round updates to the normalized version of . Why it converges to the dominant right singular vector can be expanded: write the singular value decomposition of as and the initial value as ; then
Every round multiplies the coefficient of component by , so after normalization the share of component is , the dominant term is , and the rate is governed by the ratio
When is clearly below one, a few rounds suffice. The estimator actually used is
which satisfies (because ); that is, power iteration gives a lower-bound estimate, usually close enough to the truth.
Step 5: three engineering details. (i) Only 1–2 power-iteration rounds are run per step, with reused across steps as a warm start — this is why spectral normalization is cheap. (ii) The normalization uses an estimate, so strictly speaking the network is only approximately 1-Lipschitz, but that is enough for the Wasserstein duality to hold approximately (the duality of Derivation 9 requires functions inside the constrained class, and an approximate constraint only shifts the dual value slightly). (iii) Batch normalization (BN) destroys the Lipschitz property, because it rescales by batch statistics, so networks with spectral normalization usually drop BN or replace it with a batch-independent normalization.
Step 6: why an over-tight bound hurts expressiveness. The bound of Step 2 is a product over layers; if every layer is pinned to one, the whole-network bound is exactly one. But a real network often needs some layers to have gain larger than one in order to express complex functions (for example, to amplify a weak conditional signal). Pinning everything to one makes such amplification impossible, which shows up as reduced sample diversity or convergence to a simple solution. This is exactly the trade-off between spectral normalization and the gradient penalty: the gradient penalty constrains the gradient only near the interpolation points (soft, local), whereas spectral normalization constrains the whole network on every input (hard, global); the former is more expressive but constrains incompletely, the latter constrains completely but may be too tight.
3.8 Mode Collapse: An Inevitable Consequence of Reverse KL
Mode collapse means that the generator covers only part of the modes of the data distribution, and its outputs are highly homogeneous. Its mathematical root was already planted in Section 3.3: under the optimal discriminator the generator minimizes , and once the support of “aligns” with one mode of , the JS penalty for “whether the other modes are covered” is very weak.
A more precise statement must look at the direction of the KL. The generator of a GAN is in effect minimizing (the reverse KL, opposite in direction to the forward KL of maximum likelihood). The behavioral difference between the two is textbook-level:
- Forward KL : whenever has mass somewhere and does not, the integrand blows up. So the forward KL forces the model to cover all modes, at the price of possibly spreading mass thinly between modes (blurriness). VAE and diffusion take this road.
- Reverse KL : whenever has mass somewhere and does not, the integrand blows up. So the reverse KL forces the model not to generate things that are not in the data, but fully allows it to ignore some modes. This is mode-seeking behavior.
Mode collapse can therefore be summarized in one sentence: the reverse KL penalizes only “saying too much”, not “saying too little”, so the generator has an incentive to pick one mode and describe it thoroughly.
Why it is the reverse KL: under the optimal discriminator, . When and already partially overlap, of the two terms of the gradient of dominates (because it acts on the support of ), which is equivalent to pulling toward and then toward — the net effect of the direction is the reverse KL. A rigorous derivation requires a variational argument; only the conclusion is kept here: the gradient direction of the JS objective leans toward the reverse KL, and the reverse KL is mode-seeking.
Common mitigation techniques:
| Technique | Mechanism | Explanation |
|---|---|---|
| Minibatch discrimination | Let see the statistics of the whole batch | Directly penalizes “a batch of samples that look too much alike” |
| PacGAN | Concatenate samples and feed them to | Same as above, simpler |
| Unrolled GAN | Unroll several steps of ‘s update when updating the generator | Prevents from chasing ‘s instantaneous weaknesses |
| AdaGAN / ensembles | Train a generator that “fills the gaps” each round | Gradually covers the modes |
| VEEGAN | Add an “invertibility” regularizer | Forces the map to be invertible |
| Change the objective | Use , or switch to diffusion directly | Replaces the geometry of JS at the root |
The most practical diagnostic in engineering is: if the coverage metric (such as recall or mode count) is clearly below the quality metric (precision), it is almost certainly mode collapse; if both are low, it is insufficient capacity or insufficient training. The fixes for the two are completely opposite, so they must be distinguished first.
Derivation 30: The smallest counterexample to mode collapse — why reverse KL "picks one mode and explains it well", while JS cannot tell which one was picked
Step 1: build a toy distribution on three points. Take and set
is bimodal (two modes at ) and is unimodal (mass at , with leaking to each side). This single toy separates the behavior of all three objectives.
Step 2: forward KL demands coverage, and the price is infinite. Term by term,
with the middle term handled by the convention . As this tends to . This is the coverage pressure of forward KL: whenever has mass at a point where has none, the penalty diverges, so the model must leave some probability on every mode — which is why VAE and diffusion samples rarely “produce only one kind of image”.
Step 3: reverse KL may ignore modes, at a price of only . Reverse the direction and squeeze onto one mode (say all mass at ):
Here , is at , and has zero mass at the other points, so the sum keeps a single term. If stays at , then diverges, because while . Comparing the two, the optimum of reverse KL is to put all mass on a single mode, at a finite cost of . This is the quantitative meaning of “mode-seeking”.
Step 4: the optimum in the general case. For a discrete and any ,
The first term is the negative entropy , minimized at when is a point mass; the second is minimized when puts its mass where is largest. Weighing the two, the optimal under reverse KL concentrates on one local maximum of and does not allocate mass according to the relative heights of . If has modes of equal height, any one is equally good and — this is the fixed price of “dropping modes”. It does not decrease with training time, so the generator has no incentive to cover the remaining modes.
Step 5: why JS cannot tell which mode was picked. Take two distributions with disjoint supports, and ; their midpoint is , which puts on each point. Hence
As long as the two distributions do not overlap, JS is exactly , completely independent of whether they are apart or apart. More importantly, its gradient with respect to the parameters is zero (Derivation 8 already established this), so the discriminator cannot tell the generator “you are now a little closer to the other mode” — the signal simply contains no notion of distance.
Step 6: the dynamical lock-in. Putting the previous steps together: early in training and hardly overlap, the JS gradient is nearly zero, and only the signal from the small region where they do overlap pushes the generator; once one mode is covered, JS gives a finite gradient there and still no gradient for the other modes, so the generator keeps moving along “make this mode even more alike”, and the incentive to cover the rest is always zero. This is the mechanistic explanation of “once collapsed, hard to recover by itself”.
Step 7: a comparison of the three objectives. The toy conclusions are summarized in the table:
The table also explains “why switching the objective (, diffusion) mitigates mode collapse”: still grows linearly with distance when the supports are disjoint, so “moving closer to another mode” itself carries a gradient.
3.9 Pseudocode: WGAN-GP (with a Note on the Difference from the BCE Version)
Algorithm: WGAN-GP (generator 1 step / critic n_critic steps, alternating)
Input: training set D, noise dimension d_z, batch size B, learning rates η_G, η_D, penalty coefficient λ, n_critic
Output: generator G_θ, critic f_φ
Initialize: G_θ (transposed convolution / attention structure), f_φ (convolutional network without sigmoid)
for iter = 1 .. N_iter:
# ================= Segment A: critic update (repeat n_critic times) =================
for k = 1 .. n_critic:
{x^(i)} ~ real data, take B samples
{z^(i)} ~ N(0, I), take B samples
x̃^(i) ← G_θ(z^(i)) # generated samples, detach G's gradient
# ---- interpolation points for the gradient penalty ----
ε^(i) ~ U(0,1), one scalar per sample
x̂^(i) ← ε^(i) * x^(i) + (1 − ε^(i)) * x̃^(i) # x̂ must participate in gradient computation
s_real ← (1/B) Σ_i f_φ(x^(i))
s_fake ← (1/B) Σ_i f_φ(x̃^(i))
g_pen ← (1/B) Σ_i (||∇_{x̂^(i)} f_φ(x̂^(i))||_2 − 1)²
L_D ← s_fake − s_real + λ * g_pen # minimizing it maximizes the dual objective
φ ← Adam(φ, ∇_φ L_D, η_D)
# ================= Segment B: generator update (1 time) =================
{z^(i)} ~ N(0, I), take B samples
L_G ← −(1/B) Σ_i f_φ(G_θ(z^(i))) # raise the score of fake samples
θ ← Adam(θ, ∇_θ L_G, η_G)
return G_θ
Difference of the original BCE version of GAN (replace segments A/B above with):
L_D ← −(1/B) Σ_i [ log D_φ(x^(i)) + log(1 − D_φ(x̃^(i))) ]
L_G ← −(1/B) Σ_i log D_φ(G_θ(z^(i))) # non-saturating loss
# D's output must go through sigmoid; n_critic is usually 1; no gradient penalty needed
Sampling phase: , , one forward pass.
3.10 Section-by-Section Walkthrough of the Pseudocode
Segment A ①: why the critic is updated several steps. The inner layer of the dual objective is . If the inner problem is not solved well, the gradient direction the outer layer receives is wrong. is the default in the WGAN-GP paper. The original GAN generally uses 1, because its is in the sense of “classification accuracy”, and multiple steps easily overfit to the current and instead saturate.
Segment A ②: the position of detach. The generated sample must have its gradient to cut when the critic is updated, otherwise will count “making the generated sample better” into the critic’s update, and the two networks contaminate each other. In PyTorch this is x_tilde = G(z).detach(). The symptom of getting this wrong is: the critic’s loss does not decrease and the generator does not learn, but the code reports no error — this is the most common class of silent bug in GAN implementations.
Segment A ③: the interpolation point must be differentiable. The gradient penalty takes with respect to , so must be inside the computation graph (requires_grad=True) and must not be wrapped in torch.no_grad(). At the same time, the construction of must use a per-sample (shape ), not a single scalar shared by the whole batch.
Segment A ④: why the penalty is “gradient norm equal to 1” rather than “less than or equal to 1”. Because in the one-dimensional construction the optimal attains the extreme everywhere (Step 3 of Derivation 9). Theoretically only is required, but the equality form converges better in practice and provides the extra signal “do not be flat where you should not be flat”.
Segment B ⑤: the generator is updated only once. The generator’s objective is the outer , which depends on “the current optimal critic”, so one update after each critic has roughly caught up is enough. Updating too many times makes the generator optimize against the critic’s instantaneous weaknesses (which is exactly what unrolled GAN tries to solve).
Segment B ⑥: the gradient path of . , and the gradient must pass through to . So here must not have detach added, but at the optimizer level only should be used (in PyTorch optimizer_G receives only G.parameters() and optimizer_D only D.parameters(), each with its own zero_grad).
Segment B ⑦: why there is no . The critic outputs a real-valued score, not a probability. The objective has a constant gradient magnitude when “the fake sample’s score is low”, and does not saturate — this is what Step 5 of Derivation 9 means by “the gradient of is of the same order as the distance”.
Segment A ⑧: BatchNorm and batch coupling. If the critic uses BatchNorm, the gradient penalty has a side effect on “the output of one sample depending on the other samples in the same batch” (because BN makes depend on the whole batch’s statistics, so is no longer per-sample). The WGAN-GP paper explicitly recommends that the critic not use BN, and use LayerNorm or no normalization instead. This is why many people fail to reproduce it.
3.11 Per-Step Read/Write and State-Maintenance Checklist
GAN is the one of the four model families whose “state is easiest to misconfigure”. The core is three checklists: whose parameters are updated when, which tensors must be detached, and which statistics must be refreshed every step.
| Quantity | Update frequency | Participates in gradients | Kept across steps | Consequence of getting it wrong |
|---|---|---|---|---|
| (generator) | Once per round | Yes (Segment B) | Kept | Mixing it with in one optimizer makes them interfere |
| (critic/discriminator) | times per round | Yes (Segment A) | Kept | — |
| Every update | Must be detached | No | Not detaching contaminates ‘s gradient | |
| (interpolation point) | Every update | Must be differentiable | No | Wrapping it in no_grad makes the penalty term identically 0 |
| (interpolation coefficient) | Every update | No | No | Sharing within a batch degenerates the penalty into “one direction for the whole batch” |
| BN running stats | Every forward pass | No | Kept | Using BN in breaks the per-sample nature of the gradient penalty |
| Generator EMA parameters | Every step | No | Kept | Used only for evaluation; mixing them into training slows convergence |
| Historical sample buffer (optional) | Every step | No | Kept | A buffer that is too small fails to “prevent forgetting” |
| Fixed noise (optional, for visualization) | Every few steps | No | Kept | Redrawing every step makes the loss curve too noisy |
Four decision principles:
- “Two optimizers, two sets of parameters, two zero_grad calls.” The parameters of and must never be put into the same optimizer, otherwise ‘s update carries ‘s momentum, and vice versa.
- “Detach the generated sample when updating the critic; do not detach the critic when updating the generator.” These two sentences point in opposite directions, and are the pair most easily confused.
- “Do not use BatchNorm in the discriminator.” Use LayerNorm / InstanceNorm / spectral normalization instead; the generator may use BN.
- “Evaluate with EMA parameters.” The instantaneous parameters of GAN fluctuate a lot, and EMA (with a decay around 0.999) significantly improves FID without changing the training dynamics.
3.12 Pitfall List
| Symptom | Possible cause | Fix |
|---|---|---|
| ‘s loss rapidly goes to 0 and does not move at all | The discriminator is too strong, JS saturates (Derivation 8) | Lower ‘s learning rate, add noise/label smoothing, switch to WGAN-GP |
| The losses of and oscillate violently at the same time | Learning rate too high, mismatched | Lower the learning rate, TTUR ( fast, slow) |
| Generated samples are highly repetitive | Mode collapse (reverse KL) | PacGAN / minibatch discriminator, switch to |
| Only some classes appear | Class imbalance + reverse KL | Conditional GAN, resampling, class-aware loss |
| FID suddenly collapses and then recovers | The discriminator falls into a local optimum | Historical buffer, EMA, gradient penalty |
| The gradient penalty term is identically 0 | is not in the computation graph | Turn on requires_grad |
| Training looks normal but the sampled images are all noise | The generator’s last layer uses sigmoid while the data are in | Align the data normalization range (tanh for ) |
| Training with BN in is unstable | The gradient penalty conflicts with BN | Use LayerNorm / spectral normalization in |
| It simply will not train after switching datasets | The architecture is sensitive to resolution | Change the architecture (StyleGAN-like) or switch to diffusion |
The last row deserves emphasis: the hyperparameters and architecture of GAN are extremely sensitive to the dataset. The same DCGAN setup that is rock-solid on MNIST completely fails to converge on 1024-resolution faces. This is not an implementation bug but the inherent difficulty of the JS objective in high dimensions when the supports do not intersect (Derivation 8). This is also the direct reason why the mainstream of image generation shifted from GAN to diffusion after 2020.
3.13 Scope of Applicability
Suitable for:
- Very fast sampling that needs a single forward pass: real-time face swapping, speech synthesis (vocoder-style), super-resolution, image translation (pix2pix, CycleGAN);
- Cases that need extremely high sharpness: GAN samples are usually sharper than those of VAE from the same era, because its loss is driven directly by “can this fool the discriminator” and never passes through pixel averaging;
- Two-domain mapping with paired or unpaired data: structures such as CycleGAN are most natural inside the GAN framework;
- As a component of other models: the feature discriminator inside a perceptual loss, and adversarial distillation for diffusion (compressing many steps into a few with a GAN loss).
Not suitable for:
- Cases that need to cover all modes: the mode-seeking tendency of reverse KL cannot be removed, only mitigated;
- Cases that need reproducible training and little hyperparameter tuning: GAN convergence is sensitive to the random seed, the architecture, and the learning rate;
- Cases that need a likelihood or a density: GAN provides none; use a flow or a diffusion model for density estimation;
- Being the first choice for high resolution and large datasets: today this position has been taken over by diffusion and flow matching, and GAN is used more for “distilling an already trained large model into a few steps”.
4. Normalizing Flow
4.1 Why It Is Needed: A Density That Can Be Computed
VAE can only give a lower bound, and GAN does not even have a density. If the goal is exactly an exact log-likelihood (density estimation, anomaly detection, model comparison, invertible latent-space editing), a new route is required: use a chain of invertible transformations to carry a simple distribution onto a complex one, while making the Jacobian determinant computable in or .
The mathematical foundation of this route is a single formula — the change of variables formula. It writes “how the density changes” as one determinant, and all remaining work is designing invertible structures that are both expressive and cheap in the determinant.
4.2 The Change of Variables Formula
Let be a bijection (a one-to-one invertible mapping), let (usually a standard Gaussian), and let . Then the density of is
Taking the logarithm:
Note that the first term on the right depends only on (easy), while the second term is “the log absolute value of the Jacobian determinant” (the hard part). The entire research history of normalizing flow is the history of “how to make this term cheap”.
Derivation 10: The change of variables formula, from the 1-D density transform to the high-dimensional Jacobian determinant
Step 1: The one-dimensional case (derived with the CDF). Let be strictly monotonically increasing, and let be the cumulative distribution functions. Because is monotone,
Differentiate both sides with respect to and use the chain rule (writing ):
If is monotonically decreasing, then ; a density must be positive, so we take the absolute value: . This is the one-dimensional change of variables.
Step 2: The high-dimensional case (derived from “conservation of probability mass”). Take any measurable set and let (that is, all that map into ). Because is a bijection, the events and are the same event:
Step 3: Substitute inside the right-hand integral. Let and change the integration variable from to . The multivariate substitution formula gives
Step 4: Compare the integrands. The identity above holds for every , so the integrands are equal almost everywhere:
Step 5: Replace the determinant of the inverse map by that of the original map. By the inverse function theorem, , so taking determinants gives , and after taking absolute values:
Substituting back yields the formula in the main text.
Step 6: Geometric interpretation (why it is a determinant). Consider a small hypercube of side around , with volume . The map carries it onto a parallelepiped whose volume equals . The probability mass on the two regions is the same number, so
Canceling on both sides gives the change of variables formula. The sentence “a determinant is a local volume scaling factor” is the key to understanding every flow model: invertibility guarantees that no volume is lost, and the determinant guarantees that the volume scaling can be tracked.
Step 7: The price of invertibility. A bijection forces the input and the output to have the same dimension ( to ), so a flow cannot perform dimensionality reduction — this differs from VAE () and from GAN (). This constraint directly makes flow models heavier in parameters and computation, and is one of the main reasons why they are less popular than diffusion for image generation.
4.3 The Two Families of Invertible Structures
With the formula in hand, the question becomes: which is both expressive and cheap in ?
Using a free-form neural network directly does not work: computing a determinant costs , and for images , which is entirely infeasible. So must be split into several “structurally restricted but stackable” layers, each with a triangular Jacobian, so that the determinant equals the product of the diagonal entries ().
Two families:
| Family | Structure | | Inverse transform | Representatives | | --- | --- | --- | --- | --- | | Coupling flow | Split the input in two; one half is the identity, the other half is affinely transformed by the first half | | Explicit, | RealNVP, Glow | | Autoregressive flow | Dimension is determined by dimensions | | Requires sequential computation | MAF, IAF |
Both have triangular Jacobians; the difference is which direction is fast: the inverse of a coupling flow is as fast as its forward direction (both ), whereas an autoregressive flow is fast in the forward direction (computing the likelihood) and slow in the inverse direction (sampling, which requires sequential steps), or vice versa (IAF). This asymmetry is the key consideration when choosing between them.
4.4 Affine Coupling Layer
Split into (the first dimensions) and (the remaining dimensions), and define
where are arbitrary neural networks (no invertibility and no special constraint required) whose inputs are only . The inverse transform is
The elegance of this design: the expressiveness is placed inside , while invertibility is guaranteed by “leaving untouched”. The functions can be arbitrarily complex because they only act on the affine parameters and play no part in invertibility.
Derivation 11: The Jacobian of an affine coupling layer is triangular, so $\log\left|\det J\right|=\sum s_i$
Step 1: Write the four blocks of the Jacobian. Differentiate with respect to and write it block by block:
Step 2: Compute block by block.
- , so and ;
- , so the partial derivative with respect to is (because do not depend on );
- the partial derivative with respect to is more complicated: , but we do not need to compute it.
Step 3: Use the determinant formula for block-triangular matrices. Because the upper-right block is zero,
The key step above is “the determinant of a block-triangular matrix equals the product of the determinants of the diagonal blocks”, which holds for both upper and lower triangular matrices.
Step 4: Take the log absolute value.
Step 5: Check “why the upper-right block must be zero”. If depended on , the upper-right block would be nonzero, the determinant would no longer be , and one would have to compute a determinant, collapsing the whole route. So the first design principle of a coupling layer is: the half that is copied must remain completely untouched.
Step 6: Do we really not need ? We do not. The likelihood uses only , which depends only on the diagonal blocks. The terms and only affect the values of at sampling time and do not affect the determinant. This is exactly why coupling layers are more efficient than general invertible networks: they decouple “the expressiveness of the mapping” from “the computability of the determinant”.
Step 7: Existence of the inverse transform. The equation gives ; then gives . The whole procedure only needs the values of at ; it requires no matrix inversion and no iteration. This is what “explicitly invertible” means.
Derivation 21: The inverse of a coupling layer, the reciprocal determinants, and the triangular Jacobian of autoregressive flows
Derivation 11 only proved “the Jacobian of a coupling layer is triangular and ”. But a flow model must be usable in both directions: the forward direction computes the density during training, and the inverse direction performs the inverse transform during sampling. This subsection fills in the explicit form of the inverse transform, the reciprocal relation between the determinants in the two directions, and the same triangular argument for autoregressive flows (MAF/IAF).
Step 1: Write the inverse of the coupling layer. Following the notation of Section 4.4 (, with taking the copied half as input):
where are arbitrary functions (they need not be invertible) and is elementwise multiplication. The inverse transform only has to solve the equation above for :
Note that the inverse of or never appears in the inverse transform — this is precisely the point of a coupling layer: it downgrades the requirement of “invertibility” from “the function must be invertible” to “the function only translates and scales”, and translation and scaling are always invertible. That is why and can be arbitrarily complex neural networks.
Step 2: Prove that the determinants of the two directions are reciprocals. The forward Jacobian (Derivation 11) is a lower block-triangular matrix:
The Jacobian of the inverse transform, obtained by differentiating with respect to , is likewise lower triangular:
The determinants of both matrices equal the product of the diagonal blocks:
Therefore
This identity says: both the forward and the inverse direction of the same layer cost only (one elementwise sum), and one never actually computes a determinant. It is the mathematical source of “the training and sampling costs of a flow model are symmetric”, and the most essential difference between flow and autoregressive models (whose sampling must proceed sequentially).
Step 3: Why numerical stability is a problem about . The density formula contains , not . This means that what really needs to be controlled is the magnitude of , not the magnitude of each individual : even if every is only 0.5, with we get and the exponential has long since overflowed. Two common treatments:
- squash through a bounded function (for example
tanhmultiplied by a scale) into , so that is controllable; - accumulate in the log domain throughout (
logsumexpstyle) and exponentiate only at the very end — this is also the origin of the implementation rule “never compute first and then take the log”.
Step 4: The Jacobian of an autoregressive flow. A Masked Autoregressive Flow (MAF) is defined as
where . Differentiating the Jacobian entry by entry:
Because depends only on , and depends only on , the derivative must vanish for . So is lower triangular, and its determinant is the product of the diagonal entries:
Step 5: The cost asymmetry between MAF and IAF. The formula above requires to take as input, that is, “compute the parameters from the data”. This introduces an asymmetry between the two directions:
| Direction | MAF () | IAF (, that is, the forward direction is defined on ) |
|---|---|---|
| Computing the density (the forward direction ) | One parallel forward pass (the for all can be computed simultaneously) | Requires sequential forward passes |
| Sampling (the inverse direction ) | Requires sequential forward passes | One parallel forward pass |
| Typical use | Density estimation, and as a flexible posterior for VAE (training needs the density) | Fast sampling (training only needs sampling, not the density) |
This table explains “why MAF is used for density estimation and IAF for variational inference”: the two have exactly the same Jacobian (both ), and the only difference is whether the parameters depend on or on , which determines which direction can be parallelized.
Step 6: A unified view — the essence of a flow is a matrix structure. Looking at the two kinds of layers together, they both do the same thing: make the Jacobian triangular, so that the determinant degenerates into a product of diagonal entries. A coupling layer is “block-partitioned by channel with a triangular structure between blocks”, and an autoregressive flow is “term by term along the dimension, strictly triangular”. This unified view says that designing a flow model is not “designing an invertible network” but “designing a Jacobian structure whose determinant can be computed in ” — invertibility is merely a by-product of that structure. Conversely, any transform with a dense Jacobian (such as a free MLP) cannot serve as a flow, because it requires an determinant.
4.5 Glow’s Invertible Convolution
A coupling layer has one obvious weakness: it transforms only half of the dimensions each time, so many layers must be stacked before every dimension participates. Glow introduces an “invertible convolution” to fill this hole: it performs one linear mixing along the channel dimension, so that any channel can influence any other channel.
where is a matrix ( being the number of channels) that acts independently at every pixel location.
Derivation 12: $\log\left|\det W\right|$ for the invertible $1\times1$ convolution and the LU parameterization
Step 1: The Jacobian of the whole feature map is block-diagonal. Let the feature map have size and be flattened into a vector of dimensions. The convolution applies the same at every pixel location, so the Jacobian is a block-diagonal matrix made of copies of :
Step 2: The determinant of a block-diagonal matrix.
Step 3: The cost of computing directly. The naive approach is an LU decomposition at every forward pass. With this is operations, and it would have to be recomputed after every parameter update — too expensive. Glow’s solution is to parameterize in LU form:
where is a fixed random permutation matrix (constant during training), is strictly lower triangular with unit diagonal, is strictly upper triangular, and is the diagonal vector. All three are trainable parameters.
Step 4: What the determinant becomes under this parameterization. By the multiplicative property of the determinant:
because is unit lower triangular (all diagonal entries are 1, and the determinant equals the product of the diagonal entries). Hence
Step 5: The inverse transform. With the LU decomposition of already available, solving requires only two triangular back-substitutions () and no matrix inverse. This is the key to bringing both “the determinant” and “the inverse” down to .
Step 6: Why a fixed is needed. Without the permutation matrix, the product easily becomes numerically ill-conditioned, in the sense that “diagonal dominance disappears” (the determinant approaches 0, or some approaches 0). Adding a fixed random permutation is equivalent to one fixed reordering of the channels, which makes the numerics more stable without adding parameters.
Step 7: Its role inside the flow. A coupling layer mixes only “half of the dimensions”, whereas the convolution mixes “all channels”; alternating the two builds the basic Glow block: ActNorm (per-channel affine transform, for numerical stability) → invertible convolution (to mix channels) → coupling layer (to perform the nonlinear transform). Every step is invertible and has a cheap log-determinant.
4.6 Continuous Flow: Replacing “Layers” with “Time”
A discrete flow is “a composition of invertible transforms”. A continuous normalizing flow (CNF) pushes this to the limit: infinitely many layers, described by an ordinary differential equation (ODE).
Now the likelihood no longer relies on “accumulating layer by layer” but on an integral:
The derivation of this expression uses the “continuity equation”, and the trace inside it is estimated in practice with the Hutchinson estimator.
Derivation 13: The instantaneous change of variables for continuous flows and the Hutchinson trace estimator
Step 1: Write the continuity equation of the probability flow. Let be the probability density at time and the velocity field. Conservation of probability mass requires
This is the continuity equation from fluid mechanics; here it expresses that “probability is neither created nor destroyed”.
Step 2: Expand it.
Step 3: Compute “the rate of change of the log-density along a trajectory”. Consider a point that follows the flow; its total derivative with respect to time is
Substituting the result of Step 2:
Step 4: Divide by to obtain the rate of change of the log-density.
Here we used “the divergence equals the trace of the Jacobian”: .
Step 5: Integrate from to .
This is the formula in the main text. It corresponds exactly to the discrete-flow expression : the sum becomes an integral, and per-layer determinants become instantaneous traces.
Step 6: Why the trace can be estimated cheaply. For a -dimensional , computing the trace exactly requires backward passes (each computing one diagonal entry ), at a cost of . The Hutchinson estimator uses a random probe vector :
Step 7: Verify this identity. Let (take to be a random vector with independent, zero-mean, unit-variance components, such as Rademacher or standard Gaussian). Then
The second equality uses “a scalar can be written as a trace”, , and the third uses that the expectation and the trace can be exchanged.
Step 8: One backward pass suffices. The quantity can be written as , where is a vector-Jacobian product (VJP) that one backward pass computes at a cost of . So the whole trace estimate costs one backward pass, which is an order of magnitude cheaper than the backward passes of the exact trace. The feasibility of models such as FFJORD rests on this step.
Step 9: Invertibility. The solution map of the ODE, , is a bijection provided that satisfies a Lipschitz condition in (which guarantees a unique solution that depends continuously on the initial value). The inverse transform is obtained by solving the ODE in reverse time: start from and integrate back to with as the velocity field. So a continuous flow is also “invertible”, except that the inverse transform is a numerical integration and therefore carries error.
4.7 Engineering Details of Training and Sampling
The likelihood of a flow model is exact, which is unique among the four model families, but the price is that three engineering details must be handled:
(1) Dequantization. Image pixels are discrete (0–255). A flow is defined on a continuous density, so computing “the density of a discrete value” directly gives zero (the probability of a single point is zero) and the likelihood degenerates. The standard treatment is to add uniform noise to every pixel:
This is equivalent to viewing the discrete distribution as “the bin-wise integral of a continuous density”. The reported likelihood must then be shifted by for the unit conversion, yielding bits per dimension (bpd):
(2) Multiscale structure. On high-resolution images is enormous, and applying a full-dimensional transform at every layer is too expensive. RealNVP and Glow handle this by “freezing” part of the channels after each layer — storing them directly as output — while the remaining channels continue to be transformed. This reduces computation and also lets different layers handle different frequency bands (shallow layers handle high-frequency detail, deep layers handle low-frequency structure).
(3) Tempering. Sampling directly from sometimes yields samples that are “too typical” (close to the training-set average). One can anneal with (), first sampling at a high temperature (more spread out) and then lowering to the target temperature. This is an optional trick and not part of the model itself.
(4) The latent space has the same dimension as the data. This is a structural property of flows and also their limitation: no compression, no semantic disentanglement (unlike the of VAE). To perform “attribute editing”, one needs additional latent-disentanglement methods, or simply the naive approach of “shift along some direction and then decode”.
Derivation 22: Why dequantization is necessary, and where the $+\log_2 256$ in bpd comes from
Section 4.7 gave the dequantization recipe and the bpd formula, but did not explain two things: why “not adding noise to discrete data” makes the likelihood of a flow model meaningless, and which volume factor the additive term actually comes from. This subsection derives both.
Step 1: The correct relation between discrete probabilities and continuous densities. Let each pixel take values . View the value as a “cell” of side :
The relation between a continuous density and a discrete probability is defined by “integrating over the cell”:
This is the only correct relation: a discrete probability is the integral of a continuous density over a cell, not “the value of the density at a point”.
Step 2: Use Jensen to turn the integral into a “samplable expectation”. Take the uniform distribution on the cell; its density is , so
Because is concave,
Substituting :
Step 3: Negate both sides to obtain an upper bound on bpd. The direction of the inequality above matters: it gives a lower bound on , hence an upper bound on :
Dividing both sides by :
And . This is the origin of in the bpd formula: it is the volume factor of “taking the log of the cell volume and converting it into bits”, not an empirical correction term. The inequality also clarifies the direction: the reported bpd (dequantized continuous likelihood plus 8) is an upper bound on the discrete-likelihood bpd — that is, a conservative estimate, and the true discrete NLL cannot be worse than it.
Step 4: How large is the Jensen gap. Equality holds if and only if is constant on every cell. The more violently varies inside a cell, the larger the gap:
- high-resolution natural images: the density varies gently between neighboring pixels, so within one cell (a pixel-value range of ) the variation is tiny and the gap is typically on the order of bpd;
- low resolution, strong texture, or insufficient training ( develops spikes): the gap can exceed bpd, in which case “the dequantized bpd” substantially overestimates (reports a worse value).
This explains a practical phenomenon: when comparing bpd across papers, the dequantization scheme (noise injection versus variational) must be the same, otherwise that 0.1 bpd difference gets misread as a difference in model quality.
Step 5: What happens without noise (why noise is mandatory). If the discrete values are treated as continuous data and the density is evaluated at the point , maximum likelihood rewards solutions that “pile the density into spikes”: the model can make extremely high at every discrete point of the training set and extremely low elsewhere, pushing arbitrarily high while does not improve at all. Mathematically this shows up as ” converging to a sum of functions” — the density has no upper bound, the likelihood is infinite, but the samples are nothing but memorized training examples.
The role of dequantization () is exactly to force to be smooth on every cell: the model can no longer profit from “piling a spike on a single point”, because lands at a random position inside the cell and a spike can cover only a small part of it. In the notation of Step 2, dequantization is equivalent to “replacing with ”, and the latter is insensitive to spikes.
Step 6: Do models of continuous data have the same problem? They do, only in a different form. If VAE normalizes pixels to and uses a Gaussian likelihood, it models a continuous density, and reporting the likelihood likewise requires the unit conversion between and (the same equivalent of subtracting ). The of a diffusion model, by contrast, does not contain this constant term — so diffusion papers usually report FID rather than bpd, or, when they do report bpd, must explicitly state “which discretization was used”. The rule “bpd is comparable only under the same objective and the same discretization” has its roots in this volume factor.
4.8 Pseudocode: A RealNVP-Style Coupling Flow
Algorithm: coupling flow (K affine coupling layers + alternating splits)
Input: training set D, number of layers K, split dimension d, batch size B, learning rate η
Output: flow f_θ (invertible), exact log-likelihood function
Initialize: two small networks per layer s_k, t_k (arbitrary architecture, output dimension D − d)
# ---------- Forward: z → x, accumulating log|det J| ----------
function FORWARD(x):
logdet ← 0
for k = 1 .. K:
# Alternating split: odd layers split the first d dimensions, even layers split the last d dimensions
(x1, x2) ← SPLIT_k(x)
s ← s_k(x1)
t ← t_k(x1)
x2 ← exp(s) ⊙ x2 + t
x ← CONCAT(x1, x2)
logdet ← logdet + Σ_j s_j # Derivation 11
return x, logdet
# ---------- Inverse: x → z ----------
function INVERSE(x):
for k = K .. 1:
(y1, y2) ← SPLIT_k(x)
s ← s_k(y1) # note: recomputed from y1, not cached
t ← t_k(y1)
y2 ← exp(−s) ⊙ (y2 − t)
x ← CONCAT(y1, y2)
return x
# ---------- Training: exact maximum likelihood ----------
for each minibatch {x^(i)}:
x^(i) ← x^(i) + u^(i)/256, u^(i) ~ U[0,1) # dequantization
z^(i), logdet^(i) ← FORWARD(x^(i))
NLL ← (1/B) Σ_i [ −log p_Z(z^(i)) − logdet^(i) ]
θ ← Adam(θ, ∇_θ NLL, η)
# ---------- Sampling: z ~ prior → x ----------
function SAMPLE(M):
z ~ N(0, I), shape [M, D]
x ← INVERSE(z)
return x
4.9 Section-by-Section Walkthrough of the Pseudocode
① The forward and the inverse direction use the same set of . This is where a coupling flow saves the most: the inverse transform needs neither a second trained network nor a matrix inverse. The price is that the inverse transform must recompute (because the input of is , which is the same quantity as in the forward pass; in principle it could be cached, but caching per layer costs a lot of memory, so in practice it is usually recomputed).
② The splits must alternate. If every layer split the first dimensions, those first dimensions would never change — they would merely be “copied” from beginning to end, and the model would have no expressiveness over them. Alternating splits (odd layers split the first half, even layers the second half) guarantee that every dimension gets transformed. This is the original RealNVP design and the step most easily overlooked.
③ logdet is a scalar accumulation, not a matrix. Each layer contributes only one scalar, . This is precisely why flow models can work in high dimensions: they never explicitly construct the Jacobian matrix.
④ The training objective is simply the negative log-likelihood (NLL), with no lower bound and no adversary. This is the biggest advantage of flows over VAE/GAN: the objective is exact, single-term, and reproducible. All of its difficulty shifts onto architecture design (it must be invertible, it must preserve dimension, and the determinant must be cheap).
⑤ Dequantization is mandatory, not optional. If this step is forgotten, the NLL computed on image data becomes abnormally large (because the value of the continuous density at a discrete point is magnified by the ), and training tends to “pile the density on the discrete points”, learning a degenerate distribution.
⑥ Sampling is one inverse transform over layers. This is the same order as one forward pass of GAN and far faster than the dozens to thousands of steps of diffusion. The sampling cost of a flow is of the same order as its training cost, which is a genuine advantage over diffusion.
4.10 Per-Step Read/Write and State-Maintenance Checklist
| Quantity | When read | When written | Kept across steps | Consequence of getting it wrong |
|---|---|---|---|---|
| (the copied half) | Every layer | Every layer | No | Modifying it breaks invertibility and the determinant |
| Every layer | Every layer (computed by the network) | No (recomputed in the inverse) | Caching the forward while the input does not match makes the inverse transform wrong | |
| accumulator | Every layer | Accumulated every layer | Kept within a sample | Forgetting to accumulate turns the likelihood into “the likelihood of the last layer only” |
| Split mask | Every layer | Fixed | Kept (fixed) | The same mask at every layer leaves some dimensions never transformed |
| (parameters of ) | Every step | Every step | Kept | — |
| ActNorm mean/variance | Every forward pass | Fixed after initialization at the first forward pass | Kept | Re-estimating every step breaks invertibility (the inverse uses different statistics) |
| of the convolution (LU parameters) | Every layer | Every step | Kept | Re-randomizing every step prevents training from accumulating |
| Temperature (at sampling time) | At sampling time | Per schedule | Kept | Using a temperature during training changes the objective |
Three decision principles:
- “Invertibility comes from structure, expressiveness from the sub-networks.” Any change that “makes the sub-networks more complex” does not affect invertibility; any change that “lets the copied half participate in the transform” breaks invertibility.
- “The determinant can only accumulate scalars.” As soon as a matrix appears in the code, the architecture design is wrong.
- “Recompute in the inverse, do not cache.” Except in memory-optimization scenarios, do not reuse the forward inside the inverse transform.
4.11 Pitfall List
| Symptom | Possible cause | Fix |
|---|---|---|
| The likelihood is NaN or | Dequantization was forgotten; or a 0 appears inside $\log\left | \det\right |
| The training loss decreases but the samples are pure noise | The split mask is identical at every layer, so some dimensions are never transformed | Alternate the splits |
| The inverse transform does not match the forward | The inverse used the wrong inputs | The inverse must recompute with |
| The likelihood suddenly becomes a large positive number | The sign of logdet is flipped (it should be ) | Check |
| Checkerboard artifacts appear at the image edges | The split is not aligned with the spatial structure | Split by channel, or use a spatial checkerboard mask |
| Training is extremely slow | Every layer computes the full Jacobian | Switch to a triangular structure |
| Out of memory at high resolution | No multiscale freezing | Add squeeze plus frozen branches |
| Sampling diversity is poor | Improper temperature or wrong prior variance | Check that matches the prior used in training |
4.12 Scope of Applicability
Suitable for:
- Cases that need an exact log-likelihood: density estimation, strict comparison with other generative models, bits/dim benchmarks;
- Cases that need an invertible mapping: latent-space editing, invertible transforms inside style transfer, and the “bidirectional” property of normalizing flows (both are cheap);
- Cases that need fast sampling without many steps: a single inverse transform suffices, which suits latency-sensitive scenarios;
- Anomaly detection and out-of-distribution detection: an exact likelihood can serve directly as a score (although in high dimensions a high likelihood and “being in-distribution” do not always agree);
- As a component of other models: the flow-based posterior of VAE (replacing a diagonal Gaussian with a flow), the continuous-flow view of diffusion (flow matching / CNF), and normalizing-flow priors.
Not suitable for:
- Cases that need dimensionality reduction and compression: a bijection preserves dimension and cannot compress to a low dimension the way VAE does;
- Cases that need extremely strong expressiveness with few parameters: the constraints of invertible structures make their parameter efficiency lower than that of diffusion;
- Being the mainstream choice for image generation: at resolutions above and on large datasets, diffusion and flow matching perform better and train more stably;
- Cases that need a semantically disentangled latent space: an equal-dimensional invertible mapping does not disentangle by nature.
5. Diffusion Model
5.1 Why It Is Needed: Turning “One Giant Leap” into “A Thousand Small Shifts”
Each of the previous three families has one hard flaw that cannot be sidestepped, and all of them point to the same root cause: they all require a single mapping to cross the huge gap between the data manifold and the noise.
| Model | Hard flaw | Mathematical root |
|---|---|---|
| VAE | The posterior must be approximated by a unimodal diagonal Gaussian, while the true posterior is often multimodal | The variational family is too narrow, and the ELBO gap comes mainly from the approximation error (Derivation 3) |
| GAN | Once the discriminator saturates, the generator’s gradient is zero | The JS divergence is constant when the supports do not intersect (Derivation 8) |
| Normalizing flow | It must be an equal-dimensional bijection with a computable Jacobian, so the structure is restricted | The change of variables formula requires to be computable (Derivation 10) |
| Diffusion | — | Uses “many small displacements” to bypass all three at once |
The idea of a diffusion model (a generative model that learns the distribution by progressively adding noise to data and then learning to progressively denoise) can be summarized in one sentence:
Do not learn “jump from noise to data in one step”, but learn “move one small step backwards from the noise”; because the distributions at the two ends of each small step overlap heavily, the regression problem of every small step is very simple.
This “decomposition” brings three immediately visible benefits:
- The supervision signal of each step is known. The forward noising process is a Markov chain that we define ourselves, so has a closed-form solution (Derivation 15) and can serve directly as the “teacher”; no discriminator and no adversarial game are needed.
- The two distributions of each step overlap strongly. The KL between the marginal distributions of adjacent times, and , is small, so distances such as KL and JS — which “fail once the supports do not intersect” — work properly here. This step directly bypasses the dead end of Derivation 8.
- The objective is still the likelihood. The whole training objective can be derived rigorously from the evidence lower bound of the log-likelihood (Derivation 15), so unlike GAN it lacks no density interpretation, and unlike flows it is not constrained by structure.
The price is equally clear: sampling must be iterative. Generating one image requires running the network forward dozens to thousands of times, which is the source of the public impression that diffusion models are “the best in quality but the slowest”. Only later did the Denoising Diffusion Implicit Model (DDIM) and distillation bring the number of steps down to single digits, making the method genuinely practical in engineering.
One contrast that must be remembered: GAN learns “a mapping that carries noise onto data”, VAE learns “a density with latent variables”, a flow learns “an invertible density transform”, and diffusion learns “a time-varying vector field , that is, the direction of “which way to move to look more like data” at each noise level”. Among the four, only diffusion takes a “direction” rather than a “mapping” as the object of learning, and this is the fundamental reason for its stable training and good coverage.
5.2 The Forward Chain and the Reverse Chain: Two Directions, Two Roles
The forward process (also called the diffusion process) is a fixed Markov chain with no learnable parameters whatsoever; its only role is to progressively destroy the data into noise:
The equivalent reparameterized form is
where is the noise variance of step , conventionally written as and .
The reverse process is the part to be learned; it progressively restores noise into data:
In practice is almost always fixed and only the network predicts the mean (or, equivalently, the noise, the clean sample, or the score; Section 5.5 explains that these four parameterizations are equivalent).
| Item | Forward | Reverse |
|---|---|---|
| Contains parameters | No, fully determined by | Yes, parameterized by a neural network |
| Direction | Data → noise (entropy increase) | Noise → data (entropy decrease) |
| Role in training | Provides the supervision signal (the “teacher”) | The object being trained (the “student”) |
| Role in sampling | Does not appear | The only part that is called |
| Known closed forms | Both and have one | None, except for |
The last row of the table is the key to the whole article: the reverse chain has no closed form, but “the reverse chain conditioned on ” does. Training uses the latter to supervise the former — this is what distinguishes diffusion from VAE: the approximate posterior of VAE is learnable and must be approximated by the model itself, whereas the “teacher posterior” of diffusion is computed and exactly known.
5.3 Closed-Form Marginal of the Forward Process (Derivation 14)
If training had to actually run noising steps to obtain , the cost would be and the whole method would be unusable. Fortunately, the marginal distribution at any point of the forward chain is a closed-form Gaussian.
Derivation 14: $q(x_t\mid x_0)$ is a closed-form Gaussian, $x_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\varepsilon$
Step 1: Write “a single step” as an affine transform. By definition,
If the distribution of is known to be , then is a linear combination of two independent Gaussians ( and ), hence still Gaussian, with mean and covariance
Step 2: Establish the induction base at . is a deterministic observation (treated as a degenerate Gaussian with zero variance), so
where the last equality used .
Step 3: Assume it holds for and advance one step.
Substituting into the single-step formula:
Step 4: Merge the two independent Gaussians. A weighted sum of two independent zero-mean Gaussians is again zero-mean Gaussian, with the variances adding:
Therefore
Note that is neither nor but a normalized mixture of the two; it is standard Gaussian because “a linear combination of independent Gaussians is still Gaussian, with the variance normalized”.
Step 5: Write down the conclusion and its three uses.
Use one: training needs only one sample. No matter how large is, constructing costs : draw one and evaluate the formula once. This is the prerequisite that makes diffusion training feasible.
Use two: the reverse “teacher” becomes computable. Only with this can be rearranged into a closed-form Gaussian in Derivation 15.
Use three: the noise level is controllable. decreases monotonically; when , is almost the data, and when , it is almost pure noise. This curve is exactly the “noise schedule”.
The noise schedule determines the shape of and therefore determines “in which segment the signal gets drowned”. Two mainstream choices:
| Schedule | Definition | Shape | Trade-off |
|---|---|---|---|
| Linear | increases linearly from to () | drops steeply first and then flattens | Simple to implement and consistent with the original paper; the low-noise segment is too dense and the final segment wastes steps |
| Cosine | Approximately uniform decline | Balanced utilization of every noise segment and better FID; requires recalibration so that |
The role of a schedule can be described more precisely as “how much training budget is allocated to each noise level”. Because uniform sampling of is equivalent to non-uniform sampling over according to “the of each step”: under a linear schedule the low-noise segment (the interval where is close to 1) occupies a large number of steps, so the model is trained there over and over while the high-noise segment gets almost no steps. The cosine schedule flattens this distribution. This is also why changing the schedule forces one to retune the number of training steps and the learning rate — what is changed is not a constant but the distribution of training samples along the noise dimension.
5.4 The Evidence Lower Bound and the True Posterior (Derivation 15)
The training objective of diffusion comes from the evidence lower bound (ELBO, a computable lower bound on ) of the log-likelihood. Compared with the ELBO of VAE, the special feature here is that the approximate posterior is fixed to the forward process, so the ELBO can be rearranged term by term into a sum that is “almost entirely closed-form Gaussian KL terms”.
Derivation 15: The term-by-term rearrangement of the ELBO, and the closed-form rearrangement of $q(x_{t-1}\mid x_t,x_0)$
Step 1: Write down the ELBO. Introduce the forward process as the approximate posterior (it does not depend on , so it is not “a learned approximation” but “a specified approximation”):
The inequality comes from Jensen ( is concave). Equality holds if and only if , in which case the gap is zero — this tells us that the “forward destruction process” should be made as close as possible to “the true posterior of the reverse generative process”, rather than being specified arbitrarily.
Step 2: Factor both joint distributions into products.
Step 3: Rearrange term by term (this step is where the whole trick lies). The goal is to replace by , so that each term contains only the ratio of “two adjacent terms”:
The first equality uses the Markov property ( and are conditionally independent given ); the second is Bayes’ rule, rewriting “first ” as “first , then back from ”.
Step 4: Substitute and let adjacent terms cancel. Substitute the expression above into the ratio inside the ELBO:
Expand the sum: (the -th term) and (the -th term) cancel pairwise, leaving only the two ends:
Step 5: Write it as three terms: KL and reconstruction. Take the expectation and reorganize each term into a KL:
The three terms mean the following: requires “the distribution after noising all the way to the last step” to be close to the standard Gaussian prior (guaranteed by the schedule, and almost constant); is the final step that reconstructs from ; is the main body, and it requires the reverse network to reproduce, at every step, “the true conditional distribution of given and ”.
Step 6: Rearrange the true posterior into a closed form. It is the product of two Gaussian densities (Bayes):
Collect the quadratic and linear terms in inside the exponents. The coefficient of the quadratic term is
so the posterior variance is
The linear terms give the mean (writing the quadratic coefficient as ):
Step 7: Conclusion. Therefore
This is a fully closed-form Gaussian with no parameters. therefore becomes “the KL between two Gaussians”, and the KL of two Gaussians has a closed form (Derivation 4 gave the diagonal-Gaussian case), so the entire training objective becomes a differentiable, samplable regression problem. This is the whole secret of “diffusion needs no adversary and no variational family, yet still has a likelihood interpretation”.
There is a corollary here that is easily overlooked but crucial: because the true posterior is Gaussian with a known variance, the reverse network does not need to learn the variance. only requires the mean of to match ; the variance part, with fixed, is a constant and can be deleted from the loss. This simplifies “learning a distribution” into “regressing a vector”, which is the structural reason why diffusion training is stable.
5.5 Four Parameterizations: Predict , , , or the Score
requires . But is a function of and , and is unknown. So there are two routes: regress directly (in which case the network must know ), or replace with “the estimate recovered from and the noise”. The latter route leads to four equivalent parameterizations.
From the closed-form marginal , we can solve backwards:
Differentiating the Gaussian density in turn gives the score (the gradient of the log-density with respect to the input):
So the four prediction targets are linear transforms of one another:
| Network output | Notation | Relation to | How to recover at use time |
|---|---|---|---|
| Noise | It is the target itself | ||
| Clean sample | Use it directly | ||
| Mean | Recovered from the expression for | Substitute back into and solve for | |
| Score |
Why is the parameterization chosen almost everywhere in practice? There are three reasons:
- A stable numerical scale. is always a standard Gaussian with unit variance, so the magnitude of the regression target is independent of ; whereas is almost unrecoverable from when is large, so the error of regressing it gets amplified by a factor of .
- Natural equivalence with score matching. Predicting is equivalent to predicting the score (up to a constant factor that depends only on ), so it is simultaneously “a denoising objective” and “a score-matching objective”, and one loss serves two theoretical viewpoints (developed in Section 5.7).
- Consistency with the form of the simplified loss. The simplified loss (Derivation 16) is exactly the mean squared error on and needs no additional transformation.
The four parameterizations are not equivalent — mathematically they are linear transforms of one another, but the gradient scale, the error propagation, and the training difficulty are completely different. That distinction has its own section in Diffusion Model Notes (error propagation across parameterizations); here we only stress the conclusion: choose unless there is an explicit reason not to (for example, greater accuracy at very low noise levels, or consistency distillation).
Derivation 31: The conversion among the four parameterizations ($x_0$, $\varepsilon$, $\mu$, $v$), and why $v$ is a 45-degree rotation
Step 1: unified notation. Let
The closed-form forward marginal (Derivation 14) reads
Step 2: the three parameterizations are linear transforms of one another. From the expression above,
The mean parameterization is given by Step 4 of Derivation 16:
Each of the three equalities uses “solve a linear equation” once and introduces no approximation. So mathematically the four carry exactly the same information; the only difference is which quantity the network regresses.
Step 3: how the errors convert into each other. Let the network’s prediction error on be . From , the same gives
so the two losses satisfy
This is where “the simplified loss is really a signal-to-noise-ratio-weighted regression on ” comes from (Derivation 23). For large () it barely penalizes the error, and for small () it penalizes it enormously, so regressing directly is amplified by in the low-noise regime, which makes training unstable. This is the first practical reason for choosing .
Step 4: the definition of the parameterization and its orthogonality. Let
Write the relation between and as a matrix:
The determinant of this matrix is , and its two rows are orthogonal (), so it is an orthogonal matrix, i.e., a rotation. The rotation angle satisfies and , that is, . When we have and — this is the precise meaning of ” is a 45-degree rotation”: it rotates the axes in the plane by an angle fixed by the noise schedule, and the more noise, the more it rotates.
Step 5: the inverse transform. The inverse of an orthogonal matrix is its transpose, hence
Written out term by term,
Substituting back into Step 1 verifies both identities:
Step 6: why is stable at both ends. Let the errors of and be ; then
If the two errors are independent with common variance , then
independent of . Compared with the extreme amplification of in the low-noise regime, the error scale of stays constant at both and . This is the motivation for the parameterization (common in progressive distillation and consistency models): it replaces “hard at both ends” with “easy at both ends, slightly harder in the middle”.
Step 7: geometric summary. All four parameterizations merely “choose one coordinate on the same line ”: and are the two end directions of that line, is a particular point on the line, and is a direction at 45 degrees to the line. Choosing a coordinate is equivalent to choosing “in which direction the loss is weighted equally” — this is the geometric explanation of “changing the parameterization means changing the loss weights”.
5.6 From the Term-by-Term KL to the Simplified Loss (Derivation 16)
Expanding into a computable expression yields a mean squared error with a coefficient that depends on . The authors of DDPM did something that looked bold at the time: they simply dropped that coefficient.
Derivation 16: $L_{t-1}$ becomes noise regression, and "why the coefficient can be dropped"
Step 1: The KL of two equal-variance Gaussians keeps only the mean term. Let and . From the closed form of Derivation 4 (the variances are equal, so the terms cancel):
Step 2: Substitute into . Take the variance of to be (one may take or ; the latter is simpler and performs about the same), then
Step 3: Rewrite in terms of and . From Step 6 of Derivation 15,
Substitute :
(The algebra of this step: merge the two terms into minus a term containing ; the merge uses and .)
Step 4: Let the network output the same form. Set
Then the difference of the two means is
Step 5: Substitute back into the KL to obtain a weighted noise regression.
Step 6: Drop the coefficient to obtain .
Step 7: Why the coefficient can be dropped — three levels of reasoning.
- It is still a valid lower bound (in weighted form). equals the sum of reweighted by . As long as the weights are positive, it is still “a positively weighted sum of several KL terms”, hence still a valid variational objective — only no longer a tight ELBO.
- Dropping the coefficient corrects a training bias. The original coefficient tends to zero when is small ( small, ). That is: under ELBO training, the low-noise segment (the segment that decides image detail) carries almost no weight. After dropping the coefficient every has equal weight, so the low-noise segment gets the attention it deserves — this is exactly why sample detail improves.
- It is equivalent to “signal-to-noise-ratio-weighted” score matching. One can show that differs from “least-squares regression on the score” only by a constant factor depending on , so it is still minimizing the score-matching error, just with different weights. The theoretical “likelihood” gives way to the practical “perceptual quality”, and this substitution happens to improve both — one of the few places in diffusion where engineering intuition and theoretical conclusion point in the same direction.
Step 8: An easily confused point. Dropping the coefficient is not the same as giving up the likelihood. If the goal is a strict likelihood metric such as bits/dim, the coefficient should be kept (or a tighter bound obtained through “loss weighting plus importance sampling”); if the goal is generation quality, is better. Both routes exist in the literature, and which one to choose depends on the evaluation metric — this is also an instance of the divergence described in Section 6.2, “the objective and the metric do not agree”.
Derivation 23: What the coefficient dropped by $L_{\text{simple}}$ really is — per-term weights and SNR
Section 5.6 said “the coefficient can be dropped” and gave three levels of reasoning (the weights of different do not change the optimum, is a reweighting of the ELBO, and reweighting amounts to changing the noise schedule). This subsection computes “the dropped coefficient” exactly, and explains why numerically it makes training favor certain noise levels.
Step 1: Write out the ELBO term by term (the conclusion of Derivation 15).
Step 2: Each KL term is the KL of two Gaussians and can be computed directly. Both the true posterior and the model posterior are taken as diagonal Gaussians:
For two diagonal Gaussians with the same covariance (), the KL keeps only the mean term:
Step 3: Replace the means by noise predictions. From the rearrangement in Derivation 15, both means can be written as ” minus a term scaled by ”:
Subtracting the two, the terms cancel:
Step 4: Substitute back into the KL to obtain “noise regression plus a coefficient”.
Denote this coefficient by :
If (the common choice in DDPM), then .
Step 5: is exactly “replace every by 1”.
So “dropping the coefficient” is mathematically exactly equivalent to “multiplying the -th term by ”. This is not an approximation but an exact reweighting — the rigorous version of the first level of reasoning in Section 5.6.
Step 6: How varies with (this is the key). Take and treat as small, expanding at the two ends:
- Small (high SNR, ): , hence
which decreases rapidly as grows;
- Large (low SNR, ): and a constant, hence
Step 7: So what is doing. replaces by the weight 1, which is equivalent to multiplying each term by :
- in the small- segment (low noise, high SNR), is very small — these terms are heavily downweighted;
- in the large- segment (high noise, low SNR), is nearly constant — the weights of these terms are essentially unchanged.
So the actual effect of is “relatively more emphasis on the high-noise segment, neglecting the detail of the low-noise segment”. This matches the empirical remark in the DDPM paper: makes the model learn “the large structure” first and leaves “pixel-level detail” to the later stages — at the cost of insufficient training in the low-noise segment (the segment that decides texture and detail). This is the quantitative explanation of ” gives good sample quality but a poor likelihood”: what it optimizes is not the likelihood but a weighted likelihood that suppresses the low-noise terms.
Step 8: Why Min-SNR weighting works. If instead one wants to flatten the gradient magnitude of the various segments, one can set the weights explicitly. The common choice is
where is the truncation threshold (5 is common). The motivation: the gradient norms at different differ by orders of magnitude, so a few dominate the update; truncating the weight in the low-SNR segment stops the high-noise segment from overwhelming the others. Note that this weight is not the of the ELBO (the two point in different directions); it is “an artificial reweighting introduced to stabilize optimization” — which also shows that “dropping the coefficient” and “changing the weights” are both legitimate, because a reweighting only changes the optimization trajectory, not the optimum (the first level of reasoning in Section 5.6).
Step 9: A verifiable corollary. If is substituted back exactly during training (that is, using the full ELBO rather than ), the resulting model should have a better likelihood and a worse FID; conversely should have a better FID and a worse likelihood. This agrees with the empirical literature (the DDPM paper reported that has a slightly worse bpd but clearly better sample quality). The corollary turns “why is the engineering default” from “a practical convention” into “a direct consequence of the choice of objective”.
5.7 The Score Viewpoint: the Tweedie Formula, Score Matching, and DDIM
This section puts the three main threads needed for the comparison into one continuous derivation (fuller treatments appear in Chapters 2 and 7 of the site’s Diffusion Model Notes).
(1) Denoising is equivalent to estimating the score. From the third expression in Section 5.5, . So “predicting the noise” and “estimating the conditional score” are two sides of the same thing. The training loss can be rewritten as
that is, is a weighted version of “conditional score matching”. The significance of this step is that the score needs no normalization constant. Because ( is a constant and its gradient is zero) — this is exactly where the dead end of “the partition function is intractable” in Derivation 1 gets bypassed. Among the four model families, only diffusion (and score matching) exploits the property that “the gradient cancels the partition function”.
(2) The Tweedie formula gives the optimal “one-step denoising” estimate. Differentiating with respect to gives
which rearranges to
This expression says: given a noisy sample , the optimal minimum-mean-square-error estimate of the clean sample is “one step along the score direction”. Substituting immediately gives — this is the entire basis of “first guess the clean sample, then add back a little noise” at every sampling step.
Incidentally, a frequently asked point: the given by the Tweedie formula is a conditional expectation, hence “the best on average”, but a single sample is not equal to the true . When is large ( small), carries almost no information about , so degenerates to “somewhere near the dataset mean”, which is merely a blurry average image — this explains why at large cannot be used directly as the result and the iteration must continue.
(3) DDIM: turning stochastic sampling into deterministic sampling. The reverse process need not be Markovian. The DDIM update is
Three choices of give three behaviors:
| Value of | Behavior | Characteristic |
|---|---|---|
| Equivalent to DDPM | Most stochastic; repeated sampling gives different results | |
| Fully deterministic | The same initial noise always yields the same image; interpolation and inversion are possible | |
| Between the two | The parameter controls the degree of randomness |
When , the expression degenerates into “first predict , then reproject along the and directions”. The reason it can skip steps (for example, taking only 20 steps instead of 1000) is that deterministic sampling discretizes “an ODE trajectory in continuous time” rather than running a Markov chain — the step size can be enlarged, and the error comes only from numerical integration.
(4) Probability flow ordinary differential equation (PF-ODE). Taking the step count of DDIM to the limit gives a deterministic ODE:
where and are the drift and diffusion coefficients of the forward stochastic differential equation (SDE). Its key property is that this ODE has exactly the same marginal distributions as the original SDE, but its trajectories are deterministic. Hence “sampling with the ODE” and “sampling with the SDE” are equivalent in the distributional sense: the former can take large steps and can be inverted (the map also holds), while the latter is more stochastic and may give better single-sample quality. DDIM is the first-order discretization of this ODE.
(5) What these three threads mean for the “four-model comparison”. They answer three questions:
- Why does diffusion need no partition function? — Because what is learned is the score, and the gradient of is zero (this item).
- Why can diffusion cover multiple modes? — Because the score field has different attractors at different modes, and is a per-sample regression with no tendency to “average the modes away” (in contrast with the reverse KL of GAN and the mean collapse of VAE).
- Why can diffusion be accelerated to a few steps? — Because sampling can be viewed as the numerical integration of an ODE, and step size trades off against accuracy (DDIM, distillation, and flow matching all rest on this property).
Derivation 24: Where the score of classifier-free guidance comes from, and why $\gamma>1$ extrapolates
Conditional generation needs to compute , but the trained network only gives (the unconditional score). Guidance solves exactly “assembling the conditional score from the unconditional score”. This subsection derives the formulas of classifier guidance and classifier-free guidance (CFG), and explains which distribution is actually being sampled when .
Step 1: Split the conditional score with Bayes’ rule.
Taking the log gradient with respect to : does not depend on , so
This identity is the starting point of every guidance method: conditional score = unconditional score + the score of “the dependence of the condition on the data”.
Step 2: Classifier guidance is “approximating the second term with a classifier”. Train a classifier ; then
where is the guidance strength. When it is the exact expression of Step 1 (provided the classifier equals the true ); when the direction of “looking like ” is artificially amplified. The cost is that one must train an additional noise-robust classifier, and the classifier must be usable at every noise level.
Step 3: CFG replaces the second term by “the difference of two scores”. During training, the condition is randomly replaced by the empty condition , so a single network approximates both and (the latter written as ). The CFG score is
which rearranges to
Written in the noise parameterization, this is the familiar (because and the score differ by a factor , multiplying both sides gives this).
Step 4: What distribution does this score correspond to? The right-hand side of Step 3 is “the gradient of a convex combination of two log densities”, so it is the score of
(because ). This is the key conclusion: what CFG samples is not but a geometric interpolation between the conditional and the unconditional distribution. At it degenerates to the conditional distribution, and at to the unconditional distribution.
Step 5: Why is “extrapolation” rather than “a stronger condition”. The geometric interpolation has negative exponents when and is in general no longer a normalized probability distribution (its integral may diverge), so it has no strict probabilistic meaning. It is only “a score field”, and sampling follows that field. The effect can be seen directly: take the one-dimensional Gaussian example,
then
The mean is pushed to while the variance stays 1. So the effect of is to “amplify the displacement along the conditional direction by a factor of ”: the sample is more “typical” and expresses the condition more strongly, but deviates from the true data manifold as a whole, showing up as oversaturation, overexposed colors, and overly hard textures. This explains “FID gets worse once the guidance strength is raised beyond some point”: the displacement has gone outside the support of the data distribution.
Step 6: The formula for combining multiple conditions. With two conditions , under the assumption that they are conditionally independent given ,
In the difference form of CFG this becomes
This is the score addition of composable generation. Its only mathematical basis is “conditional independence”, so when the two conditions are strongly correlated (for example “cat” and “black”), the addition gives samples that do not follow the joint distribution — this is why compositional guidance fails.
Step 7: The mathematical constraint on the training side — the condition dropout rate. CFG requires the network to be able to compute , and this can only be obtained by “dropping during training”. Let the dropout probability be ; then the network learns the unconditional distribution on a fraction of the samples and the conditional distribution on the rest. If is too small, the unconditional branch is under-trained ( has a large bias and the guidance direction is inaccurate); if too large, the conditional branch is under-trained. The common value is 10%–20%, precisely the compromise at which “both branches are accurate enough”.
Step 8: The relation to “temperature”. If is viewed as a “sharpening parameter”, CFG is similar in effect to “lowering the sampling temperature” (both make the samples more concentrated), but the mechanism differs: temperature applies a power to the whole distribution, whereas CFG applies a power to “the ratio of conditional to unconditional”. The former changes diversity, the latter changes “condition consistency”. This also explains why the two are often tuned together: temperature controls overall diversity, controls condition strength, and they are two orthogonal directions in score space.
Derivation 32: From the Fokker-Planck equation to the probability-flow ODE, and why DDIM is its Euler discretization
Step 1: Write down the forward stochastic differential equation. The forward process of a diffusion model is a stochastic differential equation (SDE):
Taking the variance preserving (VP) form, and , gives
Here is a standard Brownian motion, formally .
Step 2: The Fokker-Planck equation. The marginal density of the SDE satisfies the forward Kolmogorov equation (also called the Fokker-Planck equation):
Deriving it requires the Ito formula plus integration by parts against test functions; here it is taken as a known result, and the key point is the rewriting in the next step.
Step 3: Rewrite the diffusion term as “transport”. Two identities are used: , and (the latter requires ). Hence
Substituting back into Step 2,
Step 4: Read off the continuity equation and the velocity field. The expression above is exactly the continuity equation
with velocity field
The continuity equation is the differential statement of “conservation of probability mass”: is transported along the velocity field and its total mass does not change. The key point is that the evolution of is determined by alone, and depends only on , , and , not on any particular realization of the noise.
Step 5: Obtain the probability-flow ODE. Since fully determines the marginal distribution, the stochastic term can be replaced by a deterministic flow:
Its marginals coincide with those of the original SDE at every time instant, because the two satisfy the same continuity equation and the solution of that equation is unique given the initial condition. This step is the whole argument for the probability-flow ODE: absorb the diffusion term of the Fokker-Planck equation into the velocity field and the randomness disappears while the marginals stay unchanged.
Step 6: Substitute the VP coefficients. Inserting and into Step 5,
The inside the bracket can be replaced by the trained noise network (, see Step 1 of Derivation 24), so sampling becomes an ODE that needs only network forward passes and no stochastic sampling.
Step 7: Discretizing it is exactly DDIM. Return from continuous time to discrete steps; first-order Euler gives
A more common route reparameterizes time as and . The velocity field then simplifies to (increasing is the noising direction, so reverse sampling decreases ). Taking Euler steps in :
Rewriting with yields the DDIM update
where , , , . The substitution is: insert into the previous equation,
Combining the terms gives the formula above. This is DDIM: not a different model, but one Euler step of the probability-flow ODE in the coordinate (the step can be far larger than one training step, which is why 20 steps already produce an image).
Step 8: Why DDIM needs fewer steps but its samples look slightly “dead”. A deterministic ODE carries no stochastic term, so errors are not re-scattered by noise; when the step is too large, trajectory drift appears. Stochastic SDE sampling injects noise at every step, which is equivalent to correcting errors near the trajectory (the correction step in the predictor-corrector framework), so at the same step count the stochastic sampler yields more diverse samples. The fact that both share the same marginals is precisely the theoretical basis for “one model can have both a deterministic and a stochastic sampling implementation”.
5.8 Complete Pseudocode
Three pseudocode blocks are given below: training, DDPM sampling, and DDIM sampling. They share the same set of definitions; the only difference is “how to move from to ”.
# ===== Common definitions =====
# Input: data x0 ~ p_data, noise schedule beta[1..T], network eps_theta(x_t, t)
# Precomputed: alpha[t] = 1 - beta[t], alphabar[t] = prod_{s<=t} alpha[s]
# Time-step sampling distribution during training: t ~ Uniform{1..T} (or weighted by SNR)
# ===== Segment A: training =====
TRAIN(batch x0, network eps_theta):
t <- sample_t() # scalar, or one t per sample
eps <- randn_like(x0) # standard Gaussian, same shape as x0
x_t <- sqrt(alphabar[t]) * x0 + sqrt(1 - alphabar[t]) * eps
eps_hat <- eps_theta(x_t, t) # network forward pass
loss <- mean((eps - eps_hat)^2) # L_simple
grad <- backward(loss) # differentiate only with respect to the parameters of eps_theta
update(eps_theta, grad)
return loss
# ===== Segment B: DDPM sampling (stochastic, needs T steps) =====
SAMPLE_DDPM(network eps_theta, steps = T):
x <- randn(shape) # x_T ~ N(0, I)
for t in T down to 1:
eps_hat <- eps_theta(x, t)
x0_hat <- (x - sqrt(1 - alphabar[t]) * eps_hat) / sqrt(alphabar[t])
mean <- coef_x0[t] * x0_hat + coef_xt[t] * x # that is, mu_tilde of Derivation 15
if t > 1:
z <- randn_like(x)
x <- mean + sigma[t] * z # sigma[t] = sqrt(beta_tilde[t])
else:
x <- mean # no more noise at t = 1
return x # approximate sample x0
# ===== Segment C: DDIM sampling (deterministic, can skip steps) =====
SAMPLE_DDIM(network eps_theta, sub_steps = S, eta = 0.0):
x <- randn(shape) # x_T ~ N(0, I)
ts <- linspace(T, 1, S) # only S steps, e.g. S = 20
for i in 0 .. S-1:
t, t_next <- ts[i], ts[i+1]
eps_hat <- eps_theta(x, t)
x0_hat <- (x - sqrt(1 - alphabar[t]) * eps_hat) / sqrt(alphabar[t])
sigma <- eta * sqrt((1 - alphabar[t_next]) / (1 - alphabar[t])) \
* sqrt(1 - alphabar[t] / alphabar[t_next])
dir <- sqrt(1 - alphabar[t_next] - sigma^2) * eps_hat
x <- sqrt(alphabar[t_next]) * x0_hat + dir
if sigma > 0:
x <- x + sigma * randn_like(x)
return x
5.9 Section-by-Section Walkthrough of the Pseudocode
Segment A ①: Why must be sampled randomly rather than in order. Each defines “a regression task at a different noise level”, and random sampling is equivalent to training on all tasks in turn. If the order were fixed (first large , then small ), catastrophic forgetting would set in: what the network learns at small would overwrite its ability at large . Random sampling has a side benefit: samples within one batch can have different , so the gradient is an unbiased mixture of the gradients of several tasks.
Segment A ②: Why is computed in one shot with the closed-form formula. This is a direct application of Derivation 14. If one really looped times to add noise, the per-sample training cost would be and training would be infeasible. The closed-form formula reduces the cost to — this is the dividing line between “diffusion can be trained” and “diffusion cannot be trained”.
Segment A ③: Why the regression target is rather than . Three reasons (Section 5.5): has a stable scale, it is equivalent to score matching, and it matches the form of the simplified loss. If one regressed , then at large the target itself would be close to “the data mean”, the network would learn only a constant, and the gradient signal would be extremely weak.
Segment A ④: Why has no coefficient in . Derivation 16 gives the full reasoning. Here is an engineering intuition: after dropping the coefficient, every noise level is weighted equally, so the network also denoises carefully in the “almost clean” final steps — and those steps determine the detail and texture of the final image. With the original ELBO coefficient, the weight of those steps is close to zero and the image is visibly blurry.
Segment A ⑤: The gradient flows only to . is constructed from and , and the construction contains no parameters, so there is no need (and no reason) to backpropagate into . In code this means both and should be detached. There is one exception: if you are training models such as “a jointly trained encoder plus a diffusion prior”, you do need the gradient to pass through , and then you must enable it explicitly.
Segment B ①: Why sampling starts from . This is the requirement of (the prior-matching term). The schedule guarantees , so , which is almost identical to the prior and . If the schedule is not tuned well ( still clearly larger than 0), the starting point of sampling does not match the terminal state seen during training, and the symptom is “a clear offset in the first few steps”.
Segment B ②: Why compute first and the mean afterwards. This is what of Derivation 15 becomes after the parameterization. plays two roles here: it makes “the clean sample that the current step believes in” explicit, which helps debugging and visualization; and it makes it convenient to later add “threshold clipping” (clipping into ) or “guidance” (applying the conditional gradient to ).
Segment B ③: Why no more noise is added at . Because is deterministic data, the last step should not introduce randomness; if noise were still added at , the output would carry an irreducible noise floor. This is a common implementation error, and its symptoms are “samples that are blurry overall with fine-grained noise speckles in the background”.
Segment B ④: Where the stochasticity of DDPM sampling comes from. It comes from at every step. It lets “the same starting point” generate different samples, and makes the sampling procedure equivalent to the discretization of a reverse SDE. The benefit of stochasticity is that “repeated sampling can correct early mistakes”; the cost is “large error when the step count is small”.
Segment C ①: Why DDIM can skip steps. Because with the update is deterministic, it corresponds to the Euler discretization of an ODE; numerical integration of an ODE allows larger step sizes, at the cost of only discretization error rather than “insufficient mixing of a Markov chain”. Empirically to already approaches the quality of .
Segment C ②: Where the formula for comes from. It is solved from the constraint “keep the marginal distribution unchanged”: set the variance of equal to the variance in the DDPM case, and the remaining degree of freedom is controlled by . With the whole variance term is absorbed by ; with DDPM is reproduced exactly.
Segment C ③: Two extra benefits of deterministic sampling. The first is invertibility: given , integrating the ODE forward yields the corresponding , which enables “real image editing” (first invert to noise, change the condition, then generate forward). The second is interpolability: a linear interpolation between two noises corresponds to a reasonable generation path. Neither GAN nor VAE has these two properties (the GAN latent space can interpolate but cannot be inverted to an exact ).
Segment C ④: Should be clipped? For images normalized to or , the data is bounded during training, but the formula for does not guarantee boundedness (especially at large ). In practice clipping is often applied, and its role is “prevent extreme values in the early steps from throwing the trajectory off course”; its side effect is “clipping introduces bias and may lose dynamic range”. Whether it is needed depends on the data normalization and the number of sampling steps.
5.10 Per-Step Read/Write and State-Maintenance Checklist
| Quantity | During training | During sampling | Kept | Note |
|---|---|---|---|---|
| , | Read | Read | Kept (a precomputed table) | Depends only on the schedule; training and sampling must use the same table |
| Read (to construct ) | Absent | Not kept | Only exists at sampling time | |
| Read (the regression target) | Absent | Not kept | At sampling time the network output is used | |
| An intermediate quantity | The state | Kept (a loop variable) | At sampling time it is the only state | |
| Computed | Computed | Not kept | Discarded after each step (except for debugging) | |
| Absent | An intermediate quantity | Optionally kept | Used for clipping, guidance, and visualization | |
| (DDIM) | Absent | Read | Kept (precomputed) | Determined by and the schedule |
| Time step | Randomly sampled | A fixed sequence | Kept (a schedule table) | DDIM uses a subsequence rather than all |
| Network parameters | Updated | Frozen | Kept | Sampling must use the same parameters |
| Random seed | Not fixed | Fixed (reproducible) | Kept (optional) | Under deterministic sampling the seed determines the output |
Four decision principles:
- “The schedule table is the only shared constant.” Training, DDPM sampling, and DDIM sampling must all read the same ; changing the schedule requires retraining, and changing only the sampling side is not allowed.
- “The only sampling state is .” Apart from and , any quantity carried across steps is wrong (unless it is a condition used for guidance, or the teacher trajectory used in distillation). Code that “caches the of the previous step into the next step” can essentially be diagnosed as an implementation bug.
- ” and are constants in training, not variables.” Both are “known quantities derived from the data and from random numbers”, so both must be
detached; treating them as learnable lengthens the gradient path with no benefit whatsoever. - “The of DDIM is a subsequence, not consecutive integers.” When skipping steps, must take the next value of the subsequence and must not be written as . This error throws no exception; it merely makes sample quality inexplicably poor.
5.11 Pitfall List
| Symptom | Possible cause | Fix |
|---|---|---|
| All samples are blurry, like dataset averages | sampling favors large ; or the coefficient was not dropped (Derivation 16) | Use SNR-uniform sampling; confirm the loss is |
| Samples have a fixed noise floor | Noise is still added at | Do not add at the last step |
| The training loss looks normal but all samples are wrong | The used for sampling does not match training | Unify the schedule table and check for index offsets |
| Quality collapses after DDIM step skipping | is used instead of the next subsequence value | Look up explicitly in the table |
| The high-noise segment does not learn | is regressed instead of | Switch to the parameterization |
| Sample diversity is poor | Guidance strength too high; or overtraining | Lower the guidance coefficient ; check for overfitting |
| Out of memory | Activations are kept at every step for backpropagation | Backpropagate through a single random only; do not unroll the whole chain |
| The loss rebounds late in training | The learning rate was not adjusted with the schedule; or data augmentation is too strong | Use a cosine schedule, lower the learning rate, check the augmentation |
| Sampling is extremely slow | The full steps are used | Switch to DDIM (20–50 steps) or distillation |
| Conditional generation does not follow the prompt | The gradient does not pass through the condition in the guidance implementation | Check the classifier-free concatenation and the dropout ratio |
The last two rows deserve one more sentence: “guidance strength” and “diversity” are the two ends of the same knob. Classifier guidance and classifier-free guidance both amplify “the conditional score” into ; with the adherence to the condition rises and diversity falls. This trade-off is the same kind of operation as “the lower the temperature , the more exploitation; the higher, the more exploration” in reinforcement learning (Section 6.7 gives the correspondence).
5.12 Scope of Applicability
Suitable for:
- High-quality image, video, and audio generation: better than GAN across the board in coverage and stability, and currently the mainstream;
- Cases that need a likelihood interpretation or a score estimate: the objective can be derived from the ELBO, and the score can be used on its own (for example image inpainting or solving inverse problems);
- Multimodal data: per-sample regression, with no tendency to “average the modes away”;
- Cases that need conditional generation and controllable editing: guidance, inversion, inpainting, and super-resolution can all be done in the same framework;
- Cases that need to be combined with other models: latent diffusion (placing diffusion inside the latent space of a VAE) is the typical marriage of VAE and diffusion.
Not suitable for:
- Extremely low latency, single-step generation: original diffusion needs dozens to thousands of steps; distillation or flow matching must be added before it can be deployed;
- Very small models / very small datasets: the parameters and training cost of a multistep structure outweigh the benefit;
- Cases that need an exact, fast log-likelihood: the likelihood of diffusion is only a lower bound, and it must be estimated over thousands of steps;
- Discrete data (text): Gaussian noising does not suit discrete tokens and requires dedicated discrete diffusion (this route is still weaker than autoregressive models).
5.13 Relations with the Previous Three (One Table to Close)
| Question | VAE | GAN | Flow | Diffusion |
|---|---|---|---|---|
| What is learned | Encoder + decoder + prior | Generator + discriminator | Invertible transform | A score field that varies with |
| Objective | ELBO (with KL) | Minimax (implicit) | Exact log-likelihood | ELBO (a regression after rearrangement) |
| Needs a partition function? | No (there is a lower bound) | No (no density) | No (the Jacobian is computable) | No (the gradient cancels ) |
| Sampling steps | 1 | 1 | 1 | (compressible to a few) |
| Main failure mode | Posterior collapse, blur | Mode collapse, instability | Structural restrictions, equal-dimension constraint | Slow, sensitive to step count |
| Analogy with RL | Policy with latent variables + variational inference | Adversarial policy improvement (similar to a two-player game) | Invertible policy transform | Multi-step policy (diffusion policy) |
The most important information in this table is: the four families are not “four parallel options” but four different ways of “getting around” the same difficulty (the partition function / disjoint supports / structural constraints). VAE gets around it with a lower bound, GAN with an adversarial signal, flow with an invertible structure, and diffusion with multiple steps plus the score. Once the “way around” is understood, model selection is no longer a matter of memorizing conclusions.
6. Cross-Cutting Summary: Putting the Four Models in One Coordinate System
6.1 Master Table
| Dimension | VAE | GAN | Normalizing Flow | Diffusion |
|---|---|---|---|---|
| Density | Has a lower bound, not exactly computable | Implicit, not computable | Exactly computable | Has a lower bound (computable step by step) |
| Training signal | ELBO regression + KL | The adversarial signal provided by the discriminator | Exact log-likelihood | Noise regression (score matching) |
| Stability | High (but needs tuning of / free bits) | Low (needs many tricks) | High | High |
| Sampling cost | 1 forward pass | 1 forward pass | 1 inverse transform | steps (compressible to 4–50) |
| Coverage | Medium (prone to posterior collapse) | Low (prone to mode collapse) | High | High |
| Sample quality (images) | Rather low (blurry) | High but needs careful tuning | Medium | Highest |
| Structural constraints | Weak (encoder/decoder arbitrary) | Weak (generator arbitrary) | Strong (must be invertible and equal-dimensional) | Weak (network arbitrary) |
| Latent space | Yes, medium interpretability | Yes (noise), not invertible | Yes, equal-dimensional to the data | None (or borrowed from a VAE latent space) |
| Main cost | The variational gap | Manual tuning effort | Loss of expressiveness from the structural design | Sampling compute |
| Best at | Representation learning, compression, a conditional-generation backbone | High-fidelity fast generation in a specific domain (such as faces) | Density estimation, invertible editing, anomaly detection | General high-fidelity generation, conditional editing |
| Typical representatives | -VAE, VQ-VAE, NVAE | DCGAN, StyleGAN, BigGAN | RealNVP, Glow, MAF, FFJORD | DDPM, DDIM, LDM, Flow Matching |
6.2 The Six Key Divergences
Divergence 1: Do we need a computable density?
This is the most fundamental item. Wanting a density (the lower bound of VAE, the exact value of a flow) means the objective must be likelihood-based, and the metrics can only be “correct on average” measures such as bits/dim and test-set likelihood, and such metrics are insensitive to perceptual quality — a blurry “average face” may be better in likelihood than a sharp face that “does not belong to any specific person”. Not wanting a density (GAN, the implicit use of diffusion) means perceptual metrics (FID, human evaluation) can be used to select the model, at the cost of losing the strict interpretation of “how much probability the model actually assigns to the data”.
Divergence 2: Does the training signal come from “comparison” or from “regression”?
GAN learns “how to keep the discriminator from telling the difference”, and the signal comes from the comparison of two networks; VAE, flow, and diffusion all learn “how to reproduce a known target quantity” (the posterior, the inverse transform, the noise), and the signal comes from regression. This divergence directly determines stability: the gradient of a comparison objective depends on the state of the opponent, and the gradient changes as the opponent changes; the target of a regression objective is fixed, and the gradient does not disappear because “the other network got stronger”. Derivation 8 already proved that the gradient of a comparison objective can be exactly zero when the supports do not intersect. This is why the mainstream of image generation shifted from GAN to diffusion after 2021 — not because GAN’s results are poor, but because its stability cost is too high.
Divergence 3: One step or many steps?
One-step generation (VAE, GAN, flow) has the lowest latency, but it requires the network to cross a large distribution gap in one go; multistep generation (diffusion) cuts the gap into many small segments, each of which is easy to learn, at the cost of multiple forward passes at sampling time. In essence this divergence is “whether to put the difficulty into training or into sampling”: GAN puts the difficulty into training (the balance must be tuned), and diffusion puts the difficulty into sampling (many steps must be run). Which one to choose in engineering depends on whether training compute or inference compute is cheaper, and on whether latency is a hard constraint.
Divergence 4: Is trading expressiveness for structural constraints worth it?
The invertible, equal-dimensional constraint of flows lets it compute the likelihood exactly and map in both directions, but it also prevents dimensionality reduction and the use of arbitrary network structures. This is an explicit trade: expressiveness for computability. Diffusion does the opposite, trading “many steps” for “completely free network structure”. VAE trades “latent variables plus a variational approximation” for “dimensionality reduction and representation”, at the cost of a gap. Each of the three trades has its own scope, and none of them is “more advanced”.
Divergence 5: Is the approximate posterior “learned” or “specified”?
The approximate posterior of VAE must be learned, and a poor fit produces a gap; the approximate posterior of diffusion is simply the forward process, which is specified and exact, so its ELBO contains no “approximation error” term (only the term “how well the reverse network fits”). This divergence explains why the likelihood lower bound of diffusion is usually tighter and its training more stable: it replaces the hard task of “guessing the posterior” with the easy task of “computing the posterior from a formula”. The price is that one must accept a multi-step chain.
Divergence 6: Do the objective function and the evaluation metric agree?
All four families run into this contradiction:
- VAE optimizes the ELBO, but the ELBO prefers blur (because blur can cover more possibilities);
- GAN optimizes JS/Wasserstein, but the evaluation uses FID/IS, and the two are not always aligned;
- flows optimize the exact likelihood, but samples with high likelihood are not necessarily good-looking;
- diffusion optimizes (already a reweighted score matching), while the evaluation uses FID, so the same “the training objective does not match the metric” problem appears again.
None of the four achieves “whatever is optimized is what is evaluated”. The practical meaning of this divergence is: when choosing a model, fix the evaluation metric first and then work backwards to what should be optimized, rather than “train one first and look at the metric afterwards”. This point is completely isomorphic to the difficulty of “the reward design does not match the evaluation metric” in reinforcement learning.
6.3 The Six-Question Selection Decision Chain
Answer six questions in order; each step eliminates a group of candidates:
Question 1: Do we need a likelihood that is computable or lower-bounded?
- Need an exact likelihood (density estimation, compression coding, strict comparison) → Normalizing Flow;
- Need a likelihood lower bound and a latent space (representation learning, semi-supervision, a backbone for conditional generation) → VAE;
- Do not need one → go to Question 2.
Question 2: Is inference latency a hard constraint (for example it must be a single step, ms)?
- Yes → go to Question 3 (choose between GAN and flow);
- No → Diffusion (the best quality and stability; if the step count is too high, add DDIM / distillation / flow matching).
Question 3: Is the data “single-domain, high-fidelity, large in volume” (such as faces or specific product images)?
- Yes → GAN (the StyleGAN family is still hard to beat in that domain, and it is single-step);
- No (multiple domains, multimodal, open domain) → Flow or Diffusion + distillation (GAN has a high risk of mode collapse on multimodal data).
Question 4: Do we need a latent space that can be edited, interpolated, and inverted?
- Need invertibility (both directions of , exact reconstruction) → Flow;
- Need a low-dimensional semantic latent space (editing attributes, producing representations) → VAE (or latent diffusion, that is, VAE + diffusion);
- Only need “change the condition and regenerate” → Diffusion (guidance plus inversion suffices).
Question 5: Is training compute tight or sampling compute tight?
- Training compute tight, sampling allowed to be slow → Diffusion (stable training, no repeated balance tuning);
- Sampling compute tight, training allowed to be long → GAN (one forward pass, but a high tuning cost);
- Both tight → Flow (one forward pass plus stable training, at the cost of structural constraints).
Question 6: How large is the dataset?
- Very small (a few thousand images) → prefer methods with “a strong structural prior”: VAE (latent space plus prior) or Flow (the invertible structure is itself a strong regularizer), while diffusion overfits easily;
- Medium → GAN needs caution (the discriminator overfits easily), while diffusion and flow are more stable;
- Very large → Diffusion (the best scalability; LDM places diffusion in a compressed latent space to cut the cost further).
This chain is not the only correct order, but it makes the six most expensive decision points explicit. The most common mistake in practice is not “choosing the wrong model” but skipping Questions 1 and 2 and choosing directly by “which model has the lowest FID” — that amounts to letting the evaluation metric make the two business decisions “do we need a likelihood” and “is this latency acceptable” on your behalf.
6.4 The Four Most Easily Mismatched Combinations
Mismatch 1: Using VAE for high-fidelity image generation and then complaining about “blur”.
In pixel space, the ELBO of VAE is equivalent to “assuming an independent Gaussian for every pixel”, and a Gaussian assumption is inherently unfriendly to “sharp edges”: blur can cover several possibilities at once and therefore yields a higher likelihood. The fix is not to tune the network but to change the objective (a GAN loss or a perceptual loss) or to change the model (diffusion). The successes of NVAE and VQ-VAE-2 are also not “VAE got stronger” but “the likelihood objective was replaced by a hierarchical structure plus a better prior”.
Mismatch 2: Training GAN on small data, and the discriminator memorizes the training set.
The capacity of the discriminator is enough to memorize every training image, so it gives high scores to “real images” and low scores to “any generated image”, and the gradient the generator receives no longer points toward the data distribution but toward “fooling this memorizer”. The symptom is a good FID together with samples that closely resemble the training set (overfitting). Fix: reduce the discriminator’s capacity, add data augmentation (differentiable augmentation), and use the dedicated regularizers of few-shot GAN.
Mismatch 3: Using a flow for a task that “needs dimensionality reduction”.
The bijection of a flow forces the input and the output to have the same dimension, so “compress 1024 dimensions into 64” simply does not exist inside a flow. Forcing it only yields “reduce dimension first, then flow”, and the dimensionality-reduction step is then not part of the flow. If the task is essentially representation learning or compression, VAE is the right tool.
Mismatch 4: Using diffusion for interactive generation that “must be real time”.
Sampling in diffusion is serial steps, and latency grows linearly with the step count. Putting it into a real-time interaction requires DDIM (20–50 steps), distillation (4–8 steps), or flow matching (few steps), otherwise the latency is unacceptable. “Diffusion has the best quality” does not mean “diffusion can be used anywhere” — its quality advantage is bought with sampling cost.
6.5 One-Page Cheat Sheet
If only ten sentences are to be remembered:
- All four families get around the same difficulty: the partition function is intractable. VAE gets around it with a lower bound, GAN with adversarial training, flow with an invertible structure, and diffusion with the score (the gradient cancels ).
- The gap of VAE comes from “guessing the posterior”, and the gap of diffusion comes from “fitting the reverse process”; the former is hard, the latter easy, which is why diffusion is more stable.
- The root cause of GAN’s disease is that JS has zero gradient when the supports do not intersect; WGAN changing the distance and WGAN-GP / spectral normalization adding constraints are all treatments for this disease.
- Every cost of a flow comes from “it must be invertible and equal-dimensional”; its exact likelihood and bidirectional mapping are the returns of that trade.
- Every cost of diffusion comes from “it must take many steps”; its stability and coverage are the returns of that trade.
- For the parameterization choose ; for the loss use ; for the schedule prefer cosine.
- “Stochastic” is not the same as “exploration”, and “many steps” is not the same as “better”; the former needs shaping through selection pressure, and the latter needs an actual trade-off between step count and quality.
- The objective function and the evaluation metric never agree; fix the metric first, then choose the objective.
- The first question of model selection is “do we need a likelihood”, and the second is “is the latency acceptable”, not “which FID is lower”.
- The strongest combinations are usually hybrids: VAE + diffusion (latent diffusion), flow + diffusion (flow matching), GAN + likelihood (adversarial plus reconstruction).
6.6 Five Universal Principles
- Identify the structure of the problem first, then choose the model. This is consistent with the “no free lunch” of Section 1.4: every model carries a prior, and when the prior is mismatched no amount of hyperparameter tuning can save it.
- Treat “computability” as a first-class citizen. Whether is needed, whether is needed, and whether is needed — the answers to these three questions determine the candidate set, not the other way around.
- Separate “training difficulty” from “sampling difficulty”. The two can be transferred into each other (going from GAN to diffusion is exactly one such transfer), so model selection has to count the compute and the latency of both sides.
- Do not optimize outside the metric. If the final evaluation is the human eye, do not look only at bits/dim; if the final evaluation is the compression rate, do not look only at FID. The metric determines the objective, and the objective determines the model.
- Hybrid models are the norm, not the exception. Modern systems are almost all hybrids: VAE supplies the latent space, diffusion supplies generation, flow supplies exact transforms, and GAN supplies the discriminator signal (or an adversarial term for distillation). Treating the four families as “four building blocks” rather than “four opponents” is the key to understanding the current landscape of generative models.
6.7 The Concept Correspondence with Reinforcement Learning
| Reinforcement learning concept | VAE | GAN | Flow | Diffusion |
|---|---|---|---|---|
| Policy | Encoder | Generator | Inverse transform | Reverse chain |
| Environment dynamics | Prior | Data distribution (implicit) | Base distribution | Forward chain |
| Reward / objective | ELBO | Discriminator score | Log-likelihood | Denoising loss (negative score-matching error) |
| Critic / value function | — | Discriminator | — | The score network itself (doubling as a “direction critic”) |
| Exploration | Posterior sampling | Noise input | Base-distribution sampling | Initial noise + per-step randomness |
| Entropy regularization | The β term (KL to the prior) | Entropy term (rarely used) | — | Noise injected at each step |
| Policy collapse | Posterior collapse | Mode collapse | — (bijections do not collapse) | Good coverage, rarely collapses |
| Multi-step decision making | Single step (one encode–decode) | Single step | Single step | Many steps (naturally sequential) |
| Temperature | Prior temperature / β | Sampling temperature | Base-distribution temperature | Guidance strength , sampling stochasticity |
| Training-stability problem | Posterior collapse | Game imbalance | Structural restriction | Sensitivity to step count and schedule |
The most valuable row of this table is the “critic” row: the discriminator of GAN and the critic of Actor-Critic are doing the same thing — scoring “the result currently generated” and using that score to improve the generator. The difference is that the critic of GAN is an “opponent” (it wants to defeat the generator), while the critic of Actor-Critic is a “teacher” (it wants to evaluate the policy accurately). This difference is exactly the root of GAN’s instability: when the critic has an incentive to give a wrong score, what the policy learns is the wrong direction. Diffusion has no critic at all; it uses a fixed target quantity (the noise) as the teacher, and therefore has no “the teacher deliberately teaches it wrong” problem.
References
Variational Autoencoders
- Kingma, D. P., & Welling, M. (2013). Auto-Encoding Variational Bayes. arXiv:1312.6114.
- Rezende, D. J., Mohamed, S., & Wierstra, D. (2014). Stochastic Backpropagation and Approximate Inference in Deep Generative Models. ICML.
- Burda, Y., Grosse, R., & Salakhutdinov, R. (2015). Importance Weighted Autoencoders. arXiv:1509.00519.
- Bowman, S. R., et al. (2016). Generating Sentences from a Continuous Space. CoNLL.
- Higgins, I., et al. (2017). β-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework. ICLR.
- Burgess, C. P., et al. (2018). Understanding Disentangling in β-VAE. arXiv:1804.03599.
- van den Oord, A., Vinyals, O., & Kavukcuoglu, K. (2017). Neural Discrete Representation Learning. NeurIPS. (VQ-VAE)
- Razavi, A., van den Oord, A., & Vinyals, O. (2019). Generating Diverse High-Fidelity Images with VQ-VAE-2. NeurIPS.
- Alemi, A., Poole, B., et al. (2018). Fixup Initialization / Fixing a Broken ELBO. ICML. (a systematic analysis of free bits)
- Tolstikhin, I., et al. (2018). Wasserstein Auto-Encoders. ICLR. (related discussion of the prior hole problem)
Generative Adversarial Networks
- Goodfellow, I., et al. (2014). Generative Adversarial Nets. NeurIPS.
- Radford, A., Metz, L., & Chintala, S. (2016). Unsupervised Representation Learning with Deep Convolutional GANs. ICLR.
- Arjovsky, M., Chintala, S., & Bottou, L. (2017). Wasserstein GAN. ICML.
- Gulrajani, I., et al. (2017). Improved Training of Wasserstein GANs. NeurIPS. (WGAN-GP)
- Miyato, T., et al. (2018). Spectral Normalization for Generative Adversarial Networks. ICLR.
- Mirza, M., & Osindero, S. (2014). Conditional Generative Adversarial Nets. arXiv:1411.1784.
- Karras, T., Laine, S., & Aila, T. (2019). A Style-Based Generator Architecture for GANs. CVPR. (StyleGAN)
- Nowozin, S., Cseke, B., & Tomioka, R. (2016). f-GAN: Training GANs with Variational Divergence Minimization. NeurIPS.
- Salimans, T., et al. (2016). Improved Techniques for Training GANs. NeurIPS.
Normalizing Flows
- Dinh, L., Sohl-Dickstein, J., & Bengio, S. (2017). Density Estimation using Real NVP. ICLR.
- Kingma, D. P., & Dhariwal, P. (2018). Glow: Generative Flow with Invertible Convolutions. NeurIPS.
- Papamakarios, G., Pavlakou, T., & Murray, I. (2017). Masked Autoregressive Flow for Density Estimation. NeurIPS.
- Kingma, D. P., et al. (2016). Improving Variational Inference with Inverse Autoregressive Flow. NeurIPS.
- Rezende, D. J., & Mohamed, S. (2015). Variational Inference with Normalizing Flows. ICML.
- Chen, R. T. Q., et al. (2018). Neural Ordinary Differential Equations. NeurIPS.
- Grathwohl, W., et al. (2019). FFJORD: Free-form Continuous Dynamics for Scalable Reversible Generative Models. ICLR.
- Papamakarios, G., et al. (2021). Normalizing Flows for Probabilistic Modeling and Inference. JMLR. (review)
Diffusion Models and Score Matching
- Sohl-Dickstein, J., et al. (2015). Deep Unsupervised Learning using Nonequilibrium Thermodynamics. ICML.
- Vincent, P. (2011). A Connection Between Score Matching and Denoising Autoencoders. Neural Computation.
- Hyvärinen, A. (2005). Estimation of Non-Normalized Statistical Models by Score Matching. JMLR.
- Song, Y., & Ermon, S. (2019). Generative Modeling by Estimating Gradients of the Data Distribution. NeurIPS. (NCSN)
- Ho, J., Jain, A., & Abbeel, P. (2020). Denoising Diffusion Probabilistic Models. NeurIPS. (DDPM)
- Song, J., Meng, C., & Ermon, S. (2021). Denoising Diffusion Implicit Models. ICLR. (DDIM)
- Song, Y., et al. (2021). Score-Based Generative Modeling through Stochastic Differential Equations. ICLR.
- Nichol, A., & Dhariwal, P. (2021). Improved Denoising Diffusion Probabilistic Models. ICML. (cosine schedule)
- Dhariwal, P., & Nichol, A. (2021). Diffusion Models Beat GANs on Image Synthesis. NeurIPS.
- Ho, J., & Salimans, T. (2022). Classifier-Free Diffusion Guidance. arXiv:2207.12598.
- Rombach, R., et al. (2022). High-Resolution Image Synthesis with Latent Diffusion Models. CVPR.
- Lipman, Y., et al. (2023). Flow Matching for Generative Modeling. ICLR.
- Salimans, T., & Ho, J. (2022). Progressive Distillation for Fast Sampling of Diffusion Models. ICLR.
Evaluation Metrics and Cross-Cutting References
- Heusel, M., et al. (2017). GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium. NeurIPS. (FID)
- Salimans, T., et al. (2016). Improved Techniques for Training GANs. NeurIPS. (IS)
- Kynkäänniemi, T., et al. (2019). Improved Precision and Recall Metric for Assessing Generative Models. NeurIPS.
- Theis, L., et al. (2016). A Note on the Evaluation of Generative Models. ICLR.
- Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press. (Chapter 20, Generative Models)
- Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. (Chapter 10, Variational Inference; Chapter 12, Continuous Latent Variables)
- Murphy, K. P. (2022). Probabilistic Machine Learning: Advanced Topics. MIT Press. (the systematic chapters on diffusion and score matching)
Appendix: Abbreviation Quick-Reference
| Abbreviation | Full name in English | Explanation |
|---|---|---|
| AE | Autoencoder | A neural network that encodes into a latent space and then decodes to reconstruct the input |
| bpd | bits per dimension | Bits per dimension: a density-estimation metric that converts the log-likelihood into bits per dimension |
| CFG | Classifier-Free Guidance | Classifier-free guidance: train a conditional and an unconditional model together and amplify the conditional signal by their difference |
| CNF | Continuous Normalizing Flow | Continuous normalizing flow: a continuous invertible transform defined by an ordinary differential equation |
| DDIM | Denoising Diffusion Implicit Model | Denoising diffusion implicit model: a deterministic diffusion sampling method that can skip steps |
| DDPM | Denoising Diffusion Probabilistic Model | Denoising diffusion probabilistic model: the standard multi-step noise-addition/denoising diffusion model |
| ELBO | Evidence Lower Bound | A computable lower bound on the log-likelihood |
| FID | Fréchet Inception Distance | A common metric that measures generation quality by the distance between feature distributions |
| GAN | Generative Adversarial Network | An implicit generative model in which a generator and a discriminator are trained adversarially |
| GP | Gradient Penalty | A regularizer that constrains the gradient norm of the critic to be close to one |
| IAF | Inverse Autoregressive Flow | A normalizing flow defined by an autoregressive structure |
| IS | Inception Score | A metric that measures sample quality and diversity from classifier outputs |
| IWAE | Importance Weighted Autoencoder | An autoencoder that obtains a tighter ELBO by multiple sampling |
| JS | Jensen-Shannon divergence | A symmetric combination of the KL divergences between two distributions and their average distribution |
| KL | Kullback-Leibler divergence | An asymmetric measure of the difference between two probability distributions |
| LDM | Latent Diffusion Model | A model that performs diffusion in a compressed latent space |
| LU | Lower-Upper decomposition | A decomposition that writes a matrix as the product of two triangular matrices |
| MAF | Masked Autoregressive Flow | A normalizing flow that uses masks to guarantee an autoregressive structure |
| MCMC | Markov Chain Monte Carlo | Sampling from a target distribution by means of a Markov chain |
| NCSN | Noise Conditional Score Network | A model that trains a score network across multiple noise levels |
| NF | Normalizing Flow | An exact density model built from a chain of invertible transforms |
| ODE | Ordinary Differential Equation | An equation containing derivatives with respect to a single independent variable |
| PF-ODE | Probability Flow ODE | A deterministic equation that shares its marginals with the diffusion SDE |
| RL | Reinforcement Learning | A method in which an agent interacts with an environment and improves its decisions from rewards |
| SDE | Stochastic Differential Equation | A differential equation containing a Brownian motion term |
| SNR | Signal-to-Noise Ratio | The ratio of signal power to noise power |
| VAE | Variational Autoencoder | A latent-variable generative model trained with variational inference |
| VQ-VAE | Vector Quantized VAE | A VAE that replaces the continuous latent variable with a discrete codebook |
| WGAN | Wasserstein GAN | A GAN trained with the Wasserstein distance |
| WGAN-GP | WGAN with Gradient Penalty | A WGAN that enforces the 1-Lipschitz constraint through a gradient penalty |
About the sources and language of this note
This note is an original synthesis written in Chinese and then translated into English; it does not translate any single paper sentence by sentence. Instead, it reorganizes the standard derivations found in the original papers, reviews, and textbooks of the four generative model families into a self-checkable study note. All formulas are rewritten in the unified notation of this note, and every step of every derivation states the identity or assumption it uses (Bayes’ rule, Jensen’s inequality, the Gaussian integral, the change of variables, the Kantorovich duality, etc.), so that the reader can check it against the source.
Division of labor with the site’s Diffusion Model Notes: that note covers the full engineering detail of diffusion (network architecture, guidance, latent space, flow matching, distillation, evaluation, and the connection to reinforcement learning), while this note keeps only the four main lines needed for a cross-model comparison (the closed-form forward marginal, the rearrangement of the ELBO, the equivalence of score and denoising, and deterministic DDIM sampling). When deeper diffusion detail is needed, consult the two notes together.
If you find inconsistent notation or a skipped step in a derivation, please point it out; the collapsible structure of this note exists precisely so that such problems can be checked block by block.
Comments
Loading comments…
Want to leave a note? Sign in first — comments are open to every signed-in reader.