Contents

Diffusion Model Notes: From the Evidence Lower Bound and Score Matching to DDIM, Guidance, and Flow Matching

Reinforcement Learning
#Diffusion Model#DDPM#Score Matching#DDIM#Flow Matching#Conditional Generation#Latent Diffusion#Diffusion Policy

0. Where These Notes Come From and How to Read Them

0.1 Origin

These notes are organized in the same style as the Deep Reinforcement Learning Core Algorithm Notes: for each algorithm we first explain “why it is needed” and the intuition, then give the formulas, with the key formulas collected into clickable, expandable derivations, then give the complete pseudocode, a paragraph-by-paragraph walkthrough, the gradient flow and detach checklist, a pitfall checklist, and the scope of application; the whole set ends with cross-method comparison tables and a model-selection decision chain.

The reason for treating diffusion models (Diffusion Model, a class of generative models that learn a data distribution by repeatedly adding noise to data and then learning the reverse denoising process) in this “algorithm notes” format as well is that, although diffusion models originated in generative modeling, their training and sampling structure looks very much like a sequential decision problem: sampling is a trajectory that starts from pure noise and gradually moves toward data, and at every step it chooses an “action” (the denoised sample or the predicted noise) given the “state” (the current noisy sample). Only by understanding this trajectory can one understand Diffusion Policy, which later treats diffusion models as policies, and only then can one understand why it is comparable to stochastic policies and maximum-entropy policies in reinforcement learning.

The chapter order of the whole text follows knowledge dependencies: first forward noising and the evidence lower bound, then a training objective; first score matching, then the translation of “predicting noise” into “estimating the score”; first DDPM, then DDIM and continuous time; first the continuous-time viewpoint, then the probability flow ordinary differential equation, flow matching, and distillation.

0.2 Notation

NotationMeaning
x0x_0A clean original data sample (an image, an audio clip, an action sequence, etc.)
xtx_tThe sample after tt steps of noising, t=1,…,Tt=1,\dots,T
xTx_TA pure-noise sample, approximately following the standard normal distribution N(0,I)\mathcal{N}(0,I)
TTThe total number of discrete diffusion steps (commonly 1000 or 2000; training and sampling can differ)
βt\beta_tThe noise variance (noising strength) at step tt, 0<βt<10<\beta_t<1
αt\alpha_tαt=1−βt\alpha_t=1-\beta_t, the single-step signal retention coefficient
αˉt\bar\alpha_tαˉt=∏s=1tαs\bar\alpha_t=\prod_{s=1}^{t}\alpha_s, the cumulative signal retention coefficient from x0x_0 to xtx_t
q(⋅)q(\cdot)The forward noising process (constructed artificially at training time, containing no learnable parameters)
pθ(⋅)p_\theta(\cdot)The reverse denoising process (implemented by a neural network with parameters θ\theta)
ε\varepsilonStandard Gaussian noise, ε∼N(0,I)\varepsilon\sim\mathcal{N}(0,I)
εθ(xt,t)\varepsilon_\theta(x_t,t)The network’s prediction of the noise contained in xtx_t
sθ(x,t)s_\theta(x,t)The network’s estimate of the score (that is, the gradient of the log probability density with respect to the input)
∇xlog⁡pt(x)\nabla_x\log p_t(x)The score of the marginal distribution of the data distribution at time tt
γ\gammaThe guidance strength of classifier-free guidance
λt\lambda_tThe log signal-to-noise ratio, λt=log⁡(αˉt/(1−αˉt))\lambda_t=\log\left(\bar\alpha_t/(1-\bar\alpha_t)\right)
wtw_tThe loss weight, used to reweight different noise levels
D\mathcal{D}The training data distribution
NFE\mathrm{NFE}The number of function evaluations, the core measure of sampling cost

Note: this text uses ε\varepsilon for noise and uses ϵ\epsilon only in a very few places for an infinitesimal quantity; it uses xx for samples and does not absorb the state symbol ss from reinforcement learning. Chapter 14, when discussing diffusion policies, temporarily writes actions as aa and observations as oo, and redeclares this in that section.

0.3 How to Read

  • Chapters 1 to 13 walk through the algorithms and formulas one by one in order of knowledge dependency, and are suitable for sequential reading.
  • Chapter 14 discusses the interface between diffusion models and reinforcement learning / embodied intelligence (diffusion policies), Chapter 15 gives application scenarios, and Chapter 16 is the cross-method summary: one master table, six key disagreements, and one model-selection decision chain. If you only came for “which kind of diffusion model should I use”, you can look at the master table in 16.1 first and then follow the decision chain in 16.3.
  • All derivations are placed in clickable, expandable blocks: read the conclusion and the intuition first, and expand them only when you need to check the details. The whole text contains 18 foldable derivations, covering the closed-form marginal distribution, the evidence lower bound decomposition, the posterior recipe, the simplified loss, the Tweedie formula, the DDIM update, the reverse stochastic differential equation, the probability flow ordinary differential equation, classifier-free guidance, cross-attention, parameterization error propagation, the flow matching objective, the distillation objective, the closed form of FID, and so on.
  • The first line of every pseudocode block uniformly labels “Input / Output” together with the key tensor shapes; the definition of a symbol is taken from the chapter in which it first appears, and is kept consistent when reused across chapters.

1. The Three Routes of Generative Modeling and Where Diffusion Sits

1.1 What Generative Modeling Is Really Doing

Given a batch of training samples {x(i)}i=1N\{x^{(i)}\}_{i=1}^{N}, we want to learn a probability density pθ(x)p_\theta(x) that is close to the true data distribution pdata(x)p_{\text{data}}(x) and from which we can sample new samples that look like the training data but do not duplicate it. Every generative model answers two questions:

  1. In what form is pθ(x)p_\theta(x) represented;
  2. With what objective is it trained.

According to the answers to these two questions, there are three mainstream routes.

RouteIs the density computableTraining objectiveSampling methodRepresentative modelsMain weakness
Explicit likelihoodComputable, or lower-boundableMaximize the log likelihood or its lower boundOne forward pass, or autoregressive item-by-item generationVariational Autoencoder (VAE), Autoregressive Model (AR), Normalizing FlowThe likelihood objective is insensitive to “perceptual quality”; the VAE posterior approximation is biased; autoregressive sampling is slow with a fixed order; flows have strong topological constraints
Implicit densityNot computableAdversarial game, with the discriminator providing the signalOne forward passGenerative Adversarial Network (GAN)Unstable training, mode collapse, hard to cover all modes
Score-based / diffusionThe score can be estimated without the normalization constantDenoising regression (predicting noise or the score)Multi-step iterative denoisingDenoising Diffusion Probabilistic Model (DDPM), Noise Conditional Score Network (NCSN), Flow MatchingSlow sampling (tens to thousands of network evaluations); the training and sampling step counts need tuning

1.2 The Position of Diffusion Models

Diffusion models belong to the third route, and their core idea can be summarized in one sentence: do not directly model the complex shape of p(x)p(x); instead, model the vector field that “wipes the noise away little by little”.

They simultaneously absorb the advantages of the first two routes:

  • The training objective is a regression problem (predicting noise), with no adversarial game, and is therefore stable;
  • The objective can be derived rigorously from the evidence lower bound (Evidence Lower Bound, ELBO, a lower bound on the log likelihood), so it has a likelihood interpretation;
  • Because every noise level is explicitly trained, the model is under pressure to cover multiple modes of the data distribution, so mode coverage is usually better than that of a GAN.

The price is that sampling must be iterative: starting from pure noise, each step advances only a little, requiring tens to thousands of network forward passes. This price was later compressed step by step by DDIM, distillation, and flow matching, which is how today’s common “4 steps to an image” came about.

1.3 A Formal Analogy with Reinforcement Learning

View the sampling process as a finite-horizon sequential decision problem:

Reinforcement learning conceptIts counterpart in diffusion sampling
State sts_tThe current noisy sample xtx_t
Action ata_tThe next sample xt−1x_{t-1}, or the network’s noise estimate εθ(xt,t)\varepsilon_\theta(x_t,t)
Policy π(at∣st)\pi(a_t\mid s_t)The reverse transition pθ(xt−1∣xt)p_\theta(x_{t-1}\mid x_t)
Environment dynamicsThe forward noising process q(xt∣xt−1)q(x_t\mid x_{t-1}) (fixed and known)
Episode length TTThe number of diffusion steps
Reward / objectiveMake the final sample land on the data distribution (equivalent to maximizing the lower bound on the data’s log likelihood)

This analogy has two practical uses: first, to understand the diffusion policy of Chapter 14 (which writes “action generation” as a denoising trajectory with the observation as the condition); second, to understand why the “policy” of a diffusion model is naturally multimodal — it is not a unimodal Gaussian but a flexible distribution composed of multi-step conditional distributions.


2. The Forward Process: Turning Data into Noise Little by Little

2.1 The Markov Noising Chain

The forward process is a fixed Markov chain that adds a little Gaussian noise to the sample from the previous moment at each step:

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

Writing it in reparameterized form makes sampling and analysis convenient:

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

where αt=1−βt\alpha_t=1-\beta_t. The joint distribution of the whole chain is

q(x1:T∣x0)=∏t=1Tq(xt∣xt−1)q(x_{1:T}\mid x_0)=\prod_{t=1}^{T}q(x_t\mid x_{t-1})

Two key points:

  1. There are no learnable parameters. The forward process is fully determined by the noise schedule {βt}\{\beta_t\}; at training time we simply “add noise according to the formula”, and it does not participate in the gradient.
  2. Every step is a linear Gaussian transform. Gaussian distributions are closed under linear transforms and addition, so any marginal distribution of the whole chain is still Gaussian — this is exactly why the closed-form solution in the next section holds.
Derivation: Why the marginal distribution at any time is a closed-form Gaussian

Step 1: A single step is a linear Gaussian transform. If xt−1∼N(μt−1,σt−12I)x_{t-1}\sim\mathcal{N}(\mu_{t-1},\sigma_{t-1}^2 I), then

xt=αt xt−1+βt εx_t=\sqrt{\alpha_t}\,x_{t-1}+\sqrt{\beta_t}\,\varepsilon

is a linear combination of two independent Gaussians, with mean and variance respectively

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

Step 2: Start from x0x_0 and substitute step by step to get the cumulative product form. Starting from x0x_0 being a deterministic value (with zero variance), the first step gives x1=α1x0+β1ε1x_1=\sqrt{\alpha_1}x_0+\sqrt{\beta_1}\varepsilon_1 with variance β1=1−α1\beta_1=1-\alpha_1. Assume step t−1t-1 already holds:

xt−1=αˉt−1 x0+1−αˉt−1 ε′,x_{t-1}=\sqrt{\bar\alpha_{t-1}}\,x_0+\sqrt{1-\bar\alpha_{t-1}}\,\varepsilon',

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 x0+αt(1−αˉt−1) ε′+βt ε=\sqrt{\alpha_t\bar\alpha_{t-1}}\,x_0+\sqrt{\alpha_t\left(1-\bar\alpha_{t-1}\right)}\,\varepsilon'+\sqrt{\beta_t}\,\varepsilon

Step 3: Merge the two independent Gaussians. The weighted sum of two independent zero-mean Gaussians is still a 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

Hence

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 the merged εˉ\bar\varepsilon differs from both the original ε′\varepsilon' and ε\varepsilon, yet it is still standard Gaussian — this is a direct consequence of “a linear combination of Gaussians is still Gaussian”, and the specific mixing coefficients need not be known.

Step 4: Conclusion and use. By induction we obtain

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,\ (1-\bar\alpha_t)I\right)

It means that at training time we do not actually need to run tt noising steps: we just sample one ε\varepsilon and compute xtx_t in one shot. This is the key to the training efficiency of diffusion models: no matter how large tt is, constructing xtx_t costs only O(1)O(1).

2.2 Reparameterized Sampling and the “Noise Schedule”

With the closed-form marginal distribution in hand, constructing a noisy sample at training time takes only one line:

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

The noise schedule {βt}\{\beta_t\} determines “when the signal gets drowned out”. Two commonly used schedules:

Linear schedule (the original DDPM): β1=10−4\beta_1=10^{-4} increased linearly to βT=0.02\beta_T=0.02. Its problem is that noise is added too fast in the low-noise range and hardly changes in the high-noise range, so the last few steps are wasted.

Cosine schedule (improved DDPM): define

αˉt=cos⁡2(t/T+s1+s⋅π2)cos⁡2(s1+s⋅π2),s=0.008\bar\alpha_t=\frac{\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)},\qquad s=0.008

It makes the decrease of αˉt\bar\alpha_t more uniform, smoother in the low-noise range, and faster to reach zero in the high-noise range.

ScheduleShape of αˉt\bar\alpha_tAdvantageDisadvantage
LinearSteep first, then flatSimple to implement, aligned with the original paperToo dense in the low-noise range, wasted steps at the end
CosineRoughly uniform decreaseBalanced utilization of every noise range, better FIDRequires recalibrating αˉT\bar\alpha_T to be close to 0

2.3 Signal-to-Noise Ratio: Judging “How Much Signal Is Left at This Step”

Define the log signal-to-noise ratio (signal-to-noise ratio, SNR):

λt=log⁡αˉt1−αˉt\lambda_t=\log\frac{\bar\alpha_t}{1-\bar\alpha_t}

It writes the ratio of “signal variance” to “noise variance” on a logarithmic scale, which makes linear interpolation and weighting convenient.

Derivation: Why the signal-to-noise ratio decreases monotonically over time, and its relation to the noise schedule

Step 1: Read the signal and noise power off the closed-form marginal distribution. xt=αˉtx0+1−αˉtεx_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\varepsilon, and the two terms are independent, so

SNRt=αˉt E∥x0∥2(1−αˉt) E∥ε∥2=αˉt1−αˉt⋅E∥x0∥2d\mathrm{SNR}_t=\frac{\bar\alpha_t\,\mathbb{E}\|x_0\|^2}{(1-\bar\alpha_t)\,\mathbb{E}\|\varepsilon\|^2}=\frac{\bar\alpha_t}{1-\bar\alpha_t}\cdot\frac{\mathbb{E}\|x_0\|^2}{d}

If the data have been standardized to unit variance, then SNRt=αˉt/(1−αˉt)\mathrm{SNR}_t=\bar\alpha_t/(1-\bar\alpha_t), whose logarithm is λt\lambda_t.

Step 2: Prove monotonicity. Because αˉt=∏s≤tαs\bar\alpha_t=\prod_{s\le t}\alpha_s is monotonically non-increasing in tt (each αs∈(0,1)\alpha_s\in(0,1)), the quantity αˉt/(1−αˉt)\bar\alpha_t/(1-\bar\alpha_t) is monotonically non-increasing and λt\lambda_t decreases monotonically. As λt→+∞\lambda_t\to+\infty there is almost no noise; as λt→−∞\lambda_t\to-\infty there is almost nothing but noise.

Step 3: Why this quantity matters. The training loss is far more sensitive to λt\lambda_t than to tt: the same Δt\Delta t corresponds to a large Δλ\Delta\lambda in the low-noise range and a very small one in the high-noise range. Therefore sampling time steps uniformly in λ\lambda is “fairer” than sampling uniformly in tt; this also explains why many works switch to “uniform sampling in log signal-to-noise ratio” or “SNR-weighted loss”.

2.4 The Continuous-Time Limit: From a Discrete Chain to a Stochastic Differential Equation

As T→∞T\to\infty and βt→0\beta_t\to0, the limit of the forward chain is a stochastic differential equation (Stochastic Differential Equation, SDE). Two common forms:

Variance Preserving (VP):

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

Its marginal distribution preserves unit variance, corresponding to the discrete αˉt=exp⁡(−∫0tβ(s) ds)\bar\alpha_t=\exp\left(-\int_0^t\beta(s)\,\mathrm{d}s\right).

Variance Exploding (VE):

dx=dσ2(t)dt dw\mathrm{d}x=\sqrt{\frac{\mathrm{d}\sigma^2(t)}{\mathrm{d}t}}\,\mathrm{d}w

The noise variance grows over time and the signal does not decay, corresponding to the annealed Langevin sampling of NCSN.

Chapter 7 gives the complete derivation of the reverse SDE and the probability flow ordinary differential equation (Probability Flow Ordinary Differential Equation, PF ODE). For now, remember the conclusion: discrete diffusion is a numerical discretization of a continuous SDE, and both DDPM and DDIM can be viewed as different ways of discretizing it.


3. The Reverse Process and the Evidence Lower Bound: Where the Training Objective Comes From

3.1 What the Reverse Process Has to Learn

If the forward process could be run backwards, we could generate data from noise. The reverse process is defined as

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 the variance is almost always fixed to Σθ(xt,t)=σt2I\Sigma_\theta(x_t,t)=\sigma_t^2 I, and only the mean μθ\mu_\theta is predicted by the network. The whole reverse chain is

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

3.2 The Evidence Lower Bound

The training objective is to maximize the log likelihood log⁡pθ(x0)\log p_\theta(x_0) of the data. Computing it directly is infeasible (it requires integrating over all latent variables), so we use the standard trick of variational inference: introduce the forward process as the approximate posterior and obtain a computable lower bound.

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

The right-hand side is the evidence lower bound (ELBO). Expanding it by time step yields three components with a clear structure.

Derivation: The term-by-term decomposition of the evidence lower bound and the role of the forward process

Step 1: Use Jensen’s inequality to move the logarithm inside the expectation.

