Contents

Notes on the Four Major AIGC Generative Models: Principles, Derivations, and Pseudocode for VAE, GAN, Normalizing Flow, and Diffusion Models

Generative Models
#Generative Models#AIGC#Variational Autoencoder#Generative Adversarial Network#Normalizing Flow#Diffusion Model#Variational Inference#Score Matching

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:

ModelOne-sentence answer to “how is pθ(x)p_\theta(x) represented”
Variational Autoencoder (VAE)Introduce a latent variable zz, 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 FlowCarry a simple distribution onto a complex one with a chain of invertible transforms, with determinants guaranteeing that the likelihood is exactly computable
Diffusion ModelSplit 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

SymbolMeaning
xxa data sample (an image, audio, a sequence of text tokens, etc.), of dimension DD
zzlatent variable, of dimension dd, usually d≪Dd \ll D or d∼Dd \sim D
pdata(x)p_{\text{data}}(x)the true data distribution, accessible only indirectly through training-set samples
pθ(x)p_\theta(x)the model distribution defined by parameters θ\theta
p(z)p(z)the prior distribution of the latent variable, usually N(0,I)\mathcal{N}(0,I)
qϕ(z∣x)q_\phi(z\mid x)the variational posterior (encoder), defined by parameters ϕ\phi
pθ(x∣z)p_\theta(x\mid z)the generative distribution (decoder / likelihood)
D(x)D(x)discriminator output, interpreted as the probability that xx comes from data
Gθ(z)G_\theta(z)generator, mapping noise zz to a sample
pgp_gthe sample distribution induced by the generator
fθf_\thetainvertible transform (flow model), x=fθ(z)x=f_\theta(z)
JfJ_fJacobian matrix, with entries ∂fi/∂zj\partial f_i/\partial z_j
xtx_tthe noisy sample at step tt of the diffusion process, t=0t=0 being clean data and t=Tt=T pure noise
βt\beta_tthe per-step noise variance of the forward diffusion process
αt, αˉt\alpha_t,\ \bar\alpha_tαt=1−βt\alpha_t=1-\beta_t; αˉt=∏s=1tαs\bar\alpha_t=\prod_{s=1}^{t}\alpha_s
ε\varepsilonstandard Gaussian noise, ε∼N(0,I)\varepsilon\sim\mathcal{N}(0,I)
KL(p∥q)\mathrm{KL}(p\|q)Kullback-Leibler divergence (KL divergence), Ep[log⁡(p/q)]\mathbb{E}_p[\log(p/q)]
JSD(p∥q)\mathrm{JSD}(p\|q)Jensen-Shannon divergence (Jensen-Shannon divergence), the JS divergence
W1(p,q)\mathcal{W}_1(p,q)first-order Wasserstein distance (Earth Mover’s Distance)
ELBO\mathrm{ELBO}Evidence Lower Bound, a lower bound on the log-likelihood
FID\mathrm{FID}Fréchet Inception Distance (a common metric for generation quality and diversity)
IS\mathrm{IS}Inception Score
NFE\mathrm{NFE}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 ϕ,θ\phi,\theta for encoder/decoder, GAN uses θ\theta for the generator and ϕ\phi for the discriminator, flow models use θ\theta for the whole transform, diffusion uses θ\theta for the noise network). This article unifies everything as in the table above: every “generative-side” parameter is written θ\theta, every “inference-side / opponent-side” parameter is written ϕ\phi. 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:

NumberLocationDerivation content
Derivation 11.2Why “computing the density in one step” is infeasible in general (the partition function is intractable)
Derivation 21.3The relations among the three distances: size and gradient behavior of KL, JS, and Wasserstein
Derivation 32.3The complete decomposition of the evidence lower bound (starting from log⁡pθ(x)\log p_\theta(x), including the second way of writing the gap)
Derivation 42.4The closed form of the KL divergence between two diagonal Gaussians, and why it decomposes dimension by dimension
Derivation 52.5The validity of the reparameterization trick: why gradients can pass through sampling
Derivation 63.3The closed form of the optimal discriminator D⋆D^{\star}, and why the objective at the optimum equals 2 JSD−2log⁡22\,\mathrm{JSD}-2\log 2
Derivation 73.4The gradient scale of the non-saturating loss, and why the original loss saturates
Derivation 83.5When the supports of the distributions do not overlap, the JS divergence is constant and the gradient is zero
Derivation 93.6The Kantorovich-Rubinstein duality of the Wasserstein distance (including the origin of the 1-Lipschitz constraint)
Derivation 104.2The change-of-variables formula: from one-dimensional density transformation to the high-dimensional Jacobian determinant
Derivation 114.4The Jacobian of an affine coupling layer is triangular, $\log\left
Derivation 124.5The $\log\left
Derivation 134.6The instantaneous change of variables for continuous flows and the Hutchinson trace estimate
Derivation 145.3The superposition-of-Gaussians proof of the closed-form forward marginal distribution q(xt∣x0)q(x_t\mid x_0)
Derivation 155.4The term-by-term rearrangement of the evidence lower bound, and the closed form of the true posterior q(xt−1∣xt,x0)q(x_{t-1}\mid x_t,x_0)
Derivation 165.6The simplified loss: from per-term KL to noise regression, and where the coefficients went
Derivation 172.6Why the importance-weighted bound (IWAE) is tighter than the evidence lower bound, and its limit as K→∞K\to\infty
Derivation 182.6The Lagrangian interpretation of β\beta-VAE and free bits: why both are merely penalty formulations of a KL constraint
Derivation 193.3f-GAN: the variational lower bound of an arbitrary f-divergence, the Fenchel conjugate, and the optimal discriminator T⋆=f′(p/q)T^{\star}=f'(p/q)
Derivation 203.6Why 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 214.4The reciprocal determinants of the coupling-layer inverse transform, and the lower-triangular Jacobian of MAF/IAF
Derivation 224.7Why dequantization contributes +log⁡2256+\log_2 256 to bits per dimension, and why skipping the noise is a cheating solution
Derivation 235.6The coefficient γt\gamma_t dropped by the simplified loss and the signal-to-noise-ratio weighting (including Min-SNR)
Derivation 245.7Where the score in classifier-free guidance comes from, why γ>1\gamma>1 extrapolates, and what its geometric meaning is
Derivation 251.2The 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 261.4The closed form of FID: the W22\mathcal{W}_2^2 distance between two Gaussians in feature space, including the matrix square-root term
Derivation 272.2When the decoder is Gaussian, why the reconstruction term is the mean squared error, and how σ\sigma and β\beta become the same knob
Derivation 282.6The quantitative condition for posterior collapse: βDKL>Δrec\beta D_{\mathrm{KL}}>\Delta_{\mathrm{rec}} and the effective number of latents
Derivation 293.7The 1-Lipschitz upper bound ∏lσmax⁡(Wl)\prod_l\sigma_{\max}(W_l) of spectral normalization and the convergence rate of power iteration
Derivation 303.8The minimal counterexample for mode collapse: the forward KL diverges, the reverse KL is log⁡2\log 2, and the JS divergence is always log⁡2\log 2
Derivation 315.5The conversion among the four parameterizations (x0,ε,μ,vx_0,\varepsilon,\mu,v): vv is a 45° rotation and its error scale is independent of tt
Derivation 325.7Fokker-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 {x(i)}i=1N\{x^{(i)}\}_{i=1}^{N} whose samples are drawn independently and identically from some unknown distribution pdatap_{\text{data}}, generative modeling has two jobs:

  1. Estimate the density: construct pθ(x)p_\theta(x) so that it takes high values near the data and low values elsewhere;
  2. Sample: draw new samples from pθp_\theta 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:

max⁡θ Epdata[log⁡pθ(x)]\max_\theta\ \mathbb{E}_{p_{\text{data}}}\left[\log p_\theta(x)\right]

It is equivalent to minimizing KL(pdata∥pθ)\mathrm{KL}\left(p_{\text{data}}\|p_\theta\right) (up to an entropy term independent of θ\theta). 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 pdata(x)>0p_{\text{data}}(x)>0 while pθ(x)≈0p_\theta(x)\approx0, 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:

RouteDensityTraining signalSamplingRepresentativeWeakness in one sentence
Variational / latent variableOnly a lower boundReconstruction error + KL regularizationOne decoding passVAEThe bound has a gap, the posterior approximation is biased, samples are rather blurry
AdversarialNot computed at allThe discriminator’s classification signalOne forward passGANUnstable training, mode collapse, no likelihood
Invertible transformExactly computableExact log-likelihoodOne inverse transformNormalizing Flow, RealNVP, GlowStrong structural constraints (must be invertible and dimension-preserving), many parameters
Diffusion / scoreNot computed directly, but the score is estimableDenoising regression (predicting noise or score)Multi-step iterationDDPM, DDIM, Flow MatchingSlow 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, p(x)=∏ip(xi∣x<i)p(x)=\prod_i p(x_i\mid x_{<i}); 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

pθ(x)=exp⁡(−Eθ(x))Zθ,Zθ=∫exp⁡(−Eθ(x))dxp_\theta(x)=\frac{\exp\left(-E_\theta(x)\right)}{Z_\theta},\qquad Z_\theta=\int\exp\left(-E_\theta(x)\right)\mathrm{d}x

where EθE_\theta is the energy function and ZθZ_\theta is the partition function. EθE_\theta can be computed arbitrarily easily by a neural network, but ZθZ_\theta is an integral over the whole DD-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 MM points are taken per dimension, the total number of points is MDM^D, and an image with D=256×256×3D=256\times256\times3 is simply impossible. If Monte Carlo estimation is used, an unbiased estimate requires sampling from pθp_\theta — and “sampling from pθp_\theta” 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 ∇xlog⁡pθ=∇xlog⁡exp⁡(−Eθ)=−∇xEθ\nabla_x\log p_\theta=\nabla_x\log\exp(-E_\theta)=-\nabla_x E_\theta does not depend on ZθZ_\theta — 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 log⁡∣det⁡J∣\log\left|\det J\right| in the change-of-variables formula into an O(D)O(D) sum (flow models). VAE takes the fourth route: instead of computing log⁡pθ(x)\log p_\theta(x), 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

max⁡θ max⁡ϕ L(θ,ϕ)=max⁡θ max⁡ϕ Eqϕ(z∣x)[log⁡pθ(x,z)qϕ(z∣x)]\max_{\theta}\ \max_{\phi}\ \mathcal{L}(\theta,\phi) =\max_{\theta}\ \max_{\phi}\ \mathbb{E}_{q_\phi(z|x)}\left[\log\frac{p_\theta(x,z)}{q_\phi(z|x)}\right]

The two maxima can be exchanged, because for every θ\theta the inner maximization over ϕ\phi 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

min⁡G max⁡D V(D,G)=min⁡G max⁡D (Epdata[log⁡D(x)]+Epg[log⁡(1−D(x))])\min_{G}\ \max_{D}\ V(D,G) =\min_{G}\ \max_{D}\ \left(\mathbb{E}_{p_{\text{data}}}\left[\log D(x)\right]+\mathbb{E}_{p_g}\left[\log\left(1-D(x)\right)\right]\right)

Here min⁡\min and max⁡\max generally cannot be exchanged.

Step 2: the weak duality inequality. For any G,DG,D we have V(D,G)≥min⁡G′V(D,G′)V(D,G)\ge\min_{G'}V(D,G'); taking the maximum over DD on both sides gives

max⁡Dmin⁡GV(D,G) ≤ min⁡Gmax⁡DV(D,G)\max_{D}\min_{G}V(D,G)\ \le\ \min_{G}\max_{D}V(D,G)

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 VV to be convex in one variable and concave in the other; VV is neither convex nor concave in GG (because pgp_g passes through a neural network), so equality generally fails.

Step 3: why alternating gradients just go around in circles. Take the bilinear toy objective V(x,y)=xyV(x,y)=xy, 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

x˙=∂yV=y,y˙=−∂xV=−x\dot x=\partial_y V=y,\qquad \dot y=-\partial_x V=-x

Along its solutions ddt(x2+y2)=2xx˙+2yy˙=2xy−2xy=0\frac{\mathrm{d}}{\mathrm{d}t}(x^2+y^2)=2x\dot x+2y\dot y=2xy-2xy=0, 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 L\mathcal{L} over ϕ\phi pushes in the same direction; there is no “one side wins, the other loses”. Its gradient is the variance-reduced policy-gradient form

∇ϕL=Eqϕ[∇ϕlog⁡qϕ(z∣x)(log⁡pθ(x,z)qϕ(z∣x)−L)]\nabla_\phi \mathcal{L}=\mathbb{E}_{q_\phi}\left[\nabla_\phi\log q_\phi(z|x)\left(\log\frac{p_\theta(x,z)}{q_\phi(z|x)}-\mathcal{L}\right)\right]

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 min⁡\min / max⁡\max; 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 pgp_g toward pdatap_{\text{data}} under some distribution distance. Which distance is chosen determines the nature of the training signal.

KL(p∥q)=Ep[log⁡pq],JSD(p∥q)=12KL(p∥p+q2)+12KL(q∥p+q2)\mathrm{KL}\left(p\|q\right)=\mathbb{E}_{p}\left[\log\frac{p}{q}\right],\qquad \mathrm{JSD}\left(p\|q\right)=\frac{1}{2}\mathrm{KL}\left(p\|\frac{p+q}{2}\right)+\frac{1}{2}\mathrm{KL}\left(q\|\frac{p+q}{2}\right) W1(p,q)=inf⁡γ∈Π(p,q)E(x,y)∼γ[∥x−y∥]\mathcal{W}_1(p,q)=\inf_{\gamma\in\Pi(p,q)}\mathbb{E}_{(x,y)\sim\gamma}\left[\left\|x-y\right\|\right]

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 q=0q=0 while p>0p>0, it is infinite);
  • JS saturates at the constant log⁡2\log 2 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 m=(p+q)/2m=(p+q)/2, we get

JSD(p∥q)=12Ep[log⁡pm]+12Eq[log⁡qm]\mathrm{JSD}(p\|q)=\frac{1}{2}\mathbb{E}_p\left[\log\frac{p}{m}\right]+\frac{1}{2}\mathbb{E}_q\left[\log\frac{q}{m}\right]

Both terms are non-negative (because the combination of log⁡\log and expectation is exactly the definition of KL), and both vanish when p=qp=q, so JSD∈[0,log⁡2]\mathrm{JSD}\in[0,\log2]. The upper bound log⁡2\log2 is attained when the supports do not intersect: on the support of pp we then have m=p/2m=p/2, making the first term 12log⁡2\frac{1}{2}\log2; on the support of qq we have m=q/2m=q/2, making the second term also 12log⁡2\frac{1}{2}\log2, for a total of log⁡2\log2.

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

JSD(p∥q)=12KL(p∥m)+12KL(q∥m)\mathrm{JSD}(p\|q)=\frac{1}{2}\mathrm{KL}\left(p\|m\right)+\frac{1}{2}\mathrm{KL}\left(q\|m\right)

Expand the first term: Ep[log⁡p]−Ep[log⁡m]\mathbb{E}_p[\log p]-\mathbb{E}_p[\log m]. Note that Ep[log⁡m]\mathbb{E}_p[\log m] requires evaluating mm on the support of pp, 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”. Π(p,q)\Pi(p,q) is the set of all joint distributions (couplings) with marginals pp and qq; W1\mathcal{W}_1 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, W1≤TV≤KL\mathcal{W}_1\le\mathrm{TV}\le\sqrt{\mathrm{KL}} and JSD≤log⁡2\mathrm{JSD}\le\log2 hold (where TV\mathrm{TV} 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 pgp_g be a degenerate distribution taking a value at a single point, and let pdatap_{\text{data}} be δ\delta away from it. Then the gradient of JSD=log⁡2\mathrm{JSD}=\log2 with respect to the parameter θ\theta is 00 — the discriminator is already perfect, and the generator receives no directional information; whereas W1=δ\mathcal{W}_1=\delta, 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 ℓ2\ell_2 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:

MetricBased onExplanation
Log-likelihood / bits per dimension (bpd)exact or lower-bound densitysuitable 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 imagesmeasures “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 spacethe common primary metric; sensitive to missing modes, sensitive to sample count
Precision-recallsupport overlap in feature spacereports “quality” and “coverage” separately, more interpretable than a single FID

The closed form of FID:

FID=∥μr−μg∥2+tr⁡(Σr+Σg−2(Σr1/2ΣgΣr1/2)1/2)\mathrm{FID}=\left\|\mu_r-\mu_g\right\|^2+\operatorname{tr}\left(\Sigma_r+\Sigma_g-2\left(\Sigma_r^{1/2}\Sigma_g\Sigma_r^{1/2}\right)^{1/2}\right)

where μr,Σr\mu_r,\Sigma_r are the Gaussian moments of the real-image features and μg,Σg\mu_g,\Sigma_g 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 N(μ1,σ12)\mathcal{N}(\mu_1,\sigma_1^2) and N(μ2,σ22)\mathcal{N}(\mu_2,\sigma_2^2) is

W22=(μ1−μ2)2+(σ1−σ2)2\mathcal{W}_2^2=(\mu_1-\mu_2)^2+(\sigma_1-\sigma_2)^2

The idea of the derivation: in one dimension the optimal transport map is monotone, namely T(x)=μ2+σ2σ1(x−μ1)T(x)=\mu_2+\frac{\sigma_2}{\sigma_1}(x-\mu_1); substituting it into Ex∼N1∣x−T(x)∣2\mathbb{E}_{x\sim\mathcal{N}_1}|x-T(x)|^2 yields the mean difference and the standard-deviation difference as the two terms.

Step 2: the multivariate generalization. With covariances Σ1,Σ2\Sigma_1,\Sigma_2,

W22(N1,N2)=∣μ1−μ2∣2+tr(Σ1+Σ2−2(Σ11/2Σ2Σ11/2)1/2)\mathcal{W}_2^2\left(\mathcal{N}_1,\mathcal{N}_2\right)=|\mu_1-\mu_2|^2+\mathrm{tr}\left(\Sigma_1+\Sigma_2-2\left(\Sigma_1^{1/2}\Sigma_2\Sigma_1^{1/2}\right)^{1/2}\right)

The optimal transport map is T(x)=μ2+A(x−μ1)T(x)=\mu_2+A(x-\mu_1) with

A=Σ1−1/2(Σ11/2Σ2Σ11/2)1/2Σ1−1/2A=\Sigma_1^{-1/2}\left(\Sigma_1^{1/2}\Sigma_2\Sigma_1^{1/2}\right)^{1/2}\Sigma_1^{-1/2}

Expanding E∣x−T(x)∣2\mathbb{E}|x-T(x)|^2, the cross terms tr(Σ1A)\mathrm{tr}(\Sigma_1 A) and tr(Σ2A⊤)\mathrm{tr}(\Sigma_2 A^\top) 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 SS with S⊤Σ1S=IS^\top\Sigma_1 S=I and S⊤Σ2S=ΛS^\top\Sigma_2 S=\Lambda.

Step 3: FID is exactly this. FID takes the second-to-last layer features ϕ(x)\phi(x) of an Inception network, estimates means μr,μg\mu_r,\mu_g and covariances Σr,Σg\Sigma_r,\Sigma_g from real and generated samples respectively, and then computes

FID=∣μr−μg∣2+tr(Σr+Σg−2(Σr1/2ΣgΣr1/2)1/2)\mathrm{FID}=|\mu_r-\mu_g|^2+\mathrm{tr}\left(\Sigma_r+\Sigma_g-2\left(\Sigma_r^{1/2}\Sigma_g\Sigma_r^{1/2}\right)^{1/2}\right)

In other words, FID is “the W22\mathcal{W}_2^2 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 conceptCounterpart in a generative model
Policy π(a∣s)\pi(a\mid s)Generator Gθ(z)G_\theta(z), decoder pθ(x∣z)p_\theta(x\mid z), reverse process pθ(xt−1∣xt)p_\theta(x_{t-1}\mid x_t)
Environment transitionForward noising process q(xt∣xt−1)q(x_t\mid x_{t-1}) (fixed and known), true data distribution pdatap_{\text{data}}
Trajectory / episodeOne sampling trajectory: z→xz\to x in one step, or xT→⋯→x0x_T\to\cdots\to x_0 in many steps
Reward signalDiscriminator output, reconstruction error, log-likelihood, denoising residual
Value function / criticThe discriminator (GAN), the encoder (the VAE’s approximate posterior), the score implicit in the noise-prediction network
Policy collapseMode collapse
Entropy regularizationThe VAE’s KL term, the diffusion noise schedule, the GAN’s diversity metric
On-policy / off-policyFlow 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:

  1. 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.
  2. 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

DimensionVAEGANNormalizing FlowDiffusion
Densitylower boundnoneexactlower bound (but the score is exactly computable)
Latent spaceyes, and continuousyes (noise), no structural constraintyes, of the same dimension as the data and invertibleyes (noisy samples at each noise level)
Sampling cost1 decoding pass1 forward pass1 inverse transformTT passes (tens to thousands)
Training stabilityhighlowhighhigh
Mode coveragegood (forward KL)poor (prone to collapse)goodgood
Sample sharpnessrather low (rather blurry)highmediumhigh
Main costgap in the posterior approximationtuning, stabilitystructural constraints, parameter countslow 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 xx into zz with an encoder, then restores zz into xx 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 zz; 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 zz 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:

  1. Encoder (inference network) qϕ(z∣x)q_\phi(z\mid x), usually taken as a diagonal Gaussian N(μϕ(x), diag⁡(σϕ2(x)))\mathcal{N}\left(\mu_\phi(x),\ \operatorname{diag}\left(\sigma_\phi^2(x)\right)\right);
  2. Decoder (generative network) pθ(x∣z)p_\theta(x\mid z), usually taken as a Gaussian N(μθ(z), σ2I)\mathcal{N}\left(\mu_\theta(z),\ \sigma^2 I\right) or a Bernoulli;
  3. Prior p(z)=N(0,I)p(z)=\mathcal{N}(0,I).

2.2 Principles and Formulas

The objective VAE optimizes is the Evidence Lower Bound (ELBO):

L(θ,ϕ;x)=Eqϕ(z∣x)[log⁡pθ(x∣z)]−KL(qϕ(z∣x)∥p(z))\mathcal{L}(\theta,\phi;x)=\mathbb{E}_{q_\phi(z\mid x)}\left[\log p_\theta(x\mid z)\right]-\mathrm{KL}\left(q_\phi(z\mid x)\|p(z)\right)

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 qϕq_\phi to place zz where “the decoder can restore xx”;
  • The second term, the regularization term: makes the encoded distribution close to the prior. It encourages qϕq_\phi 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 qϕq_\phi as small as possible (pinning zz to a single point, preserving information faithfully), whereas the regularization term wants qϕq_\phi to equal N(0,I)\mathcal{N}(0,I) as closely as possible (variance 1, mean 0). The ELBO is the equilibrium point of these two forces, and β\beta 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 [0,1][0,1] or [−1,1][-1,1]), it is standard to set

pθ(x∣z)=N(x^θ(z), σ2I)p_\theta(x|z)=\mathcal{N}\left(\hat x_\theta(z),\ \sigma^2 I\right)

Step 2: take the negative log. The Gaussian log density is −12σ2∣x−x^∣2−D2log⁡(2πσ2)-\frac{1}{2\sigma^2}|x-\hat x|^2-\frac{D}{2}\log(2\pi\sigma^2), hence

−log⁡pθ(x∣z)=∣x−x^θ(z)∣22σ2+D2log⁡(2πσ2)-\log p_\theta(x|z)=\frac{|x-\hat x_\theta(z)|^2}{2\sigma^2}+\frac{D}{2}\log\left(2\pi\sigma^2\right)

The second term depends on neither xx nor zz and is a constant during optimization. Therefore the reconstruction term is the mean squared error with coefficient 1/(2σ2)1/(2\sigma^2): using the mean squared error in a VAE is not a design choice but a direct consequence of a Gaussian likelihood.

Step 3: σ\sigma and β\beta are the same knob. What the VAE actually optimizes is

Lβ=Eqϕ[−log⁡pθ(x∣z)]+β DKL(qϕ(z∣x) ∥ p(z))\mathcal{L}_\beta=\mathbb{E}_{q_\phi}\left[-\log p_\theta(x|z)\right]+\beta\,D_{\mathrm{KL}}\left(q_\phi(z|x)\,\|\,p(z)\right)

Multiply the whole expression by the positive constant 2σ22\sigma^2 (this does not change the minimizer):

2σ2Lβ=E[∣x−x^∣2]+2σ2β DKL+const2\sigma^2\mathcal{L}_\beta=\mathbb{E}\left[|x-\hat x|^2\right]+2\sigma^2\beta\,D_{\mathrm{KL}}+\text{const}

So “tuning β\beta” and “tuning the assumed observation-noise standard deviation σ\sigma” are the same operation: a large β\beta is equivalent to believing the data are noisy, hence trusting the reconstruction less and the prior more. This explains why β\beta-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 xx is an 8-bit pixel, take pθ(x∣z)=∏iCategorical(xi;πi(z))p_\theta(x|z)=\prod_i \mathrm{Categorical}(x_i;\pi_i(z)); the negative log-likelihood is then a per-pixel cross-entropy and there is no σ\sigma knob, so β\beta 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 β\beta.

2.3 The Evidence Lower Bound: Derived from log⁡pθ(x)\log p_\theta(x)

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,

pθ(x)=∫pθ(x,z) dz=∫pθ(x∣z) p(z) dzp_\theta(x)=\int p_\theta(x,z)\,\mathrm{d}z=\int p_\theta(x\mid z)\,p(z)\,\mathrm{d}z

This integral becomes intractable once the dimension of zz is even moderately large (the same difficulty as Derivation 1 in Section 1.2). Introduce an arbitrary distribution qϕ(z∣x)q_\phi(z\mid x) (requiring it to have positive density on the support of pθ(z∣x)p_\theta(z\mid x), otherwise the KL diverges), and insert a “multiply by 1”:

pθ(x)=∫qϕ(z∣x) pθ(x,z)qϕ(z∣x) dz=Eqϕ(z∣x)[pθ(x,z)qϕ(z∣x)]p_\theta(x)=\int q_\phi(z\mid x)\,\frac{p_\theta(x,z)}{q_\phi(z\mid x)}\,\mathrm{d}z=\mathbb{E}_{q_\phi(z\mid x)}\left[\frac{p_\theta(x,z)}{q_\phi(z\mid x)}\right]

Step 2: use Jensen’s inequality to push the log⁡\log inside the expectation. log⁡\log is concave, so for any positive random variable YY we have log⁡E[Y]≥E[log⁡Y]\log\mathbb{E}[Y]\ge\mathbb{E}[\log Y] (this is Jensen’s inequality; equality holds if and only if YY is almost surely constant). Taking Y=pθ(x,z)/qϕ(z∣x)Y=p_\theta(x,z)/q_\phi(z\mid x):

log⁡pθ(x)≥Eqϕ(z∣x)[log⁡pθ(x,z)−log⁡qϕ(z∣x)]\log p_\theta(x)\ge\mathbb{E}_{q_\phi(z\mid x)}\left[\log p_\theta(x,z)-\log q_\phi(z\mid x)\right]

Step 3: split into the “reconstruction” and “KL” terms. Split the joint distribution as pθ(x,z)=pθ(x∣z)p(z)p_\theta(x,z)=p_\theta(x\mid z)p(z):

L=Eqϕ[log⁡pθ(x∣z)]+Eqϕ[log⁡p(z)−log⁡qϕ(z∣x)]\mathcal{L}=\mathbb{E}_{q_\phi}\left[\log p_\theta(x\mid z)\right]+\mathbb{E}_{q_\phi}\left[\log p(z)-\log q_\phi(z\mid x)\right]

The second expectation is, word for word by the definition of KL, −KL(qϕ(z∣x)∥p(z))-\mathrm{KL}\left(q_\phi(z\mid x)\|p(z)\right), 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

L=Eqϕ[log⁡pθ(x,z)−log⁡qϕ(z∣x)]=log⁡pθ(x)−KL(qϕ(z∣x)∥pθ(z∣x))\mathcal{L}=\mathbb{E}_{q_\phi}\left[\log p_\theta(x,z)-\log q_\phi(z\mid x)\right]=\log p_\theta(x)-\mathrm{KL}\left(q_\phi(z\mid x)\|p_\theta(z\mid x)\right)

Check: the right-hand side expands to log⁡pθ(x)+Eqϕ[log⁡pθ(z∣x)−log⁡qϕ(z∣x)]\log p_\theta(x)+\mathbb{E}_{q_\phi}\left[\log p_\theta(z\mid x)-\log q_\phi(z\mid x)\right], and the latter term is exactly minus the KL. Hence

log⁡pθ(x)−L=KL(qϕ(z∣x)∥pθ(z∣x))≥0\log p_\theta(x)-\mathcal{L}=\mathrm{KL}\left(q_\phi(z\mid x)\|p_\theta(z\mid x)\right)\ge0

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 qϕ(z∣x)q_\phi(z\mid x) happened to equal the true posterior pθ(z∣x)p_\theta(z\mid x), 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 pθ(x,z)/qϕ(z∣x)p_\theta(x,z)/q_\phi(z\mid x) to be constant in zz almost everywhere, i.e., qϕ(z∣x)∝pθ(x,z)q_\phi(z\mid x)\propto p_\theta(x,z). In practice qϕq_\phi 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 pθ(x∣z)=N(μθ(z),σ2I)p_\theta(x\mid z)=\mathcal{N}\left(\mu_\theta(z),\sigma^2 I\right) with σ2\sigma^2 fixed, then

−Eqϕ[log⁡pθ(x∣z)]=12σ2Eqϕ[∥x−μθ(z)∥2]+D2log⁡(2πσ2)-\mathbb{E}_{q_\phi}\left[\log p_\theta(x\mid z)\right]=\frac{1}{2\sigma^2}\mathbb{E}_{q_\phi}\left[\left\|x-\mu_\theta(z)\right\|^2\right]+\frac{D}{2}\log\left(2\pi\sigma^2\right)

The second term does not depend on θ\theta or ϕ\phi 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 σ2\sigma^2 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 qq and pp are products of independent one-dimensional Gaussians, the KL of the joint distribution equals the sum of the one-dimensional KLs:

KL(q∥p)=Eq[∑jlog⁡qj(zj)−∑jlog⁡pj(zj)]=∑jKL(qj∥pj)\mathrm{KL}(q\|p)=\mathbb{E}_{q}\left[\sum_j\log q_j(z_j)-\sum_j\log p_j(z_j)\right]=\sum_j\mathrm{KL}\left(q_j\|p_j\right)

This follows from the definition of KL plus the product structure: log⁡q(z)=∑jlog⁡qj(zj)\log q(z)=\sum_j\log q_j(z_j) and likewise for pp, and the expectation factorizes. So it suffices to look at one dimension.

Step 2: write out the log densities of that dimension. qj=N(μj,σj2)q_j=\mathcal{N}(\mu_j,\sigma_j^2), pj=N(0,1)p_j=\mathcal{N}(0,1):

log⁡qj(z)=−12log⁡(2πσj2)−(z−μj)22σj2,log⁡pj(z)=−12log⁡(2π)−z22\log q_j(z)=-\frac{1}{2}\log\left(2\pi\sigma_j^2\right)-\frac{(z-\mu_j)^2}{2\sigma_j^2},\qquad \log p_j(z)=-\frac{1}{2}\log\left(2\pi\right)-\frac{z^2}{2}

Step 3: take the difference and the expectation. The constant term 12log⁡(2π)\frac{1}{2}\log(2\pi) cancels:

KL(qj∥pj)=Eqj[−log⁡σj−(z−μj)22σj2+z22]\mathrm{KL}\left(q_j\|p_j\right)=\mathbb{E}_{q_j}\left[-\log\sigma_j-\frac{(z-\mu_j)^2}{2\sigma_j^2}+\frac{z^2}{2}\right]

Using the two second-moment identities Eqj[(z−μj)2]=σj2\mathbb{E}_{q_j}\left[(z-\mu_j)^2\right]=\sigma_j^2 and Eqj[z2]=μj2+σj2\mathbb{E}_{q_j}\left[z^2\right]=\mu_j^2+\sigma_j^2, substituting gives

KL(qj∥pj)=−log⁡σj−12+μj2+σj22\mathrm{KL}\left(q_j\|p_j\right)=-\log\sigma_j-\frac{1}{2}+\frac{\mu_j^2+\sigma_j^2}{2}

Step 4: rearrange into the common form. Write −log⁡σj-\log\sigma_j as −12log⁡σj2-\frac{1}{2}\log\sigma_j^2:

KL(qj∥pj)=12(μj2+σj2−1−log⁡σj2)\mathrm{KL}\left(q_j\|p_j\right)=\frac{1}{2}\left(\mu_j^2+\sigma_j^2-1-\log\sigma_j^2\right)

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 σj2\sigma_j^2. When σj2→0\sigma_j^2\to0, −log⁡σj2→+∞-\log\sigma_j^2\to+\infty, so the regularization term does not allow the encoder to squeeze the variance to 0; when σj2=1,μj=0\sigma_j^2=1,\mu_j=0 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 qϕq_\phi, and qϕq_\phi appears inside sampling: “draw a zz from N(μϕ,σϕ2)\mathcal{N}(\mu_\phi,\sigma_\phi^2)”. 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 z=μϕ+σϕ⊙εz=\mu_\phi+\sigma_\phi\odot\varepsilon, where ε∼N(0,I)\varepsilon\sim\mathcal{N}(0,I) is independent of ϕ\phi. Because a linear transform preserves Gaussianity,

z∼N(μϕ, diag⁡(σϕ2))z\sim\mathcal{N}\left(\mu_\phi,\ \operatorname{diag}\left(\sigma_\phi^2\right)\right)

i.e., the distribution of zz is exactly the same as before. But the way it is written has changed: the randomness comes only from ε\varepsilon, and ϕ\phi appears only in the deterministic map gϕ(ε)=μϕ+σϕ⊙εg_\phi(\varepsilon)=\mu_\phi+\sigma_\phi\odot\varepsilon.

Step 2: use a change of measure to write “the expectation over qϕq_\phi” as “an expectation over a fixed distribution”.

Eqϕ(z)[f(z)]=Ep(ε)[f(gϕ(ε))]\mathbb{E}_{q_\phi(z)}\left[f(z)\right]=\mathbb{E}_{p(\varepsilon)}\left[f\left(g_\phi(\varepsilon)\right)\right]

This step is an equality, not an approximation: both expectations are taken over the same random variable zz, only with a different parameterization.

Step 3: push the gradient inside the expectation. Provided ff and gϕg_\phi satisfy integrability and local Lipschitz conditions (in engineering terms, “the network is an ordinary neural network”),

∇ϕEqϕ[f(z)]=Ep(ε)[∇ϕf(gϕ(ε))]=Ep(ε)[f′(gϕ(ε))∇ϕgϕ(ε)]\nabla_\phi\mathbb{E}_{q_\phi}\left[f(z)\right]=\mathbb{E}_{p(\varepsilon)}\left[\nabla_\phi f\left(g_\phi(\varepsilon)\right)\right]=\mathbb{E}_{p(\varepsilon)}\left[f'\left(g_\phi(\varepsilon)\right)\nabla_\phi g_\phi(\varepsilon)\right]

This is the reparameterized gradient. Written term by term: the partial derivative with respect to μj\mu_j is f′(z)f'(z) (because ∂gj/∂μj=1\partial g_j/\partial\mu_j=1), and the partial derivative with respect to σj\sigma_j is f′(z) εjf'(z)\,\varepsilon_j.

Step 4: compare with the score function estimator. Without reparameterization, the only available unbiased estimator is

∇ϕEqϕ[f(z)]=Eqϕ[f(z) ∇ϕlog⁡qϕ(z)]\nabla_\phi\mathbb{E}_{q_\phi}\left[f(z)\right]=\mathbb{E}_{q_\phi}\left[f(z)\,\nabla_\phi\log q_\phi(z)\right]

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 f(z)f(z) to weight a high-dimensional gradient in a direction unrelated to zz, compressing the information “was this sample good” into a single number. The reparameterized version, in contrast, passes f′f' back dimension by dimension, carrying far more information.

Step 5: the cost and the boundary of applicability. Reparameterization requires qϕq_\phi to belong to a “reparameterizable” family (Gaussians, Laplace, Logistic, Gumbel-Softmax approximations, etc.) and requires ff to be differentiable with respect to zz. 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 ∇θ\nabla_\theta can pass through sampling. The mathematics is exactly the same in both places; only ff is replaced by the QQ 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 DD pixels, whereas the KL term sums over dd latent dimensions. In image tasks DD is often a hundred times dd, so the KL term is relatively negligible and the encoder “cannot be bothered” to use the latent variables — it squeezes qϕ(z∣x)q_\phi(z\mid x) onto the prior, turning zz into noise, and the decoder degenerates into an “unconditional generator”.

This phenomenon is called posterior collapse. Its criterion is very direct:

KL(qϕ(z∣x)∥p(z))≈0for almost all x\mathrm{KL}\left(q_\phi(z\mid x)\|p(z)\right)\approx0\quad\text{for almost all } x

Once it appears, the latent space loses its information content, and the VAE degenerates into “a noisy autoencoder”. There are four common countermeasures:

CountermeasureImplementationMechanism
β\beta-VAETurn the KL weight down: L=rec+β KL\mathcal{L}=\text{rec}+\beta\,\mathrm{KL}, β<1\beta<1Directly weaken the regularization term so that the encoder dares to use the latent variables; β>1\beta>1 does the opposite and is used to learn disentangled representations
KL annealingSet β=0\beta=0 early in training and increase it linearly to the target valueLet the decoder learn to use zz first, then apply pressure gradually
Free bitsPenalize only the part of each dimension’s KL that exceeds the threshold λ\lambda: max⁡(KLj,λ)\max\left(\mathrm{KL}_j,\lambda\right)Give each dimension a “free allowance” of λ\lambda nats, guaranteeing that at least some information is encoded
Limit decoder capacityUse 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 zz

β\beta-VAE with β>1\beta>1 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).

log⁡pθ(x)≥E[log⁡1K∑k=1Kpθ(x,zk)qϕ(zk∣x)],zk∼qϕ(z∣x) i.i.d.\log p_\theta(x)\ge\mathbb{E}\left[\log\frac{1}{K}\sum_{k=1}^{K}\frac{p_\theta(x,z_k)}{q_\phi(z_k\mid x)}\right],\qquad z_k\sim q_\phi(z\mid x)\ \text{i.i.d.}