log⁡pθ(x0)=log⁡∫pθ(x0:T) dx1:T=log⁡Eq(x1:T∣x0)[pθ(x0:T)q(x1:T∣x0)]≥Eq[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} =\log\mathbb{E}_{q(x_{1:T}\mid x_0)}\left[\frac{p_\theta(x_{0:T})}{q(x_{1:T}\mid x_0)}\right] \ge\mathbb{E}_{q}\left[\log\frac{p_\theta(x_{0:T})}{q(x_{1:T}\mid x_0)}\right]

The inequality comes from Jensen’s inequality (log⁡\log is concave), and equality holds when q=pθq=p_\theta, in which case the gap is zero.

Step 2: Factorize the joint distribution into a product along the Markov chain.

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

Step 3: Cancel the common factors of adjacent time steps term by term. Rewrite q(xt∣xt−1)q(x_t\mid x_{t-1}) in a conditional form that includes x0x_0 (using Bayes’ rule and the Markov property):

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)}

This step is the crux of the whole derivation: it replaces “a single forward step” with “a ratio centered on the posterior”, so that each term can be matched to a KL divergence. After substitution, adjacent terms cancel in pairs and only the boundary terms remain:

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

Step 4: Write the log ratios as KL divergences. Note that Eq[log⁡p(xT)q(xT∣x0)]=−DKL(q(xT∣x0) ∥ p(xT))\mathbb{E}_q\left[\log\frac{p(x_T)}{q(x_T\mid x_0)}\right]=-D_{\mathrm{KL}}\left(q(x_T\mid x_0)\,\|\,p(x_T)\right), hence

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

Step 5: The meaning of the three terms. LTL_T asks “is the endpoint really close to a standard Gaussian”; since the forward schedule is fixed it is nearly a constant and can be ignored in training. Lt−1L_{t-1} asks “does each reverse transition match the true posterior” and is the main workhorse of training. L0L_0 is “the reconstruction quality of the final step”, equivalent to the negative log likelihood of a Gaussian decoder. Training is therefore all about making pθ(xt−1∣xt)p_\theta(x_{t-1}\mid x_t) as close as possible to q(xt−1∣xt,x0)q(x_{t-1}\mid x_t,x_0).

3.3 The True Posterior Is a Closed-Form Gaussian

The q(xt−1∣xt,x0)q(x_{t-1}\mid x_t,x_0) inside Lt−1L_{t-1} is “the distribution of an intermediate step given both the start and the end”. Because the forward process is a linear Gaussian chain, it is also Gaussian, with both its mean and variance available in closed form.

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) μ~t=αˉt−1 βt1−αˉt x0+αt(1−αˉt−1)1−αˉt xt\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 β~t=1−αˉt−11−αˉt βt\tilde\beta_t=\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\,\beta_t
Derivation: The completing-the-square process for the posterior mean and variance

Step 1: Write down the two factors of the posterior. By Bayes’ rule,

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)

The first factor is N(αtxt−1,βtI)\mathcal{N}\left(\sqrt{\alpha_t}x_{t-1},\beta_t I\right) and the second is N(αˉt−1x0,(1−αˉt−1)I)\mathcal{N}\left(\sqrt{\bar\alpha_{t-1}}x_0,(1-\bar\alpha_{t-1})I\right). The product of two Gaussians is still Gaussian, so we only need to complete the square in the exponent.

Step 2: Keep only the quadratic and linear terms in xt−1x_{t-1}.

−12[∥xt−αtxt−1∥2βt+∥xt−1−αˉt−1x0∥21−αˉt−1]-\frac{1}{2}\left[\frac{\left\|x_t-\sqrt{\alpha_t}x_{t-1}\right\|^2}{\beta_t}+\frac{\left\|x_{t-1}-\sqrt{\bar\alpha_{t-1}}x_0\right\|^2}{1-\bar\alpha_{t-1}}\right]

The coefficient of the quadratic term is

αtβt+11−αˉt−1=αt(1−αˉt−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)+\beta_t}{\beta_t\left(1-\bar\alpha_{t-1}\right)} =\frac{1-\bar\alpha_t}{\beta_t\left(1-\bar\alpha_{t-1}\right)}

Hence the posterior variance is

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

Step 3: Find the mean. The coefficient of the linear term is

αtβtxt+αˉt−11−αˉt−1x0\frac{\sqrt{\alpha_t}}{\beta_t}x_t+\frac{\sqrt{\bar\alpha_{t-1}}}{1-\bar\alpha_{t-1}}x_0

The mean equals “the linear coefficient divided by the quadratic coefficient”:

μ~t=β~t(αtβtxt+αˉt−11−αˉt−1x0)\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)

Substituting the explicit expression of β~t\tilde\beta_t and simplifying gives

μ~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

Step 4: Rewrite the mean in terms of the noise prediction. At training time the network sees xtx_t rather than x0x_0, so we solve for x0x_0 from the closed-form marginal distribution:

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

After substitution and rearrangement we obtain a form that depends only on xtx_t and the noise:

μ~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)

This step is the direct source of the DDPM sampling formula: simply replace ε\varepsilon with the network prediction εθ(xt,t)\varepsilon_\theta(x_t,t).

3.4 From Term-by-Term KL to the Simplified Loss

Expanding the KL between the two Gaussians inside Lt−1L_{t-1} shows that it differs from “the mean squared error of the noise prediction” only by a constant weight that depends on tt.

Lt−1=Eq[βt22σt2αt(1−αˉt)∥ε−εθ(xt,t)∥2]+CL_{t-1}=\mathbb{E}_{q}\left[\frac{\beta_t^2}{2\sigma_t^2\alpha_t\left(1-\bar\alpha_t\right)}\left\|\varepsilon-\varepsilon_\theta(x_t,t)\right\|^2\right]+C

DDPM’s approach is to drop this weight outright, giving the simplified loss:

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]
Derivation: Why the term-by-term KL is equivalent to weighted noise regression, and what dropping the weight means

Step 1: The KL between two Gaussians has a closed form. For Gaussians with the same variance,

DKL(N(μ1,σ2I) ∥ N(μ2,σ2I))=∥μ1−μ2∥22σ2D_{\mathrm{KL}}\left(\mathcal{N}(\mu_1,\sigma^2I)\,\|\,\mathcal{N}(\mu_2,\sigma^2I)\right)=\frac{\left\|\mu_1-\mu_2\right\|^2}{2\sigma^2}

Step 2: Substitute the two means. The true posterior mean contains ε\varepsilon and the network mean contains εθ\varepsilon_\theta, and the only difference between them is this term:

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

Step 3: Squaring gives the weight.

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

which agrees with the expression for Lt−1L_{t-1}.

Step 4: Dropping the weight changes the optimization problem. The original weight varies sharply with tt: βt2/(2σt2αt(1−αˉt))\beta_t^2/(2\sigma_t^2\alpha_t(1-\bar\alpha_t)) is large in the low-noise range and small in the high-noise range. Dropping the weight amounts to down-weighting “reconstruction accuracy in the low-noise range” and up-weighting “coarse structure in the high-noise range”. The experimental conclusion of the original DDPM paper is that samples trained this way are better, because perceptual quality is mainly determined by structure in the low-to-medium noise range, whereas the log likelihood cares more about the exact probability of every pixel. This also explains why “optimizing the likelihood” and “optimizing perceptual quality” do not fully coincide in diffusion models.

Step 5: Weighting is a tunable design dimension. Keeping the weight means optimizing the ELBO (favoring the likelihood); dropping it favors perceptual quality. An intermediate scheme is minimum signal-to-noise ratio weighting (Min-SNR):

wt=min⁡(αˉt1−αˉt, γ)w_t=\min\left(\frac{\bar\alpha_t}{1-\bar\alpha_t},\ \gamma\right)

which caps the weight in the low-noise range and prevents a few time steps from dominating the gradient; this is a commonly used compromise in practice.

3.5 Three Equivalent Parameterizations

The network can predict any one of three things, which are mathematically equivalent but numerically different:

ParameterizationNetwork outputRelation to x0x_0Numerical characteristics
x0x_0 parameterizationx^0(xt,t)\hat x_0(x_t,t)DirectStable at low noise, errors amplified at high noise
ε\varepsilon parameterizationε^(xt,t)\hat\varepsilon(x_t,t)x^0=(xt−1−αˉtε^)/αˉt\hat x_0=\left(x_t-\sqrt{1-\bar\alpha_t}\hat\varepsilon\right)/\sqrt{\bar\alpha_t}Stable at high noise, relative errors amplified at low noise
vv parameterizationv^(xt,t)\hat v(x_t,t)x^0=αˉtxt−1−αˉtv^\hat x_0=\sqrt{\bar\alpha_t}x_t-\sqrt{1-\bar\alpha_t}\hat vFairly stable at both ends, more balanced training target variance
v=αˉt ε−1−αˉt x0v=\sqrt{\bar\alpha_t}\,\varepsilon-\sqrt{1-\bar\alpha_t}\,x_0

Chapter 10 explains from the perspective of error propagation why these three parameterizations behave differently in different noise ranges.


4. Score Matching and Langevin Dynamics: Another Equivalent Path

4.1 The Score Function

For a probability density p(x)p(x), the score is defined as

∇xlog⁡p(x)\nabla_x\log p(x)

It is a vector field pointing in “the direction in which the probability density rises fastest”. The key property is: it does not need to know the normalization constant. If p(x)=p~(x)/Zp(x)=\tilde p(x)/Z, then ∇log⁡p=∇log⁡p~\nabla\log p=\nabla\log\tilde p and ZZ is eliminated by differentiation. This makes “learning the score directly with a neural network” possible, whereas learning the density directly would run into an intractable partition function.

4.2 Explicit Score Matching and Its Difficulty

The most naive idea is to minimize

Epdata(x)[∥sθ(x)−∇xlog⁡pdata(x)∥2]\mathbb{E}_{p_{\text{data}}(x)}\left[\left\|s_\theta(x)-\nabla_x\log p_{\text{data}}(x)\right\|^2\right]

But the ground truth on the right-hand side is unavailable: we only have samples, not an analytic ∇log⁡pdata\nabla\log p_{\text{data}}. This objective cannot be computed directly.

4.3 Implicit Score Matching (Denoising Score Matching)

The solution is to not require the network to fit the score of the data distribution, but to require it to fit the score of the conditional distribution of xtx_t given x0x_0. Because the marginal distribution has a closed form, this conditional score can be computed analytically:

∇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}}

The training objective therefore becomes

LDSM=Et,x0,ε[∥sθ(xt,t)+ε1−αˉt∥2]L_{\text{DSM}}=\mathbb{E}_{t,x_0,\varepsilon}\left[\left\|s_\theta(x_t,t)+\frac{\varepsilon}{\sqrt{1-\bar\alpha_t}}\right\|^2\right]

It requires only sampling, not the true density. This is denoising score matching (Denoising Score Matching, DSM).

Derivation: Why the implicit objective is equivalent to the explicit one (up to a constant independent of the parameters)

Step 1: Write down the difference between the two objectives. Let q(xt)=∫q(xt∣x0)pdata(x0)dx0q(x_t)=\int q(x_t\mid x_0)p_{\text{data}}(x_0)\mathrm{d}x_0. Expanding the squared term:

Eq(xt)∥sθ(xt)∥2−2 Eq(xt)[sθ(xt)⊤∇log⁡q(xt)]+Eq(xt)∥∇log⁡q(xt)∥2\mathbb{E}_{q(x_t)}\left\|s_\theta(x_t)\right\|^2-2\,\mathbb{E}_{q(x_t)}\left[s_\theta(x_t)^\top\nabla\log q(x_t)\right]+\mathbb{E}_{q(x_t)}\left\|\nabla\log q(x_t)\right\|^2

The explicit objective has the same shape after expansion, except that ∇log⁡q\nabla\log q is replaced by ∇log⁡pdata\nabla\log p_{\text{data}}. So we only need to compare the difference in the middle term.

Step 2: Handle the middle term of the implicit objective with the law of total expectation over conditional distributions.

Eq(xt)[sθ(xt)⊤∇log⁡q(xt)]=Epdata(x0)Eq(xt∣x0)[sθ(xt)⊤∇log⁡q(xt∣x0)]\mathbb{E}_{q(x_t)}\left[s_\theta(x_t)^\top\nabla\log q(x_t)\right] =\mathbb{E}_{p_{\text{data}}(x_0)}\mathbb{E}_{q(x_t\mid x_0)}\left[s_\theta(x_t)^\top\nabla\log q(x_t\mid x_0)\right]

This step uses the identity that “the expectation of the score over the conditional distribution equals the expectation over the marginal distribution”: Eq(xt∣x0)[∇log⁡q(xt∣x0)]=∇log⁡q(xt)\mathbb{E}_{q(x_t\mid x_0)}\left[\nabla\log q(x_t\mid x_0)\right]=\nabla\log q(x_t), then multiplying by the outer weight and integrating over x0x_0 gives the result.

Step 3: Conclusion. The two objectives differ only by a constant that does not depend on θ\theta, so their optimal solutions are the same and their gradients are the same. Intuitively: regressing the conditional score at noise level tt is equivalent to regressing the marginal score, because the marginal score is itself a weighted average of conditional scores.

4.4 Converting Among Score, Noise, and Clean Sample (the Tweedie Formula)

The same network output can be translated into three meanings: noise, score, and clean-sample estimate.

sθ(xt,t)=−εθ(xt,t)1−αˉts_\theta(x_t,t)=-\frac{\varepsilon_\theta(x_t,t)}{\sqrt{1-\bar\alpha_t}} x^0=xt−1−αˉt εθ(xt,t)αˉt=xt+(1−αˉt)sθ(xt,t)αˉt\hat x_0=\frac{x_t-\sqrt{1-\bar\alpha_t}\,\varepsilon_\theta(x_t,t)}{\sqrt{\bar\alpha_t}}=\frac{x_t+\left(1-\bar\alpha_t\right)s_\theta(x_t,t)}{\sqrt{\bar\alpha_t}}

The second expression is the concrete form of the Tweedie formula in diffusion models.

Derivation: The Tweedie formula gives the optimal estimate of the posterior mean

Step 1: Write the log gradient of the posterior p(x0∣xt)p(x_0\mid x_t). By Bayes’ rule,

∇xtlog⁡p(xt)=∇xtlog⁡∫p(xt∣x0)p(x0)dx0\nabla_{x_t}\log p(x_t)=\nabla_{x_t}\log\int p(x_t\mid x_0)p(x_0)\mathrm{d}x_0

Step 2: Swap the integral and the derivative, and use the closed form of p(xt∣x0)p(x_t\mid x_0). Differentiating the Gaussian conditional density gives

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

Step 3: Solve for the posterior mean.

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

This is the Tweedie formula. It says: the score field encodes the optimal direction “from a noisy sample back to a clean sample”, so learning the score with one network means simultaneously learning to denoise and to estimate x0x_0.

Step 4: Align with the noise parameterization. Substituting ∇log⁡pt(xt)=−ε/1−αˉt\nabla\log p_t(x_t)=-\varepsilon/\sqrt{1-\bar\alpha_t} immediately gives

E[x0∣xt]=xt−1−αˉt εαˉt\mathbb{E}\left[x_0\mid x_t\right]=\frac{x_t-\sqrt{1-\bar\alpha_t}\,\varepsilon}{\sqrt{\bar\alpha_t}}

The conversion relations among the three are thereby closed, which also explains why DDPM’s “predicting noise” and NCSN’s “predicting the score” are the same thing.

4.5 Annealed Langevin Dynamics Sampling

Once the score is available, we can sample from the distribution with Langevin dynamics:

x←x+η2∇xlog⁡p(x)+η z,z∼N(0,I)x\leftarrow x+\frac{\eta}{2}\nabla_x\log p(x)+\sqrt{\eta}\,z,\qquad z\sim\mathcal{N}(0,I)

When the step size η→0\eta\to0 and the number of iterations is large enough, the sample distribution converges to p(x)p(x). The difficulty of the diffusion-model version is that the data distribution is “smoothed out” by many noise levels, and the score at a single noise level only corresponds to a smoothed distribution. The solution is annealing: start from a high noise level, lower the noise level gradually, and run a number of Langevin steps with the corresponding conditional score at each level.

x←x+ηi2sθ(x,σi)+ηi z,σ1>σ2>⋯>σLx\leftarrow x+\frac{\eta_i}{2}s_\theta\left(x,\sigma_i\right)+\sqrt{\eta_i}\,z,\qquad \sigma_1>\sigma_2>\cdots>\sigma_L

This is the sampling algorithm of NCSN, and in the continuous limit it belongs to the same family as DDPM’s ancestral sampling.

4.6 The Relation to DDPM in One Sentence

ViewpointTraining objectiveSampling method
Variational / likelihood viewpoint (DDPM)Predict noise, equivalent to maximizing a simplified version of the ELBOAncestral sampling, injecting noise at every step
Score viewpoint (NCSN)Predict the score, equivalent to denoising score matchingAnnealed Langevin
Continuous viewpoint (SDE)Predict the score / noise, with continuous timeReverse SDE or probability flow ODE

These three are not three models but three languages for the same model. Chapter 7 unifies them in the stochastic differential equation.


5. DDPM: The Complete Algorithm, Pseudocode, and Engineering Details

5.1 The Algorithm at a Glance