KK samples are averaged with weights and then passed through log⁡\log; Jensen’s inequality still gives a lower bound, but a tighter one than K=1K=1 (the larger KK 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 KK, 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 KK samples z1,…,zKz_1,\dots,z_K independently from qϕ(z∣x)q_\phi(z\mid x), and define the importance weight of each sample as

wk=pθ(x,zk)qϕ(zk∣x),k=1,…,Kw_k=\frac{p_\theta(x,z_k)}{q_\phi(z_k\mid x)},\qquad k=1,\dots,K

Note that wkw_k is a random variable (it depends on zkz_k), and that Eqϕ[wk]=pθ(x)\mathbb{E}_{q_\phi}\left[w_k\right]=p_\theta(x) — this is exactly the fact ”pθ(x)p_\theta(x) is the expectation of ww”, and it is the fulcrum of all the inequalities that follow.

Step 2: write out the KK-sample lower bound.

LK=Eqϕ(z1∣x)⋯qϕ(zK∣x)[log⁡(1K∑k=1Kwk)]\mathcal{L}_K=\mathbb{E}_{q_\phi(z_1\mid x)\cdots q_\phi(z_K\mid x)}\left[\log\left(\frac{1}{K}\sum_{k=1}^{K}w_k\right)\right]

For K=1K=1 it degenerates to E[log⁡w1]=LELBO\mathbb{E}\left[\log w_1\right]=\mathcal{L}_{\text{ELBO}}.

Step 3: prove that it is a lower bound (Jensen, same direction as the ELBO). log⁡\log is concave, hence

LK≤log⁡E[1K∑kwk]=log⁡(1K∑kE[wk])=log⁡pθ(x)\mathcal{L}_K\le\log\mathbb{E}\left[\frac{1}{K}\sum_k w_k\right]=\log\left(\frac{1}{K}\sum_k\mathbb{E}\left[w_k\right]\right)=\log p_\theta(x)

The last step uses E[wk]=pθ(x)\mathbb{E}[w_k]=p_\theta(x) and the fact that the sum of KK terms equals K pθ(x)K\,p_\theta(x). So LK\mathcal{L}_K 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 log⁡\log, use once more “the log of an average is no smaller than the average of the logs”:

log⁡(1K∑k=1Kwk)≥1K∑k=1Klog⁡wk\log\left(\frac{1}{K}\sum_{k=1}^{K}w_k\right)\ge\frac{1}{K}\sum_{k=1}^{K}\log w_k

Taking expectations on both sides, the right-hand side is 1K∑kE[log⁡wk]=E[log⁡w1]=LELBO\frac{1}{K}\sum_k\mathbb{E}\left[\log w_k\right]=\mathbb{E}\left[\log w_1\right]=\mathcal{L}_{\text{ELBO}}. Hence

LELBO≤LK≤log⁡pθ(x)\mathcal{L}_{\text{ELBO}}\le\mathcal{L}_K\le\log p_\theta(x)

Equality condition: log⁡(1K∑wk)=1K∑log⁡wk\log\left(\frac{1}{K}\sum w_k\right)=\frac{1}{K}\sum\log w_k holds if and only if all wkw_k are equal, i.e., qϕ(zk∣x)∝pθ(x,zk)q_\phi(z_k\mid x)\propto p_\theta(x,z_k) for every kk — that is, the posterior approximation is exact. This is the same condition as the Jensen equality condition of Derivation 3, except that now KK samples must satisfy it simultaneously, which has lower probability, and therefore in practice the larger KK is, the less likely equality is attained, and the tighter the bound becomes instead.

Step 5: monotonicity and consistency. Regard the K+1K+1 weights of LK+1\mathcal{L}_{K+1} as a mixture of “the average of the first KK” and “the (K+1)(K+1)-th one”:

1K+1∑k=1K+1wk=KK+1wˉ1:K+1K+1wK+1,wˉ1:K=1K∑k=1Kwk\frac{1}{K+1}\sum_{k=1}^{K+1}w_k=\frac{K}{K+1}\bar w_{1:K}+\frac{1}{K+1}w_{K+1},\qquad \bar w_{1:K}=\frac{1}{K}\sum_{k=1}^{K}w_k

Then, by the concavity of log⁡\log, E[log⁡(KK+1wˉ+1K+1wK+1)]≥KK+1E[log⁡wˉ]+1K+1E[log⁡wK+1]\mathbb{E}\left[\log\left(\frac{K}{K+1}\bar w+\frac{1}{K+1}w_{K+1}\right)\right]\ge\frac{K}{K+1}\mathbb{E}\left[\log\bar w\right]+\frac{1}{K+1}\mathbb{E}\left[\log w_{K+1}\right], where the first term on the right is a combination of KK+1LK\frac{K}{K+1}\mathcal{L}_K and the second term 1K+1LELBO\frac{1}{K+1}\mathcal{L}_{\text{ELBO}}, and therefore

LK+1≥KK+1LK+1K+1LELBO≥LK\mathcal{L}_{K+1}\ge\frac{K}{K+1}\mathcal{L}_K+\frac{1}{K+1}\mathcal{L}_{\text{ELBO}}\ge\mathcal{L}_K

i.e., LK\mathcal{L}_K is monotonically non-decreasing in KK. As K→∞K\to\infty, by the law of large numbers wˉ→E[w]=pθ(x)\bar w\to\mathbb{E}[w]=p_\theta(x) almost surely, and log⁡\log is continuous, hence LK→log⁡pθ(x)\mathcal{L}_K\to\log p_\theta(x). So IWAE is a sequence of lower bounds that converges to the true likelihood as KK grows, which is the key difference from the ELBO (where KK 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

log⁡pθ(x)−LK≤log⁡pθ(x)−LELBO=KL(qϕ(z∣x)∥pθ(z∣x))\log p_\theta(x)-\mathcal{L}_K\le\log p_\theta(x)-\mathcal{L}_{\text{ELBO}}=\mathrm{KL}\left(q_\phi(z\mid x)\|p_\theta(z\mid x)\right)

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), KK between 8 and 64 suffices; if the posterior family is weak (a diagonal Gaussian fitting a multimodal posterior), then no matter how large KK 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 LK\mathcal{L}_K:

∇ϕLK=E[∑k=1Kwk∑jwj ∇ϕlog⁡wk]\nabla_\phi\mathcal{L}_K=\mathbb{E}\left[\sum_{k=1}^{K}\frac{w_k}{\sum_{j}w_j}\,\nabla_\phi\log w_k\right]

The factor wk∑jwj\frac{w_k}{\sum_j w_j} inside the bracket is a softmax weight. When KK is large, the weights concentrate on the few largest wkw_k (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 K=32K=32 (rather than K=1000K=1000), and it is the mathematical explanation of “for IWAE, larger KK is not always better”. If a large KK really is needed, it must be combined with gradient truncation (applying stop-gradient to log⁡wk\log w_k) 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 KK, 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

max⁡θ,ϕ  Eqϕ[log⁡pθ(x∣z)]−KL(qϕ(z∣x)∥p(z))\max_{\theta,\phi}\ \ \mathbb{E}_{q_\phi}\left[\log p_\theta(x\mid z)\right]-\mathrm{KL}\left(q_\phi(z\mid x)\|p(z)\right)

β\beta-VAE changes it to

max⁡θ,ϕ  Eqϕ[log⁡pθ(x∣z)]−β KL(qϕ(z∣x)∥p(z)),β>0\max_{\theta,\phi}\ \ \mathbb{E}_{q_\phi}\left[\log p_\theta(x\mid z)\right]-\beta\,\mathrm{KL}\left(q_\phi(z\mid x)\|p(z)\right),\qquad \beta>0

On the surface it is merely “a different weight”, but as shown below: every β\beta corresponds to the optimal multiplier of some KL upper-bound constraint, so β\beta-VAE is not arbitrary weighting but the solution of a family of constrained problems.

Step 2: write the constrained form. Consider

max⁡θ,ϕ  Eqϕ[log⁡pθ(x∣z)]s.t.KL(qϕ(z∣x)∥p(z))≤C\max_{\theta,\phi}\ \ \mathbb{E}_{q_\phi}\left[\log p_\theta(x\mid z)\right]\quad\text{s.t.}\quad \mathrm{KL}\left(q_\phi(z\mid x)\|p(z)\right)\le C

Introducing the multiplier β≥0\beta\ge0, the Lagrangian is

J=Eqϕ[log⁡pθ(x∣z)]−β(KL(qϕ∥p)−C)\mathcal{J}=\mathbb{E}_{q_\phi}\left[\log p_\theta(x\mid z)\right]-\beta\left(\mathrm{KL}\left(q_\phi\|p\right)-C\right)

Maximize over ϕ\phi and minimize over β\beta (a saddle point). Given β\beta, the subproblem in ϕ\phi is exactly the objective of β\beta-VAE (the constant βC\beta C does not affect the gradient). So the objective of β\beta-VAE is the Lagrangian of the upper-bound constrained problem.

Step 3: KKT and “what β\beta means”. The complementary slackness condition is β(KL−C)=0\beta\left(\mathrm{KL}-C\right)=0. Two cases:

  • if the KL of the optimal solution is strictly smaller than CC (the constraint is inactive), then β=0\beta=0, and the problem degenerates into an ordinary autoencoder that “only reconstructs and ignores regularization”;
  • if the KL exactly equals CC (the constraint is active), then β>0\beta>0, and β\beta is exactly “how much reconstruction one is willing to sacrifice in order to relax the KL constraint by one unit”.

Therefore β<1\beta<1 is equivalent to relaxing CC (allowing a larger KL, hence stronger encoding), and β>1\beta>1 is equivalent to tightening CC (forcing a smaller KL, hence forcing the dimensions to be independent and producing disentanglement). This translates “what is actually being done by turning β\beta up or down” into a constrained problem with units: CC is measured in nats (units of information), and β\beta 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 λ\lambda of information, i.e., the constraint

KLj=KL(qϕ(zj∣x)∥p(zj))≥λ,j=1,…,d\mathrm{KL}_j=\mathrm{KL}\left(q_\phi(z_j\mid x)\|p(z_j)\right)\ge\lambda,\qquad j=1,\dots,d

This is a “lower bound constraint”. Write it as a penalty function (penalizing the shortfall):

Lfb=Eqϕ[log⁡pθ(x∣z)]−∑j=1dmax⁡(KLj,λ)\mathcal{L}_{\text{fb}}=\mathbb{E}_{q_\phi}\left[\log p_\theta(x\mid z)\right]-\sum_{j=1}^{d}\max\left(\mathrm{KL}_j,\lambda\right)

Step 5: look at the piecewise behavior of this max⁡\max dimension by dimension. For the jj-th dimension:

∂∂ KLjmax⁡(KLj,λ)={1,KLj>λ0,KLj<λ\frac{\partial}{\partial\,\mathrm{KL}_j}\max\left(\mathrm{KL}_j,\lambda\right)= \begin{cases} 1, & \mathrm{KL}_j>\lambda\\ 0, & \mathrm{KL}_j<\lambda \end{cases}

So when KLj<λ\mathrm{KL}_j<\lambda, this term produces no gradient at all — those λ\lambda 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 qϕq_\phi toward the prior”, and in the region KLj<λ\mathrm{KL}_j<\lambda 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 zz; only after KLj\mathrm{KL}_j exceeds λ\lambda does the standard regularization take over.

Step 6: the contrast with β\beta-VAE. The two are in fact two directions of the same Lagrangian framework:

MethodConstraint typePenalty termGradient behaviorProblem addressed
β\beta-VAE (β<1\beta<1)KL upper bound KL≤C\mathrm{KL}\le Cβ KL\beta\,\mathrm{KL}Global scaling (every dimension shrinks)Posterior collapse, latent variables not used
β\beta-VAE (β>1\beta>1)Tighter KL upper boundβ KL\beta\,\mathrm{KL}Global amplificationPursuing disentangled representations
Free bitsPer-dimension lower bound KLj≥λ\mathrm{KL}_j\ge\lambda∑jmax⁡(KLj,λ)\sum_j\max\left(\mathrm{KL}_j,\lambda\right)Piecewise: zero below the thresholdPosterior collapse, with a per-dimension floor

The key difference lies in “per dimension”: β\beta is a global scalar, and it cannot prevent “one dimension being completely squeezed dead while another dimension carries all the information”; the λ\lambda 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 β\beta 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 zz, a distribution close to pdatap_{\text{data}}, then the reconstruction term is almost independent of zz:

Eqϕ(z∣x)[−log⁡pθ(x∣z)]≈−log⁡pdata(x)\mathbb{E}_{q_\phi(z|x)}\left[-\log p_\theta(x|z)\right]\approx-\log p_{\text{data}}(x)

Then the only term still depending on zz is the KL, whose minimum is attained at qϕ(z∣x)=p(z)=N(0,I)q_\phi(z|x)=p(z)=\mathcal{N}(0,I) with value zero. So the objective admits a solution: the encoder ignores xx 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 qϕ(z∣x)=N(μϕ(x),diag(σϕ2(x)))q_\phi(z|x)=\mathcal{N}\left(\mu_\phi(x),\mathrm{diag}\left(\sigma_\phi^2(x)\right)\right); the per-dimension KL (closed form from Derivation 4) is

DKL,j=12(μj2+σj2−1−log⁡σj2)D_{\mathrm{KL},j}=\frac{1}{2}\left(\mu_j^2+\sigma_j^2-1-\log\sigma_j^2\right)

As μj→0\mu_j\to0 and σj→1\sigma_j\to1, DKL,j→0D_{\mathrm{KL},j}\to0. 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

Neff=#{j: DKL,j>τ}N_{\text{eff}}=\#\left\{j:\ D_{\mathrm{KL},j}>\tau\right\}

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 β\beta makes collapse easier. In the objective the KL carries coefficient β\beta and the reconstruction term coefficient one. The collapsed solution pushes the KL from some positive value down to zero, a gain of βDKL\beta D_{\mathrm{KL}}, at the cost of raising the reconstruction term by Δrec\Delta_{\text{rec}}. Whenever

β DKL>Δrec\beta\,D_{\mathrm{KL}}>\Delta_{\text{rec}}

the collapsed solution is actually better. And Δrec\Delta_{\text{rec}} shrinks as the decoder capacity grows (the decoder can fit the data by itself), so the stronger the decoder and the larger the β\beta, the easier the collapse — the danger of “large decoder + high β\beta”.

Step 4: the mechanism of the three remedies. (i) free bits: replace the KL with max⁡(τ,DKL,j)\max\left(\tau,D_{\mathrm{KL},j}\right), so the first τ\tau nats are free and the collapsed solution is no longer free (the Lagrangian interpretation is Derivation 18); (ii) KL annealing: ramp β\beta 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 Δrec\Delta_{\text{rec}} 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 log⁡σ2\log\sigma^2 rather than σ\sigma. If σ\sigma were output directly, an extra positivity constraint would be needed (such as softplus or taking the absolute value), and σ\sigma has poor gradients near 0; outputting log⁡σ2\log\sigma^2 lets the network work on the unconstrained real line, and σ2=elog⁡σ2\sigma^2=e^{\log\sigma^2} is naturally positive. The KL formula already contains log⁡σ2\log\sigma^2, so this parameterization also saves one log⁡\log.

Segment 1 ②: clamp is not optional. Early in training log⁡σ2\log\sigma^2 can run to +30+30, and e15e^{15} blows zz up to 10610^6, the decoder output becomes NaN, and the whole training collapses afterwards. Restricting log⁡σ2\log\sigma^2 to [−20,10][-20,10] is what almost every open-source implementation does.

Segment 2 ③: ε\varepsilon 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 ε\varepsilon, 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, pθ(x∣z)=N(μθ(z),σ2I)p_\theta(x\mid z)=\mathcal{N}\left(\mu_\theta(z),\sigma^2 I\right), 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 ∑j(⋅)\sum_j(\cdot) for each sample, then average over the batch. If one averages μ\mu over the batch first and then plugs it into the formula, what is obtained is KL(N(μˉ,⋅)∥p)\mathrm{KL}\left(\mathcal{N}(\bar\mu,\cdot)\|p\right), which is not the same thing as “the average of the KLs”; the two differ by a Var(μ)\mathrm{Var}(\mu) term. This is one of the most hidden errors in implementations.

Segment 4 ⑥: what β\beta tunes is “whether the latent variables are used”. With a small β\beta the reconstruction dominates, the latent space carries more information but may be irregular; with a large β\beta the regularization dominates, the latent space is regular but may collapse. In engineering it is advisable to first get things running with β=1\beta=1, 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 zz, 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 zz 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 qϕ(z∣xtrain)q_\phi(z\mid x_{\text{train}}) 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 z∼N(0,I)z\sim\mathcal{N}(0,I), 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”:

QuantityWhen readWhen writtenKept across stepsConsequence of getting it wrong
μϕ(x)\mu_\phi(x)Every stepEvery stepNo (discarded after the step)Mistaking it for a reusable representation breaks batch independence
log⁡σϕ2(x)\log\sigma_\phi^2(x)Every stepEvery stepNoForgetting clamp leads to numerical explosion
ε\varepsilonEvery stepNewly drawn every stepNoSharing within a batch invalidates the variance estimate
zzAt decodingEvery stepNoReusing an old zz across steps makes the gradient mismatch the current parameters
θ\thetaEvery stepEvery stepKept—
ϕ\phiEvery stepEvery stepKept—
KL termEvery stepEvery stepNoOmitting it leaves the latent space unconstrained, degenerating into an AE
β\betaEvery stepPer schedule (during annealing)Kept (may be increased)Starting with a large β\beta causes collapse

Three decision principles:

  1. “Randomness may come only from exogenous noise.” Sampling must be written as z=μ+σ⊙εz=\mu+\sigma\odot\varepsilon; one must not call .sample() on a distribution object and then cut the graph — the latter silently cuts the gradient to ϕ\phi, and training looks normal while the encoder does not learn.
  2. “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.
  3. “Generation uses the prior, reconstruction uses the posterior.” These two paths must not be mixed: training uses the posterior (because xx must be seen), likelihood evaluation uses the posterior (importance weighting), and generation uses the prior.

2.10 Pitfall List

SymptomPossible causeFix
Generated samples are all blurry average imagesGaussian decoder + fixed large variance + posterior approximation gapReduce 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 workingPosterior collapseLower β\beta, KL annealing, free bits, weaken the decoder
The training loss looks normal but the samples are highly similar to the training setThe encoder output was used at generation timeGeneration must use z∼N(0,I)z\sim\mathcal{N}(0,I)
Some latent dimensions are always 0Excessive KL penalty (β\beta too large)Lower β\beta; or let free bits give each dimension an allowance
The reconstruction term does not decreaseInsufficient decoder capacity / latent dimension too smallWiden the decoder, increase dd; or check normalization
σ\sigma is learned close to 0 and training is unstableMissing clamp or KL weight too smallclamp(logσ²); check whether the KL is really included in the loss
The KL differs enormously between two batchesAggregating before computing the KLCompute the KL per sample, then average
Non-numeric values appear when interpolating in the latent spacePrior and aggregated posterior do not match (prior hole)Use β<1\beta<1, or regularize the aggregated posterior (VAMP prior)

Among them, “prior hole” deserves a separate mention: a VAE guarantees only that each qϕ(z∣x)q_\phi(z\mid x) is close to the prior, not that the aggregated posterior qϕ(z)=Epdata(x)[qϕ(z∣x)]q_\phi(z)=\mathbb{E}_{p_{\text{data}}(x)}[q_\phi(z\mid x)] 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 (β\beta-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 256×256×3256\times256\times3 image into a 32×32×432\times32\times4 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 KK, 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 GθG_\theta maps noise z∼N(0,I)z\sim\mathcal{N}(0,I) to a sample Gθ(z)G_\theta(z), and wants the distribution pgp_g of its output to be indistinguishable from pdatap_{\text{data}};
  • Discriminator DϕD_\phi 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:

min⁡θmax⁡ϕ V(Dϕ,Gθ)=Ex∼pdata[log⁡Dϕ(x)]+Ez∼p(z)[log⁡(1−Dϕ(Gθ(z)))]\min_{\theta}\max_{\phi}\ V(D_\phi,G_\theta)=\mathbb{E}_{x\sim p_{\text{data}}}\left[\log D_\phi(x)\right]+\mathbb{E}_{z\sim p(z)}\left[\log\left(1-D_\phi\left(G_\theta(z)\right)\right)\right]

A few notes on how it is written:

  • max⁡ϕ\max_\phi is the discriminator’s objective (push both terms up: real samples judged 1, fake samples judged 0);
  • min⁡θ\min_\theta is the generator’s objective (push the second term up, i.e., make D(G(z))D(G(z)) close to 1);
  • the first term has no gradient with respect to θ\theta (xx 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 p=pdatap=p_{\text{data}} and q=pgq=p_g:

V(D,G)=∫p(x)log⁡D(x) dx+∫q(x)log⁡(1−D(x))dxV(D,G)=\int p(x)\log D(x)\,\mathrm{d}x+\int q(x)\log\left(1-D(x)\right)\mathrm{d}x

The integrand at each xx depends only on the value of D(x)D(x), so “maximizing over the function DD” can be done pointwise: for each xx independently maximize

fx(d)=p(x)log⁡d+q(x)log⁡(1−d),d∈(0,1)f_x(d)=p(x)\log d+q(x)\log(1-d),\qquad d\in(0,1)

Step 2: differentiate pointwise and set to zero.

fx′(d)=p(x)d−q(x)1−d=0 ⟹ p(x)(1−d)=q(x)d ⟹ d=p(x)p(x)+q(x)f_x'(d)=\frac{p(x)}{d}-\frac{q(x)}{1-d}=0\ \Longrightarrow\ p(x)(1-d)=q(x)d\ \Longrightarrow\ d=\frac{p(x)}{p(x)+q(x)}

Step 3: since fx′′(d)=−p/d2−q/(1−d)2<0f_x''(d)=-p/d^2-q/(1-d)^2<0, this is the maximum point, and it is unique. Therefore

D⋆(x)=pdata(x)pdata(x)+pg(x)D^{\star}(x)=\frac{p_{\text{data}}(x)}{p_{\text{data}}(x)+p_g(x)}

Note the condition under which this conclusion applies: pp and qq have densities with respect to the same measure (if pgp_g 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 D⋆D^{\star} back into the objective. Denote the midpoint distribution m=(p+q)/2m=(p+q)/2, so p+q=2mp+q=2m:

V(D⋆,G)=∫plog⁡pp+q dx+∫qlog⁡qp+q dxV(D^{\star},G)=\int p\log\frac{p}{p+q}\,\mathrm{d}x+\int q\log\frac{q}{p+q}\,\mathrm{d}x

Step 5: massage it into the form of KL. Split each term into “relative to the midpoint” plus a constant:

∫plog⁡pp+q=∫plog⁡p2m=∫plog⁡pm−log⁡2∫p=KL(p∥m)−log⁡2\int p\log\frac{p}{p+q}=\int p\log\frac{p}{2m}=\int p\log\frac{p}{m}-\log2\int p=\mathrm{KL}(p\|m)-\log2

The second term is likewise KL(q∥m)−log⁡2\mathrm{KL}(q\|m)-\log2. Both ∫p\int p and ∫q\int q equal 1 (probability normalization).

Step 6: combine.

V(D⋆,G)=KL(p∥m)+KL(q∥m)−2log⁡2=2 JSD(p∥q)−2log⁡2V(D^{\star},G)=\mathrm{KL}(p\|m)+\mathrm{KL}(q\|m)-2\log2=2\,\mathrm{JSD}(p\|q)-2\log2

Since JSD∈[0,log⁡2]\mathrm{JSD}\in[0,\log2], we have V(D⋆,G)∈[−2log⁡2, 0]V(D^{\star},G)\in[-2\log2,\ 0], and the global minimum −2log⁡2-2\log2 is attained if and only if p=qp=q.

Step 7: three corollaries of this result.

  1. The generator’s optimal solution is pg=pdatap_g=p_{\text{data}}, at which D⋆≡1/2D^{\star}\equiv1/2 (the discriminator is completely unable to tell them apart and can only guess). This gives the theoretical convergence point of GAN;
  2. 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);
  3. D⋆D^{\star} depends on the current value of pgp_g, so the optimal discriminator changes after every generator update. DD 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 f:R+→Rf:\mathbb{R}_+\to\mathbb{R} be a convex function with f(1)=0f(1)=0. The f-divergence of two distributions PP and QQ (with densities pp and qq, and pp integrable where q>0q>0) is

Df(P ∥ Q)=∫q(x) f(p(x)q(x))dxD_f\left(P\,\|\,Q\right)=\int q(x)\,f\left(\frac{p(x)}{q(x)}\right)\mathrm{d}x

When f(u)=ulog⁡uf(u)=u\log u it is KL(P∥Q)\mathrm{KL}(P\|Q); when f(u)=−(u+1)log⁡u+12+ulog⁡uf(u)=-\left(u+1\right)\log\frac{u+1}{2}+u\log u it is 2 JSD2\,\mathrm{JSD}; when f(u)=(u−1)2f(u)=(u-1)^2 it is the Pearson χ2\chi^2. Note that ff being convex with f(1)=0f(1)=0 guarantees that Df≥0D_f\ge0 and Df=0D_f=0 if and only if P=QP=Q (Jensen: ∫q f(p/q)≥f(∫p)=f(1)=0\int q\,f(p/q)\ge f\left(\int p\right)=f(1)=0).

Step 2: linearize ff with the Fenchel conjugate. The conjugate of a convex function is

f⋆(t)=sup⁡u∈dom f[tu−f(u)]f^{\star}(t)=\sup_{u\in\mathrm{dom}\,f}\left[tu-f(u)\right]

By the definition of the conjugate, f(u)≥tu−f⋆(t)f(u)\ge tu-f^{\star}(t) for all u,tu,t (simply drop the sup⁡\sup). Take tt to be a function T(x)T(x) and u=p(x)/q(x)u=p(x)/q(x), then multiply both sides by q(x)q(x) and integrate over xx:

∫q(x) f(p(x)q(x))dx ≥ ∫q(x)[T(x)p(x)q(x)−f⋆(T(x))]dx\int q(x)\,f\left(\frac{p(x)}{q(x)}\right)\mathrm{d}x\ \ge\ \int q(x)\left[T(x)\frac{p(x)}{q(x)}-f^{\star}\left(T(x)\right)\right]\mathrm{d}x

i.e.,

Df(P ∥ Q) ≥ EP[T(x)]−EQ[f⋆(T(x))]D_f\left(P\,\|\,Q\right)\ \ge\ \mathbb{E}_{P}\left[T(x)\right]-\mathbb{E}_{Q}\left[f^{\star}\left(T(x)\right)\right]

Step 3: taking the supremum of this lower bound over TT gives the exact value. By the equality condition of the conjugate, u=(f⋆)′(t)u=\left(f^{\star}\right)'(t) (i.e., t=f′(u)t=f'(u)), the optimal point is

T⋆(x)=f′(p(x)q(x))T^{\star}(x)=f'\left(\frac{p(x)}{q(x)}\right)

Substituting it back makes the lower bound equal to DfD_f. Hence

Df(P ∥ Q)=sup⁡T {EP[T(x)]−EQ[f⋆(T(x))]}D_f\left(P\,\|\,Q\right)=\sup_{T}\ \left\{\mathbb{E}_{P}\left[T(x)\right]-\mathbb{E}_{Q}\left[f^{\star}\left(T(x)\right)\right]\right\}

This is the complete origin of f-GAN: the discriminator TT is a function that “maps the density ratio p/qp/q 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:

f(u)f(u)Namef⋆(t)f^{\star}(t)Optimal T⋆T^{\star}Corresponding discriminator output
ulog⁡uu\log uKLet−1e^{t-1}log⁡pq\log\frac{p}{q}log density ratio (no activation)
−(u+1)log⁡u+12+ulog⁡u-\left(u+1\right)\log\frac{u+1}{2}+u\log u2 JSD2\,\mathrm{JSD}−log⁡(2−et)-\log\left(2-e^{t}\right)log⁡2pp+q\log\frac{2p}{p+q}log⁡D⋆1−D⋆+log⁡2\log\frac{D^{\star}}{1-D^{\star}}+\log2 (sigmoid output, off by a constant)
(u−1)2(u-1)^2Pearson χ2\chi^2t24+t\frac{t^2}{4}+t2(pq−1)2\left(\frac{p}{q}-1\right)linear output (LSGAN)

The second row is another way of writing Derivation 6: D⋆=pp+qD^{\star}=\frac{p}{p+q}, hence log⁡D⋆1−D⋆=log⁡pq\log\frac{D^{\star}}{1-D^{\star}}=\log\frac{p}{q}, while T⋆=log⁡2pp+q=log⁡D⋆1−D⋆+log⁡2T^{\star}=\log\frac{2p}{p+q}=\log\frac{D^{\star}}{1-D^{\star}}+\log2 — the two differ only by the constant log⁡2\log2, which does not affect how the supremum is taken, but after substituting back into the objective it produces a shift of −2log⁡2-2\log2, which is exactly the origin of that term in “the objective at the optimum equals 2 JSD−2log⁡22\,\mathrm{JSD}-2\log2”. The third row shows that the Least Squares GAN (LSGAN) is not “trying a different loss” but “choosing the χ2\chi^2 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 ff. If JS is used (the original GAN), the range of TT is restricted by the domain of f⋆f^{\star} (2−et>02-e^{t}>0), so a sigmoid must be applied to squeeze TT into (−∞,log⁡2)(-\infty,\log2); if χ2\chi^2 is used, TT is unbounded and a linear output is fine. A common mistake in practice is “changing the loss but not the activation”, which lets f⋆(T)f^{\star}(T) 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, χ2\chi^2) 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 T⋆T^{\star} depends only on the density ratio p/qp/q, not on the specific shapes of pp and qq 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 D(G(z))≈0D(G(z))\approx0, and at that point the generator’s loss log⁡(1−D(G(z)))\log(1-D(G(z))) is already close to its minimum log⁡1=0\log1=0, so the gradient is nearly zero and the generator cannot learn. Goodfellow’s fix is to change the loss:

min⁡θ −Ez[log⁡Dϕ(Gθ(z))]\min_\theta\ -\mathbb{E}_{z}\left[\log D_\phi\left(G_\theta(z)\right)\right]

This is called the non-saturating loss. Note that it is not the original objective (it replaces log⁡(1−D)\log(1-D) with −log⁡D-\log D, and the two have completely different shapes when DD 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 a(x)a(x) be the discriminator’s logit output and D(x)=σ(a(x))D(x)=\sigma\left(a(x)\right), where σ\sigma is the sigmoid function. Its derivative is

σ′(a)=σ(a)(1−σ(a))=D(1−D)\sigma'(a)=\sigma(a)\left(1-\sigma(a)\right)=D(1-D)

Step 2: compute the gradient of the original loss with respect to the logit. The generator minimizes

ℓsat=log⁡(1−D),D=σ(a)\ell_{\text{sat}}=\log\left(1-D\right),\qquad D=\sigma(a)

By the chain rule:

∂ℓsat∂a=11−D⋅(−σ′(a))=−D(1−D)1−D=−D\frac{\partial\ell_{\text{sat}}}{\partial a}=\frac{1}{1-D}\cdot\left(-\sigma'(a)\right)=-\frac{D(1-D)}{1-D}=-D

Step 3: compute the gradient of the non-saturating loss with respect to the logit.

ℓns=−log⁡D ⟹ ∂ℓns∂a=−1D⋅σ′(a)=−D(1−D)D=−(1−D)\ell_{\text{ns}}=-\log D\ \Longrightarrow\ \frac{\partial\ell_{\text{ns}}}{\partial a}=-\frac{1}{D}\cdot\sigma'(a)=-\frac{D(1-D)}{D}=-(1-D)

Step 4: look at the behavior as D→0D\to0. When the generated samples are obviously fake, D(G(z))≈0D(G(z))\approx0:

  • the original loss gradient ≈−D→0\approx-D\to0: it vanishes. Moreover a→−∞a\to-\infty at this point, σ\sigma is already saturated, and ∂D/∂x=D(1−D)∂a/∂x\partial D/\partial x=D(1-D)\partial a/\partial x also tends to 0, so multiplying the two layers gives a second-order small quantity;
  • the non-saturating loss gradient ≈−(1−D)→−1\approx-(1-D)\to-1: it does not vanish. The factor 1/D1/D exactly cancels the DD inside σ′\sigma'.

Step 5: the behavior as D→1D\to1 (reverse check). When the generated samples are already good, the gradients of both losses tend to 0 (the original loss →−D≈−1\to-D\approx-1, the non-saturating one →−(1−D)≈0\to-(1-D)\approx0). 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 DD approaches 1, log⁡(1−D)\log(1-D) saturates and the gradient vanishes”. That describes the case where the discriminator judges fake samples as real (as D(G(z))→1D(G(z))\to1, log⁡(1−D)→−∞\log(1-D)\to-\infty, 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 D→0D\to0 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 256×256256\times256 image lives in a 196608196608-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 AA such that all the mass of pdatap_{\text{data}} lies inside AA and all the mass of pgp_g lies in the complement of AA (strictly: pg(A)=0p_g(A)=0, pdata(Ac)=0p_{\text{data}}(A^c)=0). This is “the supports do not intersect”.

Step 2: the optimal discriminator takes two extreme values inside and outside AA. From D⋆=p/(p+q)D^{\star}=p/(p+q) of Derivation 6: inside AA we have q=0q=0, hence D⋆=1D^{\star}=1; inside AcA^c we have p=0p=0, hence D⋆=0D^{\star}=0. That is,

D⋆(x)={1,x∈A0,x∈AcD^{\star}(x)=\begin{cases}1,& x\in A\\ 0,& x\in A^c\end{cases}

Step 3: compute the optimal objective value. The first term is ∫Aplog⁡1=0\int_A p\log1=0; the second term is ∫Acqlog⁡(1−0)=0\int_{A^c}q\log(1-0)=0. So V(D⋆,G)=0V(D^{\star},G)=0. Checking against the formula of Derivation 6: 2JSD−2log⁡2=2log⁡2−2log⁡2=02\mathrm{JSD}-2\log2=2\log2-2\log2=0, consistent.

Step 4: differentiate with respect to the generator parameters — and get zero. The generator appears only in the second term: ∫q(x)log⁡(1−D⋆(x))dx\int q(x)\log\left(1-D^{\star}(x)\right)\mathrm{d}x. On AcA^c, D⋆=0D^{\star}=0 and the integrand is q(x)log⁡1=0q(x)\log1=0, identically zero; on AA, q=0q=0. So this term is identically 0 and independent of θ\theta, and the gradient is

∇θ V(D⋆,Gθ)=0\nabla_\theta\ V(D^{\star},G_\theta)=0

Step 5: even without the optimal discriminator, saturation is enough. In practice DD does not take exactly 0/1, but it gets very close. At that point ∂D/∂x=D(1−D)∂a/∂x\partial D/\partial x=D(1-D)\partial a/\partial x 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.

  1. Early on the discriminator must be “let off” (fewer update steps, added noise, label smoothing), otherwise it saturates right away;
  2. 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);
  3. 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 W1\mathcal{W}_1 itself is an optimization problem of “taking the infimum over all couplings”, which cannot be computed directly — its dual form is needed.

W1(p,q)=inf⁡γ∈Π(p,q)E(x,y)∼γ[∥x−y∥]=sup⁡∥f∥L≤1(Ep[f(x)]−Eq[f(y)])\mathcal{W}_1(p,q)=\inf_{\gamma\in\Pi(p,q)}\mathbb{E}_{(x,y)\sim\gamma}\left[\left\|x-y\right\|\right] =\sup_{\left\|f\right\|_{L}\le1}\left(\mathbb{E}_{p}\left[f(x)\right]-\mathbb{E}_{q}\left[f(y)\right]\right)

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: ff 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 ff be 1-Lipschitz, i.e., ∣f(x)−f(y)∣≤∥x−y∥\left|f(x)-f(y)\right|\le\left\|x-y\right\| for all x,yx,y. For any coupling γ∈Π(p,q)\gamma\in\Pi(p,q),

Eγ[f(x)−f(y)]≤Eγ[∣f(x)−f(y)∣]≤Eγ[∥x−y∥]\mathbb{E}_{\gamma}\left[f(x)-f(y)\right]\le\mathbb{E}_{\gamma}\left[\left|f(x)-f(y)\right|\right]\le\mathbb{E}_{\gamma}\left[\left\|x-y\right\|\right]

The left-hand side depends only on the marginals: Eγ[f(x)]=Ep[f(x)]\mathbb{E}_\gamma[f(x)]=\mathbb{E}_p[f(x)], Eγ[f(y)]=Eq[f(y)]\mathbb{E}_\gamma[f(y)]=\mathbb{E}_q[f(y)]. Hence for every such ff,

Ep[f]−Eq[f]≤inf⁡γEγ[∥x−y∥]=W1(p,q)\mathbb{E}_p[f]-\mathbb{E}_q[f]\le\inf_{\gamma}\mathbb{E}_\gamma\left[\left\|x-y\right\|\right]=\mathcal{W}_1(p,q)

Taking the supremum over all 1-Lipschitz ff gives sup⁡f(⋅)≤W1\sup_f(\cdot)\le\mathcal{W}_1.

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 ∥x−y∥\left\|x-y\right\| is continuous, and p,qp,q 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 F,GF,G be the cumulative distribution functions (CDFs) of p,qp,q. Take

f(x)=∫0xsign⁡(F(u)−G(u))duf(x)=\int_{0}^{x}\operatorname{sign}\left(F(u)-G(u)\right)\mathrm{d}u

Then ∣f′(x)∣=∣sign⁡(F(x)−G(x))∣≤1\left|f'(x)\right|=\left|\operatorname{sign}\left(F(x)-G(x)\right)\right|\le1, so ff is 1-Lipschitz. Compute the dual objective using integration by parts (or the density form p=F′p=F', q=G′q=G'):

Ep[f]−Eq[f]=∫(F(x)−G(x))f′(x) dx=∫∣F(x)−G(x)∣dx\mathbb{E}_p[f]-\mathbb{E}_q[f]=\int\left(F(x)-G(x)\right)f'(x)\,\mathrm{d}x=\int\left|F(x)-G(x)\right|\mathrm{d}x

And the one-dimensional W1\mathcal{W}_1 happens to equal ∫∣F(x)−G(x)∣dx\int\left|F(x)-G(x)\right|\mathrm{d}x (this is the integral of the difference of the quantile functions, an equivalent form). So this ff 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 F−GF-G” — a function that climbs monotonically, rising where pp has more mass than qq and falling where qq has more mass than pp. 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

min⁡θ max⁡ϕ: ∥fϕ∥L≤1 Ex∼pdata[fϕ(x)]−Ez[fϕ(Gθ(z))]\min_\theta\ \max_{\phi:\ \left\|f_\phi\right\|_{L}\le1}\ \mathbb{E}_{x\sim p_{\text{data}}}\left[f_\phi(x)\right]-\mathbb{E}_{z}\left[f_\phi\left(G_\theta(z)\right)\right]

The gradient with respect to ϕ\phi is “the score of real samples minus the score of fake samples”, and the gradient with respect to θ\theta is “raise the score of fake samples”. Note that here there is no log⁡\log and no sigmoid, so there is no saturation; when the two distributions are δ\delta apart, W1=δ\mathcal{W}_1=\delta, and the gradient magnitude is of the same order as δ\delta (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 W1=sup⁡∥f∥L≤1(Ep[f]−Eq[f])\mathcal{W}_1=\sup_{\|f\|_L\le1}\left(\mathbb{E}_p[f]-\mathbb{E}_q[f]\right), 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 ff be differentiable almost everywhere. The definition of ff being 1-Lipschitz is

∣f(y)−f(x)∣≤∥y−x∥,∀x,y\left|f(y)-f(x)\right|\le\left\|y-x\right\|,\qquad\forall x,y

Step 2: prove that ”∥∇f∥≤1\left\|\nabla f\right\|\le1 ⇒\Rightarrow 1-Lipschitz”. Along the straight line x(t)=x+t(y−x)x(t)=x+t\left(y-x\right), by the fundamental theorem of calculus,

f(y)−f(x)=∫01∇f(x(t))⊤(y−x)dtf(y)-f(x)=\int_0^1\nabla f\left(x(t)\right)^{\top}\left(y-x\right)\mathrm{d}t

Taking absolute values and applying Cauchy-Schwarz:

∣f(y)−f(x)∣≤∫01∥∇f(x(t))∥∥y−x∥dt≤sup⁡z∥∇f(z)∥⋅∥y−x∥\left|f(y)-f(x)\right|\le\int_0^1\left\|\nabla f\left(x(t)\right)\right\|\left\|y-x\right\|\mathrm{d}t\le\sup_{z}\left\|\nabla f(z)\right\|\cdot\left\|y-x\right\|

So sup⁡z∥∇f(z)∥≤1\sup_z\left\|\nabla f(z)\right\|\le1 is enough for 1-Lipschitz.

Step 3: prove that the converse also holds (11-Lipschitz ⇒\Rightarrow ∥∇f∥≤1\left\|\nabla f\right\|\le1). Take y=x+εvy=x+\varepsilon v (vv a unit vector), then

∣f(x+εv)−f(x)∣≤ε\left|f(x+\varepsilon v)-f(x)\right|\le\varepsilon

Dividing both sides by ε\varepsilon and letting ε→0\varepsilon\to0 gives ∣∇f(x)⊤v∣≤1\left|\nabla f(x)^{\top}v\right|\le1 for every unit vector vv; taking v=∇f(x)/∥∇f(x)∥v=\nabla f(x)/\left\|\nabla f(x)\right\| gives ∥∇f(x)∥≤1\left\|\nabla f(x)\right\|\le1.

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 ∥∇f∥≤1\left\|\nabla f\right\|\le1, whose penalty should be λ E[max⁡(0,∥∇f∥−1)2]\lambda\,\mathbb{E}\left[\max\left(0,\left\|\nabla f\right\|-1\right)^2\right] (one-sided). WGAN-GP uses a two-sided square:

LGP=λ Ex^∼px^[(∥∇x^f(x^)∥−1)2]\mathcal{L}_{\text{GP}}=\lambda\,\mathbb{E}_{\hat x\sim p_{\hat x}}\left[\left(\left\|\nabla_{\hat x}f(\hat x)\right\|-1\right)^2\right]

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 ∥∇f∥<1\left\|\nabla f\right\|<1 somewhere, then ff can be “magnified” there (increasing the slope along that direction) without changing the sign constraint on Ep[f]−Eq[f]\mathbb{E}_p[f]-\mathbb{E}_q[f], thereby continuing to raise the dual objective; therefore the optimal ff necessarily pushes the gradient norm up to 1 on the region connecting the data supports. In other words, ∥∇f∥=1\left\|\nabla f\right\|=1 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 p=δap=\delta_{a}, q=δbq=\delta_{b} (a<ba<b), then W1=b−a\mathcal{W}_1=b-a. The dual problem sup⁡ff(a)−f(b)\sup_f f(a)-f(b) under the 1-Lipschitz constraint has the optimal solution f(x)=−xf(x)=-x (linear, slope −1-1), with ∥∇f∥=1\left\|\nabla f\right\|=1 everywhere. If f(x)=−12xf(x)=-\frac{1}{2}x is taken instead, the objective value is b−a2\frac{b-a}{2}, 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

x^=ϵx+(1−ϵ)y,x∼p, y∼q, ϵ∼U[0,1]\hat x=\epsilon x+\left(1-\epsilon\right)y,\qquad x\sim p,\ y\sim q,\ \epsilon\sim U[0,1]

The reason is that “the equality of the optimal 1-Lipschitz ff holds only along the paths that carry the mass of pp to qq”. Forcing ∥∇f∥=1\left\|\nabla f\right\|=1 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 x^\hat x depends on the coupling between pp and qq, and the easiest implementation is “random pairing within the same batch”, which corresponds to a particular coupling, not necessarily the optimal transport coupling between pp and qq; thus GP is only “a local approximation to the optimal ff”.

Step 7: why spectral normalization is the “hard constraint” version. Spectral Normalization (SN) replaces each layer’s linear map WW with W/σ(W)W/\sigma\left(W\right) (σ\sigma 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 ≤1\le1 (provided the intermediate activations are 1-Lipschitz, such as ReLU and LeakyReLU). The difference from GP is:

ApproachConstraint typeCostSide effect
Weight clipping (original WGAN)Hard constraint, but it clips weights rather than gradientsExtremely cheapParameters squeezed into a small range, capacity loss, gradients vanish or explode
Gradient penalty (WGAN-GP)Soft constraint, acting on interpolation pointsOne extra backward pass per stepDepends on the interpolation distribution, λ\lambda needs tuning
Spectral normalization (SN)Hard constraint, acting on each layer’s weightsOne power iteration per stepThe 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 λ\lambda 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:

TechniqueLevel it acts onImplementationSide effect
DCGAN structural constraintsArchitectureUse strided convolution instead of pooling, BatchNorm, remove fully connected layers, LeakyReLUNot enough for high resolution
Label smoothingObjectiveReal-sample labels set to 0.9 instead of 1Mitigates discriminator over-confidence
Input noiseDataAdd a small amount of Gaussian noise to DD‘s inputEquivalent to regularizing DD
One-sided smoothingObjectiveSmooth only the real-sample sideMore common than two-sided
TTUROptimizationDD‘s learning rate higher than GG‘s (e.g., 4 times)Needs tuning
Gradient penalty (WGAN-GP)ObjectiveSee the formula belowOne extra backward pass per step, slow
Spectral normalizationLayerNormalize each layer’s weights by the largest singular valueCheap to compute, constraint exact at the layer level
Exponential moving average (EMA) of generator weightsEvaluationSample with the moving-average parametersUnrelated to the training loss, purely improves the metric
Historical sample bufferObjectiveTrain DD with historical generated samplesPrevents DD from forgetting

Gradient penalty (WGAN-GP):

LD=Epg[fϕ(x)]−Epdata[fϕ(x)]+λ Ex^[(∥∇x^fϕ(x^)∥2−1)2]\mathcal{L}_D=\mathbb{E}_{p_g}\left[f_\phi(x)\right]-\mathbb{E}_{p_{\text{data}}}\left[f_\phi(x)\right]+\lambda\,\mathbb{E}_{\hat x}\left[\left(\left\|\nabla_{\hat x}f_\phi(\hat x)\right\|_2-1\right)^2\right]

where x^=ϵxreal+(1−ϵ)xfake\hat x=\epsilon x_{\text{real}}+(1-\epsilon)x_{\text{fake}}, ϵ∼U(0,1)\epsilon\sim U(0,1), 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, f′=±1f'=\pm1 means exactly this). λ\lambda is usually taken as 10.

The mechanism of spectral normalization: for each layer’s weight matrix WW, estimate its largest singular value σ(W)\sigma(W) with power iteration, then set W~=W/σ(W)\tilde W=W/\sigma(W). Because ∥W~x∥≤∥x∥\left\|\tilde W x\right\|\le\left\|x\right\|, 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 f:Rn→Rmf:\mathbb{R}^{n}\to\mathbb{R}^{m}, the Lipschitz constant is defined as

Lip(f)=sup⁡x≠y∥f(x)−f(y)∥∥x−y∥\mathrm{Lip}(f)=\sup_{x\ne y}\frac{\left\|f(x)-f(y)\right\|}{\left\|x-y\right\|}

For the linear layer x↦Wxx\mapsto Wx, this is exactly the spectral norm of the matrix:

∥W∥2=σmax⁡(W)=sup⁡x≠0∥Wx∥∥x∥\left\|W\right\|_{2}=\sigma_{\max}(W)=\sup_{x\ne0}\frac{\left\|Wx\right\|}{\left\|x\right\|}

This uses the equivalent definition of the spectral norm: ∥W∥22=λmax⁡(WTW)\left\|W\right\|_{2}^{2}=\lambda_{\max}\left(W^{T}W\right), and the square root of the largest eigenvalue of WTWW^{T}W is the largest singular value.

Step 2: the Lipschitz constant of a composition is at most the product of the layers. A network with LL layers is written

f(x)=TL∘σ∘TL−1∘⋯∘σ∘T1(x),Tl(h)=Wlh+blf(x)=T_{L}\circ\sigma\circ T_{L-1}\circ\cdots\circ\sigma\circ T_{1}(x),\qquad T_{l}(h)=W_{l}h+b_{l}

If the activation σ\sigma 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 1/41/4), then for any x,yx,y, repeatedly applying the triangle inequality gives

∥f(x)−f(y)∥≤∥WL∥2∥hL−1(x)−hL−1(y)∥≤⋯≤(∏l=1L∥Wl∥2)∥x−y∥\left\|f(x)-f(y)\right\|\le\left\|W_{L}\right\|_{2}\left\|h_{L-1}(x)-h_{L-1}(y)\right\|\le\cdots\le\left(\prod_{l=1}^{L}\left\|W_{l}\right\|_{2}\right)\left\|x-y\right\|

Hence Lip(f)≤∏lσmax⁡(Wl)\mathrm{Lip}(f)\le\prod_{l}\sigma_{\max}\left(W_{l}\right). 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

W~l=Wlσmax⁡(Wl)⟹σmax⁡(W~l)=1\tilde W_{l}=\frac{W_{l}}{\sigma_{\max}\left(W_{l}\right)}\quad\Longrightarrow\quad\sigma_{\max}\left(\tilde W_{l}\right)=1

Substituting into Step 2 gives Lip(f)≤∏l1=1\mathrm{Lip}(f)\le\prod_{l}1=1. 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 σmax⁡\sigma_{\max} is estimated at every step — power iteration. Computing σmax⁡\sigma_{\max} exactly requires a singular value decomposition, which is too expensive at every step. Power iteration keeps a vector vv and alternates

u←Wv∥Wv∥,v←WTu∥WTu∥u\leftarrow\frac{Wv}{\left\|Wv\right\|},\qquad v\leftarrow\frac{W^{T}u}{\left\|W^{T}u\right\|}

Each round updates vv to the normalized version of WTWvW^{T}Wv. Why it converges to the dominant right singular vector can be expanded: write the singular value decomposition of WW as W=∑iσiuiviTW=\sum_{i}\sigma_{i}u_{i}v_{i}^{T} and the initial value as v=∑iciviv=\sum_{i}c_{i}v_{i}; then

WTWv=∑iciσi2viW^{T}Wv=\sum_{i}c_{i}\sigma_{i}^{2}v_{i}

Every round multiplies the coefficient of component ii by σi2\sigma_{i}^{2}, so after normalization the share of component ii is ciσi2kc_{i}\sigma_{i}^{2k}, the dominant term is c1σ12kc_{1}\sigma_{1}^{2k}, and the rate is governed by the ratio

∣c2∣σ22k∣c1∣σ12k=∣c2∣∣c1∣(σ2σ1)2k\frac{\left|c_{2}\right|\sigma_{2}^{2k}}{\left|c_{1}\right|\sigma_{1}^{2k}}=\frac{\left|c_{2}\right|}{\left|c_{1}\right|}\left(\frac{\sigma_{2}}{\sigma_{1}}\right)^{2k}

When σ2/σ1\sigma_{2}/\sigma_{1} is clearly below one, a few rounds suffice. The estimator actually used is

σ^=∥WTu∥,u=Wv∥Wv∥\hat\sigma=\left\|W^{T}u\right\|,\qquad u=\frac{Wv}{\left\|Wv\right\|}

which satisfies σ^≤σmax⁡\hat\sigma\le\sigma_{\max} (because ∥WTu∥≤∥W∥2∥u∥=σmax⁡\left\|W^{T}u\right\|\le\left\|W\right\|_{2}\left\|u\right\|=\sigma_{\max}); 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 u,vu,v 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 2JSD−2log⁡22\mathrm{JSD}-2\log2, and once the support of pgp_g “aligns” with one mode of pdatap_{\text{data}}, 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 KL(pg∥pdata)\mathrm{KL}(p_g\|p_{\text{data}}) (the reverse KL, opposite in direction to the forward KL of maximum likelihood). The behavioral difference between the two is textbook-level:

  • Forward KL KL(pdata∥pg)\mathrm{KL}(p_{\text{data}}\|p_g): whenever pdatap_{\text{data}} has mass somewhere and pgp_g 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 KL(pg∥pdata)\mathrm{KL}(p_g\|p_{\text{data}}): whenever pgp_g has mass somewhere and pdatap_{\text{data}} 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, V(D⋆,G)=2JSD−2log⁡2V(D^{\star},G)=2\mathrm{JSD}-2\log2. When pgp_g and pdatap_{\text{data}} already partially overlap, of the two terms of JSD\mathrm{JSD} the gradient of KL(pg∥m)\mathrm{KL}(p_g\|m) dominates (because it acts on the support of pgp_g), which is equivalent to pulling pgp_g toward mm and then toward pdatap_{\text{data}} — 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:

TechniqueMechanismExplanation
Minibatch discriminationLet DD see the statistics of the whole batchDirectly penalizes “a batch of samples that look too much alike”
PacGANConcatenate kk samples and feed them to DDSame as above, simpler
Unrolled GANUnroll several steps of DD‘s update when updating the generatorPrevents GG from chasing DD‘s instantaneous weaknesses
AdaGAN / ensemblesTrain a generator that “fills the gaps” each roundGradually covers the modes
VEEGANAdd an “invertibility” regularizerForces the z→xz\to x map to be invertible
Change the objectiveUse W1\mathcal{W}_1, or switch to diffusion directlyReplaces 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 x∈{−1,0,+1}x\in\{-1,0,+1\} and set

p=(12, 0, 12),qθ=(ϵ, 1−2ϵ, ϵ)p=\left(\tfrac12,\ 0,\ \tfrac12\right),\qquad q_{\theta}=\left(\epsilon,\ 1-2\epsilon,\ \epsilon\right)

pp is bimodal (two modes at ±1\pm1) and qθq_{\theta} is unimodal (mass at 00, with ϵ\epsilon 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,

KL(p∥qθ)=12log⁡1/2ϵ+0⋅log⁡01−2ϵ+12log⁡1/2ϵ=log⁡12ϵ\mathrm{KL}\left(p\|q_{\theta}\right)=\frac12\log\frac{1/2}{\epsilon}+0\cdot\log\frac{0}{1-2\epsilon}+\frac12\log\frac{1/2}{\epsilon}=\log\frac{1}{2\epsilon}

with the middle term handled by the convention 0log⁡0=00\log0=0. As ϵ→0\epsilon\to0 this tends to +∞+\infty. This is the coverage pressure of forward KL: whenever pp has mass at a point where qq 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 log⁡2\log2. Reverse the direction and squeeze qθq_{\theta} onto one mode (say all mass at −1-1):

KL(q∥p)=log⁡11/2=log⁡2≈0.693\mathrm{KL}\left(q\|p\right)=\log\frac{1}{1/2}=\log2\approx0.693

Here q=(1,0,0)q=(1,0,0), pp is 1/21/2 at −1-1, and qq has zero mass at the other points, so the sum keeps a single term. If qθq_{\theta} stays at 00, then KL(qθ∥p)\mathrm{KL}\left(q_{\theta}\|p\right) diverges, because p(0)=0p(0)=0 while qθ(0)=1−2ϵ>0q_{\theta}(0)=1-2\epsilon>0. Comparing the two, the optimum of reverse KL is to put all mass on a single mode, at a finite cost of log⁡2\log2. This is the quantitative meaning of “mode-seeking”.

Step 4: the optimum in the general case. For a discrete pp and any qq,

KL(q∥p)=∑xq(x)log⁡q(x)−∑xq(x)log⁡p(x)\mathrm{KL}\left(q\|p\right)=\sum_{x}q(x)\log q(x)-\sum_{x}q(x)\log p(x)

The first term is the negative entropy −H(q)-H(q), minimized at 00 when qq is a point mass; the second is minimized when qq puts its mass where pp is largest. Weighing the two, the optimal qq under reverse KL concentrates on one local maximum of pp and does not allocate mass according to the relative heights of pp. If pp has KK modes of equal height, any one is equally good and min⁡qKL(q∥p)=log⁡K\min_{q}\mathrm{KL}\left(q\|p\right)=\log K — this log⁡K\log K is the fixed price of “dropping K−1K-1 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, p=δ−1p=\delta_{-1} and q=δ+1q=\delta_{+1}; their midpoint is m=(p+q)/2m=(p+q)/2, which puts 1/21/2 on each point. Hence

KL(p∥m)=log⁡11/2=log⁡2,KL(q∥m)=log⁡11/2=log⁡2\mathrm{KL}\left(p\|m\right)=\log\frac{1}{1/2}=\log2,\qquad \mathrm{KL}\left(q\|m\right)=\log\frac{1}{1/2}=\log2 JSD(p∥q)=12log⁡2+12log⁡2=log⁡2\mathrm{JSD}\left(p\|q\right)=\frac12\log2+\frac12\log2=\log2

As long as the two distributions do not overlap, JS is exactly log⁡2\log2, completely independent of whether they are 0.10.1 apart or 100100 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 qθq_{\theta} and pp 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:

targetoptimal qbehaviorKL(p∥q)spread over all modescovering, blurredKL(q∥p)one modemode-seekingJSDany disjoint choiceno distance signal\begin{array}{c|c|c} \text{target} & \text{optimal q} & \text{behavior}\\ \hline \mathrm{KL}(p\|q) & \text{spread over all modes} & \text{covering, blurred}\\ \mathrm{KL}(q\|p) & \text{one mode} & \text{mode-seeking}\\ \mathrm{JSD} & \text{any disjoint choice} & \text{no distance signal} \end{array}

The table also explains “why switching the objective (W1\mathcal{W}_{1}, diffusion) mitigates mode collapse”: W1\mathcal{W}_{1} 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: z∼N(0,I)z\sim\mathcal{N}(0,I), x=Gθ(z)x=G_\theta(z), 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 max⁡ϕ\max_\phi. If the inner problem is not solved well, the gradient direction the outer layer receives is wrong. ncritic=5n_{\text{critic}}=5 is the default in the WGAN-GP paper. The original GAN generally uses 1, because its max⁡\max is in the sense of “classification accuracy”, and multiple steps easily overfit to the current pgp_g and instead saturate.

Segment A ②: the position of detach. The generated sample x~=Gθ(z)x̃=G_\theta(z) must have its gradient to θ\theta cut when the critic is updated, otherwise ∇ϕLD\nabla_\phi L_D 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 x^x̂ must be differentiable. The gradient penalty takes ∇\nabla with respect to x^x̂, so x^x̂ 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 x^x̂ must use a per-sample ϵ\epsilon (shape [B,1,1,1][B,1,1,1]), 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 f′=±1f'=\pm1 attains the extreme everywhere (Step 3 of Derivation 9). Theoretically only ≤1\le1 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 min⁡θ\min_\theta, 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 θ\theta. LG=−E[fϕ(Gθ(z))]L_G=-\mathbb{E}[f_\phi(G_\theta(z))], and the gradient must pass through fϕf_\phi to GθG_\theta. So here fϕf_\phi must not have detach added, but at the optimizer level only ∇θ\nabla_\theta 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 log⁡\log. The critic outputs a real-valued score, not a probability. The objective −E[f]-\mathbb{E}[f] 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 W1\mathcal{W}_1 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 f(xi)f(x_i) depend on the whole batch’s statistics, so ∇xif\nabla_{x_i}f 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.

QuantityUpdate frequencyParticipates in gradientsKept across stepsConsequence of getting it wrong
θ\theta (generator)Once per roundYes (Segment B)KeptMixing it with ϕ\phi in one optimizer makes them interfere
ϕ\phi (critic/discriminator)ncriticn_{\text{critic}} times per roundYes (Segment A)Kept—
x~=Gθ(z)x̃=G_\theta(z)Every DD updateMust be detachedNoNot detaching contaminates ϕ\phi‘s gradient
x^x̂ (interpolation point)Every DD updateMust be differentiableNoWrapping it in no_grad makes the penalty term identically 0
ϵ\epsilon (interpolation coefficient)Every DD updateNoNoSharing within a batch degenerates the penalty into “one direction for the whole batch”
BN running statsEvery forward passNoKeptUsing BN in DD breaks the per-sample nature of the gradient penalty
Generator EMA parametersEvery stepNoKeptUsed only for evaluation; mixing them into training slows convergence
Historical sample buffer (optional)Every stepNoKeptA buffer that is too small fails to “prevent forgetting”
Fixed noise (optional, for visualization)Every few stepsNoKeptRedrawing every step makes the loss curve too noisy

Four decision principles:

  1. “Two optimizers, two sets of parameters, two zero_grad calls.” The parameters of GG and DD must never be put into the same optimizer, otherwise DD‘s update carries GG‘s momentum, and vice versa.
  2. “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.
  3. “Do not use BatchNorm in the discriminator.” Use LayerNorm / InstanceNorm / spectral normalization instead; the generator may use BN.
  4. “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

SymptomPossible causeFix
DD‘s loss rapidly goes to 0 and GG does not move at allThe discriminator is too strong, JS saturates (Derivation 8)Lower DD‘s learning rate, add noise/label smoothing, switch to WGAN-GP
The losses of GG and DD oscillate violently at the same timeLearning rate too high, ncriticn_{\text{critic}} mismatchedLower the learning rate, TTUR (DD fast, GG slow)
Generated samples are highly repetitiveMode collapse (reverse KL)PacGAN / minibatch discriminator, switch to W1\mathcal{W}_1
Only some classes appearClass imbalance + reverse KLConditional GAN, resampling, class-aware loss
FID suddenly collapses and then recoversThe discriminator falls into a local optimumHistorical buffer, EMA, gradient penalty
The gradient penalty term is identically 0x^x̂ is not in the computation graphTurn on requires_grad
Training looks normal but the sampled images are all noiseThe generator’s last layer uses sigmoid while the data are in [−1,1][-1,1]Align the data normalization range (tanh for [−1,1][-1,1])
Training with BN in DD is unstableThe gradient penalty conflicts with BNUse LayerNorm / spectral normalization in DD
It simply will not train after switching datasetsThe architecture is sensitive to resolutionChange 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 O(1)O(1) or O(D)O(D).

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 fθ:RD→RDf_\theta:\mathbb{R}^D\to\mathbb{R}^D be a bijection (a one-to-one invertible mapping), let z∼pZ(z)z\sim p_Z(z) (usually a standard Gaussian), and let x=fθ(z)x=f_\theta(z). Then the density of xx is

pX(x)=pZ(z)∣det⁡Jf(z)∣−1,z=fθ−1(x)p_X(x)=p_Z(z)\left|\det J_{f}\left(z\right)\right|^{-1},\qquad z=f_\theta^{-1}(x)

Taking the logarithm:

log⁡pX(x)=log⁡pZ(z)−log⁡∣det⁡∂fθ(z)∂z∣\log p_X(x)=\log p_Z(z)-\log\left|\det \frac{\partial f_\theta(z)}{\partial z}\right|

Note that the first term on the right depends only on zz (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 x=f(z)x=f(z) be strictly monotonically increasing, and let FX,FZF_X,F_Z be the cumulative distribution functions. Because ff is monotone,

FX(x)=P(X≤x)=P(f(Z)≤x)=P(Z≤f−1(x))=FZ(f−1(x))F_X(x)=P\left(X\le x\right)=P\left(f(Z)\le x\right)=P\left(Z\le f^{-1}(x)\right)=F_Z\left(f^{-1}(x)\right)

Differentiate both sides with respect to xx and use the chain rule (writing z=f−1(x)z=f^{-1}(x)):

pX(x)=pZ(z)dzdx=pZ(z)1f′(z)p_X(x)=p_Z(z)\frac{\mathrm{d}z}{\mathrm{d}x}=p_Z(z)\frac{1}{f'(z)}

If ff is monotonically decreasing, then dz/dx<0\mathrm{d}z/\mathrm{d}x<0; a density must be positive, so we take the absolute value: pX(x)=pZ(z)/∣f′(z)∣p_X(x)=p_Z(z)/\left|f'(z)\right|. This is the one-dimensional change of variables.

Step 2: The high-dimensional case (derived from “conservation of probability mass”). Take any measurable set AA and let B=f−1(A)B=f^{-1}(A) (that is, all zz that map into AA). Because ff is a bijection, the events {X∈A}\{X\in A\} and {Z∈B}\{Z\in B\} are the same event:

∫ApX(x) dx=P(X∈A)=P(Z∈B)=∫BpZ(z) dz\int_A p_X(x)\,\mathrm{d}x=P\left(X\in A\right)=P\left(Z\in B\right)=\int_B p_Z(z)\,\mathrm{d}z

Step 3: Substitute inside the right-hand integral. Let z=f−1(x)z=f^{-1}(x) and change the integration variable from zz to xx. The multivariate substitution formula gives

∫BpZ(z) dz=∫ApZ(f−1(x))∣det⁡∂f−1(x)∂x∣dx\int_B p_Z(z)\,\mathrm{d}z=\int_A p_Z\left(f^{-1}(x)\right)\left|\det \frac{\partial f^{-1}(x)}{\partial x}\right|\mathrm{d}x

Step 4: Compare the integrands. The identity above holds for every AA, so the integrands are equal almost everywhere:

pX(x)=pZ(f−1(x))∣det⁡Jf−1(x)∣p_X(x)=p_Z\left(f^{-1}(x)\right)\left|\det J_{f^{-1}}(x)\right|

Step 5: Replace the determinant of the inverse map by that of the original map. By the inverse function theorem, Jf−1(x)=[Jf(z)]−1J_{f^{-1}}(x)=\left[J_f(z)\right]^{-1}, so taking determinants gives det⁡Jf−1(x)=1/det⁡Jf(z)\det J_{f^{-1}}(x)=1/\det J_f(z), and after taking absolute values:

∣det⁡Jf−1(x)∣=1∣det⁡Jf(z)∣\left|\det J_{f^{-1}}(x)\right|=\frac{1}{\left|\det J_f(z)\right|}

Substituting back yields the formula in the main text.

Step 6: Geometric interpretation (why it is a determinant). Consider a small hypercube of side Δ\Delta around zz, with volume ΔD\Delta^D. The map ff carries it onto a parallelepiped whose volume equals ∣det⁡Jf(z)∣ΔD\left|\det J_f(z)\right|\Delta^D. The probability mass on the two regions is the same number, so

pX(x)⋅∣det⁡Jf∣ΔD≈pZ(z)⋅ΔDp_X(x)\cdot\left|\det J_f\right|\Delta^D\approx p_Z(z)\cdot\Delta^D

Canceling ΔD\Delta^D 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 (DD to DD), so a flow cannot perform dimensionality reduction — this differs from VAE (D→dD\to d) and from GAN (d→Dd\to D). 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 ff is both expressive and cheap in log⁡∣det⁡J∣\log\left|\det J\right|?

Using a free-form neural network directly does not work: computing a D×DD\times D determinant costs O(D3)O(D^3), and for images D=196608D=196608, which is entirely infeasible. So ff 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 (O(D)O(D)).

Two families:

| Family | Structure | log⁡∣det⁡J∣\log\left|\det J\right| | 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 | ∑isi(x1)\sum_i s_i(x_1) | Explicit, O(D)O(D) | RealNVP, Glow | | Autoregressive flow | Dimension ii is determined by dimensions 1,…,i−11,\dots,i-1 | ∑isi(x<i)\sum_i s_i(x_{<i}) | 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 O(D)O(D)), whereas an autoregressive flow is fast in the forward direction (computing the likelihood) and slow in the inverse direction (sampling, which requires DD sequential steps), or vice versa (IAF). This asymmetry is the key consideration when choosing between them.

4.4 Affine Coupling Layer

Split xx into x1x_1 (the first dd dimensions) and x2x_2 (the remaining D−dD-d dimensions), and define

y1=x1,y2=exp⁡(sθ(x1))⊙x2+tθ(x1)y_1=x_1,\qquad y_2=\exp\left(s_\theta(x_1)\right)\odot x_2+t_\theta(x_1)

where sθ,tθs_\theta,t_\theta are arbitrary neural networks (no invertibility and no special constraint required) whose inputs are only x1x_1. The inverse transform is

x1=y1,x2=exp⁡(−sθ(y1))⊙(y2−tθ(y1))x_1=y_1,\qquad x_2=\exp\left(-s_\theta(y_1)\right)\odot\left(y_2-t_\theta(y_1)\right)

The elegance of this design: the expressiveness is placed inside s,ts,t, while invertibility is guaranteed by “leaving x1x_1 untouched”. The functions s,ts,t 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 y=(y1,y2)y=(y_1,y_2) with respect to x=(x1,x2)x=(x_1,x_2) and write it block by block:

J=∂y∂x=[∂y1∂x1∂y1∂x2∂y2∂x1∂y2∂x2]J=\frac{\partial y}{\partial x}= \begin{bmatrix} \dfrac{\partial y_1}{\partial x_1} & \dfrac{\partial y_1}{\partial x_2}\\ \dfrac{\partial y_2}{\partial x_1} & \dfrac{\partial y_2}{\partial x_2} \end{bmatrix}

Step 2: Compute block by block.

  • y1=x1y_1=x_1, so ∂y1∂x1=Id\dfrac{\partial y_1}{\partial x_1}=I_d and ∂y1∂x2=0\dfrac{\partial y_1}{\partial x_2}=0;
  • y2=exp⁡(s)⊙x2+ty_2=\exp(s)\odot x_2+t, so the partial derivative with respect to x2x_2 is ∂y2∂x2=diag⁡(exp⁡(s))\dfrac{\partial y_2}{\partial x_2}=\operatorname{diag}\left(\exp(s)\right) (because s,ts,t do not depend on x2x_2);
  • the partial derivative with respect to x1x_1 is more complicated: ∂y2∂x1=diag⁡(exp⁡(s)⊙x2)∂s∂x1+∂t∂x1\dfrac{\partial y_2}{\partial x_1}=\operatorname{diag}\left(\exp(s)\odot x_2\right)\dfrac{\partial s}{\partial x_1}+\dfrac{\partial t}{\partial x_1}, 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,

det⁡J=det⁡Id⋅det⁡diag⁡(exp⁡(s))=∏iexp⁡(si)=exp⁡(∑isi)\det J=\det I_d\cdot\det\operatorname{diag}\left(\exp(s)\right)=\prod_{i}\exp(s_i)=\exp\left(\sum_i s_i\right)

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.

log⁡∣det⁡J∣=∑isi\log\left|\det J\right|=\sum_i s_i

Step 5: Check “why the upper-right block must be zero”. If y1y_1 depended on x2x_2, the upper-right block would be nonzero, the determinant would no longer be ∏exp⁡(si)\prod\exp(s_i), and one would have to compute a D×DD\times D 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 ∂y2/∂x1\partial y_2/\partial x_1? We do not. The likelihood uses only log⁡∣det⁡J∣\log\left|\det J\right|, which depends only on the diagonal blocks. The terms ∂s/∂x1\partial s/\partial x_1 and ∂t/∂x1\partial t/\partial x_1 only affect the values of s,ts,t 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 y1=x1y_1=x_1 gives x1x_1; then y2=exp⁡(s)⊙x2+ty_2=\exp(s)\odot x_2+t gives x2=exp⁡(−s)⊙(y2−t)x_2=\exp(-s)\odot(y_2-t). The whole procedure only needs the values of s,ts,t at y1y_1; 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 log⁡∣det⁡J∣=∑isi\log\left|\det J\right|=\sum_i s_i”. 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 (y=f(x)y=f(x), with s,ts,t taking the copied half x1x_1 as input):

y1=x1,y2=exp⁡(s(x1))⊙x2+t(x1)y_1=x_1,\qquad y_2=\exp\left(s\left(x_1\right)\right)\odot x_2+t\left(x_1\right)

where s,ts,t are arbitrary functions (they need not be invertible) and ⊙\odot is elementwise multiplication. The inverse transform only has to solve the equation above for x2x_2:

x1=y1,x2=(y2−t(y1))⊙exp⁡(−s(y1))x_1=y_1,\qquad x_2=\left(y_2-t\left(y_1\right)\right)\odot\exp\left(-s\left(y_1\right)\right)

Note that the inverse of ss or tt 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 ss and tt 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:

Jf=[I0∂y2/∂x1diag⁡(exp⁡s)]J_f= \begin{bmatrix} I & 0\\ \partial y_2/\partial x_1 & \operatorname{diag}\left(\exp s\right) \end{bmatrix}

The Jacobian of the inverse transform, obtained by differentiating with respect to yy, is likewise lower triangular:

Jf−1=[I0∂x2/∂y1diag⁡(exp⁡(−s))]J_{f^{-1}}= \begin{bmatrix} I & 0\\ \partial x_2/\partial y_1 & \operatorname{diag}\left(\exp\left(-s\right)\right) \end{bmatrix}

The determinants of both matrices equal the product of the diagonal blocks:

det⁡Jf=∏iesi,det⁡Jf−1=∏ie−si=1det⁡Jf\det J_f=\prod_i e^{s_i},\qquad \det J_{f^{-1}}=\prod_i e^{-s_i}=\frac{1}{\det J_f}

Therefore

log⁡∣det⁡Jf−1∣=−∑isi=−log⁡∣det⁡Jf∣\log\left|\det J_{f^{-1}}\right|=-\sum_i s_i=-\log\left|\det J_f\right|

This identity says: both the forward and the inverse direction of the same layer cost only O(D)O(D) (one elementwise sum), and one never actually computes a D×DD\times D 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 ∑si\sum s_i. The density formula contains ∑isi=log⁡∣det⁡Jf∣\sum_i s_i=\log\left|\det J_f\right|, not ∏iesi\prod_i e^{s_i}. This means that what really needs to be controlled is the magnitude of ∑si\sum s_i, not the magnitude of each individual sis_i: even if every sis_i is only 0.5, with D=1024D=1024 we get ∑si=512\sum s_i=512 and the exponential has long since overflowed. Two common treatments:

  • squash ss through a bounded function (for example tanh multiplied by a scale) into [−a,a][-a,a], so that ∣∑si∣≤aD|\sum s_i|\le aD is controllable;
  • accumulate ∑si\sum s_i in the log domain throughout (logsumexp style) and exponentiate only at the very end — this is also the origin of the implementation rule “never compute ∏esi\prod e^{s_i} first and then take the log”.

Step 4: The Jacobian of an autoregressive flow. A Masked Autoregressive Flow (MAF) is defined as

xi=μi(x<i)+exp⁡(si(x<i))zi,i=1,…,Dx_i=\mu_i\left(x_{<i}\right)+\exp\left(s_i\left(x_{<i}\right)\right)z_i,\qquad i=1,\dots,D

where x<i=(x1,…,xi−1)x_{<i}=\left(x_1,\dots,x_{i-1}\right). Differentiating the Jacobian entry by entry:

∂xi∂zj={0,j>iexp⁡(si),j=i(nonzero),j<i\frac{\partial x_i}{\partial z_j}= \begin{cases} 0, & j>i\\ \exp\left(s_i\right), & j=i\\ \text{(nonzero)}, & j<i \end{cases}

Because xix_i depends only on x<ix_{<i}, and x<ix_{<i} depends only on z<iz_{<i}, the derivative must vanish for j>ij>i. So JJ is lower triangular, and its determinant is the product of the diagonal entries:

log⁡∣det⁡J∣=∑i=1Dsi(x<i)\log\left|\det J\right|=\sum_{i=1}^{D}s_i\left(x_{<i}\right)

Step 5: The cost asymmetry between MAF and IAF. The formula above requires sis_i to take x<ix_{<i} as input, that is, “compute the parameters from the data”. This introduces an asymmetry between the two directions:

DirectionMAF (xi=μi(x<i)+exp⁡(si(x<i))zix_i=\mu_i(x_{<i})+\exp(s_i(x_{<i}))z_i)IAF (zi=μi(z<i)+exp⁡(si(z<i))xiz_i=\mu_i(z_{<i})+\exp(s_i(z_{<i}))x_i, that is, the forward direction is defined on zz)
Computing the density (the forward direction z→xz\to x)One parallel forward pass (the μi,si\mu_i,s_i for all ii can be computed simultaneously)Requires DD sequential forward passes
Sampling (the inverse direction x→zx\to z)Requires DD sequential forward passesOne parallel forward pass
Typical useDensity 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 ∑si\sum s_i), and the only difference is whether the parameters depend on x<ix_{<i} or on z<iz_{<i}, 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 O(D)O(D)” — 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 O(D3)O(D^3) determinant.

4.5 Glow’s Invertible 1×11\times1 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 1×11\times1 convolution” to fill this hole: it performs one linear mixing along the channel dimension, so that any channel can influence any other channel.

y=Wxy=W x

where WW is a C×CC\times C matrix (CC 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 h×w×Ch\times w\times C and be flattened into a vector of D=hwCD=hwC dimensions. The 1×11\times1 convolution applies the same WW at every pixel location, so the Jacobian is a block-diagonal matrix made of hwhw copies of WW:

J=blockdiag⁡(W,W,…,W)J=\operatorname{blockdiag}\left(W,W,\ldots,W\right)

Step 2: The determinant of a block-diagonal matrix.

det⁡J=(det⁡W)hw ⟹ log⁡∣det⁡J∣=hwlog⁡∣det⁡W∣\det J=\left(\det W\right)^{hw}\ \Longrightarrow\ \log\left|\det J\right|=hw\log\left|\det W\right|

Step 3: The cost of computing det⁡W\det W directly. The naive approach is an O(C3)O(C^3) LU decomposition at every forward pass. With C=512C=512 this is 1.3×1081.3\times10^8 operations, and it would have to be recomputed after every parameter update — too expensive. Glow’s solution is to parameterize WW in LU form:

W=P L(U+diag⁡(s))W=P\,L\left(U+\operatorname{diag}(s)\right)

where PP is a fixed random permutation matrix (constant during training), LL is strictly lower triangular with unit diagonal, UU is strictly upper triangular, and ss 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:

det⁡W=det⁡P⋅det⁡L⋅det⁡(U+diag⁡(s))=(±1)⋅1⋅∏isi\det W=\det P\cdot\det L\cdot\det\left(U+\operatorname{diag}(s)\right)=\left(\pm1\right)\cdot1\cdot\prod_i s_i

det⁡L=1\det L=1 because LL is unit lower triangular (all diagonal entries are 1, and the determinant equals the product of the diagonal entries). Hence

log⁡∣det⁡W∣=∑ilog⁡∣si∣\log\left|\det W\right|=\sum_i\log\left|s_i\right|

Step 5: The inverse transform. With the LU decomposition of WW already available, solving Wx=yWx=y requires only two triangular back-substitutions (O(C2)O(C^2)) and no matrix inverse. This is the key to bringing both “the determinant” and “the inverse” down to O(C2)O(C^2).

Step 6: Why a fixed PP is needed. Without the permutation matrix, the product L(U+diag⁡(s))L\left(U+\operatorname{diag}(s)\right) easily becomes numerically ill-conditioned, in the sense that “diagonal dominance disappears” (the determinant approaches 0, or some sis_i 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 1×11\times1 convolution mixes “all channels”; alternating the two builds the basic Glow block: ActNorm (per-channel affine transform, for numerical stability) → invertible 1×11\times1 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 KK invertible transforms”. A continuous normalizing flow (CNF) pushes this to the limit: infinitely many layers, described by an ordinary differential equation (ODE).

dz(t)dt=fθ(z(t),t),z(0)=z0,z(1)=x\frac{\mathrm{d}z(t)}{\mathrm{d}t}=f_\theta\left(z(t),t\right),\qquad z(0)=z_0,\quad z(1)=x

Now the likelihood no longer relies on “accumulating log⁡∣det⁡J∣\log\left|\det J\right| layer by layer” but on an integral:

log⁡pX(x)=log⁡pZ(z0)−∫01tr⁡(∂fθ(z(t),t)∂z(t))dt\log p_X(x)=\log p_Z(z_0)-\int_{0}^{1}\operatorname{tr}\left(\frac{\partial f_\theta\left(z(t),t\right)}{\partial z(t)}\right)\mathrm{d}t

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 p(z,t)p(z,t) be the probability density at time tt and f(z,t)f(z,t) the velocity field. Conservation of probability mass requires

∂p∂t+∇⋅(pf)=0\frac{\partial p}{\partial t}+\nabla\cdot\left(p f\right)=0

This is the continuity equation from fluid mechanics; here it expresses that “probability is neither created nor destroyed”.

Step 2: Expand it.

∂p∂t=−∇⋅(pf)=−p ∇⋅f−f⋅∇p\frac{\partial p}{\partial t}=-\nabla\cdot\left(pf\right)=-p\,\nabla\cdot f-f\cdot\nabla p

Step 3: Compute “the rate of change of the log-density along a trajectory”. Consider a point z(t)z(t) that follows the flow; its total derivative with respect to time is

dp(z(t),t)dt=∂p∂t+f⋅∇p\frac{\mathrm{d}p\left(z(t),t\right)}{\mathrm{d}t}=\frac{\partial p}{\partial t}+f\cdot\nabla p

Substituting the result of Step 2:

dpdt=−p ∇⋅f\frac{\mathrm{d}p}{\mathrm{d}t}=-p\,\nabla\cdot f

Step 4: Divide by pp to obtain the rate of change of the log-density.

dlog⁡p(z(t),t)dt=−∇⋅f(z(t),t)=−tr⁡(∂f∂z)\frac{\mathrm{d}\log p\left(z(t),t\right)}{\mathrm{d}t}=-\nabla\cdot f\left(z(t),t\right)=-\operatorname{tr}\left(\frac{\partial f}{\partial z}\right)

Here we used “the divergence equals the trace of the Jacobian”: ∇⋅f=∑i∂fi/∂zi=tr⁡(∂f/∂z)\nabla\cdot f=\sum_i\partial f_i/\partial z_i=\operatorname{tr}\left(\partial f/\partial z\right).

Step 5: Integrate from t=0t=0 to t=1t=1.

log⁡pX(x)=log⁡pZ(z0)−∫01tr⁡(∂f∂z(z(t),t))dt\log p_X(x)=\log p_Z(z_0)-\int_{0}^{1}\operatorname{tr}\left(\frac{\partial f}{\partial z}\left(z(t),t\right)\right)\mathrm{d}t

This is the formula in the main text. It corresponds exactly to the discrete-flow expression log⁡pZ−∑log⁡∣det⁡Jk∣\log p_Z-\sum\log\left|\det J_k\right|: the sum becomes an integral, and per-layer determinants become instantaneous traces.

Step 6: Why the trace can be estimated cheaply. For a DD-dimensional ff, computing the trace exactly requires DD backward passes (each computing one diagonal entry ∂fi/∂z\partial f_i/\partial z), at a cost of O(D2)O(D^2). The Hutchinson estimator uses a random probe vector ε\varepsilon:

tr⁡(A)=Eε[ε⊤Aε]\operatorname{tr}(A)=\mathbb{E}_{\varepsilon}\left[\varepsilon^{\top}A\varepsilon\right]

Step 7: Verify this identity. Let E[εε⊤]=I\mathbb{E}\left[\varepsilon\varepsilon^{\top}\right]=I (take ε\varepsilon to be a random vector with independent, zero-mean, unit-variance components, such as Rademacher or standard Gaussian). Then

E[ε⊤Aε]=E[tr⁡(Aεε⊤)]=tr⁡(A E[εε⊤])=tr⁡(A)\mathbb{E}\left[\varepsilon^{\top}A\varepsilon\right]=\mathbb{E}\left[\operatorname{tr}\left(A\varepsilon\varepsilon^{\top}\right)\right]=\operatorname{tr}\left(A\,\mathbb{E}\left[\varepsilon\varepsilon^{\top}\right]\right)=\operatorname{tr}(A)

The second equality uses “a scalar can be written as a trace”, ε⊤Aε=tr⁡(ε⊤Aε)=tr⁡(Aεε⊤)\varepsilon^{\top}A\varepsilon=\operatorname{tr}\left(\varepsilon^{\top}A\varepsilon\right)=\operatorname{tr}\left(A\varepsilon\varepsilon^{\top}\right), and the third uses that the expectation and the trace can be exchanged.

Step 8: One backward pass suffices. The quantity ε⊤Aε=ε⊤(∂f/∂z)ε\varepsilon^{\top}A\varepsilon=\varepsilon^{\top}\left(\partial f/\partial z\right)\varepsilon can be written as ε⋅[(∂f/∂z)ε]\varepsilon\cdot\left[\left(\partial f/\partial z\right)\varepsilon\right], where (∂f/∂z)ε\left(\partial f/\partial z\right)\varepsilon is a vector-Jacobian product (VJP) that one backward pass computes at a cost of O(D)O(D). So the whole trace estimate costs one backward pass, which is an order of magnitude cheaper than the DD 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, Φ1:z0↦z(1)\Phi_1:z_0\mapsto z(1), is a bijection provided that ff satisfies a Lipschitz condition in zz (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 xx and integrate back to z0z_0 with −f-f 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:

xcont=x+u256,u∼U[0,1)x_{\text{cont}}=x+\frac{u}{256},\qquad u\sim U[0,1)

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 log⁡256\log 256 for the unit conversion, yielding bits per dimension (bpd):

bpd=−log⁡pX(x)Dlog⁡2+log⁡2256\mathrm{bpd}=\frac{-\log p_X(x)}{D\log 2}+\log_2 256

(2) Multiscale structure. On high-resolution images DD 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 pXp_X sometimes yields samples that are “too typical” (close to the training-set average). One can anneal with pXαp_X^{\alpha} (α<1\alpha<1), 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 d≪Dd\ll D 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 +log⁡2256+\log_2 256 actually comes from. This subsection derives both.

Step 1: The correct relation between discrete probabilities and continuous densities. Let each pixel take values 0,…,2550,\dots,255. View the value xx as a “cell” of side 1/2561/256:

cell(x)=∏j=1D[xj256, xj+1256),V=(1256)D\mathrm{cell}(x)=\prod_{j=1}^{D}\left[\frac{x_j}{256},\ \frac{x_j+1}{256}\right),\qquad V=\left(\frac{1}{256}\right)^{D}

The relation between a continuous density pp and a discrete probability PP is defined by “integrating over the cell”:

P(x)=∫cell(x)p(x′)dx′P(x)=\int_{\mathrm{cell}(x)}p\left(x'\right)\mathrm{d}x'

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 u∼U(cell(x))u\sim U\left(\mathrm{cell}(x)\right) on the cell; its density is 1/V1/V, so

P(x)=∫cell(x)p(x′)dx′=V Eu[p(x+u)]P(x)=\int_{\mathrm{cell}(x)}p\left(x'\right)\mathrm{d}x'=V\,\mathbb{E}_{u}\left[p\left(x+u\right)\right]

Because log⁡\log is concave,

log⁡P(x)=log⁡V+log⁡Eu[p(x+u)] ≥ log⁡V+Eu[log⁡p(x+u)]\log P(x)=\log V+\log\mathbb{E}_u\left[p\left(x+u\right)\right]\ \ge\ \log V+\mathbb{E}_u\left[\log p\left(x+u\right)\right]

Substituting log⁡V=−Dlog⁡256\log V=-D\log 256:

log⁡P(x) ≥ Eu[log⁡p(x+u)]−Dlog⁡256\log P(x)\ \ge\ \mathbb{E}_u\left[\log p\left(x+u\right)\right]-D\log 256

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 log⁡P\log P, hence an upper bound on −log⁡P-\log P:

−log⁡P(x) ≤ −Eu[log⁡p(x+u)]+Dlog⁡256-\log P(x)\ \le\ -\mathbb{E}_u\left[\log p\left(x+u\right)\right]+D\log 256

Dividing both sides by Dlog⁡2D\log2:

bpddisc ≤ −Eu[log⁡p(x+u)]Dlog⁡2+log⁡256log⁡2\mathrm{bpd}_{\text{disc}}\ \le\ \frac{-\mathbb{E}_u\left[\log p\left(x+u\right)\right]}{D\log 2}+\frac{\log 256}{\log 2}

And log⁡256/log⁡2=log⁡2256=8\log 256/\log2=\log_2 256=8. This is the origin of +log⁡2256+\log_2 256 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 pp is constant on every cell. The more violently pp 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 1/2561/256) the variation is tiny and the gap is typically on the order of 0.010.01 bpd;
  • low resolution, strong texture, or insufficient training (pp develops spikes): the gap can exceed 0.10.1 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 p(x)p(x) is evaluated at the point xx, maximum likelihood rewards solutions that “pile the density into spikes”: the model can make pp extremely high at every discrete point of the training set and extremely low elsewhere, pushing log⁡p(x)\log p(x) arbitrarily high while P(x)P(x) does not improve at all. Mathematically this shows up as ”pp converging to a sum of δ\delta functions” — the density has no upper bound, the likelihood is infinite, but the samples are nothing but memorized training examples.

The role of dequantization (x+u/256x+u/256) is exactly to force pp to be smooth on every cell: the model can no longer profit from “piling a spike on a single point”, because x+ux+u 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 log⁡p(x)\log p(x) with Eu[log⁡p]\mathbb{E}_u[\log p]”, 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 [0,1][0,1] and uses a Gaussian likelihood, it models a continuous density, and reporting the likelihood likewise requires the unit conversion between −log⁡P-\log P and −log⁡p-\log p (the same equivalent of subtracting Dlog⁡256D\log 256). The LsimpleL_{\text{simple}} 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 sk,tks_k,t_k. 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 s,ts,t (because the input of s,ts,t is y1y_1, which is the same quantity as x1x_1 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 dd dimensions, those first dd 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, ∑jsj\sum_j s_j. 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 log⁡\log), and training tends to “pile the density on the discrete points”, learning a degenerate distribution.

⑥ Sampling is one inverse transform over O(K)O(K) 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

QuantityWhen readWhen writtenKept across stepsConsequence of getting it wrong
x1x_1 (the copied half)Every layerEvery layerNoModifying it breaks invertibility and the determinant
s,ts,tEvery layerEvery layer (computed by the network)No (recomputed in the inverse)Caching the forward s,ts,t while the input does not match makes the inverse transform wrong
log⁡det⁡\log\det accumulatorEvery layerAccumulated every layerKept within a sampleForgetting to accumulate turns the likelihood into “the likelihood of the last layer only”
Split maskEvery layerFixedKept (fixed)The same mask at every layer leaves some dimensions never transformed
θ\theta (parameters of s,ts,t)Every stepEvery stepKept—
ActNorm mean/varianceEvery forward passFixed after initialization at the first forward passKeptRe-estimating every step breaks invertibility (the inverse uses different statistics)
WW of the 1×11\times1 convolution (LU parameters)Every layerEvery stepKeptRe-randomizing every step prevents training from accumulating
Temperature α\alpha (at sampling time)At sampling timePer scheduleKeptUsing a temperature during training changes the objective

Three decision principles:

  1. “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.
  2. “The determinant can only accumulate scalars.” As soon as a D×DD\times D matrix appears in the code, the architecture design is wrong.
  3. “Recompute in the inverse, do not cache.” Except in memory-optimization scenarios, do not reuse the forward s,ts,t inside the inverse transform.

4.11 Pitfall List

SymptomPossible causeFix
The likelihood is NaN or −∞-\inftyDequantization was forgotten; or a 0 appears inside $\log\left\det\right
The training loss decreases but the samples are pure noiseThe split mask is identical at every layer, so some dimensions are never transformedAlternate the splits
The inverse transform does not match the forwardThe inverse used the wrong s,ts,t inputsThe inverse must recompute with y1y_1
The likelihood suddenly becomes a large positive numberThe sign of logdet is flipped (it should be −log⁡det⁡-\log\det)Check log⁡pX=log⁡pZ−log⁡det⁡\log p_X=\log p_Z-\log\det
Checkerboard artifacts appear at the image edgesThe split is not aligned with the spatial structureSplit by channel, or use a spatial checkerboard mask
Training is extremely slowEvery layer computes the full D×DD\times D JacobianSwitch to a triangular structure
Out of memory at high resolutionNo multiscale freezingAdd squeeze plus frozen branches
Sampling diversity is poorImproper temperature or wrong prior varianceCheck that pZp_Z 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 x↔zx\leftrightarrow z 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 256256 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.

ModelHard flawMathematical root
VAEThe posterior must be approximated by a unimodal diagonal Gaussian, while the true posterior is often multimodalThe variational family is too narrow, and the ELBO gap comes mainly from the approximation error (Derivation 3)
GANOnce the discriminator saturates, the generator’s gradient is zeroThe JS divergence is constant when the supports do not intersect (Derivation 8)
Normalizing flowIt must be an equal-dimensional bijection with a computable Jacobian, so the structure is restrictedThe change of variables formula requires det⁡J\det J 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:

  1. The supervision signal of each step is known. The forward noising process is a Markov chain that we define ourselves, so q(xt−1∣xt,x0)q(x_{t-1}\mid x_t,x_0) has a closed-form solution (Derivation 15) and can serve directly as the “teacher”; no discriminator and no adversarial game are needed.
  2. The two distributions of each step overlap strongly. The KL between the marginal distributions of adjacent times, q(xt−1)q(x_{t-1}) and q(xt)q(x_t), 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.
  3. 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 ∇xlog⁡qt(x)\nabla_x\log q_t(x), 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:

q(xt∣xt−1)=N(xt;1−βt xt−1, βtI)q(x_t\mid x_{t-1})=\mathcal{N}\left(x_t;\sqrt{1-\beta_t}\,x_{t-1},\ \beta_t I\right)

The equivalent reparameterized form is

xt=1−βt xt−1+βt εt−1,εt−1∼N(0,I)x_t=\sqrt{1-\beta_t}\,x_{t-1}+\sqrt{\beta_t}\,\varepsilon_{t-1},\qquad \varepsilon_{t-1}\sim\mathcal{N}(0,I)

where βt∈(0,1)\beta_t\in(0,1) is the noise variance of step tt, conventionally written as αt=1−βt\alpha_t=1-\beta_t and αˉt=∏s=1tαs\bar\alpha_t=\prod_{s=1}^{t}\alpha_s.

The reverse process is the part to be learned; it progressively restores noise into data:

pθ(xt−1∣xt)=N(xt−1;μθ(xt,t), Σθ(xt,t))p_\theta(x_{t-1}\mid x_t)=\mathcal{N}\left(x_{t-1};\mu_\theta(x_t,t),\ \Sigma_\theta(x_t,t)\right)

In practice Σθ=σt2I\Sigma_\theta=\sigma_t^2 I is almost always fixed and only the network predicts the mean μθ\mu_\theta (or, equivalently, the noise, the clean sample, or the score; Section 5.5 explains that these four parameterizations are equivalent).

ItemForward qqReverse pθp_\theta
Contains parametersNo, fully determined by {βt}\{\beta_t\}Yes, parameterized by a neural network
DirectionData → noise (entropy increase)Noise → data (entropy decrease)
Role in trainingProvides the supervision signal (the “teacher”)The object being trained (the “student”)
Role in samplingDoes not appearThe only part that is called
Known closed formsBoth q(xt∣x0)q(x_t\mid x_0) and q(xt−1∣xt,x0)q(x_{t-1}\mid x_t,x_0) have oneNone, except for t=1t=1

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 x0x_0” 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 tt noising steps to obtain xtx_t, the cost would be O(t)O(t) 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,

xt=αt xt−1+βt εt−1,αt=1−βtx_t=\sqrt{\alpha_t}\,x_{t-1}+\sqrt{\beta_t}\,\varepsilon_{t-1},\qquad \alpha_t=1-\beta_t

If the distribution of xt−1x_{t-1} is known to be N(μt−1,σt−12I)\mathcal{N}(\mu_{t-1},\sigma_{t-1}^2 I), then xtx_t is a linear combination of two independent Gaussians (xt−1x_{t-1} and εt−1\varepsilon_{t-1}), hence still Gaussian, with mean and covariance

E[xt]=αt μt−1,Cov[xt]=αtσt−12I+βtI\mathbb{E}[x_t]=\sqrt{\alpha_t}\,\mu_{t-1},\qquad \mathrm{Cov}[x_t]=\alpha_t\sigma_{t-1}^2 I+\beta_t I

Step 2: Establish the induction base at t=1t=1. x0x_0 is a deterministic observation (treated as a degenerate Gaussian with zero variance), so

q(x1∣x0)=N(α1x0, β1I)=N(αˉ1x0, (1−αˉ1)I)q(x_1\mid x_0)=\mathcal{N}\left(\sqrt{\alpha_1}x_0,\ \beta_1 I\right) =\mathcal{N}\left(\sqrt{\bar\alpha_1}x_0,\ \left(1-\bar\alpha_1\right)I\right)

where the last equality used β1=1−α1=1−αˉ1\beta_1=1-\alpha_1=1-\bar\alpha_1.

Step 3: Assume it holds for t−1t-1 and advance one step.

xt−1=αˉt−1 x0+1−αˉt−1 ε′,ε′∼N(0,I)x_{t-1}=\sqrt{\bar\alpha_{t-1}}\,x_0+\sqrt{1-\bar\alpha_{t-1}}\,\varepsilon',\qquad \varepsilon'\sim\mathcal{N}(0,I)

Substituting into the single-step formula:

xt=αt(αˉt−1x0+1−αˉt−1 ε′)+βt εx_t=\sqrt{\alpha_t}\left(\sqrt{\bar\alpha_{t-1}}x_0+\sqrt{1-\bar\alpha_{t-1}}\,\varepsilon'\right)+\sqrt{\beta_t}\,\varepsilon =αtαˉt−1⏟=αˉt x0+αt(1−αˉt−1) ε′+βt ε⏟two independent zero-mean Gaussians=\underbrace{\sqrt{\alpha_t\bar\alpha_{t-1}}}_{=\sqrt{\bar\alpha_t}}\,x_0+\underbrace{\sqrt{\alpha_t\left(1-\bar\alpha_{t-1}\right)}\,\varepsilon'+\sqrt{\beta_t}\,\varepsilon}_{\text{two independent zero-mean Gaussians}}

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:

αt(1−αˉt−1)+βt=αt−αtαˉt−1+1−αt=1−αtαˉt−1=1−αˉt\alpha_t\left(1-\bar\alpha_{t-1}\right)+\beta_t =\alpha_t-\alpha_t\bar\alpha_{t-1}+1-\alpha_t =1-\alpha_t\bar\alpha_{t-1} =1-\bar\alpha_t

Therefore

xt=αˉt x0+1−αˉt εˉ,εˉ∼N(0,I)x_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\bar\varepsilon,\qquad \bar\varepsilon\sim\mathcal{N}(0,I)

Note that εˉ\bar\varepsilon is neither ε′\varepsilon' nor ε\varepsilon 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.

q(xt∣x0)=N(xt;αˉt x0, (1−αˉt)I)q(x_t\mid x_0)=\mathcal{N}\left(x_t;\sqrt{\bar\alpha_t}\,x_0,\ \left(1-\bar\alpha_t\right)I\right)

Use one: training needs only one sample. No matter how large tt is, constructing xtx_t costs O(1)O(1): draw one ε\varepsilon 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 q(xt−1∣xt,x0)q(x_{t-1}\mid x_t,x_0) be rearranged into a closed-form Gaussian in Derivation 15.

Use three: the noise level is controllable. αˉt\bar\alpha_t decreases monotonically; when αˉt≈1\bar\alpha_t\approx1, xtx_t is almost the data, and when αˉt≈0\bar\alpha_t\approx0, it is almost pure noise. This curve is exactly the “noise schedule”.

The noise schedule determines the shape of αˉt\bar\alpha_t and therefore determines “in which segment the signal gets drowned”. Two mainstream choices:

ScheduleDefinitionShapeTrade-off
Linearβt\beta_t increases linearly from 10−410^{-4} to 0.020.02 (T=1000T=1000)αˉt\bar\alpha_t drops steeply first and then flattensSimple to implement and consistent with the original paper; the low-noise segment is too dense and the final segment wastes steps
Cosineαˉt=cos⁡2(t/T+s1+s⋅π2)cos⁡2(s1+s⋅π2), s=0.008\bar\alpha_t=\dfrac{\cos^2\left(\frac{t/T+s}{1+s}\cdot\frac{\pi}{2}\right)}{\cos^2\left(\frac{s}{1+s}\cdot\frac{\pi}{2}\right)},\ s=0.008Approximately uniform declineBalanced utilization of every noise segment and better FID; requires recalibration so that αˉT≈0\bar\alpha_T\approx0

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 tt is equivalent to non-uniform sampling over αˉt\bar\alpha_t according to “the Δαˉ\Delta\bar\alpha of each step”: under a linear schedule the low-noise segment (the interval where αˉt\bar\alpha_t 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 log⁡pθ(x0)\log p_\theta(x_0)) 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 θ\theta, so it is not “a learned approximation” but “a specified approximation”):

log⁡pθ(x0)=log⁡∫pθ(x0:T) dx1:T≥Eq(x1:T∣x0)[log⁡pθ(x0:T)q(x1:T∣x0)]\log p_\theta(x_0)=\log\int p_\theta(x_{0:T})\,\mathrm{d}x_{1:T} \ge\mathbb{E}_{q(x_{1:T}\mid x_0)}\left[\log\frac{p_\theta(x_{0:T})}{q(x_{1:T}\mid x_0)}\right]

The inequality comes from Jensen (log⁡\log is concave). Equality holds if and only if q(x1:T∣x0)=pθ(x1:T∣x0)q(x_{1:T}\mid x_0)=p_\theta(x_{1:T}\mid x_0), 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.

pθ(x0:T)=p(xT)∏t=1Tpθ(xt−1∣xt),q(x1:T∣x0)=∏t=1Tq(xt∣xt−1)p_\theta(x_{0:T})=p(x_T)\prod_{t=1}^{T}p_\theta(x_{t-1}\mid x_t),\qquad q(x_{1:T}\mid x_0)=\prod_{t=1}^{T}q(x_t\mid x_{t-1})

Step 3: Rearrange term by term (this step is where the whole trick lies). The goal is to replace q(xt∣xt−1)q(x_t\mid x_{t-1}) by q(xt−1∣xt,x0)q(x_{t-1}\mid x_t,x_0), so that each term tt contains only the ratio of “two adjacent terms”:

q(xt∣xt−1)=q(xt∣xt−1,x0)=q(xt−1∣xt,x0) q(xt∣x0)q(xt−1∣x0)q(x_t\mid x_{t-1})=q(x_t\mid x_{t-1},x_0) =\frac{q(x_{t-1}\mid x_t,x_0)\,q(x_t\mid x_0)}{q(x_{t-1}\mid x_0)}

The first equality uses the Markov property (xtx_t and x0x_0 are conditionally independent given xt−1x_{t-1}); the second is Bayes’ rule, rewriting “first x0→xt−1→xtx_0\to x_{t-1}\to x_t” as “first x0→xtx_0\to x_t, then back from xt→xt−1x_t\to x_{t-1}”.

Step 4: Substitute and let adjacent terms cancel. Substitute the expression above into the ratio inside the ELBO:

log⁡pθ(x0:T)q(x1:T∣x0)=log⁡p(xT)+∑t=1Tlog⁡pθ(xt−1∣xt)q(xt∣xt−1)\log\frac{p_\theta(x_{0:T})}{q(x_{1:T}\mid x_0)} =\log p(x_T)+\sum_{t=1}^{T}\log\frac{p_\theta(x_{t-1}\mid x_t)}{q(x_t\mid x_{t-1})} =log⁡p(xT)+∑t=1T[log⁡pθ(xt−1∣xt)+log⁡q(xt−1∣x0)−log⁡q(xt∣x0)−log⁡q(xt−1∣xt,x0)]=\log p(x_T)+\sum_{t=1}^{T}\left[\log p_\theta(x_{t-1}\mid x_t)+\log q(x_{t-1}\mid x_0)-\log q(x_t\mid x_0)-\log q(x_{t-1}\mid x_t,x_0)\right]

Expand the sum: log⁡q(xt−1∣x0)\log q(x_{t-1}\mid x_0) (the tt-th term) and −log⁡q(xt∣x0)-\log q(x_t\mid x_0) (the (t+1)(t+1)-th term) cancel pairwise, leaving only the two ends:

=log⁡p(xT)q(xT∣x0)+log⁡pθ(x0∣x1)+∑t=2Tlog⁡pθ(xt−1∣xt)q(xt−1∣xt,x0)=\log\frac{p(x_T)}{q(x_T\mid x_0)}+\log p_\theta(x_0\mid x_1)+\sum_{t=2}^{T}\log\frac{p_\theta(x_{t-1}\mid x_t)}{q(x_{t-1}\mid x_t,x_0)}

Step 5: Write it as three terms: KL and reconstruction. Take the expectation and reorganize each term into a KL:

ELBO=Eq[log⁡pθ(x0∣x1)]⏟L0 reconstruction term−KL(q(xT∣x0) ∥ p(xT))⏟LT prior matching−∑t=2TEq[KL(q(xt−1∣xt,x0) ∥ pθ(xt−1∣xt))]⏟Lt−1 denoising matching\mathrm{ELBO}=\underbrace{\mathbb{E}_q\left[\log p_\theta(x_0\mid x_1)\right]}_{L_0\ \text{reconstruction term}} -\underbrace{\mathrm{KL}\left(q(x_T\mid x_0)\,\middle\|\,p(x_T)\right)}_{L_T\ \text{prior matching}} -\sum_{t=2}^{T}\underbrace{\mathbb{E}_q\left[\mathrm{KL}\left(q(x_{t-1}\mid x_t,x_0)\,\middle\|\,p_\theta(x_{t-1}\mid x_t)\right)\right]}_{L_{t-1}\ \text{denoising matching}}

The three terms mean the following: LTL_T 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); L0L_0 is the final step that reconstructs x0x_0 from x1x_1; Lt−1L_{t-1} is the main body, and it requires the reverse network to reproduce, at every step, “the true conditional distribution of xt−1x_{t-1} given xtx_t and x0x_0”.

Step 6: Rearrange the true posterior q(xt−1∣xt,x0)q(x_{t-1}\mid x_t,x_0) into a closed form. It is the product of two Gaussian densities (Bayes):

q(xt−1∣xt,x0)∝q(xt∣xt−1) q(xt−1∣x0)q(x_{t-1}\mid x_t,x_0)\propto q(x_t\mid x_{t-1})\,q(x_{t-1}\mid x_0) ∝exp⁡(−∥xt−αtxt−1∥22βt)⋅exp⁡(−∥xt−1−αˉt−1x0∥22(1−αˉt−1))\propto\exp\left(-\frac{\left\|x_t-\sqrt{\alpha_t}x_{t-1}\right\|^2}{2\beta_t}\right)\cdot\exp\left(-\frac{\left\|x_{t-1}-\sqrt{\bar\alpha_{t-1}}x_0\right\|^2}{2\left(1-\bar\alpha_{t-1}\right)}\right)

Collect the quadratic and linear terms in xt−1x_{t-1} inside the exponents. The coefficient of the quadratic term is

αtβt+11−αˉt−1=αt(1−αˉt−1)+1−αtβt(1−αˉt−1)=1−αˉtβt(1−αˉt−1)\frac{\alpha_t}{\beta_t}+\frac{1}{1-\bar\alpha_{t-1}} =\frac{\alpha_t\left(1-\bar\alpha_{t-1}\right)+1-\alpha_t}{\beta_t\left(1-\bar\alpha_{t-1}\right)} =\frac{1-\bar\alpha_t}{\beta_t\left(1-\bar\alpha_{t-1}\right)}

so the posterior variance is

β~t=1−αˉt−11−αˉt βt\tilde\beta_t=\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\,\beta_t

The linear terms give the mean (writing the quadratic coefficient as 1/β~t1/\tilde\beta_t):

μ~t=β~t(αtβtxt+αˉt−11−αˉt−1x0)=αˉt−1 βt1−αˉtx0+αt(1−αˉt−1)1−αˉtxt\tilde\mu_t=\tilde\beta_t\left(\frac{\sqrt{\alpha_t}}{\beta_t}x_t+\frac{\sqrt{\bar\alpha_{t-1}}}{1-\bar\alpha_{t-1}}x_0\right) =\frac{\sqrt{\bar\alpha_{t-1}}\,\beta_t}{1-\bar\alpha_t}x_0+\frac{\sqrt{\alpha_t}\left(1-\bar\alpha_{t-1}\right)}{1-\bar\alpha_t}x_t

Step 7: Conclusion. Therefore

q(xt−1∣xt,x0)=N(xt−1;μ~t(xt,x0), β~tI)q(x_{t-1}\mid x_t,x_0)=\mathcal{N}\left(x_{t-1};\tilde\mu_t(x_t,x_0),\ \tilde\beta_t I\right)

This is a fully closed-form Gaussian with no parameters. Lt−1L_{t-1} 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. Lt−1L_{t-1} only requires the mean of pθp_\theta to match μ~t\tilde\mu_t; the variance part, with Σθ=β~tI\Sigma_\theta=\tilde\beta_t I 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 μ\mu, x0x_0, ε\varepsilon, or the Score

Lt−1L_{t-1} requires μθ(xt,t)≈μ~t\mu_\theta(x_t,t)\approx\tilde\mu_t. But μ~t\tilde\mu_t is a function of xtx_t and x0x_0, and x0x_0 is unknown. So there are two routes: regress μ~t\tilde\mu_t directly (in which case the network must know x0x_0), or replace x0x_0 with “the estimate recovered from xtx_t and the noise”. The latter route leads to four equivalent parameterizations.

From the closed-form marginal xt=αˉtx0+1−αˉtεx_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\varepsilon, we can solve backwards:

x0=xt−1−αˉt εαˉt,ε=xt−αˉt x01−αˉtx_0=\frac{x_t-\sqrt{1-\bar\alpha_t}\,\varepsilon}{\sqrt{\bar\alpha_t}},\qquad \varepsilon=\frac{x_t-\sqrt{\bar\alpha_t}\,x_0}{\sqrt{1-\bar\alpha_t}}

Differentiating the Gaussian density in turn gives the score (the gradient of the log-density with respect to the input):

∇xtlog⁡q(xt∣x0)=−xt−αˉtx01−αˉt=−ε1−αˉt\nabla_{x_t}\log q(x_t\mid x_0)=-\frac{x_t-\sqrt{\bar\alpha_t}x_0}{1-\bar\alpha_t}=-\frac{\varepsilon}{\sqrt{1-\bar\alpha_t}}

So the four prediction targets are linear transforms of one another:

Network outputNotationRelation to ε\varepsilonHow to recover x^0\hat x_0 at use time
Noiseεθ(xt,t)\varepsilon_\theta(x_t,t)It is the target itselfx^0=(xt−1−αˉt εθ)/αˉt\hat x_0=\left(x_t-\sqrt{1-\bar\alpha_t}\,\varepsilon_\theta\right)/\sqrt{\bar\alpha_t}
Clean samplex^0,θ(xt,t)\hat x_{0,\theta}(x_t,t)ε=(xt−αˉtx^0)/1−αˉt\varepsilon=\left(x_t-\sqrt{\bar\alpha_t}\hat x_0\right)/\sqrt{1-\bar\alpha_t}Use it directly
Meanμθ(xt,t)\mu_\theta(x_t,t)Recovered from the expression for μ~t\tilde\mu_tSubstitute back into μ~t\tilde\mu_t and solve for x0x_0
Scoresθ(xt,t)s_\theta(x_t,t)ε=−1−αˉt sθ\varepsilon=-\sqrt{1-\bar\alpha_t}\,s_\thetax^0=(xt+(1−αˉt)sθ)/αˉt\hat x_0=\left(x_t+\left(1-\bar\alpha_t\right)s_\theta\right)/\sqrt{\bar\alpha_t}

Why is the ε\varepsilon parameterization chosen almost everywhere in practice? There are three reasons:

  1. A stable numerical scale. ε\varepsilon is always a standard Gaussian with unit variance, so the magnitude of the regression target is independent of tt; whereas x0x_0 is almost unrecoverable from xtx_t when tt is large, so the error of regressing it gets amplified by a factor of 1/αˉt1/\sqrt{\bar\alpha_t}.
  2. Natural equivalence with score matching. Predicting ε\varepsilon is equivalent to predicting the score (up to a constant factor that depends only on tt), so it is simultaneously “a denoising objective” and “a score-matching objective”, and one loss serves two theoretical viewpoints (developed in Section 5.7).
  3. Consistency with the form of the simplified loss. The simplified loss (Derivation 16) is exactly the mean squared error on ε\varepsilon 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 ε\varepsilon 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

at=αˉt,σt=1−αˉt,at2+σt2=1a_{t}=\sqrt{\bar\alpha_{t}},\qquad \sigma_{t}=\sqrt{1-\bar\alpha_{t}},\qquad a_{t}^{2}+\sigma_{t}^{2}=1

The closed-form forward marginal (Derivation 14) reads

xt=atx0+σtε,ε∼N(0,I)x_{t}=a_{t}x_{0}+\sigma_{t}\varepsilon,\qquad \varepsilon\sim\mathcal{N}(0,I)

Step 2: the three parameterizations are linear transforms of one another. From the expression above,

x0=xt−σtεat,ε=xt−atx0σtx_{0}=\frac{x_{t}-\sigma_{t}\varepsilon}{a_{t}},\qquad \varepsilon=\frac{x_{t}-a_{t}x_{0}}{\sigma_{t}}

The mean parameterization is given by Step 4 of Derivation 16:

μt=1αt(xt−βtσtε)=αˉt−1βtat2x0+αt(1−αˉt−1)at2xt\mu_{t}=\frac{1}{\sqrt{\alpha_{t}}}\left(x_{t}-\frac{\beta_{t}}{\sigma_{t}}\varepsilon\right) =\frac{\sqrt{\bar\alpha_{t-1}}\beta_{t}}{a_{t}^{2}}x_{0}+\frac{\sqrt{\alpha_{t}}\left(1-\bar\alpha_{t-1}\right)}{a_{t}^{2}}x_{t}

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 x0x_{0} be δ0=x^0−x0\delta_{0}=\hat x_{0}-x_{0}. From ε=(xt−atx0)/σt\varepsilon=\left(x_{t}-a_{t}x_{0}\right)/\sigma_{t}, the same x^0\hat x_{0} gives

ε^−ε=atσt(x^0−x0)\hat\varepsilon-\varepsilon=\frac{a_{t}}{\sigma_{t}}\left(\hat x_{0}-x_{0}\right)

so the two losses satisfy

Lε=at2σt2Lx0=SNRt Lx0,SNRt=αˉt1−αˉtL_{\varepsilon}=\frac{a_{t}^{2}}{\sigma_{t}^{2}}L_{x_{0}}=\mathrm{SNR}_{t}\,L_{x_{0}},\qquad \mathrm{SNR}_{t}=\frac{\bar\alpha_{t}}{1-\bar\alpha_{t}}

This is where “the simplified loss is really a signal-to-noise-ratio-weighted regression on x0x_{0}” comes from (Derivation 23). For large tt (SNRt→0\mathrm{SNR}_{t}\to0) it barely penalizes the x0x_{0} error, and for small tt (SNRt→∞\mathrm{SNR}_{t}\to\infty) it penalizes it enormously, so regressing x0x_{0} directly is amplified by SNRt\mathrm{SNR}_{t} in the low-noise regime, which makes training unstable. This is the first practical reason for choosing ε\varepsilon.

Step 4: the definition of the vv parameterization and its orthogonality. Let

v=atε−σtx0v=a_{t}\varepsilon-\sigma_{t}x_{0}

Write the relation between (xt,v)(x_{t},v) and (x0,ε)(x_{0},\varepsilon) as a matrix:

(xtv)=(atσt−σtat)(x0ε)\begin{pmatrix}x_{t}\\ v\end{pmatrix}= \begin{pmatrix}a_{t}&\sigma_{t}\\ -\sigma_{t}&a_{t}\end{pmatrix} \begin{pmatrix}x_{0}\\ \varepsilon\end{pmatrix}

The determinant of this matrix is at2+σt2=1a_{t}^{2}+\sigma_{t}^{2}=1, and its two rows are orthogonal (at(−σt)+σtat=0a_{t}\left(-\sigma_{t}\right)+\sigma_{t}a_{t}=0), so it is an orthogonal matrix, i.e., a rotation. The rotation angle θt\theta_{t} satisfies cos⁡θt=at\cos\theta_{t}=a_{t} and sin⁡θt=σt\sin\theta_{t}=\sigma_{t}, that is, θt=arctan⁡(σt/at)\theta_{t}=\arctan\left(\sigma_{t}/a_{t}\right). When αˉt=1/2\bar\alpha_{t}=1/2 we have at=σt=1/2a_{t}=\sigma_{t}=1/\sqrt2 and θt=45∘\theta_{t}=45^{\circ} — this is the precise meaning of ”vv is a 45-degree rotation”: it rotates the axes in the (x0,ε)(x_{0},\varepsilon) 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

(x0ε)=(at−σtσtat)(xtv)\begin{pmatrix}x_{0}\\ \varepsilon\end{pmatrix}= \begin{pmatrix}a_{t}&-\sigma_{t}\\ \sigma_{t}&a_{t}\end{pmatrix} \begin{pmatrix}x_{t}\\ v\end{pmatrix}

Written out term by term,

x0=atxt−σtv,ε=σtxt+atvx_{0}=a_{t}x_{t}-\sigma_{t}v,\qquad \varepsilon=\sigma_{t}x_{t}+a_{t}v

Substituting back into Step 1 verifies both identities:

atxt−σtv=at(atx0+σtε)−σt(atε−σtx0)=(at2+σt2)x0=x0a_{t}x_{t}-\sigma_{t}v=a_{t}\left(a_{t}x_{0}+\sigma_{t}\varepsilon\right)-\sigma_{t}\left(a_{t}\varepsilon-\sigma_{t}x_{0}\right)=\left(a_{t}^{2}+\sigma_{t}^{2}\right)x_{0}=x_{0}

Step 6: why vv is stable at both ends. Let the errors of ε^\hat\varepsilon and x^0\hat x_{0} be δε,δ0\delta_{\varepsilon},\delta_{0}; then

v^−v=at(ε^−ε)−σt(x^0−x0)=atδε−σtδ0\hat v-v=a_{t}\left(\hat\varepsilon-\varepsilon\right)-\sigma_{t}\left(\hat x_{0}-x_{0}\right)=a_{t}\delta_{\varepsilon}-\sigma_{t}\delta_{0}

If the two errors are independent with common variance ν2\nu^{2}, then

E∥v^−v∥2=at2ν2+σt2ν2=ν2\mathbb{E}\left\|\hat v-v\right\|^{2}=a_{t}^{2}\nu^{2}+\sigma_{t}^{2}\nu^{2}=\nu^{2}

independent of tt. Compared with the extreme amplification of Lε=SNRtLx0L_{\varepsilon}=\mathrm{SNR}_{t}L_{x_{0}} in the low-noise regime, the error scale of vv stays constant at both t→0t\to0 and t→Tt\to T. This is the motivation for the vv 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 xt=atx0+σtεx_{t}=a_{t}x_{0}+\sigma_{t}\varepsilon”: x0x_{0} and ε\varepsilon are the two end directions of that line, μ\mu is a particular point on the line, and vv 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 Lt−1L_{t-1} into a computable expression yields a mean squared error with a coefficient that depends on tt. 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 p=N(μ1,σ2I)p=\mathcal{N}(\mu_1,\sigma^2 I) and q=N(μ2,σ2I)q=\mathcal{N}(\mu_2,\sigma^2 I). From the closed form of Derivation 4 (the variances are equal, so the log⁡\log terms cancel):

KL(p ∥ q)=12σ2∥μ1−μ2∥2\mathrm{KL}(p\,\|\,q)=\frac{1}{2\sigma^2}\left\|\mu_1-\mu_2\right\|^2

Step 2: Substitute into Lt−1L_{t-1}. Take the variance of pθp_\theta to be σt2\sigma_t^2 (one may take β~t\tilde\beta_t or βt\beta_t; the latter is simpler and performs about the same), then

Lt−1=Eq[12σt2∥μ~t(xt,x0)−μθ(xt,t)∥2]L_{t-1}=\mathbb{E}_q\left[\frac{1}{2\sigma_t^2}\left\|\tilde\mu_t(x_t,x_0)-\mu_\theta(x_t,t)\right\|^2\right]

Step 3: Rewrite μ~t\tilde\mu_t in terms of xtx_t and ε\varepsilon. From Step 6 of Derivation 15,

μ~t=αˉt−1βt1−αˉtx0+αt(1−αˉt−1)1−αˉtxt\tilde\mu_t=\frac{\sqrt{\bar\alpha_{t-1}}\beta_t}{1-\bar\alpha_t}x_0+\frac{\sqrt{\alpha_t}\left(1-\bar\alpha_{t-1}\right)}{1-\bar\alpha_t}x_t

Substitute x0=(xt−1−αˉtε)/αˉtx_0=\left(x_t-\sqrt{1-\bar\alpha_t}\varepsilon\right)/\sqrt{\bar\alpha_t}:

μ~t=1αt(xt−βt1−αˉt ε)\tilde\mu_t=\frac{1}{\sqrt{\alpha_t}}\left(x_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\varepsilon\right)

(The algebra of this step: merge the two terms into 1αtxt\frac{1}{\sqrt{\alpha_t}}x_t minus a term containing ε\varepsilon; the merge uses αˉt=αtαˉt−1\bar\alpha_t=\alpha_t\bar\alpha_{t-1} and 1−αˉt=βt+αt(1−αˉt−1)1-\bar\alpha_t=\beta_t+\alpha_t\left(1-\bar\alpha_{t-1}\right).)

Step 4: Let the network output the same form. Set

μθ(xt,t)=1αt(xt−βt1−αˉt εθ(xt,t))\mu_\theta(x_t,t)=\frac{1}{\sqrt{\alpha_t}}\left(x_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\varepsilon_\theta(x_t,t)\right)

Then the difference of the two means is

μ~t−μθ=−βtαt1−αˉt(ε−εθ)\tilde\mu_t-\mu_\theta=-\frac{\beta_t}{\sqrt{\alpha_t}\sqrt{1-\bar\alpha_t}}\left(\varepsilon-\varepsilon_\theta\right)

Step 5: Substitute back into the KL to obtain a weighted noise regression.

Lt−1=Ex0,ε[βt22σt2 αt(1−αˉt)∥ε−εθ(αˉtx0+1−αˉtε, t)∥2]L_{t-1}=\mathbb{E}_{x_0,\varepsilon}\left[\frac{\beta_t^2}{2\sigma_t^2\,\alpha_t\left(1-\bar\alpha_t\right)}\left\|\varepsilon-\varepsilon_\theta\left(\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\varepsilon,\ t\right)\right\|^2\right]

Step 6: Drop the coefficient to obtain LsimpleL_{\text{simple}}.

Lsimple=Et,x0,ε[∥ε−εθ(αˉtx0+1−αˉtε, t)∥2]L_{\text{simple}}=\mathbb{E}_{t,x_0,\varepsilon}\left[\left\|\varepsilon-\varepsilon_\theta\left(\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\varepsilon,\ t\right)\right\|^2\right]

Step 7: Why the coefficient can be dropped — three levels of reasoning.

  1. It is still a valid lower bound (in weighted form). LsimpleL_{\text{simple}} equals the sum of Lt−1L_{t-1} reweighted by wt=2σt2αt(1−αˉt)βt2w_t=\frac{2\sigma_t^2\alpha_t\left(1-\bar\alpha_t\right)}{\beta_t^2}. 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.
  2. Dropping the coefficient corrects a training bias. The original coefficient βt22σt2αt(1−αˉt)\frac{\beta_t^2}{2\sigma_t^2\alpha_t\left(1-\bar\alpha_t\right)} tends to zero when tt is small (βt\beta_t small, αˉt≈1\bar\alpha_t\approx1). That is: under ELBO training, the low-noise segment (the segment that decides image detail) carries almost no weight. After dropping the coefficient every tt has equal weight, so the low-noise segment gets the attention it deserves — this is exactly why sample detail improves.
  3. It is equivalent to “signal-to-noise-ratio-weighted” score matching. One can show that LsimpleL_{\text{simple}} differs from “least-squares regression on the score” only by a constant factor depending on tt, 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, LsimpleL_{\text{simple}} 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 tt do not change the optimum, LsimpleL_{\text{simple}} 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).

ELBO=Eq[log⁡pθ(x0∣x1)]−KL(q(xT∣x0)∥p(xT))−∑t=2TEq[KL(q(xt−1∣xt,x0)∥pθ(xt−1∣xt))]\mathrm{ELBO}=\mathbb{E}_{q}\left[\log p_\theta\left(x_0\mid x_1\right)\right]-\mathrm{KL}\left(q\left(x_T\mid x_0\right)\|p\left(x_T\right)\right)-\sum_{t=2}^{T}\mathbb{E}_{q}\left[\mathrm{KL}\left(q\left(x_{t-1}\mid x_t,x_0\right)\|p_\theta\left(x_{t-1}\mid x_t\right)\right)\right]

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:

q(xt−1∣xt,x0)=N(μ~t, β~tI),pθ(xt−1∣xt)=N(μθ(xt,t), σt2I)q\left(x_{t-1}\mid x_t,x_0\right)=\mathcal{N}\left(\tilde\mu_t,\ \tilde\beta_t I\right),\qquad p_\theta\left(x_{t-1}\mid x_t\right)=\mathcal{N}\left(\mu_\theta\left(x_t,t\right),\ \sigma_t^{2}I\right)

For two diagonal Gaussians with the same covariance (σt2=β~t\sigma_t^2=\tilde\beta_t), the KL keeps only the mean term:

KL=12σt2∥μ~t−μθ(xt,t)∥2\mathrm{KL}=\frac{1}{2\sigma_t^{2}}\left\|\tilde\mu_t-\mu_\theta\left(x_t,t\right)\right\|^{2}

Step 3: Replace the means by noise predictions. From the rearrangement in Derivation 15, both means can be written as ”xtx_t minus a term scaled by ε\varepsilon”:

μ~t=1αt(xt−βt1−αˉt ε),μθ=1αt(xt−βt1−αˉt εθ(xt,t))\tilde\mu_t=\frac{1}{\sqrt{\alpha_t}}\left(x_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\varepsilon\right),\qquad \mu_\theta=\frac{1}{\sqrt{\alpha_t}}\left(x_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\varepsilon_\theta\left(x_t,t\right)\right)

Subtracting the two, the xtx_t terms cancel:

μ~t−μθ=βtαt1−αˉt(εθ−ε)\tilde\mu_t-\mu_\theta=\frac{\beta_t}{\sqrt{\alpha_t}\sqrt{1-\bar\alpha_t}}\left(\varepsilon_\theta-\varepsilon\right)

Step 4: Substitute back into the KL to obtain “noise regression plus a coefficient”.

KL=βt22σt2αt(1−αˉt)∥ε−εθ∥2\mathrm{KL}=\frac{\beta_t^{2}}{2\sigma_t^{2}\alpha_t\left(1-\bar\alpha_t\right)}\left\|\varepsilon-\varepsilon_\theta\right\|^{2}

Denote this coefficient by γt\gamma_t:

γt=βt22σt2αt(1−αˉt)\gamma_t=\frac{\beta_t^{2}}{2\sigma_t^{2}\alpha_t\left(1-\bar\alpha_t\right)}

If σt2=βt\sigma_t^{2}=\beta_t (the common choice in DDPM), then γt=βt2αt(1−αˉt)\gamma_t=\dfrac{\beta_t}{2\alpha_t\left(1-\bar\alpha_t\right)}.

Step 5: LsimpleL_{\text{simple}} is exactly “replace every γt\gamma_t by 1”.

ELBO=constant−∑tγt E[∥ε−εθ∥2],Lsimple=∑tE[∥ε−εθ∥2]\mathrm{ELBO}=\text{constant}-\sum_{t}\gamma_t\,\mathbb{E}\left[\left\|\varepsilon-\varepsilon_\theta\right\|^{2}\right],\qquad L_{\text{simple}}=\sum_{t}\mathbb{E}\left[\left\|\varepsilon-\varepsilon_\theta\right\|^{2}\right]

So “dropping the coefficient” is mathematically exactly equivalent to “multiplying the tt-th term by 1/γt1/\gamma_t”. 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 γt\gamma_t varies with tt (this is the key). Take σt2=βt\sigma_t^{2}=\beta_t and treat βt\beta_t as small, expanding at the two ends:

  • Small tt (high SNR, αˉt≈1\bar\alpha_t\approx1): 1−αˉt≈∑s≤tβs1-\bar\alpha_t\approx\sum_{s\le t}\beta_s, hence
γt≈βt2αt∑s≤tβs≈12t\gamma_t\approx\frac{\beta_t}{2\alpha_t\sum_{s\le t}\beta_s}\approx\frac{1}{2t}

which decreases rapidly as tt grows;

  • Large tt (low SNR, αˉt→0\bar\alpha_t\to0): 1−αˉt→11-\bar\alpha_t\to1 and αt→\alpha_t\to a constant, hence
γt≈βt2αt≈constant (about 1/2)\gamma_t\approx\frac{\beta_t}{2\alpha_t}\approx\text{constant (about }1/2\text{)}

Step 7: So what is LsimpleL_{\text{simple}} doing. LsimpleL_{\text{simple}} replaces γt\gamma_t by the weight 1, which is equivalent to multiplying each term by 1/γt1/\gamma_t:

  • in the small-tt segment (low noise, high SNR), 1/γt≈2t1/\gamma_t\approx2t is very small — these terms are heavily downweighted;
  • in the large-tt segment (high noise, low SNR), 1/γt≈21/\gamma_t\approx2 is nearly constant — the weights of these terms are essentially unchanged.

So the actual effect of LsimpleL_{\text{simple}} 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: LsimpleL_{\text{simple}} 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 ”LsimpleL_{\text{simple}} 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

wt=min⁡(SNRt, κ),SNRt=αˉt1−αˉtw_t=\min\left(\mathrm{SNR}_t,\ \kappa\right),\qquad \mathrm{SNR}_t=\frac{\bar\alpha_t}{1-\bar\alpha_t}

where κ\kappa is the truncation threshold (5 is common). The motivation: the gradient norms at different tt differ by orders of magnitude, so a few tt 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 γt\gamma_t 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 γt\gamma_t is substituted back exactly during training (that is, using the full ELBO rather than LsimpleL_{\text{simple}}), the resulting model should have a better likelihood and a worse FID; conversely LsimpleL_{\text{simple}} should have a better FID and a worse likelihood. This agrees with the empirical literature (the DDPM paper reported that LsimpleL_{\text{simple}} has a slightly worse bpd but clearly better sample quality). The corollary turns “why LsimpleL_{\text{simple}} 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, ε=−1−αˉt∇xtlog⁡q(xt∣x0)\varepsilon=-\sqrt{1-\bar\alpha_t}\nabla_{x_t}\log q(x_t\mid x_0). So “predicting the noise” and “estimating the conditional score” are two sides of the same thing. The training loss can be rewritten as

L=Et,x0,ε[∥ε−εθ∥2]=E[(1−αˉt)∥sθ(xt,t)−∇xtlog⁡q(xt∣x0)∥2]L=\mathbb{E}_{t,x_0,\varepsilon}\left[\left\|\varepsilon-\varepsilon_\theta\right\|^2\right] =\mathbb{E}\left[\left(1-\bar\alpha_t\right)\left\|s_\theta(x_t,t)-\nabla_{x_t}\log q(x_t\mid x_0)\right\|^2\right]

that is, LsimpleL_{\text{simple}} is a weighted version of “conditional score matching”. The significance of this step is that the score needs no normalization constant. Because ∇xlog⁡p(x)=∇xlog⁡p~(x)\nabla_x\log p(x)=\nabla_x\log\tilde p(x) (log⁡Z\log Z 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 q(xt)=∫q(xt∣x0)p(x0) dx0q(x_t)=\int q(x_t\mid x_0)p(x_0)\,\mathrm{d}x_0 with respect to xtx_t gives

∇xtlog⁡q(xt)=11−αˉt(E[x0∣xt]αˉt−xt)\nabla_{x_t}\log q(x_t)=\frac{1}{1-\bar\alpha_t}\left(\mathbb{E}\left[x_0\mid x_t\right]\sqrt{\bar\alpha_t}-x_t\right)

which rearranges to

E[x0∣xt]=1αˉt(xt+(1−αˉt)∇xtlog⁡q(xt))\mathbb{E}\left[x_0\mid x_t\right]=\frac{1}{\sqrt{\bar\alpha_t}}\left(x_t+\left(1-\bar\alpha_t\right)\nabla_{x_t}\log q(x_t)\right)

This expression says: given a noisy sample xtx_t, the optimal minimum-mean-square-error estimate of the clean sample is “one step along the score direction”. Substituting ∇log⁡q=−ε/1−αˉt\nabla\log q=-\varepsilon/\sqrt{1-\bar\alpha_t} immediately gives x^0=(xt−1−αˉtεθ)/αˉt\hat x_0=\left(x_t-\sqrt{1-\bar\alpha_t}\varepsilon_\theta\right)/\sqrt{\bar\alpha_t} — 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 x^0\hat x_0 given by the Tweedie formula is a conditional expectation, hence “the best on average”, but a single sample is not equal to the true x0x_0. When tt is large (αˉt\bar\alpha_t small), xtx_t carries almost no information about x0x_0, so x^0\hat x_0 degenerates to “somewhere near the dataset mean”, which is merely a blurry average image — this explains why x^0\hat x_0 at large tt 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

xt−1=αˉt−1 x^0+1−αˉt−1−σt2  εθ(xt,t)+σt ε,ε∼N(0,I)x_{t-1}=\sqrt{\bar\alpha_{t-1}}\,\hat x_0+\sqrt{1-\bar\alpha_{t-1}-\sigma_t^2}\;\varepsilon_\theta(x_t,t)+\sigma_t\,\varepsilon,\qquad \varepsilon\sim\mathcal{N}(0,I)

Three choices of σt\sigma_t give three behaviors:

Value of σt\sigma_tBehaviorCharacteristic
σt=1−αˉt−11−αˉt1−αˉtαˉt−1\sigma_t=\sqrt{\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}}\sqrt{1-\frac{\bar\alpha_t}{\bar\alpha_{t-1}}}Equivalent to DDPMMost stochastic; repeated sampling gives different results
σt=0\sigma_t=0Fully deterministicThe same initial noise always yields the same image; interpolation and inversion are possible
0<σt<σtmax⁡0<\sigma_t<\sigma_t^{\max}Between the twoThe η\eta parameter controls the degree of randomness

When σt=0\sigma_t=0, the expression degenerates into “first predict x0x_0, then reproject along the αˉt−1\sqrt{\bar\alpha_{t-1}} and 1−αˉt−1\sqrt{1-\bar\alpha_{t-1}} 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:

dxtdt=f(xt,t)−12g(t)2 ∇xtlog⁡qt(xt)\frac{\mathrm{d}x_t}{\mathrm{d}t}=f(x_t,t)-\frac{1}{2}g(t)^2\,\nabla_{x_t}\log q_t(x_t)

where ff and gg 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 qtq_t 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 x0→xTx_0\to x_T 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 log⁡Z\log Z is zero (this item).
  • Why can diffusion cover multiple modes? — Because the score field has different attractors at different modes, and LsimpleL_{\text{simple}} 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 ∇xlog⁡pθ(x∣c)\nabla_x\log p_\theta\left(x\mid c\right), but the trained network only gives ∇xlog⁡pθ(x)\nabla_x\log p_\theta\left(x\right) (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 γ>1\gamma>1.

Step 1: Split the conditional score with Bayes’ rule.

p(x∣c)=p(x)p(c∣x)p(c)p\left(x\mid c\right)=\frac{p\left(x\right)p\left(c\mid x\right)}{p\left(c\right)}

Taking the log gradient with respect to xx: p(c)p(c) does not depend on xx, so

∇xlog⁡p(x∣c)=∇xlog⁡p(x)+∇xlog⁡p(c∣x)\nabla_x\log p\left(x\mid c\right)=\nabla_x\log p\left(x\right)+\nabla_x\log p\left(c\mid x\right)

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 pη(c∣x)p_\eta\left(c\mid x\right); then

∇xlog⁡p(x∣c)≈∇xlog⁡p(x)+s ∇xlog⁡pη(c∣x)\nabla_x\log p\left(x\mid c\right)\approx\nabla_x\log p\left(x\right)+s\,\nabla_x\log p_\eta\left(c\mid x\right)

where s>0s>0 is the guidance strength. When s=1s=1 it is the exact expression of Step 1 (provided the classifier equals the true p(c∣x)p(c\mid x)); when s>1s>1 the direction of “looking like cc” 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 cc is randomly replaced by the empty condition ∅\varnothing, so a single network approximates both pθ(x∣c)p_\theta\left(x\mid c\right) and pθ(x)p_\theta\left(x\right) (the latter written as pθ(x∣∅)=pθ(x)p_\theta\left(x\mid\varnothing\right)=p_\theta(x)). The CFG score is

∇xlog⁡p~γ(x∣c)=∇xlog⁡pθ(x)+γ(∇xlog⁡pθ(x∣c)−∇xlog⁡pθ(x))\nabla_x\log\tilde p_\gamma\left(x\mid c\right)=\nabla_x\log p_\theta\left(x\right)+\gamma\left(\nabla_x\log p_\theta\left(x\mid c\right)-\nabla_x\log p_\theta\left(x\right)\right)

which rearranges to

∇xlog⁡p~γ(x∣c)=(1−γ)∇xlog⁡pθ(x)+γ ∇xlog⁡pθ(x∣c)\nabla_x\log\tilde p_\gamma\left(x\mid c\right)=\left(1-\gamma\right)\nabla_x\log p_\theta\left(x\right)+\gamma\,\nabla_x\log p_\theta\left(x\mid c\right)

Written in the noise parameterization, this is the familiar εγ=ε(x,∅)+γ(ε(x,c)−ε(x,∅))\varepsilon_\gamma=\varepsilon\left(x,\varnothing\right)+\gamma\left(\varepsilon\left(x,c\right)-\varepsilon\left(x,\varnothing\right)\right) (because ε\varepsilon and the score differ by a factor −1−αˉt-\sqrt{1-\bar\alpha_t}, 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

p~γ(x∣c) ∝ pθ(x)1−γ pθ(x∣c)γ\tilde p_\gamma\left(x\mid c\right)\ \propto\ p_\theta\left(x\right)^{1-\gamma}\,p_\theta\left(x\mid c\right)^{\gamma}

(because ∇log⁡(p1−γqγ)=(1−γ)∇log⁡p+γ∇log⁡q\nabla\log\left(p^{1-\gamma}q^{\gamma}\right)=\left(1-\gamma\right)\nabla\log p+\gamma\nabla\log q). This is the key conclusion: what CFG samples is not p(x∣c)p\left(x\mid c\right) but a geometric interpolation between the conditional and the unconditional distribution. At γ=1\gamma=1 it degenerates to the conditional distribution, and at γ=0\gamma=0 to the unconditional distribution.

Step 5: Why γ>1\gamma>1 is “extrapolation” rather than “a stronger condition”. The geometric interpolation p1−γqγp^{1-\gamma}q^{\gamma} has negative exponents when γ>1\gamma>1 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,

pθ(x)=N(0,1),pθ(x∣c)=N(μ,1)p_\theta\left(x\right)=\mathcal{N}\left(0,1\right),\qquad p_\theta\left(x\mid c\right)=\mathcal{N}\left(\mu,1\right)

then

p~γ ∝ exp⁡(−1−γ2x2−γ2(x−μ)2)=N(γμ, 1)\tilde p_\gamma\ \propto\ \exp\left(-\frac{1-\gamma}{2}x^{2}-\frac{\gamma}{2}\left(x-\mu\right)^{2}\right)=\mathcal{N}\left(\gamma\mu,\ 1\right)

The mean is pushed to γμ\gamma\mu while the variance stays 1. So the effect of γ>1\gamma>1 is to “amplify the displacement along the conditional direction by a factor of γ\gamma”: 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 c1,c2c_1,c_2, under the assumption that they are conditionally independent given xx,

∇log⁡p(x∣c1,c2)=∇log⁡p(x)+∇log⁡p(c1∣x)p(c1)+∇log⁡p(c2∣x)p(c2)\nabla\log p\left(x\mid c_1,c_2\right)=\nabla\log p\left(x\right)+\nabla\log\frac{p\left(c_1\mid x\right)}{p\left(c_1\right)}+\nabla\log\frac{p\left(c_2\mid x\right)}{p\left(c_2\right)}

In the difference form of CFG this becomes

∇log⁡p~γ(x∣c1,c2)=∇log⁡pθ(x)+∑i=12γi(∇log⁡pθ(x∣ci)−∇log⁡pθ(x))\nabla\log\tilde p_\gamma\left(x\mid c_1,c_2\right)=\nabla\log p_\theta\left(x\right)+\sum_{i=1}^{2}\gamma_i\left(\nabla\log p_\theta\left(x\mid c_i\right)-\nabla\log p_\theta\left(x\right)\right)

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 ∇log⁡pθ(x)\nabla\log p_\theta\left(x\right), and this can only be obtained by “dropping cc during training”. Let the dropout probability be pdropp_{\text{drop}}; then the network learns the unconditional distribution on a pdropp_{\text{drop}} fraction of the samples and the conditional distribution on the rest. If pdropp_{\text{drop}} is too small, the unconditional branch is under-trained (ε(x,∅)\varepsilon\left(x,\varnothing\right) 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 γ\gamma 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 p1/Tp^{1/T} 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, γ\gamma 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):

dx=f(x,t) dt+g(t) dw\mathrm{d}x=f(x,t)\,\mathrm{d}t+g(t)\,\mathrm{d}w

Taking the variance preserving (VP) form, f(x,t)=−12β(t)xf(x,t)=-\frac12\beta(t)x and g(t)=β(t)g(t)=\sqrt{\beta(t)}, gives

dx=−12β(t)x dt+β(t) dw\mathrm{d}x=-\frac12\beta(t)x\,\mathrm{d}t+\sqrt{\beta(t)}\,\mathrm{d}w

Here ww is a standard Brownian motion, formally dw∼N(0,dt)\mathrm{d}w\sim\mathcal{N}(0,\mathrm{d}t).

Step 2: The Fokker-Planck equation. The marginal density pt(x)p_{t}(x) of the SDE satisfies the forward Kolmogorov equation (also called the Fokker-Planck equation):

∂pt∂t=−∇⋅[f(x,t)pt(x)]+12g(t)2∇2pt(x)\frac{\partial p_{t}}{\partial t}=-\nabla\cdot\left[f(x,t)p_{t}(x)\right]+\frac12g(t)^{2}\nabla^{2}p_{t}(x)

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: ∇2p=∇⋅(∇p)\nabla^{2}p=\nabla\cdot\left(\nabla p\right), and ∇p=p∇log⁡p\nabla p=p\nabla\log p (the latter requires p>0p>0). Hence

12g2∇2p=12g2∇⋅(∇p)=∇⋅(12g2p∇log⁡p)\frac12g^{2}\nabla^{2}p=\frac12g^{2}\nabla\cdot\left(\nabla p\right)=\nabla\cdot\left(\frac12g^{2}p\nabla\log p\right)

Substituting back into Step 2,

∂pt∂t=−∇⋅[fpt−12g2pt∇log⁡pt]\frac{\partial p_{t}}{\partial t}=-\nabla\cdot\left[f p_{t}-\frac12g^{2}p_{t}\nabla\log p_{t}\right]

Step 4: Read off the continuity equation and the velocity field. The expression above is exactly the continuity equation

∂pt∂t+∇⋅(pt v(x,t))=0\frac{\partial p_{t}}{\partial t}+\nabla\cdot\left(p_{t}\,v(x,t)\right)=0

with velocity field

v(x,t)=f(x,t)−12g(t)2∇xlog⁡pt(x)v(x,t)=f(x,t)-\frac12g(t)^{2}\nabla_{x}\log p_{t}(x)

The continuity equation is the differential statement of “conservation of probability mass”: ptp_{t} is transported along the velocity field vv and its total mass does not change. The key point is that the evolution of ptp_{t} is determined by vv alone, and vv depends only on ff, gg, and ∇log⁡pt\nabla\log p_{t}, not on any particular realization of the noise.

Step 5: Obtain the probability-flow ODE. Since vv fully determines the marginal distribution, the stochastic term can be replaced by a deterministic flow:

dxdt=v(x,t)=f(x,t)−12g(t)2∇xlog⁡pt(x)\frac{\mathrm{d}x}{\mathrm{d}t}=v(x,t)=f(x,t)-\frac12g(t)^{2}\nabla_{x}\log p_{t}(x)

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 f=−12βxf=-\frac12\beta x and g2=βg^{2}=\beta into Step 5,

dxdt=−12β(t)x−12β(t)∇xlog⁡pt(x)=−12β(t)[x+∇xlog⁡pt(x)]\frac{\mathrm{d}x}{\mathrm{d}t}=-\frac12\beta(t)x-\frac12\beta(t)\nabla_{x}\log p_{t}(x)=-\frac12\beta(t)\left[x+\nabla_{x}\log p_{t}(x)\right]

The ∇log⁡pt\nabla\log p_{t} inside the bracket can be replaced by the trained noise network (sθ=−εθ/1−αˉts_{\theta}=-\varepsilon_{\theta}/\sqrt{1-\bar\alpha_{t}}, 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

xt−Δt=xt−Δt 12β(t)[xt+sθ(xt,t)]x_{t-\Delta t}=x_{t}-\Delta t\,\frac12\beta(t)\left[x_{t}+s_{\theta}\left(x_{t},t\right)\right]

A more common route reparameterizes time as at=αˉta_{t}=\sqrt{\bar\alpha_{t}} and σt=1−αˉt\sigma_{t}=\sqrt{1-\bar\alpha_{t}}. The velocity field then simplifies to dx/dσ=εθ(x,σ)\mathrm{d}x/\mathrm{d}\sigma=\varepsilon_{\theta}\left(x,\sigma\right) (increasing σ\sigma is the noising direction, so reverse sampling decreases σ\sigma). Taking Euler steps in σ\sigma:

xσ−Δσ=xσ−Δσ εθ(xσ,σ)x_{\sigma-\Delta\sigma}=x_{\sigma}-\Delta\sigma\,\varepsilon_{\theta}\left(x_{\sigma},\sigma\right)

Rewriting with x^0=(xσ−σεθ)/a\hat x_{0}=\left(x_{\sigma}-\sigma\varepsilon_{\theta}\right)/a yields the DDIM update

xσ′=σ′σxσ+(a′−σ′σa)x^0x_{\sigma'}=\frac{\sigma'}{\sigma}x_{\sigma}+\left(a'-\frac{\sigma'}{\sigma}a\right)\hat x_{0}

where a′=αˉt−1a'=\sqrt{\bar\alpha_{t-1}}, σ′=1−αˉt−1\sigma'=\sqrt{1-\bar\alpha_{t-1}}, a=αˉta=\sqrt{\bar\alpha_{t}}, σ=1−αˉt\sigma=\sqrt{1-\bar\alpha_{t}}. The substitution is: insert εθ=(xσ−ax^0)/σ\varepsilon_{\theta}=\left(x_{\sigma}-a\hat x_{0}\right)/\sigma into the previous equation,

xσ′=xσ−(σ−σ′)xσ−ax^0σ=σ′σxσ+(a−σ′σa)x^0+σ′σax^0−σ′σax^0x_{\sigma'}=x_{\sigma}-\left(\sigma-\sigma'\right)\frac{x_{\sigma}-a\hat x_{0}}{\sigma} =\frac{\sigma'}{\sigma}x_{\sigma}+\left(a-\frac{\sigma'}{\sigma}a\right)\hat x_{0}+\frac{\sigma'}{\sigma}a\hat x_{0}-\frac{\sigma'}{\sigma}a\hat x_{0}

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 σ\sigma 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 xtx_t to xt−1x_{t-1}”.

# ===== 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 tt must be sampled randomly rather than in order. Each tt 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 tt, then small tt), catastrophic forgetting would set in: what the network learns at small tt would overwrite its ability at large tt. Random sampling has a side benefit: samples within one batch can have different tt, so the gradient is an unbiased mixture of the gradients of several tasks.

Segment A ②: Why xtx_t is computed in one shot with the closed-form formula. This is a direct application of Derivation 14. If one really looped tt times to add noise, the per-sample training cost would be O(t)O(t) and training would be infeasible. The closed-form formula reduces the cost to O(1)O(1) — this is the dividing line between “diffusion can be trained” and “diffusion cannot be trained”.

Segment A ③: Why the regression target is ε\varepsilon rather than μ~t\tilde\mu_t. Three reasons (Section 5.5): ε\varepsilon has a stable scale, it is equivalent to score matching, and it matches the form of the simplified loss. If one regressed μ~t\tilde\mu_t, then at large tt 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 LsimpleL_{\text{simple}} has no coefficient in tt. 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 εθ\varepsilon_\theta. xtx_t is constructed from x0x_0 and ε\varepsilon, and the construction contains no parameters, so there is no need (and no reason) to backpropagate into xtx_t. In code this means both x0x_0 and ε\varepsilon 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 x0x_0, and then you must enable it explicitly.

Segment B ①: Why sampling starts from xT∼N(0,I)x_T\sim\mathcal{N}(0,I). This is the requirement of LTL_T (the prior-matching term). The schedule guarantees αˉT≈0\bar\alpha_T\approx0, so q(xT∣x0)≈N(0,I)q(x_T\mid x_0)\approx\mathcal{N}(0,I), which is almost identical to the prior and LT≈0L_T\approx0. If the schedule is not tuned well (αˉT\bar\alpha_T 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 x^0\hat x_0 first and the mean afterwards. This is what μ~t\tilde\mu_t of Derivation 15 becomes after the ε\varepsilon parameterization. x^0\hat x_0 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 x^0\hat x_0 into [−1,1][-1,1]) or “guidance” (applying the conditional gradient to x^0\hat x_0).

Segment B ③: Why no more noise is added at t=1t=1. Because x0x_0 is deterministic data, the last step should not introduce randomness; if noise were still added at t=1t=1, 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 zz 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 σt=0\sigma_t=0 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 S=20S=20 to 5050 already approaches the quality of T=1000T=1000.

Segment C ②: Where the formula for σt\sigma_t comes from. It is solved from the constraint “keep the marginal distribution q(xt−1∣xt)q(x_{t-1}\mid x_t) unchanged”: set the variance of xt−1x_{t-1} equal to the variance in the DDPM case, and the remaining degree of freedom is controlled by η\eta. With η=0\eta=0 the whole variance term is absorbed by 1−αˉt−1−σ2\sqrt{1-\bar\alpha_{t-1}-\sigma^2}; with η=1\eta=1 DDPM is reproduced exactly.

Segment C ③: Two extra benefits of deterministic sampling. The first is invertibility: given x0x_0, integrating the ODE forward yields the corresponding xTx_T, 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 x0x_0).

Segment C ④: Should x^0\hat x_0 be clipped? For images normalized to [0,1][0,1] or [−1,1][-1,1], the data is bounded during training, but the formula for x^0\hat x_0 does not guarantee boundedness (especially at large tt). 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

QuantityDuring trainingDuring samplingKeptNote
αˉt\bar\alpha_t, βt\beta_tReadReadKept (a precomputed table)Depends only on the schedule; training and sampling must use the same table
x0x_0Read (to construct xtx_t)AbsentNot keptOnly x^0\hat x_0 exists at sampling time
ε\varepsilonRead (the regression target)AbsentNot keptAt sampling time the network output εθ\varepsilon_\theta is used
xtx_tAn intermediate quantityThe stateKept (a loop variable)At sampling time it is the only state
εθ(xt,t)\varepsilon_\theta(x_t,t)ComputedComputedNot keptDiscarded after each step (except for debugging)
x^0\hat x_0AbsentAn intermediate quantityOptionally keptUsed for clipping, guidance, and visualization
σt\sigma_t (DDIM)AbsentReadKept (precomputed)Determined by η\eta and the schedule
Time step ttRandomly sampledA fixed sequenceKept (a schedule table)DDIM uses a subsequence rather than all tt
Network parameters θ\thetaUpdatedFrozenKeptSampling must use the same parameters
Random seedNot fixedFixed (reproducible)Kept (optional)Under deterministic sampling the seed determines the output

Four decision principles:

  1. “The schedule table is the only shared constant.” Training, DDPM sampling, and DDIM sampling must all read the same αˉt\bar\alpha_t; changing the schedule requires retraining, and changing only the sampling side is not allowed.
  2. “The only sampling state is xtx_t.” Apart from xtx_t and tt, 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 εθ\varepsilon_\theta of the previous step into the next step” can essentially be diagnosed as an implementation bug.
  3. ”x0x_0 and ε\varepsilon 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.
  4. “The tt of DDIM is a subsequence, not consecutive integers.” When skipping steps, αˉtnext\bar\alpha_{t_{\text{next}}} must take the next value of the subsequence and must not be written as αˉt−1\bar\alpha_{t-1}. This error throws no exception; it merely makes sample quality inexplicably poor.

5.11 Pitfall List

SymptomPossible causeFix
All samples are blurry, like dataset averagestt sampling favors large tt; or the coefficient was not dropped (Derivation 16)Use SNR-uniform sampling; confirm the loss is LsimpleL_{\text{simple}}
Samples have a fixed noise floorNoise is still added at t=1t=1Do not add zz at the last step
The training loss looks normal but all samples are wrongThe αˉt\bar\alpha_t used for sampling does not match trainingUnify the schedule table and check for index offsets
Quality collapses after DDIM step skippingαˉt−1\bar\alpha_{t-1} is used instead of the next subsequence valueLook up tnextt_{\text{next}} explicitly in the table
The high-noise segment does not learnx0x_0 is regressed instead of ε\varepsilonSwitch to the ε\varepsilon parameterization
Sample diversity is poorGuidance strength too high; or overtrainingLower the guidance coefficient γ\gamma; check for overfitting
Out of memoryActivations are kept at every step for backpropagationBackpropagate through a single random tt only; do not unroll the whole chain
The loss rebounds late in trainingThe learning rate was not adjusted with the schedule; or data augmentation is too strongUse a cosine schedule, lower the learning rate, check the augmentation
Sampling is extremely slowThe full TT steps are usedSwitch to DDIM (20–50 steps) or distillation
Conditional generation does not follow the promptThe gradient does not pass through the condition in the guidance implementationCheck 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 ∇log⁡p(x∣c)+γ(∇log⁡p(x∣c)−∇log⁡p(x))\nabla\log p(x\mid c)+\gamma\left(\nabla\log p(x\mid c)-\nabla\log p(x)\right); with γ>1\gamma>1 the adherence to the condition rises and diversity falls. This trade-off is the same kind of operation as “the lower the temperature τ\tau, 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)

QuestionVAEGANFlowDiffusion
What is learnedEncoder + decoder + priorGenerator + discriminatorInvertible transform ffA score field that varies with tt
ObjectiveELBO (with KL)Minimax (implicit)Exact log-likelihoodELBO (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 log⁡Z\log Z)
Sampling steps111TT (compressible to a few)
Main failure modePosterior collapse, blurMode collapse, instabilityStructural restrictions, equal-dimension constraintSlow, sensitive to step count
Analogy with RLPolicy with latent variables + variational inferenceAdversarial policy improvement (similar to a two-player game)Invertible policy transformMulti-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

DimensionVAEGANNormalizing FlowDiffusion
DensityHas a lower bound, not exactly computableImplicit, not computableExactly computableHas a lower bound (computable step by step)
Training signalELBO regression + KLThe adversarial signal provided by the discriminatorExact log-likelihoodNoise regression (score matching)
StabilityHigh (but needs tuning of β\beta / free bits)Low (needs many tricks)HighHigh
Sampling cost1 forward pass1 forward pass1 inverse transformTT steps (compressible to 4–50)
CoverageMedium (prone to posterior collapse)Low (prone to mode collapse)HighHigh
Sample quality (images)Rather low (blurry)High but needs careful tuningMediumHighest
Structural constraintsWeak (encoder/decoder arbitrary)Weak (generator arbitrary)Strong (must be invertible and equal-dimensional)Weak (network arbitrary)
Latent spaceYes, medium interpretabilityYes (noise), not invertibleYes, equal-dimensional to the dataNone (or borrowed from a VAE latent space)
Main costThe variational gapManual tuning effortLoss of expressiveness from the structural designSampling compute
Best atRepresentation learning, compression, a conditional-generation backboneHigh-fidelity fast generation in a specific domain (such as faces)Density estimation, invertible editing, anomaly detectionGeneral high-fidelity generation, conditional editing
Typical representativesβ\beta-VAE, VQ-VAE, NVAEDCGAN, StyleGAN, BigGANRealNVP, Glow, MAF, FFJORDDDPM, 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 qϕ(z∣x)q_\phi(z\mid x) 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 LsimpleL_{\text{simple}} (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, <10<10 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 x↔zx\leftrightarrow z, 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 TT 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:

  1. 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 log⁡Z\log Z).
  2. 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.
  3. 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.
  4. 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.
  5. Every cost of diffusion comes from “it must take many steps”; its stability and coverage are the returns of that trade.
  6. For the parameterization choose ε\varepsilon; for the loss use LsimpleL_{\text{simple}}; for the schedule prefer cosine.
  7. “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.
  8. The objective function and the evaluation metric never agree; fix the metric first, then choose the objective.
  9. 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”.
  10. The strongest combinations are usually hybrids: VAE + diffusion (latent diffusion), flow + diffusion (flow matching), GAN + likelihood (adversarial plus reconstruction).

6.6 Five Universal Principles

  1. 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.
  2. Treat “computability” as a first-class citizen. Whether log⁡p\log p is needed, whether det⁡J\det J is needed, and whether ∇log⁡p\nabla\log p is needed — the answers to these three questions determine the candidate set, not the other way around.
  3. 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.
  4. 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.
  5. 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 conceptVAEGANFlowDiffusion
Policy π(a∣s)\pi(a\mid s)Encoder qϕ(z∣x)q_\phi(z\mid x)Generator Gθ(z)G_\theta(z)Inverse transform f−1f^{-1}Reverse chain pθ(xt−1∣xt)p_\theta(x_{t-1}\mid x_t)
Environment dynamicsPrior p(z)p(z)Data distribution (implicit)Base distribution pZp_ZForward chain q(xt∣xt−1)q(x_t\mid x_{t-1})
Reward / objectiveELBODiscriminator scoreLog-likelihoodDenoising loss (negative score-matching error)
Critic / value function—Discriminator DψD_\psi—The score network itself (doubling as a “direction critic”)
ExplorationPosterior samplingNoise inputBase-distribution samplingInitial noise + per-step randomness
Entropy regularizationThe β term (KL to the prior)Entropy term (rarely used)—Noise injected at each step
Policy collapsePosterior collapseMode collapse— (bijections do not collapse)Good coverage, rarely collapses
Multi-step decision makingSingle step (one encode–decode)Single stepSingle stepMany steps (naturally sequential)
TemperaturePrior temperature / βSampling temperatureBase-distribution temperatureGuidance strength γ\gamma, sampling stochasticity η\eta
Training-stability problemPosterior collapseGame imbalanceStructural restrictionSensitivity 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

  1. Kingma, D. P., & Welling, M. (2013). Auto-Encoding Variational Bayes. arXiv:1312.6114.
  2. Rezende, D. J., Mohamed, S., & Wierstra, D. (2014). Stochastic Backpropagation and Approximate Inference in Deep Generative Models. ICML.
  3. Burda, Y., Grosse, R., & Salakhutdinov, R. (2015). Importance Weighted Autoencoders. arXiv:1509.00519.
  4. Bowman, S. R., et al. (2016). Generating Sentences from a Continuous Space. CoNLL.
  5. Higgins, I., et al. (2017). β-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework. ICLR.
  6. Burgess, C. P., et al. (2018). Understanding Disentangling in β-VAE. arXiv:1804.03599.
  7. van den Oord, A., Vinyals, O., & Kavukcuoglu, K. (2017). Neural Discrete Representation Learning. NeurIPS. (VQ-VAE)
  8. Razavi, A., van den Oord, A., & Vinyals, O. (2019). Generating Diverse High-Fidelity Images with VQ-VAE-2. NeurIPS.
  9. Alemi, A., Poole, B., et al. (2018). Fixup Initialization / Fixing a Broken ELBO. ICML. (a systematic analysis of free bits)
  10. Tolstikhin, I., et al. (2018). Wasserstein Auto-Encoders. ICLR. (related discussion of the prior hole problem)

Generative Adversarial Networks

  1. Goodfellow, I., et al. (2014). Generative Adversarial Nets. NeurIPS.
  2. Radford, A., Metz, L., & Chintala, S. (2016). Unsupervised Representation Learning with Deep Convolutional GANs. ICLR.
  3. Arjovsky, M., Chintala, S., & Bottou, L. (2017). Wasserstein GAN. ICML.
  4. Gulrajani, I., et al. (2017). Improved Training of Wasserstein GANs. NeurIPS. (WGAN-GP)
  5. Miyato, T., et al. (2018). Spectral Normalization for Generative Adversarial Networks. ICLR.
  6. Mirza, M., & Osindero, S. (2014). Conditional Generative Adversarial Nets. arXiv:1411.1784.
  7. Karras, T., Laine, S., & Aila, T. (2019). A Style-Based Generator Architecture for GANs. CVPR. (StyleGAN)
  8. Nowozin, S., Cseke, B., & Tomioka, R. (2016). f-GAN: Training GANs with Variational Divergence Minimization. NeurIPS.
  9. Salimans, T., et al. (2016). Improved Techniques for Training GANs. NeurIPS.

Normalizing Flows

  1. Dinh, L., Sohl-Dickstein, J., & Bengio, S. (2017). Density Estimation using Real NVP. ICLR.
  2. Kingma, D. P., & Dhariwal, P. (2018). Glow: Generative Flow with Invertible 1×11\times1 Convolutions. NeurIPS.
  3. Papamakarios, G., Pavlakou, T., & Murray, I. (2017). Masked Autoregressive Flow for Density Estimation. NeurIPS.
  4. Kingma, D. P., et al. (2016). Improving Variational Inference with Inverse Autoregressive Flow. NeurIPS.
  5. Rezende, D. J., & Mohamed, S. (2015). Variational Inference with Normalizing Flows. ICML.
  6. Chen, R. T. Q., et al. (2018). Neural Ordinary Differential Equations. NeurIPS.
  7. Grathwohl, W., et al. (2019). FFJORD: Free-form Continuous Dynamics for Scalable Reversible Generative Models. ICLR.
  8. Papamakarios, G., et al. (2021). Normalizing Flows for Probabilistic Modeling and Inference. JMLR. (review)

Diffusion Models and Score Matching

  1. Sohl-Dickstein, J., et al. (2015). Deep Unsupervised Learning using Nonequilibrium Thermodynamics. ICML.
  2. Vincent, P. (2011). A Connection Between Score Matching and Denoising Autoencoders. Neural Computation.
  3. Hyvärinen, A. (2005). Estimation of Non-Normalized Statistical Models by Score Matching. JMLR.
  4. Song, Y., & Ermon, S. (2019). Generative Modeling by Estimating Gradients of the Data Distribution. NeurIPS. (NCSN)
  5. Ho, J., Jain, A., & Abbeel, P. (2020). Denoising Diffusion Probabilistic Models. NeurIPS. (DDPM)
  6. Song, J., Meng, C., & Ermon, S. (2021). Denoising Diffusion Implicit Models. ICLR. (DDIM)
  7. Song, Y., et al. (2021). Score-Based Generative Modeling through Stochastic Differential Equations. ICLR.
  8. Nichol, A., & Dhariwal, P. (2021). Improved Denoising Diffusion Probabilistic Models. ICML. (cosine schedule)
  9. Dhariwal, P., & Nichol, A. (2021). Diffusion Models Beat GANs on Image Synthesis. NeurIPS.
  10. Ho, J., & Salimans, T. (2022). Classifier-Free Diffusion Guidance. arXiv:2207.12598.
  11. Rombach, R., et al. (2022). High-Resolution Image Synthesis with Latent Diffusion Models. CVPR.
  12. Lipman, Y., et al. (2023). Flow Matching for Generative Modeling. ICLR.
  13. Salimans, T., & Ho, J. (2022). Progressive Distillation for Fast Sampling of Diffusion Models. ICLR.

Evaluation Metrics and Cross-Cutting References

  1. Heusel, M., et al. (2017). GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium. NeurIPS. (FID)
  2. Salimans, T., et al. (2016). Improved Techniques for Training GANs. NeurIPS. (IS)
  3. Kynkäänniemi, T., et al. (2019). Improved Precision and Recall Metric for Assessing Generative Models. NeurIPS.
  4. Theis, L., et al. (2016). A Note on the Evaluation of Generative Models. ICLR.
  5. Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press. (Chapter 20, Generative Models)
  6. Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. (Chapter 10, Variational Inference; Chapter 12, Continuous Latent Variables)
  7. Murphy, K. P. (2022). Probabilistic Machine Learning: Advanced Topics. MIT Press. (the systematic chapters on diffusion and score matching)

Appendix: Abbreviation Quick-Reference

AbbreviationFull name in EnglishExplanation
AEAutoencoderA neural network that encodes into a latent space and then decodes to reconstruct the input
bpdbits per dimensionBits per dimension: a density-estimation metric that converts the log-likelihood into bits per dimension
CFGClassifier-Free GuidanceClassifier-free guidance: train a conditional and an unconditional model together and amplify the conditional signal by their difference
CNFContinuous Normalizing FlowContinuous normalizing flow: a continuous invertible transform defined by an ordinary differential equation
DDIMDenoising Diffusion Implicit ModelDenoising diffusion implicit model: a deterministic diffusion sampling method that can skip steps
DDPMDenoising Diffusion Probabilistic ModelDenoising diffusion probabilistic model: the standard multi-step noise-addition/denoising diffusion model
ELBOEvidence Lower BoundA computable lower bound on the log-likelihood
FIDFréchet Inception DistanceA common metric that measures generation quality by the distance between feature distributions
GANGenerative Adversarial NetworkAn implicit generative model in which a generator and a discriminator are trained adversarially
GPGradient PenaltyA regularizer that constrains the gradient norm of the critic to be close to one
IAFInverse Autoregressive FlowA normalizing flow defined by an autoregressive structure
ISInception ScoreA metric that measures sample quality and diversity from classifier outputs
IWAEImportance Weighted AutoencoderAn autoencoder that obtains a tighter ELBO by multiple sampling
JSJensen-Shannon divergenceA symmetric combination of the KL divergences between two distributions and their average distribution
KLKullback-Leibler divergenceAn asymmetric measure of the difference between two probability distributions
LDMLatent Diffusion ModelA model that performs diffusion in a compressed latent space
LULower-Upper decompositionA decomposition that writes a matrix as the product of two triangular matrices
MAFMasked Autoregressive FlowA normalizing flow that uses masks to guarantee an autoregressive structure
MCMCMarkov Chain Monte CarloSampling from a target distribution by means of a Markov chain
NCSNNoise Conditional Score NetworkA model that trains a score network across multiple noise levels
NFNormalizing FlowAn exact density model built from a chain of invertible transforms
ODEOrdinary Differential EquationAn equation containing derivatives with respect to a single independent variable
PF-ODEProbability Flow ODEA deterministic equation that shares its marginals with the diffusion SDE
RLReinforcement LearningA method in which an agent interacts with an environment and improves its decisions from rewards
SDEStochastic Differential EquationA differential equation containing a Brownian motion term
SNRSignal-to-Noise RatioThe ratio of signal power to noise power
VAEVariational AutoencoderA latent-variable generative model trained with variational inference
VQ-VAEVector Quantized VAEA VAE that replaces the continuous latent variable with a discrete codebook
WGANWasserstein GANA GAN trained with the Wasserstein distance
WGAN-GPWGAN with Gradient PenaltyA 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…

    ← Back to home