DDPM assembles the content of the previous four chapters into two loops:

  • Training loop: sample real samples and random time steps, construct noisy samples according to the closed-form marginal distribution, let the network predict the noise in them, and minimize the mean squared error.
  • Sampling loop: start from a standard Gaussian, denoise step by step according to the posterior mean formula, and re-inject a small amount of noise at every step (except the last one).

5.2 Training Pseudocode

# Input: data batch x0, shape (B, C, H, W); noise schedule beta[1..T]; network eps_theta(x_t, t)
# Output: updated parameters theta, exponential moving average parameters theta_ema
for x0 in dataloader:                       # x0: (B, C, H, W), normalized to [-1, 1]
    t = randint(1, T, size=(B,))            # (B,), an independently sampled time step per sample
    eps = randn_like(x0)                    # (B, C, H, W), standard Gaussian
    alpha_bar_t = gather(alpha_bar, t)      # (B, 1, 1, 1), cumulative coefficient per sample
    x_t = sqrt(alpha_bar_t) * x0 + sqrt(1 - alpha_bar_t) * eps
    pred = eps_theta(x_t, t)                # (B, C, H, W), predicted noise
    loss = mean((pred - eps) ** 2)          # scalar, averaged over the batch and spatial dimensions
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()
    ema_update(theta_ema, theta, decay)     # no gradient, only a sliding average of the weights

5.3 Sampling Pseudocode

# Input: the trained eps_theta, noise schedule beta[1..T], number of sampling steps T
# Output: generated samples x0, shape (B, C, H, W)
x = randn(B, C, H, W)                       # x_T, standard Gaussian
for t in range(T, 0, -1):
    eps = eps_theta(x, t)                   # (B, C, H, W)
    alpha_t = alpha[t]                      # scalar
    alpha_bar_t = alpha_bar[t]              # scalar
    beta_t = beta[t]                        # scalar
    mean = (x - beta_t / sqrt(1 - alpha_bar_t) * eps) / sqrt(alpha_t)
    if t > 1:
        sigma_t = sqrt(beta_t * (1 - alpha_bar[t-1]) / (1 - alpha_bar_t))
        x = mean + sigma_t * randn_like(x)
    else:
        x = mean                            # no more noise at the last step
return x

5.4 Paragraph-by-Paragraph Walkthrough

The training part.

  1. t = randint(1, T, size=(B,)): each sample draws its own time step independently rather than sharing one across the whole batch. This guarantees that high, medium, and low noise ranges are all covered within the same batch, so the gradient does not come from only one scale.
  2. x_t = sqrt(alpha_bar_t) * x0 + ...: this uses exactly the closed-form marginal distribution of 2.2. There is no need to actually run tt noising steps; one shot is enough, which is the key to training efficiency.
  3. pred = eps_theta(x_t, t): the network must know the time step, otherwise it cannot tell the current noise level and cannot give the correct denoising direction. The time step is usually turned into an embedding vector by a sinusoidal positional encoding plus a multilayer perceptron, and then injected into each residual block (see Chapter 10).
  4. loss = mean((pred - eps) ** 2): the objective is the simplest mean squared error, with no adversarial term, no KL term, and no importance sampling. This is the fundamental reason for the training stability of diffusion models.
  5. ema_update(...): sampling uses the exponential moving average (Exponential Moving Average, EMA) parameters rather than the instantaneous training parameters. EMA amounts to averaging the model over the most recent steps, which significantly reduces sampling variance and improves sample quality. The decay is commonly 0.999 to 0.9999; early in training a smaller decay can be used so that the average catches up faster.

The sampling part.

  1. x = randn(...): the starting point must be a standard Gaussian, because the endpoint distribution p(xT)p(x_T) of the reverse chain is defined as a standard Gaussian. If αˉT\bar\alpha_T of the forward schedule is not close to 0, this assumption will be biased, and the schedule must be tuned properly at training time.
  2. mean = (x - beta_t / sqrt(1 - alpha_bar_t) * eps) / sqrt(alpha_t): this is exactly the posterior mean derived in 3.3. Intuitively it means “first subtract the noise along the predicted noise direction, then divide by the signal retention coefficient for scale correction”.
  3. sigma_t = sqrt(beta_t * (1 - alpha_bar[t-1]) / (1 - alpha_bar_t)): this takes the posterior variance β~t\tilde\beta_t, which is “the true variance of the posterior given x0x_0”. The original DDPM paper compared another choice σt2=βt\sigma_t^2=\beta_t and concluded that the two perform similarly, but β~t\tilde\beta_t is more stable when tt approaches TT.
  4. Noise is added only if t > 1: the goal of the last step is to output x0x_0 directly, and adding noise again would destroy the details that were just recovered.

5.5 Gradient Flow and Detach Checklist

TensorNeeds a gradientExplanation
x0NoReal data, always detach or constructed under no_grad
epsNoThe sampled Gaussian noise, which is the regression target, and must be detached
x_tNo (as an input)Constructed from x0 and eps; it is the network input and gradients should not flow back to the data
tNoAn integer time step, used only for table lookup and embedding
predYesThe network output; the gradient passes only through the network parameters
theta_emaNoThe EMA update is performed under torch.no_grad() and must not be updated by the optimizer
Text / condition encoderUsually noGenerally frozen in conditional generation; only cross-attention and the backbone take part in training

Two easy-to-miss points:

  1. Do not compute the loss after data augmentation of x_t. Augmentation breaks “the correspondence between xtx_t and ε\varepsilon” and distorts the regression target. Augmentation, if any, should be applied to x0x_0 and xtx_t reconstructed afterwards.
  2. EMA parameters must not take part in backpropagation. If the EMA model is also put into the computation graph, memory usage doubles and the gradient pollutes the teacher signal. The standard practice is to update under @torch.no_grad().

5.6 Pitfall Checklist

PitfallSymptomCause and fix
Data not normalizedSamples come out all gray or all saturatedNormalize x0x_0 to [−1,1][-1,1] and make the last layer of the network output the same magnitude
Integer time-step embeddingThe high-noise range cannot be learned at allUse sinusoidal positional encoding or Fourier features so that adjacent time steps are also continuous in embedding space
alpha_bar in float16NaN or blown-up images in the low-noise rangeCompute cumulative coefficients in float32/float64 and convert to half precision only before entering the network
Copying the learning rate from classification tasksThe loss decreases but samples collapseDiffusion models commonly use 1e-4 to 2e-5 with warmup and gradient clipping
Sampling steps inconsistent with training stepsQuality drops sharply after changing T directlyThe training schedule determines the geometric trajectory; to shorten sampling use DDIM or respacing, not a hard change of the loop count
Forgetting EMASingle-step samples are noisy with blurry detailsAlways sample with the EMA parameters; if memory is tight, at least keep a copy of the EMA
Wrong batching of conditional branchesImages are overexposed or drift semantically after guidanceClassifier-free guidance needs the same batch of samples to run both “conditional” and “unconditional” passes, and the xtx_t of the two passes must be exactly identical
Adding noise at the last stepThe final image has colored specklesDo not add noise at the last step, and clip the output to the data range

5.7 Scope of Application

DDPM is suitable for: small- and medium-resolution image generation, tasks that need stable training and good mode coverage, and serving as the baseline for other methods (DDIM, distillation, flow matching). It is not suitable for: scenarios that need single-step real-time generation (sampling is too slow), tasks with extremely high likelihood accuracy requirements (the simplified loss sacrifices the likelihood), and scenarios with very high data dimensionality that cannot be reduced (the compute cost of pixel-space diffusion grows with the square of the resolution, see Chapter 9).


6. DDIM: Turning Stochastic Sampling into Deterministic Sampling

6.1 Why Change It

DDPM sampling must go through all TT steps (commonly 1000), with one network forward pass per step, so the cost is very high. Moreover, noise is injected at every step, so the same starting point gives different results in two runs. DDIM (Denoising Diffusion Implicit Model) answers two questions: can we take fewer steps? Can we take them deterministically?

Its starting point is: the Markov forward process of DDPM is not mandatory. As long as the marginal distribution q(xt∣x0)q(x_t\mid x_0) is preserved, the forward process can be replaced by a non-Markovian form, which gives the reverse process more freedom.

6.2 A Non-Markovian Forward Process

qσ(xt−1∣xt,x0)=N(xt−1;αˉt−1x0+1−αˉt−1−σt2⋅xt−αˉtx01−αˉt, σt2I)q_\sigma(x_{t-1}\mid x_t,x_0)=\mathcal{N}\left(x_{t-1};\sqrt{\bar\alpha_{t-1}}x_0+\sqrt{1-\bar\alpha_{t-1}-\sigma_t^2}\cdot\frac{x_t-\sqrt{\bar\alpha_t}x_0}{\sqrt{1-\bar\alpha_t}},\ \sigma_t^2I\right)

One can verify that marginalizing level by level according to this expression still gives qσ(xt∣x0)q_\sigma(x_t\mid x_0) equal to the original closed-form Gaussian. That is: the intermediate path changed but the endpoint distribution did not, so the training objective (which depends only on q(xt∣x0)q(x_t\mid x_0)) is completely unchanged, and a DDPM-trained network can be used directly.

6.3 The Deterministic Update

Taking σt=0\sigma_t=0 (injecting no noise at all), the reverse update becomes

xt−1=αˉt−1 x^0+1−αˉt−1 ε^x_{t-1}=\sqrt{\bar\alpha_{t-1}}\,\hat x_0+\sqrt{1-\bar\alpha_{t-1}}\,\hat\varepsilon

where ε^=εθ(xt,t)\hat\varepsilon=\varepsilon_\theta(x_t,t) and x^0=(xt−1−αˉtε^)/αˉt\hat x_0=\left(x_t-\sqrt{1-\bar\alpha_t}\hat\varepsilon\right)/\sqrt{\bar\alpha_t}.

Derivation: The consistency between the DDIM update and the non-Markovian forward process

Step 1: Start from the mean of the non-Markovian forward process. Setting σt=0\sigma_t=0, the mean of the expression above is

αˉt−1x0+1−αˉt−1⋅xt−αˉtx01−αˉt\sqrt{\bar\alpha_{t-1}}x_0+\sqrt{1-\bar\alpha_{t-1}}\cdot\frac{x_t-\sqrt{\bar\alpha_t}x_0}{\sqrt{1-\bar\alpha_t}}

Step 2: Combine the coefficients of x0x_0. Expanding and rearranging:

αˉt−1x0−αˉt1−αˉt−11−αˉtx0=x0(αˉt−1−αˉt1−αˉt−11−αˉt)\sqrt{\bar\alpha_{t-1}}x_0-\frac{\sqrt{\bar\alpha_t}\sqrt{1-\bar\alpha_{t-1}}}{\sqrt{1-\bar\alpha_t}}x_0 =x_0\left(\sqrt{\bar\alpha_{t-1}}-\frac{\sqrt{\bar\alpha_t}\sqrt{1-\bar\alpha_{t-1}}}{\sqrt{1-\bar\alpha_t}}\right)

This coefficient does not need to be computed explicitly in practice, because the next step replaces everything with x^0\hat x_0.

Step 3: Replace x0x_0 with the network estimate. Since the mean is linear in x0x_0, after replacing x0x_0 with x^0\hat x_0 the mean equals

αˉt−1x^0+1−αˉt−1⋅xt−αˉtx^01−αˉt\sqrt{\bar\alpha_{t-1}}\hat x_0+\sqrt{1-\bar\alpha_{t-1}}\cdot\frac{x_t-\sqrt{\bar\alpha_t}\hat x_0}{\sqrt{1-\bar\alpha_t}}

Substituting the definition of x^0\hat x_0 into the second term and simplifying gives

αˉt−1x^0+1−αˉt−1ε^\sqrt{\bar\alpha_{t-1}}\hat x_0+\sqrt{1-\bar\alpha_{t-1}}\hat\varepsilon

Step 4: Why we can skip steps. Because the update depends only on the two coefficients αˉt\bar\alpha_t and αˉt−1\bar\alpha_{t-1}, and not on “whether every intermediate step was actually taken”. It suffices to choose a decreasing subsequence of times t1>t2>⋯>tKt_1>t_2>\cdots>t_K and compute the updates with the corresponding αˉ\bar\alpha. This is respacing: compressing T=1000T=1000 into K=20K=20 or even K=4K=4 without retraining the trained network.

Step 5: Interpolation with σt>0\sigma_t>0. Let

σt=η1−αˉt−11−αˉt1−αˉtαˉt−1\sigma_t=\eta\sqrt{\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}}\sqrt{1-\frac{\bar\alpha_t}{\bar\alpha_{t-1}}}

η=0\eta=0 degenerates to deterministic DDIM, and η=1\eta=1 approaches DDPM’s stochastic sampling. η\eta is therefore a “stochasticity knob”: turn it up for diversity, turn it down for reproducibility and stability.

6.4 Sampling Pseudocode

# Input: eps_theta, time subsequence t_seq (length K, decreasing), eta in [0, 1]
# Output: samples x0, shape (B, C, H, W)
x = randn(B, C, H, W)
for i in range(K):
    t = t_seq[i]
    t_prev = t_seq[i + 1] if i + 1 < K else 0
    eps = eps_theta(x, t)
    x0_hat = (x - sqrt(1 - alpha_bar[t]) * eps) / sqrt(alpha_bar[t])
    sigma = eta * sqrt((1 - alpha_bar[t_prev]) / (1 - alpha_bar[t])) \
                * sqrt(1 - alpha_bar[t] / alpha_bar[t_prev])
    x = sqrt(alpha_bar[t_prev]) * x0_hat \
        + sqrt(1 - alpha_bar[t_prev] - sigma ** 2) * eps \
        + sigma * randn_like(x)
return x

6.5 Relation to the Ordinary Differential Equation

When η=0\eta=0 and the step size tends to zero, the DDIM update converges to

dxdt=−12β(t)[x+∇xlog⁡pt(x)]\frac{\mathrm{d}x}{\mathrm{d}t}=-\frac{1}{2}\beta(t)\left[x+\nabla_x\log p_t(x)\right]

which is exactly the probability flow ordinary differential equation of Chapter 7. DDIM is therefore not merely “an accelerated approximation of DDPM”: it is a first-order Euler discretization of the probability flow ODE. The fewer the steps, the larger the discretization error, and the essence of the quality drop is numerical integration error rather than a worse model.

6.6 Pitfall Checklist and Scope of Application

PitfallSymptomFix
Subsequence chosen non-uniformlyStructure collapses when steps are fewPick points uniformly in αˉ\bar\alpha or in the log signal-to-noise ratio, not uniformly in tt
Still using DDPM’s stochastic varianceVery noisy few-step samplesSet η\eta to 0 or very small when using few steps
Wrong variance at the starting pointOverall color shift in few-step samplingUse strictly N(0,I)\mathcal{N}(0,I) as the starting point and confirm αˉT≈0\bar\alpha_T\approx0
Treating DDIM as a new model to retrainWasted computeDDIM reuses DDPM weights and only changes the sampler

Scope of application: any already-trained DDPM can switch directly to DDIM sampling and reach close to thousand-step quality with 10 to 50 steps; it suits scenarios that need reproducibility, interpolation (the same noise starting point with different prompts), and image editing (inversion along a deterministic trajectory).


7. Continuous Time: Score SDE, Reverse SDE, and Probability Flow ODE

7.1 A Unified Viewpoint

Every step of discrete diffusion is “add a little noise, then learn how to remove it”. After going continuous, adding noise is a stochastic differential equation and denoising is its time reversal. The value of this viewpoint lies in:

  1. Training and sampling step counts are decoupled, so any numerical integrator can be used;
  2. DDPM, DDIM, and NCSN are all explained as different discretizations of the same family of equations;
  3. Sampling can be switched to an ODE, which enables exact inversion, interpolation, and editing.

7.2 The Forward and Reverse SDEs

Taking the VP type as an example, the forward SDE is

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

Its reverse process (time running from TT to 00) is

dx=[−12β(t)x−β(t)∇xlog⁡pt(x)]dt+β(t) dwˉ\mathrm{d}x=\left[-\frac{1}{2}\beta(t)x-\beta(t)\nabla_x\log p_t(x)\right]\mathrm{d}t+\sqrt{\beta(t)}\,\mathrm{d}\bar w

where wˉ\bar w is Brownian motion under reversed time. The score term is the only thing that needs to be learned.

Derivation: Why the reverse SDE has an extra score term

Step 1: Write the Fokker-Planck equation of the forward SDE. For

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

its marginal density pt(x)p_t(x) satisfies

∂pt∂t=−∇⋅(fpt)+12g2Δpt\frac{\partial p_t}{\partial t}=-\nabla\cdot\left(f p_t\right)+\frac{1}{2}g^2\Delta p_t

where ∇⋅\nabla\cdot is the divergence and Δ\Delta is the Laplacian.

Step 2: Write the diffusion term as “transport plus correction”. Using the identity

12g2Δpt=12g2∇⋅(pt∇log⁡pt)\frac{1}{2}g^2\Delta p_t=\frac{1}{2}g^2\nabla\cdot\left(p_t\nabla\log p_t\right)

the equation can be written in a form containing only first derivatives:

∂pt∂t=−∇⋅[(f−12g2∇log⁡pt)pt]\frac{\partial p_t}{\partial t}=-\nabla\cdot\left[\left(f-\frac{1}{2}g^2\nabla\log p_t\right)p_t\right]

Step 3: Identify the new SDE that this equation corresponds to. An SDE with only a drift term h(x,t)h(x,t) has density evolution exactly ∂tp=−∇⋅(hp)\partial_t p=-\nabla\cdot(hp). Therefore, under reversed time τ=T−t\tau=T-t, the density evolution corresponds to the drift

h=f−12g2∇log⁡pth=f-\frac{1}{2}g^2\nabla\log p_t

Switching back to forward time and adding the diffusion term gives the reverse SDE

dx=[f(x,t)−g2(t)∇xlog⁡pt(x)]dt+g(t)dwˉ\mathrm{d}x=\left[f(x,t)-g^2(t)\nabla_x\log p_t(x)\right]\mathrm{d}t+g(t)\mathrm{d}\bar w

Step 4: Substitute the VP coefficients. With f=−12βxf=-\frac12\beta x and g=βg=\sqrt\beta, we have g2=βg^2=\beta, which gives the expression in 7.2. The role of the score term is not an “extra correction”; it is what reverses in time the fact that “forward diffusion spreads the probability mass out”.

7.3 The Probability Flow ODE

The same Fokker-Planck equation can also be produced by a deterministic ODE that generates the same marginal densities:

dxdt=f(x,t)−12g2(t)∇xlog⁡pt(x)\frac{\mathrm{d}x}{\mathrm{d}t}=f(x,t)-\frac{1}{2}g^2(t)\nabla_x\log p_t(x)

For the VP type this is

dxdt=−12β(t)[x+∇xlog⁡pt(x)]\frac{\mathrm{d}x}{\mathrm{d}t}=-\frac{1}{2}\beta(t)\left[x+\nabla_x\log p_t(x)\right]
Derivation: Why the marginal distribution is unchanged after removing the diffusion term

Step 1: Compare the two drifts. The drift of the reverse SDE is f−g2∇log⁡ptf-g^2\nabla\log p_t, and the drift of the probability flow ODE is f−12g2∇log⁡ptf-\frac12g^2\nabla\log p_t. They differ by −12g2∇log⁡pt-\frac12g^2\nabla\log p_t.

Step 2: Verify the continuity equation of the ODE. For an ODE dx=h dt\mathrm{d}x=h\,\mathrm{d}t, the density satisfies ∂tp=−∇⋅(hp)\partial_t p=-\nabla\cdot(hp). Taking h=f−12g2∇log⁡pth=f-\frac12g^2\nabla\log p_t:

∂tp=−∇⋅(fp)+12∇⋅(g2p∇log⁡pt)=−∇⋅(fp)+12g2Δpt\partial_t p=-\nabla\cdot\left(fp\right)+\frac{1}{2}\nabla\cdot\left(g^2 p\nabla\log p_t\right) =-\nabla\cdot(fp)+\frac12g^2\Delta p_t

The right-hand side matches the right-hand side of the Fokker-Planck equation term by term (here the identity ∇⋅(p∇log⁡p)=Δp\nabla\cdot(p\nabla\log p)=\Delta p is used). Hence the ODE and the SDE generate the same density trajectory.

Step 3: Meaning. The noise term only “redistributes samples within the same density” and does not change the shape of the density; removing it makes samples follow deterministic streamlines and still land on the correct distribution. The cost is losing the diversity brought by stochasticity; the benefit is reproducibility, invertibility, and the availability of higher-order integrators.

Step 4: Align with DDIM. Applying explicit Euler discretization to the ODE of 7.3 gives exactly the DDIM update of Chapter 6 (up to a scale factor of one time step). So the statement “DDIM is a first-order discretization of the ODE” is precise, not an analogy.

7.4 Time Weighting and Sampling Strategy

The continuous-time training objective is

L=Et∼p(t),x0,ε[w(t)∥sθ(xt,t)−∇log⁡q(xt∣x0)∥2]L=\mathbb{E}_{t\sim p(t),x_0,\varepsilon}\left[w(t)\left\|s_\theta(x_t,t)-\nabla\log q(x_t\mid x_0)\right\|^2\right]

p(t)p(t) is the time sampling distribution and w(t)w(t) is the loss weight. Common choices:

StrategyApproachPurpose
Uniform sampling in ttt∼U[0,1]t\sim\mathcal{U}[0,1]Simple, but the log signal-to-noise ratio is unevenly distributed
Uniform in log signal-to-noise ratioTake uniform points in λ\lambdaBalanced gradient contribution from every noise range
Importance samplingAdjust p(t)p(t) according to the loss magnitudeReduce gradient variance
Loss weighting λ(t)\lambda(t)w(t)∝1/σ2w(t)\propto1/\sigma^2 or Min-SNRTrade off between likelihood and perceptual quality

7.5 Choosing a Numerical Integrator

IntegratorOrderEvaluations per stepSuitable for
Euler (DDIM)11Few steps, simple implementation
Heun (second order)22Medium step counts, quality-sensitive
Runge-Kutta44High precision, acceptable compute
DPM-Solver familyMulti-step, high order1 to 2Thousand-step quality in 10 to 20 steps

The key conclusion: after switching to an ODE, the sampling step count is no longer constrained by the training step count, and any high-order integrator can push the NFE down to 10 to 20. This is the first source of “few-step sampling”; the second source is the distillation of Chapter 12.

7.6 Pitfalls and Scope of Application

The continuous-time viewpoint is better suited to research and to implementing high-order samplers; in engineering deployment, note that: the time variable must be consistent with the schedule used in training (VP and VE conversions must not be mixed); the values of αˉ\bar\alpha and σ\sigma become ill-conditioned near the endpoints and must be computed in the log domain; ODE sampling is sensitive to the starting noise, so different starting points give different results and the random seed must be fixed during evaluation. Scope of application: high-quality few-step sampling, image editing and inversion, and scenarios that need a unified theoretical explanation.


8. Conditional Generation and Guidance: Making Sampling Listen to the Prompt

8.1 Two Kinds of Approaches to Conditional Generation

Given a condition cc (text, class, depth map, reference image), the goal is to sample from p(x∣c)p(x\mid c). The mainstream approaches fall into two categories:

  1. Conditional injection: encode cc and feed it into the network, letting the network learn pθ(xt−1∣xt,c)p_\theta(x_{t-1}\mid x_t,c) directly. This is the standard approach of latent diffusion and text-to-image models (Chapters 9 and 10).
  2. Guidance: do not change the network architecture; instead, modify the score during sampling to push the sampling distribution toward the region that “better matches the condition”. Both classifier guidance and classifier-free guidance belong here.

8.2 Classifier Guidance

By Bayes’ rule,

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

The first term is the unconditional score, and the second term is the gradient of a classifier with respect to the noisy sample. At sampling time we therefore use

ε~=εθ(xt,t)−1−αˉt γ ∇xtlog⁡pϕ(c∣xt)\tilde\varepsilon=\varepsilon_\theta(x_t,t)-\sqrt{1-\bar\alpha_t}\,\gamma\,\nabla_{x_t}\log p_\phi(c\mid x_t)

where pϕ(c∣xt)p_\phi(c\mid x_t) is an additionally trained noise-aware classifier. The drawback is that a separate classifier must be trained, and it must be reliable at every noise level.

8.3 Classifier-Free Guidance

Classifier-free guidance (Classifier-Free Guidance, CFG) needs no classifier: during training the condition is dropped with a certain probability, so that the same network learns both “conditional” and “unconditional” predictions; at sampling time the two are extrapolated linearly.

ε~θ(xt,c)=εθ(xt,∅)+γ(εθ(xt,c)−εθ(xt,∅))\tilde\varepsilon_\theta(x_t,c)=\varepsilon_\theta(x_t,\varnothing)+\gamma\left(\varepsilon_\theta(x_t,c)-\varepsilon_\theta(x_t,\varnothing)\right)

An equivalent way of writing it is ε~=(1+γ)εθ(xt,c)−γεθ(xt,∅)\tilde\varepsilon=(1+\gamma)\varepsilon_\theta(x_t,c)-\gamma\varepsilon_\theta(x_t,\varnothing).

Derivation: Where the linear combination of classifier-free guidance comes from

Step 1: Define the guided distribution. Let

pγ(x∣c)∝p(x) p(c∣x)γp_\gamma(x\mid c)\propto p(x)\,p(c\mid x)^\gamma

When γ=1\gamma=1, Bayes’ rule exactly recovers p(x∣c)p(x\mid c); when γ>1\gamma>1, the “conditional likelihood” term is amplified so that samples better match the condition.

Step 2: Take the log and then the gradient. Taking the log of both sides and differentiating with respect to xx cancels the normalization constant:

∇xlog⁡pγ(x∣c)=∇xlog⁡p(x)+γ∇xlog⁡p(c∣x)\nabla_x\log p_\gamma(x\mid c)=\nabla_x\log p(x)+\gamma\nabla_x\log p(c\mid x)

Step 3: Write the conditional score in terms of two computable quantities. By Bayes’ rule, ∇log⁡p(c∣x)=∇log⁡p(x∣c)−∇log⁡p(x)\nabla\log p(c\mid x)=\nabla\log p(x\mid c)-\nabla\log p(x). Substituting back:

∇log⁡pγ=∇log⁡p(x)+γ(∇log⁡p(x∣c)−∇log⁡p(x))=(1+γ)∇log⁡p(x∣c)−γ∇log⁡p(x)\nabla\log p_\gamma=\nabla\log p(x)+\gamma\left(\nabla\log p(x\mid c)-\nabla\log p(x)\right) =(1+\gamma)\nabla\log p(x\mid c)-\gamma\nabla\log p(x)

Step 4: Translate into the noise prediction. Using the conversion of 4.4, s=−ε/1−αˉts=-\varepsilon/\sqrt{1-\bar\alpha_t}, and multiplying both sides by −1−αˉt-\sqrt{1-\bar\alpha_t} gives

ε~=(1+γ)εθ(x,c)−γεθ(x,∅)\tilde\varepsilon=(1+\gamma)\varepsilon_\theta(x,c)-\gamma\varepsilon_\theta(x,\varnothing)

This is the CFG formula. It needs no classifier, only that the model has seen an “empty condition” during training; therefore the training stage must randomly drop the condition with probability pdropp_{\text{drop}} (commonly 0.1 to 0.2).

Step 5: The two sides of γ\gamma. What γ\gamma amplifies is “the difference between the conditional and the unconditional prediction”. This difference can be understood as “the direction brought by the condition”; amplifying it makes samples more typical and more aligned with the prompt, but at the same time pushes the distribution from p(x∣c)p(x\mid c) toward its high-score region, cutting off the tails, so diversity drops, colors become oversaturated, and details become over-sharpened. When γ\gamma is too large, artifacts even appear where “parts not mentioned in the prompt are forcibly conditioned as well”.

8.4 Training and Sampling Pseudocode

# Training: input x0 (B, C, H, W), condition embedding c (B, L, D), drop probability p_drop
c_in = where(rand(B) < p_drop, null_embedding, c)   # (B, L, D)
x_t = sqrt(alpha_bar_t) * x0 + sqrt(1 - alpha_bar_t) * eps
loss = mean((eps_theta(x_t, t, c_in) - eps) ** 2)
# Sampling: input prompt embedding c, guidance strength gamma
eps_c = eps_theta(x, t, c)                # conditional branch
eps_u = eps_theta(x, t, null_embedding)   # unconditional branch
eps = eps_u + gamma * (eps_c - eps_u)     # two predictions on the same x
x = ddim_step(x, eps, t, t_prev)

8.5 Costs and Pitfalls

ItemCost / symptomExplanation
Two forward passesSampling compute doublesThe conditional and empty conditions can be concatenated into one batch for a single forward pass, but memory also doubles
γ\gamma too largeOversaturation, reduced diversityCommon values are 3 to 9; negative prompts can be implemented as a subterm with negative γ\gamma
No condition-drop trainingThe unconditional branch is unusableRandom dropping is required at training time, otherwise CFG fails
Different random noise for the conditional and empty conditionsWrong guidance directionThe two branches must share the same xtx_t
Text encoder not frozenLanguage capability is destroyedUsually frozen; only cross-attention and the backbone are trained

Scope of application: text-to-image, class-conditional generation, super-resolution and inpainting (with a low-resolution image or mask as the condition), and interactive generation that needs “adjustable strength”. It is not suitable for tasks that must strictly preserve diversity (γ\gamma should be small or turned off), nor for applying directly to an unconditionally trained model (which has no empty-condition branch).


9. Latent-Space Diffusion: Moving Diffusion into a Low-Dimensional Space

9.1 Motivation: Pixel Space Is Too Expensive

Running diffusion directly on a 512×512×3512\times512\times3 image means every convolutional layer operates on roughly 780 thousand dimensions; doubling the resolution roughly quadruples the compute. Yet the perceptual content of an image is in fact highly redundant: adjacent pixels are strongly correlated, and what really determines semantics is lower-frequency structure. This motivates latent-space diffusion (Latent Diffusion): first compress the image into a low-dimensional latent space with an autoencoder, then run diffusion in the latent space.

z0=E(x0),x^0=D(z0)z_0=\mathcal{E}(x_0),\qquad \hat x_0=\mathcal{D}(z_0)

The diffusion process happens entirely on zz, and after sampling is finished the result is decoded back to pixels.

9.2 Two-Stage Training

  1. Train the autoencoder: the encoder E\mathcal{E} and decoder D\mathcal{D} are trained with a reconstruction loss (plus perceptual and adversarial losses), with the goal that after compressing xx to zz and restoring it, the human eye cannot tell the difference. A common downsampling factor is f=8f=8, that is, 512×512512\times512 becomes 64×6464\times64.
  2. Train the diffusion model: freeze E\mathcal{E} and D\mathcal{D}, and train the denoising network in the zz space. The condition (text) is injected through cross-attention.

9.3 Quantifying the Compute Comparison

Derivation: Why latent-space diffusion saves a large amount of compute

Step 1: The relation between compute and spatial size. The floating-point operations of a convolutional network are roughly proportional to the spatial area of the feature map (when the channel count is fixed). If the downsampling factor is ff, the spatial size of the latent space is 1/f21/f^2 of that of pixel space.

Step 2: The multiplier effect of the number of diffusion steps. At training time each sample needs one forward pass; at sampling time each sample needs TT forward passes. Hence the sampling cost of a single image is approximately

cost≈T⋅c⋅H×Wf2\text{cost}\approx T\cdot c\cdot\frac{H\times W}{f^2}

where cc is the equivalent computation per pixel per step. With 512×512512\times512, f=8f=8, and T=50T=50, the equivalent spatial size of the latent space is only 64×6464\times64, which is 1/641/64 of pixel space.

Step 3: The trade-off between quality and compression rate. If ff is too small, little compute is saved; if ff is too large, the reconstruction loss of the autoencoder grows and the diffusion model learns “the reconstructed world”, so the upper bound on detail is locked by the autoencoder. Around f=8f=8 is the common compromise: reconstruction metrics remain high while compute drops by one to two orders of magnitude.

Step 4: Why it is not as simple as “reduce the dimension first, then diffuse”. The key is that the autoencoder must be differentiable and of sufficiently high reconstruction quality, otherwise the objective optimized by the diffusion model becomes disconnected from the final pixel quality. In practice two metrics should be monitored: the perceptual similarity of the reconstruction (such as LPIPS) and the FID of the reconstruction; the former determines the upper bound on detail and the latter determines the distribution shift.

9.4 Conditional Injection: Cross-Attention

The text condition is encoded into a sequence of word vectors c∈RL×dc\in\mathbb{R}^{L\times d}, which serves as keys and values in every attention layer of the denoising network, with the latent variable as the query:

Attention(Q,K,V)=softmax(QK⊤d)V\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\left(\frac{QK^\top}{\sqrt{d}}\right)V

where Q=WQ ϕ(zt)∈RN×dQ=W_Q\,\phi(z_t)\in\mathbb{R}^{N\times d}, K=WK c∈RL×dK=W_K\,c\in\mathbb{R}^{L\times d}, V=WV c∈RL×dV=W_V\,c\in\mathbb{R}^{L\times d}, NN is the number of positions after flattening the latent space, and LL is the text length.

Derivation: Why the scaling factor of cross-attention is $\sqrt{d}$

Step 1: The magnitude of the dot product. If the components of q,kq,k are independent, zero-mean, and unit-variance, then

q⊤k=∑i=1dqikiq^\top k=\sum_{i=1}^{d}q_ik_i

has mean zero and variance dd.

Step 2: Without scaling, softmax saturates. The magnitude of the softmax input grows with dd, the gap between the largest term and the rest widens, the output approaches one-hot, the gradient approaches zero, and training stalls.

Step 3: Scaling brings it back to unit magnitude. After dividing by d\sqrt d, the variance of the dot product becomes 1 and softmax sits in a region with a larger gradient. This is why the scaling factor is d\sqrt d, not to make the numbers “look nice”.

Step 4: The difference between cross-attention and self-attention. In self-attention, Q,K,VQ,K,V all come from the same sequence, and what is modeled is “which positions inside the image are related”; in cross-attention QQ comes from the latent variable and K,VK,V come from the text, and what is modeled is “which words each position should attend to”. The two have the same structure but different semantics.

9.5 Pseudocode

# Training: input image x0 (B, 3, H, W), text tokens (B, L)
z0 = encoder(x0)                              # (B, 4, H/8, W/8), frozen
c = text_encoder(tokens)                      # (B, L, D), frozen
z_t = sqrt(alpha_bar_t) * z0 + sqrt(1 - alpha_bar_t) * eps
pred = eps_theta(z_t, t, c)                   # c injected through cross-attention
loss = mean((pred - eps) ** 2)
# Sampling: input prompt tokens, guidance strength gamma
z = randn(B, 4, H // 8, W // 8)
for t in reversed_steps:
    eps = cfg_combine(eps_theta(z, t, c), eps_theta(z, t, null), gamma)
    z = ddim_step(z, eps, t, t_prev)
x = decoder(z)                                # frozen, decoded only once at the end

9.6 Pitfalls and Scope of Application

PitfallSymptomFix
Autoencoder reconstruction too blurryMissing detail and distorted text in generated imagesIncrease the weights of the perceptual and adversarial terms in the reconstruction loss, or lower the downsampling factor
Latent distribution shiftOverall color shift in generated imagesStandardize the latent variables (scale by per-channel mean and variance)
Too few cross-attention layersThe prompt only affects global styleAdd cross-attention at multiple resolution levels
Decoder participating in trainingMemory explodes, training unstableFreeze the decoder and call it only at the end of sampling
Latent resolution inconsistent with trainingCollapse when the sampling size changesSupport multi-resolution training or use resolution-extrapolation tricks

Scope of application: high-resolution image and video generation, scenarios that need text control, and engineering with limited compute but a demand for high-quality results. Not suitable for: tasks that need pixel-level precision (quantitative analysis of medical images, lossless reconstruction), because the autoencoder introduces uncontrollable reconstruction error.


10. Network Architecture, Parameterization, and Training Engineering

10.1 U-Net Backbone

The denoising network of a diffusion model usually uses a U-Net: the encoder downsamples level by level to extract multiscale features, the decoder upsamples level by level to restore the resolution, and skip connections concatenate features of the same level so that details are not lost. Each resolution level consists of several residual blocks, and the internal order of a residual block is usually “group normalization → activation → convolution → time-step modulation → activation → convolution”.

Three key components:

  1. Time-step embedding: encode the integer tt into a continuous vector and inject it into every residual block. Sinusoidal positional encoding is commonly used:
PE(t,2i)=sin⁡(t100002i/d),PE(t,2i+1)=cos⁡(t100002i/d)\mathrm{PE}(t,2i)=\sin\left(\frac{t}{10000^{2i/d}}\right),\qquad \mathrm{PE}(t,2i+1)=\cos\left(\frac{t}{10000^{2i/d}}\right)

Two fully connected layers then turn it into a modulation vector. Sinusoidal encoding rather than one-hot is used because adjacent time steps have nearby noise levels, so their embeddings should also be nearby.

  1. Group normalization and conditioning modulation: Group Normalization normalizes each group of channels within each sample and does not depend on the batch size; the conditioning vector is injected through “scale and shift” or adaptive group normalization.

  2. Self-attention layers: usually placed only at the lower-resolution levels (such as 16×1616\times16 and 8×88\times8), because the number of positions there is small and the attention cost is acceptable, while global structure is mainly decided at that level.

10.2 Error Propagation of the Three Parameterizations

Derivation: Why different noise ranges need different prediction targets

Step 1: Write the three parameterizations as one and the same linear combination. From xt=αˉtx0+1−αˉtεx_t=\sqrt{\bar\alpha_t}x_0+\sqrt{1-\bar\alpha_t}\varepsilon, we have

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}}

Step 2: See how the error is amplified. If the network has an absolute error δ\delta when predicting x0x_0, then the error translated into noise is

∥Δε∥=αˉt1−αˉt∥δ∥\left\|\Delta\varepsilon\right\|=\frac{\sqrt{\bar\alpha_t}}{\sqrt{1-\bar\alpha_t}}\left\|\delta\right\|

As αˉt→1\bar\alpha_t\to1 (low noise), this factor tends to infinity: a tiny x0x_0 error is translated into an enormous noise error. Conversely, if the network has an error δ\delta when predicting ε\varepsilon, the error translated into x0x_0 is

∥Δx0∥=1−αˉtαˉt∥δ∥\left\|\Delta x_0\right\|=\frac{\sqrt{1-\bar\alpha_t}}{\sqrt{\bar\alpha_t}}\left\|\delta\right\|

As αˉt→0\bar\alpha_t\to0 (high noise), this factor tends to infinity.

Step 3: Conclusion. The low-noise range suits predicting ε\varepsilon (or the equivalent quantity of x0x_0), and the high-noise range suits predicting x0x_0; a single parameterization cannot be stable at both ends. This is why DDPM chose ε\varepsilon, why some models choose x0x_0, and why the vv parameterization tries to compromise.

Step 4: Why the vv parameterization compromises. Define

v=αˉt ε−1−αˉt x0v=\sqrt{\bar\alpha_t}\,\varepsilon-\sqrt{1-\bar\alpha_t}\,x_0

It weights the two quantities by their respective “stable regions”: at low noise αˉt\sqrt{\bar\alpha_t} is large, so vv mainly reflects ε\varepsilon; at high noise 1−αˉt\sqrt{1-\bar\alpha_t} is large, so vv mainly reflects x0x_0. Hence the prediction error of vv is not extremely amplified at either end, and the variance of the training target is more balanced across all noise ranges. This is why “the vv parameterization is better suited to high-resolution, high-dynamic-range data”.

10.3 Training Engineering Checklist

ItemCommon practiceNote
Mixed precisionbfloat16 for the backbone, float32 for the cumulative coefficients and the lossHalf precision saves memory and time, but αˉ\bar\alpha needs high precision in the low-noise range
Gradient clippingClip the norm at 1.0Diffusion training occasionally spikes; clipping prevents occasional exploding gradients
EMADecay 0.9999, smaller early onEssential for sampling; reduces noise markedly
Learning rate1e-4 to 2e-5, with warmupLower for large models, higher for small ones
Batch sizeAs large as possible, with gradient accumulationDiffusion is sensitive to batch variance
Data augmentationOnly on x0x_0, using distribution-preserving transforms such as horizontal flipStrong augmentation changes the data distribution and must be used carefully
Time-step samplingUniform, or by log signal-to-noise ratioAffects how well each noise range is trained
Loss monitoringTrack the loss per noise rangeLooking only at the total loss hides a range that is not learning

10.4 Scope of Application

The U-Net plus time-step modulation is the most general backbone of diffusion models, and suits images, audio spectrograms, and video (with temporal convolution or attention added). When the data are low-dimensional vectors (such as robot action sequences), lighter temporal networks (one-dimensional convolution plus attention) are commonly used and a U-Net is unnecessary.


11. Flow Matching and Rectified Flow: Writing Diffusion as a Straight Line

11.1 From “Add Noise and Denoise” to “Learn a Velocity Field”

Flow Matching takes a different perspective: instead of learning “how to denoise at each step”, it learns “how the samples flow in time”. Define a time-dependent velocity field vθ(x,t)v_\theta(x,t) and let the samples follow the ordinary differential equation

dxdt=vθ(x,t)\frac{\mathrm{d}x}{\mathrm{d}t}=v_\theta(x,t)

flowing from the noise distribution to the data distribution. As long as this velocity field is learned accurately, sampling is just solving an ODE.

11.2 The Conditional Flow Matching Objective

The simplest path is straight-line interpolation. Let t∈[0,1]t\in[0,1], with x0x_0 the noise and x1x_1 the data:

xt=(1−t) x0+t x1,dxtdt=x1−x0x_t=(1-t)\,x_0+t\,x_1,\qquad \frac{\mathrm{d}x_t}{\mathrm{d}t}=x_1-x_0

The training objective is to regress this velocity:

LCFM=Et,x0,x1[∥vθ(xt,t)−(x1−x0)∥2]L_{\text{CFM}}=\mathbb{E}_{t,x_0,x_1}\left[\left\|v_\theta(x_t,t)-\left(x_1-x_0\right)\right\|^2\right]
Derivation: Why regressing the "conditional velocity" learns the "marginal velocity"

Step 1: The velocity of the conditional path is known. Given a pair (x0,x1)(x_0,x_1), the path is a straight line and the velocity is constant at x1−x0x_1-x_0, independent of tt. This is the easiest “conditional velocity field” to construct.

Step 2: The marginal velocity is the conditional expectation of the conditional velocity. Let the marginal distribution at time tt be pt(xt)=∫p(x0,x1)δ(xt−(1−t)x0−tx1)dx0dx1p_t(x_t)=\int p(x_0,x_1)\delta\left(x_t-(1-t)x_0-tx_1\right)\mathrm{d}x_0\mathrm{d}x_1. One can show that the velocity field that makes the marginal distribution evolve correctly along the ODE is

vt(x)=E[x1−x0∣xt=x]v_t(x)=\mathbb{E}\left[x_1-x_0\mid x_t=x\right]

Step 3: The least-squares optimum is exactly the conditional expectation. For a fixed xt=xx_t=x, minimize

E[∥vθ(x,t)−(x1−x0)∥2 | xt=x]\mathbb{E}\left[\left\|v_\theta(x,t)-(x_1-x_0)\right\|^2\ \middle|\ x_t=x\right]

Differentiating with respect to vθv_\theta and setting it to zero gives vθ(x,t)=E[x1−x0∣xt=x]v_\theta(x,t)=\mathbb{E}\left[x_1-x_0\mid x_t=x\right]. Therefore, using the conditional velocity as the regression target trains exactly the marginal velocity; there is no need to know the marginal distribution explicitly, nor to simulate the ODE.

Step 4: The correspondence with diffusion. Diffusion’s score matching is “regressing the conditional score”, and flow matching is “regressing the conditional velocity”; the two structures are exactly the same: both use a computable conditional quantity as the regression target, whose conditional expectation happens to be the field that drives the evolution of the marginal distribution. This is why flow matching can be implemented with almost the same code framework.

11.3 Conversion to Diffusion Parameters

For a Gaussian path, diffusion models and flow matching can be translated into each other. Taking the αt=αˉt\alpha_t=\sqrt{\bar\alpha_t} and σt=1−αˉt\sigma_t=\sqrt{1-\bar\alpha_t} that correspond to αˉt\bar\alpha_t, the vv parameterization of diffusion

v=αtε−σtx0v=\alpha_t\varepsilon-\sigma_t x_0

is exactly “the velocity along the direction of the log signal-to-noise ratio”. Changing the time parameter to the log signal-to-noise ratio λ\lambda, the probability flow ODE is written as dx/dλ=v\mathrm{d}x/\mathrm{d}\lambda=v. Therefore flow matching is not a replacement for diffusion but another parameterization of the same family of generative paths: diffusion uses curved paths (determined by the noise schedule at each step), and straight-line flow matching uses the straightest path.

11.4 Rectified Flow and Straightening

When every pair (x0,x1)(x_0,x_1) is matched independently, the marginal trajectories of the straight-line interpolation path may still be curved. Rectified Flow straightens them iteratively:

  1. Sample with the current model to obtain pairs (x0,x^1)(x_0,\hat x_1);
  2. Retrain on these new pairs to regress x1−x0x_1-x_0;
  3. Repeat for several rounds.

Each round brings the trajectories closer to a straight line, which allows fewer sampling steps. In the extreme case, if the trajectories are perfectly straight, one step takes us from noise to data.

11.5 Pseudocode

# Training: input data x1 (B, D), noise x0 ~ N(0, I)
t = rand(B, 1)                                # (B, 1), uniformly sampled
x_t = (1 - t) * x0 + t * x1                   # (B, D)
target = x1 - x0                              # (B, D), conditional velocity
loss = mean((v_theta(x_t, t) - target) ** 2)
# Sampling: Euler integration, K steps
x = randn(B, D)
for i in range(K):
    t = i / K
    x = x + v_theta(x, t) / K                 # step size 1/K
return x

11.6 Pitfalls and Scope of Application

PitfallSymptomFix
Time sampling concentrated at both endsThe velocity in the middle range is learned poorlyUse uniform sampling or a logit-normal distribution
Arbitrary pairingCurved trajectories, steps cannot be reducedUse multi-round straightening of rectified flow, or pair by optimal transport
Velocity magnitude not normalizedTraining divergesStandardize the data, and do not add a bounded activation to the output layer
Changing the time parameter directly in diffusion codeColor shift in samplingMake explicit the direction of tt (is 0 noise or data) and the definition of the coefficients

Scope of application: few-step generation (4 steps or even 1 step), scenarios that need straight trajectories for easy interpolation and editing, and scenarios that share the backbone with diffusion but change the training target. A large number of current text-to-image and video models adopt the flow matching objective.


12. Distillation and Few-Step Sampling: Compressing Slow Sampling into a Few Steps

12.1 Three Routes to Acceleration

RouteApproachRepresentativeCost
A better integratorUse high-order ODE solversDPM-SolverThe lower bound on the step count is limited by curvature
A better pathUse straight-line flow matching to straighten the trajectoryRectified FlowRequires retraining or straightening iterations
DistillationHave a student model imitate the teacher in fewer stepsProgressive distillation, consistency modelsRequires a teacher model and extra training

12.2 Progressive Distillation

Compress “the teacher takes two steps” into “the student takes one step”. If the teacher starts from xtx_t and takes two DDIM steps to reach xt−2x_{t-2}, the student is trained to predict xt−2x_{t-2} directly from xtx_t:

L=Ext[∥fθ(xt,t)−fteacher 2 step(xt,t)∥2]L=\mathbb{E}_{x_t}\left[\left\|f_\theta(x_t,t)-f_{\text{teacher}}^{\,2\text{ step}}(x_t,t)\right\|^2\right]

Once training is finished, the student becomes the new teacher, the step count is halved again, and the process repeats for log⁡2T\log_2 T rounds until 2 to 4 steps remain.

12.3 Consistency Models

A consistency model (Consistency Model) requires that “any two points on the same ODE trajectory map to the same starting point”:

fθ(xt,t)=fθ(xt′,t′),∀ t,t′ on the same trajectoryf_\theta(x_t,t)=f_\theta(x_{t'},t'),\qquad \forall\, t,t'\ \text{on the same trajectory}

The boundary condition fθ(x0,0)=x0f_\theta(x_0,0)=x_0 guarantees that the output is itself a sample.

Derivation: Why the consistency loss uses "the teacher's one-step result" as its target

Step 1: Self-consistency is a functional equation. If ff can map any point on the trajectory back to the starting point, then for two adjacent points,

fθ(xt,t)=fθ(xt−Δt,t−Δt)f_\theta(x_t,t)=f_\theta\left(x_{t-\Delta t},t-\Delta t\right)

Step 2: Approximate the right-hand side with one ODE step. Using the teacher (or the EMA parameters θ−\theta^-) to take one step from xtx_t gives x^t−Δt\hat x_{t-\Delta t}, so the target is

fθ(xt,t)≈fθ−(x^t−Δt,t−Δt)f_\theta(x_t,t)\approx f_{\theta^-}\left(\hat x_{t-\Delta t},t-\Delta t\right)

Step 3: Write it as a loss.

L=Et,xt[d(fθ(xt,t), fθ−(x^t−Δt,t−Δt))]L=\mathbb{E}_{t,x_t}\left[d\left(f_\theta(x_t,t),\ f_{\theta^-}\left(\hat x_{t-\Delta t},t-\Delta t\right)\right)\right]

where dd is a distance (L2, or LPIPS plus L2). θ−\theta^- is updated with EMA and does not backpropagate gradients, which prevents the student from chasing a continuously moving target.

Step 4: Why one-step sampling works. After training, fθ(⋅,T)f_\theta(\cdot,T) maps pure noise directly to x0x_0 in a single step; a multi-step alternation (calling ff once per step and re-noising) can also be used to trade off between quality and speed.

Step 5: The relation to distillation. Progressive distillation “explicitly imitates the teacher’s multi-step output”, whereas the consistency model “implicitly requires the trajectory to be self-consistent”. The former needs the teacher to step along; the latter needs only one ODE step, so training is cheaper, but numerical stability and the boundary conditions must be handled carefully.

12.4 Latent Consistency Distillation

Moving the consistency model into the latent space and using the guided teacher output as the target gives the Latent Consistency Model (LCM). It reaches teacher-level quality within 4 steps and is one of the mainstream solutions for real-time generation today.

12.5 Pitfalls and Scope of Application

PitfallSymptomFix
The teacher is of poor qualityThe student’s ceiling is lockedTrain the teacher well first, then distill
The distillation target contains random noiseThe student cannot learn a deterministic mappingUse a deterministic sampler (η=0\eta=0) during distillation
Boundary conditions not enforcedOne-step output is all grayExplicitly add the boundary loss fθ(x0,0)=x0f_\theta(x_0,0)=x_0
Steps compressed too aggressivelyDetail and text break down4 steps is the common lower bound; 2 steps needs stronger training or a larger model

Scope of application: real-time generation, on-device deployment, and compute-constrained per-frame video generation. Not suitable for: academic evaluation that needs diversity and fine-grained control (distillation weakens the tails of the distribution).


13. Evaluation Metrics: How to Judge Whether a Diffusion Model Is Any Good

13.1 Four Categories of Metrics

CategoryMetricWhat it measuresLimitation
Distribution distanceFID, KIDThe gap between the generated distribution and the real distributionDepends on Inception features; not applicable to some domains
Single-sample quality and diversityIS, precision, recallWhether a single image is realistic; how many real modes are coveredIS is insensitive to mode collapse
Likelihoodbits/dim, negative log likelihoodHow well the probabilistic model fitsWeakly correlated with perceptual quality
CostNFE, samples per second, memoryEngineering usabilityNot directly comparable across different hardware

13.2 The Definition and Computation of FID

FID (Fréchet Inception Distance) sends both real and generated images into an Inception network to extract features, fits each set to a multivariate Gaussian, and then computes the Fréchet distance between the two Gaussians:

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

Smaller is better.

Derivation: Why the Fréchet distance between two Gaussians has this closed form

Step 1: Definition of the Fréchet distance. For two distributions P,QP,Q, the second-order Fréchet distance is

d2(P,Q)=min⁡γ∈Γ(P,Q)E(x,y)∼γ∥x−y∥2d^2(P,Q)=\min_{\gamma\in\Gamma(P,Q)}\mathbb{E}_{(x,y)\sim\gamma}\left\|x-y\right\|^2

where Γ\Gamma is the set of all joint distributions with marginals PP and QQ. It is the form taken by optimal transport under squared Euclidean cost.

Step 2: In the Gaussian case the optimal coupling is also Gaussian. If P=N(μr,Σr)P=\mathcal{N}(\mu_r,\Sigma_r) and Q=N(μg,Σg)Q=\mathcal{N}(\mu_g,\Sigma_g), the optimal coupling is the affine transform y=μg+A(x−μr)y=\mu_g+A(x-\mu_r), where AA satisfies AΣrA⊤=ΣgA\Sigma_rA^\top=\Sigma_g.

Step 3: Expand the expectation.

E∥x−y∥2=∥μr−μg∥2+E∥(I−A)(x−μr)∥2\mathbb{E}\left\|x-y\right\|^2=\left\|\mu_r-\mu_g\right\|^2+\mathbb{E}\left\|(I-A)(x-\mu_r)\right\|^2

The second term equals Tr((I−A)Σr(I−A)⊤)=Tr(Σr+Σg−2AΣr)\mathrm{Tr}\left((I-A)\Sigma_r(I-A)^\top\right)=\mathrm{Tr}\left(\Sigma_r+\Sigma_g-2A\Sigma_r\right).

Step 4: Take the optimal AA. The optimal solution is A=Σr−1/2(Σr1/2ΣgΣr1/2)1/2Σr−1/2A=\Sigma_r^{-1/2}\left(\Sigma_r^{1/2}\Sigma_g\Sigma_r^{1/2}\right)^{1/2}\Sigma_r^{-1/2}; substituting it back into the second term and using the cyclic property of the trace gives

Tr(Σr+Σg−2(ΣrΣg)1/2)\mathrm{Tr}\left(\Sigma_r+\Sigma_g-2\left(\Sigma_r\Sigma_g\right)^{1/2}\right)

which is the closed form of FID.

Step 5: Practical meaning. The first term measures the “mean shift” (differences in overall tone and brightness), and the second term measures the “covariance difference” (texture, structure, diversity). This also explains why FID is especially sensitive to blurry images: blurring shrinks the covariance as a whole.

13.3 Engineering Details of Evaluation

DetailCorrect practiceCommon mistake
Sample sizeAt least the same order as the real set (commonly 10 thousand to 50 thousand)Computing FID from a few hundred images, with enormous variance
PreprocessingConsistent with how Inception was trained (resizing, normalization)Feeding [−1,1][-1,1] images directly, which shifts the features
RandomnessFix the seed, and report the mean and variance over multiple samplingsReporting only the single best run
Fairness of comparisonSame resolution, same sampling steps, same guidance strengthComparing 4 steps against 1000 steps
Text conditioningUse a fixed prompt set and report every category of metricPicking only the good-looking prompts

13.4 Why Likelihood Cannot Stand for Quality

The likelihood of a diffusion model can be estimated with the ELBO, but there are two mismatches:

  1. The likelihood cares about the exact probability of every pixel, whereas the human eye cares about structure and semantics;
  2. The simplified loss is not the same as optimizing the ELBO, so a model trained with the simplified loss may have a lower likelihood than one trained with the full ELBO, yet its samples look better.

Therefore, in practice likelihood is almost never used as the headline metric; bits/dim is reported only in research scenarios that need probabilistic modeling (compression, anomaly detection).

13.5 Scope of Application

FID suits mainstream comparison of image generation; KID (Kernel Inception Distance) is more stable with small samples; precision/recall suits analyzing the trade-off between “quality and coverage”; NFE and latency suit deployment evaluation. Cross-modal tasks (audio, actions) must switch to the corresponding feature extractor and metrics, and FID cannot be applied directly.


14. Integration with Reinforcement Learning and Embodied Intelligence: Diffusion Policies

14.1 Why Policies Need Diffusion Models

In continuous control, a policy is usually modeled as a Gaussian πθ(a∣o)=N(μθ(o),σθ2I)\pi_\theta(a\mid o)=\mathcal{N}\left(\mu_\theta(o),\sigma_\theta^2 I\right). This assumption has two fatal flaws:

  1. Unimodality: if several actions are reasonable under the same observation (go around to the left or to the right), a Gaussian can only give one average, and the averaged action may hit an obstacle;
  2. Weak temporal correlation: a Gaussian policy samples independently at every step, which easily jitters, especially under high-frequency control.

A diffusion policy (Diffusion Policy) writes action generation as a denoising trajectory: conditioned on the observation oo, it starts from a noisy action sequence and denoises it step by step to obtain a chunk of actions.

14.2 Formulation

Let the observation be oo (an image or a state vector) and the action be a∈Rda\in\mathbb{R}^{d}. The diffusion policy learns the conditional distribution p(a∣o)p(a\mid o), and its training objective is exactly the same as the conditional diffusion of Chapter 8:

L=Et,a0,ε,o[∥ε−εθ(αˉta0+1−αˉtε, t, o)∥2]L=\mathbb{E}_{t,a_0,\varepsilon,o}\left[\left\|\varepsilon-\varepsilon_\theta\left(\sqrt{\bar\alpha_t}a_0+\sqrt{1-\bar\alpha_t}\varepsilon,\ t,\ o\right)\right\|^2\right]

At sampling time we start from aT∼N(0,I)a_T\sim\mathcal{N}(0,I) and denoise iteratively to obtain the action a0a_0.

14.3 Action Chunking and Closed-Loop Execution

There are two key designs in practice:

  1. Action chunking: generate the next HH actions at once (for example H=16H=16) rather than one step. This lowers the inference frequency, improves temporal consistency, and mitigates the jitter caused by “independent sampling at every step”.
  2. Receding horizon: execute only the first kk steps (for example k=8k=8), then re-observe and regenerate. This preserves closed-loop feedback and avoids the cumulative error of open-loop execution.
Execution styleApproachAdvantageDisadvantage
Single-step closed loopGenerate one action per step and execute itFastest feedbackHigh inference frequency, jitter
Open-loop chunkingGenerate HH steps and execute all of themCheap inference, temporal consistencyNo feedback, errors accumulate
Receding horizonGenerate HH steps, execute only k<Hk<HBalances consistency and feedbackRequires tuning HH and kk

14.4 Why Diffusion Policies Beat Gaussian Policies

Derivation: Why a unimodal Gaussian cannot represent a multimodal action distribution

Step 1: Construct a bimodal counterexample. Let the true conditional distribution be

p(a∣o)=12N(−1,0.12)+12N(+1,0.12)p(a\mid o)=\tfrac12\mathcal{N}(-1,0.1^2)+\tfrac12\mathcal{N}(+1,0.1^2)

The two modes represent “go around to the left” and “go around to the right”.

Step 2: The maximum-likelihood solution of a Gaussian falls between the two peaks. For a unimodal Gaussian N(μ,σ2)\mathcal{N}(\mu,\sigma^2), the optimal mean when minimizing DKL(p ∥ q)D_{\mathrm{KL}}(p\,\|\,q) is the mean of pp:

μ∗=Ep[a]=0\mu^*=\mathbb{E}_p[a]=0

And a=0a=0 happens to be the low-probability region between the two modes (in a real task, that is the obstacle).

Step 3: This is not insufficient training but insufficient expressiveness of the model family. No matter how it is trained or how many parameters it has, a unimodal Gaussian cannot put both peaks in at once; it can only choose between “cover both peaks but also raise the middle” (large variance) and “stick to one peak and drop the other” (small variance). The former samples dangerous actions, the latter loses half of the behavioral modes.

Step 4: How a diffusion policy solves this. The distribution of a diffusion policy is a “composition of multi-step conditional Gaussians”, equivalent to a highly flexible implicit distribution. It can place probability mass separately on the two peaks with very low density between them. Nor does the training objective (denoising regression) forcibly pull the mass toward the mean as maximum likelihood does, because the regression target at each noise level preserves the local multimodal structure.

Step 5: The cost. The flexibility comes from multi-step sampling, so inference is more expensive than a Gaussian policy: generating one action requires several network forward passes. In engineering, action chunking, distillation (consistency policies), and smaller networks are used to offset this cost.

14.5 Comparison with Other Policy Families

Policy familyDistribution representationTraining signalMultimodalInference costTypical algorithms
Gaussian policyUnimodal GaussianPolicy gradient / maximum likelihoodWeakOne forward passPPO, SAC
Mixture density networkA finite number of GaussiansMaximum likelihoodMediumOne forward passMDN policy
Diffusion policyImplicit distribution of multi-step denoisingDenoising regressionStrongSeveral forward passesDiffusion Policy
Flow matching policyVelocity field ODEVelocity regressionStrongA few integration stepsThe action expert of π₀
Autoregressive discrete policyDiscrete token sequenceCross entropyStrongToken by tokenRT-2, FAST

14.6 Combining with Reinforcement Learning Objectives

A diffusion policy by itself learns “imitating demonstrations”. To combine it with rewards, there are three routes:

  1. Diffusion policy plus a value function: use a Critic to score the generated actions and guide the sampling process (similar to classifier guidance, except that the “classifier” is replaced by the value gradient);
  2. Diffusion policy as the policy network: jointly optimize the denoising loss with the policy gradient objective, so that the model both resembles the demonstrations and improves the return;
  3. Diffusion model as a world model: use diffusion to generate future observations and do model-based planning.

All three routes are still under development, and their common difficulty is “the high cost of backpropagating gradients through multi-step sampling”; in practice an approximation is often used that backpropagates only through the last step or a few steps.

14.7 Pitfalls and Scope of Application

PitfallSymptomFix
Actions not normalizedSampled action magnitudes are absurdStandardize each dimension using dataset statistics
Observation conditioning too weakGenerated actions do not correspond to the sceneUse a pretrained vision encoder, and add auxiliary losses
Inference frequency inconsistent with trainingJitter on the real robotFix the action chunk length and the number of execution steps, and simulate the same latency during training
Open loop onlyErrors accumulate over long tasksUse receding horizon, with kk about half the chunk length
Too little dataMultimodality cannot be learnedDiffusion policies need sufficiently diverse demonstrations; a few dozen trajectories are often not enough

Scope of application: fine manipulation (folding clothes, inserting and removing plugs), multimodal trajectories (obstacle avoidance), and high-frequency control that needs temporal consistency. Not suitable for: hard real-time loops that are extremely sensitive to inference latency (unless distilled to 1 or 2 steps), and purely discrete action spaces (where discrete diffusion or autoregressive models should be used instead).

15. Application Scenarios: One Denoising Objective, Nine Kinds of Downstream Tasks

The first fourteen chapters were all about “how to train an add-noise → denoise chain well and how to sample it fast”. This chapter switches to the user’s perspective: the same denoising regression objective — on what grounds can it cover images, video, audio, 3D, molecules, medical images, robot actions, simulation data, and time-series imputation? The answer is that diffusion models only require “a continuous (or discrete) signal that can be noised step by step” and “an interface that can describe the condition”; these two things hold for the vast majority of modalities, so the methodology transfers, and there is no need to rewrite a set of mathematics for every modality.

Reading this chapter, hold on to three variables, which must be answered anew in every scenario:

VariableMeaningQuestion to answer when switching to a new modality
Data form x0x_0What is being noisedIs it a tensor, a sequence, a point set, a graph, or discrete tokens? How are the dimensions normalized?
Conditioning signal ccWhat guides the generationClass, text, depth map, pose, action history, ligand pocket? Where does the encoder come from?
Sampling budgetThe acceptable number of network forward passesOffline batch generation can afford more than 100 steps; real-time control can afford only 1 to 4

The master table of the nine scenarios is given first, and each is expanded below. In the “mainstream approach” column only the route that is used by default in that scenario is listed; in the “representative method” column are names that have public code or weights and can be run directly, which makes reproduction and comparison easier.

ScenarioData form x0x_0Conditioning signal ccMainstream approachTypical sampling budgetRepresentative method
Image generation and editingH×W×3H\times W\times 3 or latent h×w×ch\times w\times cClass, text, reference image, maskLatent diffusion plus classifier-free guidance20 to 50 stepsStable Diffusion family, Imagen, DALL·E 2
Video generationT×H×W×3T\times H\times W\times 3Text, first frame, camera trajectoryJoint spatiotemporal diffusion, or latent video diffusion20 to 100 stepsVideo Diffusion, Sora-style spatiotemporal diffusion
Audio, speech, and musicWaveform or mel spectrogram T×FT\times FText, speaker, scoreMel-spectrogram diffusion plus a vocoder, or waveform diffusion10 to 50 stepsDiffWave, WaveGrad, AudioLDM
3D and scenesMultiple views, point cloud, implicit field, triplaneA single image, text, sparse viewsMulti-view diffusion plus reconstruction, or native 3D diffusion30 to 100 stepsZero-1-to-3, DreamGaussian, 3D latent diffusion
Molecules and protein structuresAtomic coordinates plus atom typesPocket, properties, sequenceEquivariant diffusion (coordinate noising with a rotation-equivariant network)50 to 500 stepsGeoDiff, DiffDock, RFdiffusion
Medical images2D slices, 3D volumesSegmentation mask, low-dose input, modalityConditional diffusion for reconstruction and cross-modality translation10 to 50 stepsLow-dose CT diffusion reconstruction, MR cross-modality translation
Robot policiesAction chunk H×dH\times dObservation sequence, language instructionConditional diffusion policy plus action chunking plus receding horizon1 to 10 steps (often distilled)Diffusion Policy, consistency policy
Data augmentation and simulationImages, sensor data, trajectoriesLabels, scene parametersUnconditional or conditional diffusion for augmentation20 to 50 steps (can be offline and batched)Diffusion augmentation, synthetic-data pipelines
Time-series forecasting and imputationMultivariate sequence L×dL\times dHistory window, covariatesConditional diffusion for whole-segment generation or masked imputation10 to 100 stepsTime-series diffusion imputation, trajectory prediction

15.1 Image Generation and Editing

Task form. Unconditional generation learns p(x)p(x); text-to-image learns p(x∣ctext)p(x\mid c_{\text{text}}); editing, given a source image xsrcx_{\text{src}} and a mask mm, repaints only the region inside the mask.

Why diffusion rather than something else. Compared with a Generative Adversarial Network (GAN, a generative model trained by pitting a generator against a discriminator), the training objective of a diffusion model is a stable regression loss, so there is no “mode collapse caused by the discriminator and generator pulling against each other”; compared with a Variational Autoencoder (VAE, a generative model trained with an encoder–decoder plus a variational lower bound), a diffusion model does not depend on a fixed low-dimensional bottleneck, and reconstructs details better. The cost is slow sampling, which is exactly why latent-space diffusion exists.

Mainstream approach. The image scenario has almost converged on one pipeline: first compress a 256×256256\times 256 image into a 32×3232\times 32 latent variable with an autoencoder (a spatial downsampling factor of 8), run diffusion in the latent space, and finally restore the pixels with the decoder. The text condition goes through a pretrained text encoder (such as the Contrastive Language-Image Pretraining model, CLIP) to obtain a token sequence, which is then injected into every resolution level of the U-Net through cross-attention. At sampling time, classifier-free guidance (Classifier-Free Guidance, CFG, training both a “conditional” and an “unconditional” branch and amplifying their difference by the guidance strength at sampling time) is used to improve text alignment.

Three routes to editing. The first is masked repainting: concatenate the forward-noised result of the unmasked region with the region to be repainted, and after each denoising step replace the known region back (equivalent to treating the “known pixels” as a hard constraint). The second is inversion plus editing: use the reverse process of DDIM to invert the real image into noise and a trajectory, change the condition, and then denoise forward along the same trajectory, thereby preserving the structure of the original image. The third is instruction editing: encode instructions such as “turn the cat into a dog” as a condition and do conditional generation directly.

Evaluation. Images use FID (Fréchet Inception Distance, which compares the two Gaussian distributions of real and generated images in the Inception feature space) and KID (Kernel Inception Distance, an alternative metric estimated unbiasedly from mini-batches); text alignment is scored with CLIP similarity; human preference is measured by pairwise comparison.

Pitfalls.

PitfallSymptomFix
Guidance strength too largeSaturation explodes and details smearKeep the guidance strength between 3 and 8, with dynamic thresholding or truncated sampling
Latent variance compressedSmall text and texture are lostUse a gentler downsampling factor, or restandardize the variance in the latent space
Text encoder too weakLong sentences and negations have no effectSwitch to a stronger text encoder, and preprocess with “prompt rewriting”
Mask boundary not blendedVisible seams after editingRefill the known region after each denoising step, and feather the mask
Reporting only FIDMetrics look good but the semantics are wrongAdd CLIP score, human evaluation, and failure-case analysis

Scope of application. High-resolution natural images, artistic creation, advertising assets, photo-editing tools. Not suitable for: situations that need strict pixel-level consistency (such as generating medical annotation images), because diffusion “reasonably fabricates” details.

15.2 Video Generation

Task form. Learn p(x1:T∣c)p(x_{1:T}\mid c), where x1:Tx_{1:T} is a sequence of TT frames. Compared with images, the only additional hard constraint is temporal consistency: the same object must not jump between adjacent frames.

Mainstream approach. Two routes. The first is joint spatiotemporal diffusion: replace the 2D U-Net with a 3D one (or “2D convolution plus temporal attention”) and treat frames as one extra spatial dimension that is noised and denoised directly. The second is latent video diffusion: first compress the whole video into spatiotemporal latent variables with a video autoencoder, then run diffusion in the latent space, which lowers the compute requirement by one to two orders of magnitude. Condition injection usually uses a dual condition of “text plus first frame”, with the first frame injected by channel concatenation or cross-attention.

Key designs. The temporal attention layers operate only within a fixed window (full-sequence attention blows up memory on long videos); frame rate and duration must be modeled explicitly, and a common practice is to feed the “frame rate” as a conditioning scalar; long videos use autoregressive segmentation with “overlapping frames” stitched together, or a two-level structure of “keyframes plus frame interpolation”.

Evaluation. Besides per-frame FID, temporal consistency metrics (such as optical-flow reprojection error and inter-frame feature distance) and motion magnitude metrics must be added, otherwise “a video that hardly moves” will cheat on the per-frame metrics.

Pitfalls.

PitfallSymptomFix
Per-frame metrics onlyHigh score but flickeringAdd optical-flow consistency and manual inspection
Fully connected temporal attentionMemory grows with the square of the frame countUse local windows or block attention
First-frame condition too strongLater frames do not budge and the video is almost staticLower the weight of the first-frame condition, or add noise to it
Training clips too shortLong videos drift or the scene jumpsUse longer clips in training plus segmented autoregressive inference

Scope of application. Short video assets, advertising, film previsualization, dynamic textures in simulation environments. Not suitable for: situations that need physical accuracy (such as numerical fluid simulation results), because diffusion generates what “looks plausible” rather than what “computes correctly”.

15.3 Audio, Speech, and Music

Task form. Speech synthesis is p(waveform∣text)p(\text{waveform}\mid \text{text}); speech enhancement and denoising is p(clean waveform∣noisy waveform)p(\text{clean waveform}\mid \text{noisy waveform}); music generation is p(audio∣score or text description)p(\text{audio}\mid \text{score or text description}).

Why diffusion suits audio. Audio is a high-frequency long sequence (16000 samples per second at a 16 kHz sampling rate), and autoregressive point-by-point generation is too slow; diffusion can denoise the whole waveform or the whole spectrum in parallel, which naturally fits the need to “generate a whole segment at once”.

Mainstream approach. Two routes: the first is waveform diffusion, denoising directly in the time domain with a one-dimensional convolutional U-Net (DiffWave and WaveGrad belong here), with the mel spectrogram as the condition; the second is spectrum diffusion, generating the mel spectrogram first and restoring the waveform with a vocoder, leaving high-frequency detail to the vocoder. Music generation commonly uses “latent space plus text condition”, structurally identical to image latent diffusion, except that the autoencoder is replaced by an audio codec.

Evaluation. Speech uses word error rate (Word Error Rate, WER, the proportion of errors when a recognition model transcribes the generated speech and compares it with the original text) and mean opinion score (Mean Opinion Score, MOS, human ratings); audio generation quality uses FAD (Fréchet Audio Distance, which moves FID onto an audio feature extractor); music additionally requires evaluating the plausibility of rhythm and structure.

Pitfalls.

PitfallSymptomFix
Crude phase handlingMetallic sound, cracklingUse the complex spectrum or model the waveform directly; do not run diffusion only on the magnitude spectrum
Sequences that are too longMemory and latency unacceptableSegmented generation plus overlapping cross-fading
Conditioning not aligned with durationSpeaking-rate drift, drawn-out vowelsProvide duration or alignment conditions explicitly (such as phoneme duration prediction)
Only objective metricsMetrics are good but it sounds badMOS-type subjective evaluation must be added

Scope of application. Speech synthesis, sound-effect generation, music sketches, speech enhancement. Not suitable for: ultra-low-latency real-time call enhancement (unless distilled to very few steps).

15.4 3D and Scene Generation

Task form. Single-image 3D reconstruction is p(3D representation∣one image)p(\text{3D representation}\mid \text{one image}); text-to-3D is p(3D representation∣text)p(\text{3D representation}\mid \text{text}). The 3D representation can be multi-view images, a point cloud, a volumetric density field, an implicit signed distance field, or a triplane (a compact representation that decomposes a 3D field into three 2D feature maps).

Mainstream approach. One route is multi-view diffusion: first use diffusion to generate images from several viewpoints, then fuse them into 3D with multi-view reconstruction (such as the Neural Radiance Field, NeRF, a differentiable rendering field that represents volume density and color with a neural network). The other is native 3D diffusion: add and remove noise directly on point clouds or implicit fields, and the network must be equivariant to rotation and translation. The key design point of equivariant networks is “the noise added is also an isotropic Gaussian on the rotation group”, so that the denoising target is independent of orientation.

Evaluation. Multi-view results use FID-type metrics; 3D uses the Chamfer Distance (the bidirectional average of nearest-point distances between two point sets) and volumetric intersection over union; rendering quality uses peak signal-to-noise ratio and structural similarity; text-to-3D additionally requires evaluating semantic alignment.

Pitfalls.

PitfallSymptomFix
Inconsistent viewpointsMulti-view images do not stitch togetherShare cross-view information in the attention layers, and feed the camera poses explicitly
Equivariance brokenThe result collapses when the orientation changesUse equivariant networks and equivariant noise, not ordinary convolutions
Reconstruction error masks generation errorMetrics are good but the shape is oddEvaluate “geometry” and “texture” separately
Memory too tightHigh resolution is impossibleUse compact representations such as triplanes, and go coarse-to-fine in stages

Scope of application. 3D asset creation, scene reconstruction, building simulation environments, 3D priors for robotic grasping. Not suitable for: industrial inspection that needs measurement-grade accuracy; diffusion generates 3D that “looks plausible”.

15.5 Molecular and Protein Structure Design

Task form. Molecular conformer generation is p(atomic coordinates∣atom types)p(\text{atomic coordinates}\mid \text{atom types}); molecular docking is p(ligand pose∣protein pocket)p(\text{ligand pose}\mid \text{protein pocket}); protein backbone design is p(backbone coordinates∣functional constraints)p(\text{backbone coordinates}\mid \text{functional constraints}).

Why diffusion is especially suitable. A molecular conformation is itself a continuous quantity — “the positions of a bunch of atoms in 3D space” — and can naturally be noised. More importantly, there is a physical symmetry: invariance to translation and rotation. If the forward process of diffusion uses an isotropic Gaussian, the noising distribution is unchanged after an overall translation and rotation, and the denoising network only needs an equivariant structure (such as a tensor field network or an equivariant graph neural network) to guarantee that the output is independent of orientation. This is the technical reason diffusion is more popular than GANs in the molecular field.

Mainstream approach. Coordinates and atom types are handled separately: continuous coordinates use Gaussian diffusion, and discrete atom types use discrete diffusion or a cross-entropy classification head; the network is an equivariant graph neural network that uses “distance plus direction” as edge features. Protein design additionally needs “sequence–structure joint” constraints, and a common approach is to fix the backbone geometry first and then the sequence.

Evaluation. Conformers use RMSD (Root Mean Square Deviation, the root mean square per-atom distance between generated and reference coordinates); docking uses the success rate at an RMSD threshold; protein design uses designability, diversity, and the self-consistency of a structure prediction model (refold the generated sequence and see whether it returns to the original structure).

Pitfalls.

PitfallSymptomFix
No equivariant constraintInconsistent results after rotation, unstable trainingEquivariant network plus equivariant noise
Physical validity ignoredAbsurd bond lengths, overlapping atomsAdd auxiliary losses or post-processing for bond lengths and repulsion
Only optimizing RMSDGenerating structures that “match but do not look real”Add physical energy terms and diversity metrics
Discrete and continuous mixed improperlyAtom types jump aroundDesign separate noise and losses for the continuous and discrete branches

Scope of application. Drug candidate generation, docking pose prediction, enzyme and antibody design, exploring crystal structures of materials. Not suitable for: computations that need first-principles accuracy (such as transition-state energies), because diffusion gives a plausible geometric prior rather than a quantum-chemistry conclusion.

15.6 Medical Imaging

Task form. Low-dose Computed Tomography (CT) reconstruction is p(full dose∣low dose)p(\text{full dose}\mid \text{low dose}); Magnetic Resonance (MR) cross-modality translation is p(modality A∣modality B)p(\text{modality A}\mid \text{modality B}); segmentation can use “generation under a segmentation-mask condition” for data augmentation.

Mainstream approach. Two routes: the first is conditional reconstruction, where the measurement data serve as the condition and the diffusion prior fills in the missing high-frequency information; this step complements the idea of “compressed sensing”. The second is posterior sampling, which treats diffusion as the prior and the imaging physics model as the likelihood, and uses guided sampling to compromise between the two. The data-augmentation route is “mask-conditioned generation”: given an organ mask, generate paired images and masks to alleviate the scarcity of annotations.

Evaluation. Reconstruction uses peak signal-to-noise ratio, structural similarity, and radiologists’ subjective ratings; downstream tasks use the segmentation Dice coefficient and the lesion detection rate. It is mandatory to report “whether lesions were fabricated”, which is the failure mode specific to the medical scenario.

Pitfalls.

PitfallSymptomFix
Hallucinated lesionsGenerating structures that do not existAdd data-consistency terms, check consistency across multiple samples, and keep human review
Pixel-level metrics onlyMetrics are good but diagnostic value is lowAdd downstream task metrics and physician ratings
Data biasFails on a certain device or populationMulti-center validation, stratified evaluation by device
Privacy and complianceData cannot be sharedFederated training, de-identification, strict auditing

Scope of application. Accelerated imaging, low-dose reconstruction, cross-modality translation, annotation augmentation. Not suitable for: direct use in diagnostic decisions without human review — diffusion generates structures that “look real”, which is the most dangerous class of error in clinical practice.

15.7 Robots and Embodied Intelligence

Task form. See Chapter 14. The policy learns p(at:t+H∣ot)p(a_{t:t+H}\mid o_{t}); it can be pure imitation (behavior cloning) or combined with a value function.

Mainstream approach. Conditional diffusion policy plus action chunking plus receding horizon; to compress inference latency, consistency models or progressive distillation are commonly used to bring the step count down to 1 to 4. When combined with a Vision-Language-Action (VLA) model — one that maps visual observations and language instructions directly to actions — diffusion usually only handles the “action head”, and semantic understanding is left to the pretrained vision-language backbone.

Evaluation. Task success rate in simulation; on real robots, the success rate over multiple trials, completion time, and recovery ability; “out-of-distribution generalization” (new objects, new positions, new lighting) must also be reported.

Pitfalls.

PitfallSymptomFix
Inference too slowControl frequency drops to single digitsAction chunking plus distillation plus half-precision inference
Action chunk too longSluggish reactionsShorten the chunk length and pair it with receding horizon
Observation conditioning too weakGrabbing at nothing, hitting objectsStrengthen the vision encoder and add auxiliary tasks (such as predicting future frames)
Testing only success casesFrequent failures on the real robotSystematically test each scenario and record failure modes

Scope of application. Fine manipulation, multimodal trajectories, high-frequency control that needs temporal consistency. Not suitable for: hard real-time (millisecond-level) servo loops, and purely discrete action spaces.

15.8 Data Augmentation and Simulation

Task form. Use diffusion to generate “synthetic samples with labels”, alleviating data scarcity and long-tailed distributions.

Mainstream approach. Three routes: class-conditional generation (generate the corresponding sample given a label; the label is known by construction, which saves annotation); layout-conditional generation (generate an image given detection boxes or a segmentation mask, for detection and segmentation augmentation); domain-randomization-style generation (generate the corresponding image given scene parameters such as lighting, weather, and camera parameters, to improve robustness). In autonomous driving and robotics, the third route is the most common, because real long-tail scenes (rainy nights, backlight) are hard to collect.

Evaluation. What matters is not “whether the generated images look good” but whether the downstream task really improves: under the same training budget, compare the metrics of real data against “real plus synthetic”, and check whether the synthetic data introduce bias (for example, objects in synthetic data always have the same material).

Pitfalls.

PitfallSymptomFix
Synthetic distribution too narrowDownstream performance drops instead of risingConstrain the conditional distribution with real-data statistics, and check distribution coverage
Labels misaligned with imagesDetection boxes do not matchCheck consistency after layout-conditional generation
Test-set leakageInflated evaluationStrictly isolate synthetic samples from the real evaluation samples
Visual inspection onlyBias goes unnoticedDo grouped evaluation (by material, lighting, class)

Scope of application. Detection and segmentation augmentation, long-tail completion, asset generation for simulation environments, substitute data in privacy-restricted scenarios. Not suitable for: using synthetic data as real measurements in safety certification.

15.9 Time-Series Forecasting, Imputation, and Scientific Computing

Task form. Time-series forecasting is p(xt+1:t+H∣xt−L:t)p(x_{t+1:t+H}\mid x_{t-L:t}); missing-value imputation is p(xmissing∣xobserved)p(x_{\text{missing}}\mid x_{\text{observed}}); in scientific computing, diffusion can learn “the distribution of the solution field given boundary conditions”.

Mainstream approach. The first is whole-segment generation: treat the entire future window as x0x_0 and the history window as the condition, and denoise with a one-dimensional convolution or a Transformer. The second is masked imputation: treat the missing segment as the region to generate and the observed segment as the known region, and refill the observed segment after each denoising step (structurally identical to image masked repainting). The third is trajectory prediction: multi-agent trajectories are naturally multimodal (turn left or go straight), and the multimodal expressiveness of diffusion fits exactly, making it safer than unimodal Gaussian prediction.

Evaluation. Point prediction uses mean absolute error and mean squared error; distribution prediction uses the Continuous Ranked Probability Score (CRPS, which measures the distance between the predicted distribution and the true value) and quantile loss; multimodal trajectories use the minimum average displacement error and the minimum final displacement error (taking the best over several predictions).

Pitfalls.

PitfallSymptomFix
Noising the raw magnitude directlyLarge values dominate the lossStandardize or log-transform first, then normalize symmetrically
Time-step conditioning ignoredTrajectory drift over long forecast windowsFeed the forecast step index explicitly as a condition
Reporting only point errorMultimodality is averaged awayDistribution metrics and multi-sample metrics must be reported
Sequence too shortPeriodicity cannot be learnedUse longer windows, or use frequency-domain features as the condition

Scope of application. Traffic and pedestrian trajectory prediction, sensor imputation, weather and energy forecasting, surrogate modeling of physical fields. Not suitable for: situations that need guaranteed conservation laws (mass, energy) — diffusion does not guarantee conservation, so the conservation law must be made a hard constraint or a projection step.


16. Cross-Method Summary: One Master Table, Six Disagreements, and One Decision Chain

The first fifteen chapters unfolded in order of knowledge dependency, and by this point it is easy to “see the trees but not the forest”. This chapter puts all the methods side by side, specifically to answer three questions: where exactly do they differ, when should each be chosen, and when should diffusion not be chosen at all.

16.1 Master Table of Methods

MethodForward processSampling processTypical NFEMain advantageMain costWhen to choose it
DDPMDiscrete TT-step Markov chainDiscrete reverse Markov chain, noise added at every step1000 (can be reduced to 100 to 250)Cleanest concept, most stable training, easy to reproduceExtremely slow samplingLearning the principles, small-scale experiments
DDIMSame training objective as DDPMNon-Markovian, deterministic update20 to 50Accelerates without retraining, invertibleQuality drops when steps are too fewNeeding both speed and quality on the same weights
Score SDE (VP/VE)Continuous-time noisingReverse SDE or probability flow ODEHundreds of steps for the SDE, tens for the ODEUnified theory, any integrator can be usedRequires tuning the discretization and the integratorContinuous-time modeling, writing a new integrator
DPM-SolverContinuous timeHigh-order exponential integrator10 to 20Good few-step quality, no retrainingMany implementation detailsAn existing continuous-time model that needs few-step generation
Conditional guidance (classifier / CFG)Same as the base modelAdds a condition gradient to the scoreSame as the base modelSignificantly improves condition alignmentToo-strong guidance sacrifices diversityText-to-image, action-conditioned generation
Latent-space diffusionNoising in the compressed latent spaceSame as the base model20 to 50Resolution and quality rise sharply for the same computeNeeds an autoencoder, details are lossyHigh-resolution images and video
Flow matching (CFM)Straight-line interpolation path, no fixed forward chainVelocity field ODE integration1 to 20Straighter path, better few-step results, simple training targetNeeds a pairing or coupling designFast sampling needed (such as a VLA action head)
Rectified flow (Reflow)Iteratively straightened pathOne-step or multi-step straight ODE1 to 4Can be compressed to very few stepsRequires multiple rounds of retrainingDeployment with strict latency requirements
Consistency model / LCMDistilled from a pretrained diffusion modelOne step or a few steps mapping to x0x_01 to 4Extremely fast, acceptable qualityComplex training, slightly reduced diversityReal-time interaction, on-device deployment
Diffusion policyNoising the action chunkConditional denoising plus receding horizon1 to 10Strong multimodal expressiveness, stable trainingSlow inference, large data requirementFine manipulation and multimodal trajectories

What is most worth remembering from this table is three mutually compatible acceleration axes: change the sampler (DDIM, DPM-Solver), change the path (flow matching, rectified flow), change the model (distillation, consistency models). The three can be stacked: a common configuration is “latent space plus flow matching plus consistency distillation”, which simultaneously buys high resolution, few steps, and fast inference.

16.2 Six Key Disagreements

Disagreement 1: discrete Markov chain or continuous-time stochastic differential equation? The TT-step discrete chain of DDPM is intuitive and its pseudocode is short, but it gets slow once the step count grows; the continuous-time SDE (Stochastic Differential Equation) writes “noising” as a differential equation, so in theory any numerical integrator can be used, and it naturally leads to the Probability Flow Ordinary Differential Equation (PF ODE, a deterministic equation that shares the marginal distributions of the SDE but drops the stochastic term). Criterion: if you only have ready-made weights and just want it to run, use the discrete form; if you need to write a new sampler or want theoretical unification, use the continuous form. In the limit T→∞T\to\infty the two are the same thing, so this is not a dispute about “right and wrong” but about “convenience”.

Disagreement 2: stochastic sampling or deterministic sampling? The reverse SDE injects noise at every step, which gives good diversity and strong fault tolerance, but the same image differs between runs; the PF ODE and DDIM are deterministic, so the same initial value always gives the same result, and they are invertible (mapping a real image back to noise). Criterion: if you need “the same prompt is reproducible” or “image-to-image editing”, choose deterministic; if you need maximum diversity, or “sample many times and then pick”, choose stochastic.

Disagreement 3: pixel space or latent space? Pixel diffusion runs the network at full resolution at every step, and the compute grows with the square of the resolution; latent-space diffusion first compresses by 4 to 16 times with an autoencoder and then diffuses on the latent variables, reaching higher resolution for the same compute. The cost is that the autoencoder loses high-frequency detail, and extreme details (small text, fine texture) may be “reasonably fabricated”. Criterion: high resolution with limited compute favors the latent space; pixel-level fidelity (medical, quantitative remote sensing) favors pixel space or a high-fidelity autoencoder.

Disagreement 4: classifier guidance or classifier-free guidance? Classifier guidance (Classifier Guidance, CG, using a classifier trained on noisy data to provide the condition gradient) requires training an extra noise-robust classifier, and the guidance gradient must pass through the classifier, which makes backpropagation expensive; CFG merges the conditional and unconditional passes into one denoising network, so the difference can be computed with a single forward pass, which is far simpler in engineering. Criterion: almost always CFG, unless the conditioning signal itself comes with a ready-made differentiable discriminative model (such as certain physical constraints).

Disagreement 5: the diffusion path or the straight-line path of flow matching? The forward path of diffusion is curved: the trajectory from noise to data is not a straight line, so few-step integration has a large error; flow matching (Flow Matching, FM, directly regressing a velocity field that transports noise to data) and rectified flow can make the path nearly straight, so few steps are accurate. The cost is that flow matching requires designing the “noise–data” coupling, and rectified flow requires multiple rounds of retraining to straighten the path gradually. Criterion: pursuing few steps and low latency (robots, on-device), prefer flow matching; if diffusion weights already exist and you want fewer steps, first try DPM-Solver and distillation.

Disagreement 6: generation as policy or generation as world model? In embodied intelligence, diffusion can serve directly as a policy (generating actions) or as a world model (generating future observations for planning). The former is a “conditional generation plus control” problem, whose bottleneck is inference latency and data volume; the latter is a “long-horizon prediction accuracy” problem, whose bottleneck is error accumulation. Criterion: with plenty of demonstrations and a well-defined task, use a diffusion policy; without demonstrations and needing trial-and-error planning, use a diffusion world model together with model predictive control.

16.3 The Model-Selection Decision Chain

Judge layer by layer in the order below; each layer answers only one yes-or-no question, and the chain ends at a concrete plan. The chain deliberately puts “should diffusion be used at all” first, because diffusion is not the optimal solution in many scenarios.

Layer 1: Is the data a continuous high-dimensional signal? If not (purely discrete symbols, tabular categories), first consider autoregressive models or discrete diffusion; if yes, go to Layer 2. The point of this layer: the core assumption of diffusion is “a continuous quantity that can be noised step by step”, and where that fails, diffusion should not be forced.

Layer 2: Do you need multimodality or high-fidelity detail? If not (unimodal, low-dimensional, extremely latency-critical), prefer a Gaussian policy or a lightweight regression model — they produce a result in one forward pass, whereas diffusion needs many. If yes, go to Layer 3. This layer is the watershed of “is diffusion worth it”.

Layer 3: How much sampling budget is there? Offline batch (seconds are acceptable): go straight to standard diffusion or latent-space diffusion; online interaction (tens of milliseconds required): go to Layer 4 for acceleration. This layer determines every later technical choice.

Layer 4: Can you retrain? If you can retrain and are chasing maximum speed, use flow matching plus rectified flow, or train a consistency model directly; if you cannot retrain and only have existing diffusion weights, switch the sampler to DDIM or DPM-Solver and add post-training distillation (such as LCM). This layer separates “training-side acceleration” from “inference-side acceleration”.

Layer 5: Do you need conditional control? If yes, add CFG (text, class) or classifier guidance (with a differentiable discriminator); if you need spatially local control (mask, depth, pose), add a ControlNet-style bypass branch. If not, an unconditional model suffices. This layer determines the interface for condition injection.

Layer 6: Is resolution or sequence length tight? If tight, use latent-space diffusion or block-wise generation; if not, pixel space or native sequence diffusion is simpler. This layer determines “whether to compress”.

Layer 7: How will you evaluate? The last layer is not about choosing a model but about choosing metrics: images look at FID and CLIP score; video must add temporal consistency; actions look at task success rate and out-of-distribution generalization; molecules look at RMSD and physical validity; medical images must look at “whether lesions were fabricated”. Choose the wrong metrics and all six previous layers were wasted.

Compressed into one sentence: first decide whether diffusion should be used, then whether retraining is possible, and finally whether to compress resolution, add conditions, and switch metrics.

16.4 Four Reading Paths

Readers with different goals need not read from beginning to end:

GoalRecommended pathRoughly covered chapters
Just want to know what diffusion isChapter 0 plus Chapter 1 plus the sampling pseudocode in 5.10, 1, 5
Want to train an image model hands-on2, 3, 5, 8, 9, 10Forward process, loss, DDPM, CFG, latent space, architecture
Want to accelerate to few-step deployment6, 7, 11, 12, 13DDIM, continuous time, flow matching, distillation, metrics
Want to build a robot policy14 plus 15.7 plus the flow matching of Chapter 11Diffusion policy, embodied applications, few-step sampling

References

The references below are grouped by topic and list only publicly available original papers and surveys that are directly relevant to the derivations in these notes. When reading a paper, it is more efficient to compare it with the corresponding chapter here: read the conclusion first, then go back to the derivation.

Forward process, evidence lower bound, and DDPM

  1. Sohl-Dickstein, Weiss, Maheswaranathan, Ganguli. Deep Unsupervised Learning using Nonequilibrium Thermodynamics. ICML 2015. (The origin of diffusion models: the first paper to write “noise step by step, then denoise in reverse” as a variational inference problem.)
  2. Ho, Jain, Abbeel. Denoising Diffusion Probabilistic Models. NeurIPS 2020. (The original DDPM paper, the main basis of Chapter 5 here.)
  3. Nichol, Dhariwal. Improved Denoising Diffusion Probabilistic Models. ICML 2021. (Cosine noise schedule, learned variance, importance sampling.)
  4. Kingma, Gao, Salimans, Poole, Ho. Variational Diffusion Models. NeurIPS 2021. (The continuous signal-to-noise ratio viewpoint and the log signal-to-noise ratio parameterization.)

Score matching and Langevin dynamics

  1. Hyvärinen. Estimation of Non-Normalized Statistical Models by Score Matching. JMLR 2005. (The original form of explicit score matching.)
  2. Vincent. A Connection Between Score Matching and Denoising Autoencoders. Neural Computation 2011. (Implicit score matching, the core of Chapter 4 here.)
  3. Song, Ermon. Generative Modeling by Estimating Gradients of the Data Distribution. NeurIPS 2019. (Annealed Langevin sampling.)
  4. Song, Sohl-Dickstein, Kingma, Kumar, Ermon, Poole. Score-Based Generative Modeling through Stochastic Differential Equations. ICLR 2021. (VP/VE SDE, PF ODE, probability flow, the main basis of Chapter 7 here.)

Accelerated sampling

  1. Song, Meng, Ermon. Denoising Diffusion Implicit Models. ICLR 2021. (DDIM, Chapter 6 here.)
  2. Lu, Zhou, Bao, Chen, Li, Zhu. DPM-Solver: A Fast ODE Solver for Diffusion Probabilistic Model Sampling in Around 10 Steps. NeurIPS 2022. (High-order exponential integrators.)
  3. Liu, Gong, Liu. Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow. ICLR 2023. (Rectified flow.)
  4. Lipman, Chen, Ben-Hamu, Nickel, Le. Flow Matching for Generative Modeling. ICLR 2023. (Conditional flow matching.)
  5. Salimans, Ho. Progressive Distillation for Fast Sampling of Diffusion Models. ICLR 2022. (Progressive distillation.)
  6. Song, Dhariwal, Chen, Sutskever. Consistency Models. ICML 2023. (Consistency models.)
  7. Luo, Tan, Huang, Li, Zhao. Latent Consistency Models. 2023. (LCM, which moves consistency distillation into the latent space, Chapter 12 here.)

Conditional generation and architecture

  1. Dhariwal, Nichol. Diffusion Models Beat GANs on Image Synthesis. NeurIPS 2021. (Classifier guidance, architecture ablations.)
  2. Ho, Salimans. Classifier-Free Diffusion Guidance. 2022. (CFG, Chapter 8 here.)
  3. Rombach, Blattmann, Lorenz, Esser, Ommer. High-Resolution Image Synthesis with Latent Diffusion Models. CVPR 2022. (Latent-space diffusion, Chapter 9 here.)
  4. Zhang, Rao, Agrawala. Adding Conditional Control to Text-to-Image Diffusion Models. ICCV 2023. (ControlNet, a spatial-conditioning bypass.)
  5. Peebles, Xie. Scalable Diffusion Models with Transformers. ICCV 2023. (A Transformer backbone replacing the U-Net.)

Parameterization, weighting, and training details

  1. Salimans, Ho. Progressive Distillation for Fast Sampling of Diffusion Models. ICLR 2022. (The same paper as reference 13; its discussion of ε\varepsilon and vv parameterizations is frequently cited.)
  2. Hang, Gu, Li, et al. Efficient Diffusion Training via Min-SNR Weighting Strategy. ICCV 2023. (Weighting each loss term by the signal-to-noise ratio.)
  3. Karras, Aittala, Aila, Laine. Elucidating the Design Space of Diffusion-Based Generative Models. NeurIPS 2022. (Splitting preprocessing, training, and sampling into independent design dimensions.)

Evaluation

  1. Heusel, Ramsauer, Unterthiner, Nessler, Hochreiter. GANs Trained by a Two Time-Scale Update Rule Converge to a Local Nash Equilibrium. NeurIPS 2017. (The original FID paper.)
  2. Bińkowski, Sutherland, Arbel, Gretton. Demystifying MMD GANs. ICLR 2018. (KID.)
  3. Kynkäänniemi, Karras, Laine, Lehtinen. Improved Precision and Recall Metric for Assessing Generative Models. NeurIPS 2019. (Precision/recall.)

Diffusion policies and embodied intelligence

  1. Janner, Du, Tenenbaum, Levine. Planning with Diffusion for Flexible Behavior Synthesis. ICML 2022. (Diffusion Planner, using diffusion for trajectory planning.)
  2. Chi, Feng, Du, et al. Diffusion Policy: Visuomotor Policy Learning via Action Diffusion. RSS 2023. (Diffusion policy, Chapter 14 here.)
  3. Wang, Hunt, Zhou, et al. Diffusion Policies as an Expressive Policy Class for Offline Reinforcement Learning. ICLR 2023. (Combining diffusion policies with offline reinforcement learning.)
  4. Black, Brown, Driess, et al. π₀: A Vision-Language-Action Flow Model for General Robot Control. 2024. (A flow matching action expert.)

Surveys

  1. Yang, Zhang, Song, et al. Diffusion Models: A Comprehensive Survey of Methods and Applications. ACM Computing Surveys 2023. (The survey with the broadest coverage.)
  2. Cao, Zhang, Chen, et al. A Survey on Generative Diffusion Models. IEEE Transactions on Knowledge and Data Engineering 2024. (Leans toward theory and a review of variants.)

Note: references 21 and 13 are the same paper, cited twice because of its “parameterization discussion” and its “distillation method”; “Min-SNR weighting” in the main text refers to reference 22, and “the EDM design space” refers to reference 23. These references do not aim to be exhaustive; they only guarantee that every derivation here can be traced to a verifiable original source.

Appendix: Quick-Reference Table of Abbreviations

The table below is in alphabetical order and covers every abbreviation that appears in the text. Each is given its full English name and an explanation when it first appears in the main text; they are collected here for review and verification.

AbbreviationFull English nameExplanation
ACActor-CriticA framework that uses a value function to assist policy updates
CFGClassifier-Free GuidanceTraining both a conditional and an unconditional branch and amplifying their difference at sampling time
CFMConditional Flow MatchingTraining a generative model by regressing a conditional velocity field
CGClassifier GuidanceUsing the gradient of a noise-robust classifier as conditional guidance
CLIPContrastive Language-Image PretrainingA pretrained encoder that aligns images and text
CRPSContinuous Ranked Probability ScoreMeasuring the distance between a predictive distribution and the true value
CTComputed TomographyComputed tomography scanning
DDIMDenoising Diffusion Implicit ModelsNon-Markovian deterministic sampling for diffusion models
DDPMDenoising Diffusion Probabilistic ModelsThe standard discrete form of diffusion models
DPM-SolverDiffusion Probabilistic Model SolverA high-order integrator aimed at few-step sampling
DSMDenoising Score MatchingEstimating the score from the denoising direction of noised data
ELBOEvidence Lower BoundThe variational lower bound on the log likelihood
EMAExponential Moving AverageSmoothing current parameters with historical parameters
FADFréchet Audio DistanceMoving FID onto audio features
FIDFréchet Inception DistanceComparing the distributional gap between two sets of image features
FMFlow MatchingDirectly regressing the velocity field from noise to data
GANGenerative Adversarial NetworkA generator and a discriminator trained adversarially
ILImitation LearningLearning a policy from demonstrations
ISImportance SamplingEstimating the expectation of a new distribution with samples from an old one
KIDKernel Inception DistanceAn unbiased substitute for FID in the small-sample regime
KLKullback-Leibler DivergenceA measure of the difference between two probability distributions
LCMLatent Consistency ModelMoving consistency distillation into the latent space
MAEMean Absolute ErrorMean absolute error
MDPMarkov Decision ProcessThe standard mathematical framework for sequential decision making
MOSMean Opinion ScoreHuman perceptual rating of audio quality
MRMagnetic ResonanceMagnetic resonance imaging
NeRFNeural Radiance FieldA differentiable rendering field that represents volume density and color with a network
NFENumber of Function EvaluationsThe number of network forward passes needed for sampling
ODEOrdinary Differential EquationOrdinary differential equation
PF ODEProbability Flow ODEAn ordinary differential equation with the same marginal distributions as the SDE but without the stochastic term
POMDPPartially Observable Markov Decision ProcessPartially observable Markov decision process
ReflowRectified FlowStraightening the generative path by multiple rounds of retraining
RLReinforcement LearningOptimizing a policy by trial-and-error interaction with an environment
RMSDRoot Mean Square DeviationThe root mean square of per-atom coordinate distances
SDEStochastic Differential EquationA differential equation containing a stochastic term
SNRSignal-to-Noise RatioThe ratio of signal power to noise power
U-Net—A U-shaped encoder–decoder network, a multiscale backbone with cross-level skip connections
VAEVariational AutoencoderA latent-variable generative model trained with a variational lower bound
VE SDEVariance Exploding SDEA stochastic differential equation whose noise variance diverges over time
VLAVision-Language-ActionA model that maps observations and instructions directly to actions
VP SDEVariance Preserving SDEA stochastic differential equation whose total variance stays bounded
WERWord Error RateThe error proportion of speech-recognition transcription

On the sources and the language of these notes

These notes were originally written as Chinese study notes and follow the structure of the Deep Reinforcement Learning Core Algorithm Notes (drl-core-algorithms-notes) on the same site: for each algorithm, first the intuition and the objective, then the formulas, then the complete pseudocode, then a paragraph-by-paragraph walkthrough, and finally a pitfall checklist and the scope of application; all derivations are collected into foldable blocks, so you can read the conclusion first and expand them when you need the details. Formulas uniformly use the \left(\right) delimiters, and the first line of every pseudocode block labels the input, the output, and the tensor shapes.

Every formula in the text has been re-derived from the published papers; the notation may differ in letters from the originals (for example, the originals often write αˉt\bar\alpha_t, whereas these notes uniformly write αˉt\bar{\alpha}_t), but the mathematical meaning is identical. If you find a skipped step or an inconsistent notation, the original reference cited in the corresponding chapter takes precedence.

Comments

Loading comments…

    ← Back to home