Contents
- 0. Where These Notes Come From and How to Read Them
- 0.1 Origin
- 0.2 Notation
- 0.3 How to Read
- 1. The Three Routes of Generative Modeling and Where Diffusion Sits
- 1.1 What Generative Modeling Is Really Doing
- 1.2 The Position of Diffusion Models
- 1.3 A Formal Analogy with Reinforcement Learning
- 2. The Forward Process: Turning Data into Noise Little by Little
- 2.1 The Markov Noising Chain
- 2.2 Reparameterized Sampling and the “Noise Schedule”
- 2.3 Signal-to-Noise Ratio: Judging “How Much Signal Is Left at This Step”
- 2.4 The Continuous-Time Limit: From a Discrete Chain to a Stochastic Differential Equation
- 3. The Reverse Process and the Evidence Lower Bound: Where the Training Objective Comes From
- 3.1 What the Reverse Process Has to Learn
- 3.2 The Evidence Lower Bound
- 3.3 The True Posterior Is a Closed-Form Gaussian
- 3.4 From Term-by-Term KL to the Simplified Loss
- 3.5 Three Equivalent Parameterizations
- 4. Score Matching and Langevin Dynamics: Another Equivalent Path
- 4.1 The Score Function
- 4.2 Explicit Score Matching and Its Difficulty
- 4.3 Implicit Score Matching (Denoising Score Matching)
- 4.4 Converting Among Score, Noise, and Clean Sample (the Tweedie Formula)
- 4.5 Annealed Langevin Dynamics Sampling
- 4.6 The Relation to DDPM in One Sentence
- 5. DDPM: The Complete Algorithm, Pseudocode, and Engineering Details
- 5.1 The Algorithm at a Glance
- 5.2 Training Pseudocode
- 5.3 Sampling Pseudocode
- 5.4 Paragraph-by-Paragraph Walkthrough
- 5.5 Gradient Flow and Detach Checklist
- 5.6 Pitfall Checklist
- 5.7 Scope of Application
- 6. DDIM: Turning Stochastic Sampling into Deterministic Sampling
- 6.1 Why Change It
- 6.2 A Non-Markovian Forward Process
- 6.3 The Deterministic Update
- 6.4 Sampling Pseudocode
- 6.5 Relation to the Ordinary Differential Equation
- 6.6 Pitfall Checklist and Scope of Application
- 7. Continuous Time: Score SDE, Reverse SDE, and Probability Flow ODE
- 7.1 A Unified Viewpoint
- 7.2 The Forward and Reverse SDEs
- 7.3 The Probability Flow ODE
- 7.4 Time Weighting and Sampling Strategy
- 7.5 Choosing a Numerical Integrator
- 7.6 Pitfalls and Scope of Application
- 8. Conditional Generation and Guidance: Making Sampling Listen to the Prompt
- 8.1 Two Kinds of Approaches to Conditional Generation
- 8.2 Classifier Guidance
- 8.3 Classifier-Free Guidance
- 8.4 Training and Sampling Pseudocode
- 8.5 Costs and Pitfalls
- 9. Latent-Space Diffusion: Moving Diffusion into a Low-Dimensional Space
- 9.1 Motivation: Pixel Space Is Too Expensive
- 9.2 Two-Stage Training
- 9.3 Quantifying the Compute Comparison
- 9.4 Conditional Injection: Cross-Attention
- 9.5 Pseudocode
- 9.6 Pitfalls and Scope of Application
- 10. Network Architecture, Parameterization, and Training Engineering
- 10.1 U-Net Backbone
- 10.2 Error Propagation of the Three Parameterizations
- 10.3 Training Engineering Checklist
- 10.4 Scope of Application
- 11. Flow Matching and Rectified Flow: Writing Diffusion as a Straight Line
- 11.1 From “Add Noise and Denoise” to “Learn a Velocity Field”
- 11.2 The Conditional Flow Matching Objective
- 11.3 Conversion to Diffusion Parameters
- 11.4 Rectified Flow and Straightening
- 11.5 Pseudocode
- 11.6 Pitfalls and Scope of Application
- 12. Distillation and Few-Step Sampling: Compressing Slow Sampling into a Few Steps
- 12.1 Three Routes to Acceleration
- 12.2 Progressive Distillation
- 12.3 Consistency Models
- 12.4 Latent Consistency Distillation
- 12.5 Pitfalls and Scope of Application
- 13. Evaluation Metrics: How to Judge Whether a Diffusion Model Is Any Good
- 13.1 Four Categories of Metrics
- 13.2 The Definition and Computation of FID
- 13.3 Engineering Details of Evaluation
- 13.4 Why Likelihood Cannot Stand for Quality
- 13.5 Scope of Application
- 14. Integration with Reinforcement Learning and Embodied Intelligence: Diffusion Policies
- 14.1 Why Policies Need Diffusion Models
- 14.2 Formulation
- 14.3 Action Chunking and Closed-Loop Execution
- 14.4 Why Diffusion Policies Beat Gaussian Policies
- 14.5 Comparison with Other Policy Families
- 14.6 Combining with Reinforcement Learning Objectives
- 14.7 Pitfalls and Scope of Application
- 15. Application Scenarios: One Denoising Objective, Nine Kinds of Downstream Tasks
- 15.1 Image Generation and Editing
- 15.2 Video Generation
- 15.3 Audio, Speech, and Music
- 15.4 3D and Scene Generation
- 15.5 Molecular and Protein Structure Design
- 15.6 Medical Imaging
- 15.7 Robots and Embodied Intelligence
- 15.8 Data Augmentation and Simulation
- 15.9 Time-Series Forecasting, Imputation, and Scientific Computing
- 16. Cross-Method Summary: One Master Table, Six Disagreements, and One Decision Chain
- 16.1 Master Table of Methods
- 16.2 Six Key Disagreements
- 16.3 The Model-Selection Decision Chain
- 16.4 Four Reading Paths
- References
- Appendix: Quick-Reference Table of Abbreviations
Diffusion Model Notes: From the Evidence Lower Bound and Score Matching to DDIM, Guidance, and Flow Matching
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
| Notation | Meaning |
|---|---|
| A clean original data sample (an image, an audio clip, an action sequence, etc.) | |
| The sample after steps of noising, | |
| A pure-noise sample, approximately following the standard normal distribution | |
| The total number of discrete diffusion steps (commonly 1000 or 2000; training and sampling can differ) | |
| The noise variance (noising strength) at step , | |
| , the single-step signal retention coefficient | |
| , the cumulative signal retention coefficient from to | |
| The forward noising process (constructed artificially at training time, containing no learnable parameters) | |
| The reverse denoising process (implemented by a neural network with parameters ) | |
| Standard Gaussian noise, | |
| The network’s prediction of the noise contained in | |
| The network’s estimate of the score (that is, the gradient of the log probability density with respect to the input) | |
| The score of the marginal distribution of the data distribution at time | |
| The guidance strength of classifier-free guidance | |
| The log signal-to-noise ratio, | |
| The loss weight, used to reweight different noise levels | |
| The training data distribution | |
| The number of function evaluations, the core measure of sampling cost |
Note: this text uses for noise and uses only in a very few places for an infinitesimal quantity; it uses for samples and does not absorb the state symbol from reinforcement learning. Chapter 14, when discussing diffusion policies, temporarily writes actions as and observations as , 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 , we want to learn a probability density that is close to the true data distribution 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:
- In what form is represented;
- With what objective is it trained.
According to the answers to these two questions, there are three mainstream routes.
| Route | Is the density computable | Training objective | Sampling method | Representative models | Main weakness |
|---|---|---|---|---|---|
| Explicit likelihood | Computable, or lower-boundable | Maximize the log likelihood or its lower bound | One forward pass, or autoregressive item-by-item generation | Variational Autoencoder (VAE), Autoregressive Model (AR), Normalizing Flow | The 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 density | Not computable | Adversarial game, with the discriminator providing the signal | One forward pass | Generative Adversarial Network (GAN) | Unstable training, mode collapse, hard to cover all modes |
| Score-based / diffusion | The score can be estimated without the normalization constant | Denoising regression (predicting noise or the score) | Multi-step iterative denoising | Denoising Diffusion Probabilistic Model (DDPM), Noise Conditional Score Network (NCSN), Flow Matching | Slow 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 ; 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 concept | Its counterpart in diffusion sampling |
|---|---|
| State | The current noisy sample |
| Action | The next sample , or the network’s noise estimate |
| Policy | The reverse transition |
| Environment dynamics | The forward noising process (fixed and known) |
| Episode length | The number of diffusion steps |
| Reward / objective | Make 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:
Writing it in reparameterized form makes sampling and analysis convenient:
where . The joint distribution of the whole chain is
Two key points:
- There are no learnable parameters. The forward process is fully determined by the noise schedule ; at training time we simply “add noise according to the formula”, and it does not participate in the gradient.
- 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 , then
is a linear combination of two independent Gaussians, with mean and variance respectively
Step 2: Start from and substitute step by step to get the cumulative product form. Starting from being a deterministic value (with zero variance), the first step gives with variance . Assume step already holds:
Substituting into the single-step formula:
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:
Hence
Note that the merged differs from both the original and , 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
It means that at training time we do not actually need to run noising steps: we just sample one and compute in one shot. This is the key to the training efficiency of diffusion models: no matter how large is, constructing costs only .
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:
The noise schedule determines “when the signal gets drowned out”. Two commonly used schedules:
Linear schedule (the original DDPM): increased linearly to . 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
It makes the decrease of more uniform, smoother in the low-noise range, and faster to reach zero in the high-noise range.
| Schedule | Shape of | Advantage | Disadvantage |
|---|---|---|---|
| Linear | Steep first, then flat | Simple to implement, aligned with the original paper | Too dense in the low-noise range, wasted steps at the end |
| Cosine | Roughly uniform decrease | Balanced utilization of every noise range, better FID | Requires recalibrating 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):
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. , and the two terms are independent, so
If the data have been standardized to unit variance, then , whose logarithm is .
Step 2: Prove monotonicity. Because is monotonically non-increasing in (each ), the quantity is monotonically non-increasing and decreases monotonically. As there is almost no noise; as there is almost nothing but noise.
Step 3: Why this quantity matters. The training loss is far more sensitive to than to : the same corresponds to a large in the low-noise range and a very small one in the high-noise range. Therefore sampling time steps uniformly in is “fairer” than sampling uniformly in ; 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 and , the limit of the forward chain is a stochastic differential equation (Stochastic Differential Equation, SDE). Two common forms:
Variance Preserving (VP):
Its marginal distribution preserves unit variance, corresponding to the discrete .
Variance Exploding (VE):
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
In practice the variance is almost always fixed to , and only the mean is predicted by the network. The whole reverse chain is
3.2 The Evidence Lower Bound
The training objective is to maximize the log likelihood 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.
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.
The inequality comes from Jensen’s inequality ( is concave), and equality holds when , in which case the gap is zero.
Step 2: Factorize the joint distribution into a product along the Markov chain.
Step 3: Cancel the common factors of adjacent time steps term by term. Rewrite in a conditional form that includes (using Bayes’ rule and the Markov property):
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:
Step 4: Write the log ratios as KL divergences. Note that , hence
Step 5: The meaning of the three terms. 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. asks “does each reverse transition match the true posterior” and is the main workhorse of training. is “the reconstruction quality of the final step”, equivalent to the negative log likelihood of a Gaussian decoder. Training is therefore all about making as close as possible to .
3.3 The True Posterior Is a Closed-Form Gaussian
The inside 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.
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,
The first factor is and the second is . 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 .
The coefficient of the quadratic term is
Hence the posterior variance is
Step 3: Find the mean. The coefficient of the linear term is
The mean equals “the linear coefficient divided by the quadratic coefficient”:
Substituting the explicit expression of and simplifying gives
Step 4: Rewrite the mean in terms of the noise prediction. At training time the network sees rather than , so we solve for from the closed-form marginal distribution:
After substitution and rearrangement we obtain a form that depends only on and the noise:
This step is the direct source of the DDPM sampling formula: simply replace with the network prediction .
3.4 From Term-by-Term KL to the Simplified Loss
Expanding the KL between the two Gaussians inside shows that it differs from “the mean squared error of the noise prediction” only by a constant weight that depends on .
DDPM’s approach is to drop this weight outright, giving the simplified loss:
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,
Step 2: Substitute the two means. The true posterior mean contains and the network mean contains , and the only difference between them is this term:
Step 3: Squaring gives the weight.
which agrees with the expression for .
Step 4: Dropping the weight changes the optimization problem. The original weight varies sharply with : 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):
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:
| Parameterization | Network output | Relation to | Numerical characteristics |
|---|---|---|---|
| parameterization | Direct | Stable at low noise, errors amplified at high noise | |
| parameterization | Stable at high noise, relative errors amplified at low noise | ||
| parameterization | Fairly stable at both ends, more balanced training target variance |
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 , the score is defined as
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 , then and 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
But the ground truth on the right-hand side is unavailable: we only have samples, not an analytic . 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 given . Because the marginal distribution has a closed form, this conditional score can be computed analytically:
The training objective therefore becomes
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 . Expanding the squared term:
The explicit objective has the same shape after expansion, except that is replaced by . 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.
This step uses the identity that “the expectation of the score over the conditional distribution equals the expectation over the marginal distribution”: , then multiplying by the outer weight and integrating over gives the result.
Step 3: Conclusion. The two objectives differ only by a constant that does not depend on , so their optimal solutions are the same and their gradients are the same. Intuitively: regressing the conditional score at noise level 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.
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 . By Bayes’ rule,
Step 2: Swap the integral and the derivative, and use the closed form of . Differentiating the Gaussian conditional density gives
Step 3: Solve for the posterior mean.
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 .
Step 4: Align with the noise parameterization. Substituting immediately gives
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:
When the step size and the number of iterations is large enough, the sample distribution converges to . 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.
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
| Viewpoint | Training objective | Sampling method |
|---|---|---|
| Variational / likelihood viewpoint (DDPM) | Predict noise, equivalent to maximizing a simplified version of the ELBO | Ancestral sampling, injecting noise at every step |
| Score viewpoint (NCSN) | Predict the score, equivalent to denoising score matching | Annealed Langevin |
| Continuous viewpoint (SDE) | Predict the score / noise, with continuous time | Reverse 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.
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.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 noising steps; one shot is enough, which is the key to training efficiency.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).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.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.
x = randn(...): the starting point must be a standard Gaussian, because the endpoint distribution of the reverse chain is defined as a standard Gaussian. If of the forward schedule is not close to 0, this assumption will be biased, and the schedule must be tuned properly at training time.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”.sigma_t = sqrt(beta_t * (1 - alpha_bar[t-1]) / (1 - alpha_bar_t)): this takes the posterior variance , which is “the true variance of the posterior given ”. The original DDPM paper compared another choice and concluded that the two perform similarly, but is more stable when approaches .- Noise is added only
if t > 1: the goal of the last step is to output directly, and adding noise again would destroy the details that were just recovered.
5.5 Gradient Flow and Detach Checklist
| Tensor | Needs a gradient | Explanation |
|---|---|---|
x0 | No | Real data, always detach or constructed under no_grad |
eps | No | The sampled Gaussian noise, which is the regression target, and must be detached |
x_t | No (as an input) | Constructed from x0 and eps; it is the network input and gradients should not flow back to the data |
t | No | An integer time step, used only for table lookup and embedding |
pred | Yes | The network output; the gradient passes only through the network parameters |
theta_ema | No | The EMA update is performed under torch.no_grad() and must not be updated by the optimizer |
| Text / condition encoder | Usually no | Generally frozen in conditional generation; only cross-attention and the backbone take part in training |
Two easy-to-miss points:
- Do not compute the loss after data augmentation of
x_t. Augmentation breaks “the correspondence between and ” and distorts the regression target. Augmentation, if any, should be applied to and reconstructed afterwards. - 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
| Pitfall | Symptom | Cause and fix |
|---|---|---|
| Data not normalized | Samples come out all gray or all saturated | Normalize to and make the last layer of the network output the same magnitude |
| Integer time-step embedding | The high-noise range cannot be learned at all | Use sinusoidal positional encoding or Fourier features so that adjacent time steps are also continuous in embedding space |
alpha_bar in float16 | NaN or blown-up images in the low-noise range | Compute cumulative coefficients in float32/float64 and convert to half precision only before entering the network |
| Copying the learning rate from classification tasks | The loss decreases but samples collapse | Diffusion models commonly use 1e-4 to 2e-5 with warmup and gradient clipping |
| Sampling steps inconsistent with training steps | Quality drops sharply after changing T directly | The training schedule determines the geometric trajectory; to shorten sampling use DDIM or respacing, not a hard change of the loop count |
| Forgetting EMA | Single-step samples are noisy with blurry details | Always sample with the EMA parameters; if memory is tight, at least keep a copy of the EMA |
| Wrong batching of conditional branches | Images are overexposed or drift semantically after guidance | Classifier-free guidance needs the same batch of samples to run both “conditional” and “unconditional” passes, and the of the two passes must be exactly identical |
| Adding noise at the last step | The final image has colored speckles | Do 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 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 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
One can verify that marginalizing level by level according to this expression still gives 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 ) is completely unchanged, and a DDPM-trained network can be used directly.
6.3 The Deterministic Update
Taking (injecting no noise at all), the reverse update becomes
where and .
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 , the mean of the expression above is
Step 2: Combine the coefficients of . Expanding and rearranging:
This coefficient does not need to be computed explicitly in practice, because the next step replaces everything with .
Step 3: Replace with the network estimate. Since the mean is linear in , after replacing with the mean equals
Substituting the definition of into the second term and simplifying gives
Step 4: Why we can skip steps. Because the update depends only on the two coefficients and , and not on “whether every intermediate step was actually taken”. It suffices to choose a decreasing subsequence of times and compute the updates with the corresponding . This is respacing: compressing into or even without retraining the trained network.
Step 5: Interpolation with . Let
degenerates to deterministic DDIM, and approaches DDPM’s stochastic sampling. 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 and the step size tends to zero, the DDIM update converges to
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
| Pitfall | Symptom | Fix |
|---|---|---|
| Subsequence chosen non-uniformly | Structure collapses when steps are few | Pick points uniformly in or in the log signal-to-noise ratio, not uniformly in |
| Still using DDPM’s stochastic variance | Very noisy few-step samples | Set to 0 or very small when using few steps |
| Wrong variance at the starting point | Overall color shift in few-step sampling | Use strictly as the starting point and confirm |
| Treating DDIM as a new model to retrain | Wasted compute | DDIM 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:
- Training and sampling step counts are decoupled, so any numerical integrator can be used;
- DDPM, DDIM, and NCSN are all explained as different discretizations of the same family of equations;
- 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
Its reverse process (time running from to ) is
where 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
its marginal density satisfies
where is the divergence and is the Laplacian.
Step 2: Write the diffusion term as “transport plus correction”. Using the identity
the equation can be written in a form containing only first derivatives:
Step 3: Identify the new SDE that this equation corresponds to. An SDE with only a drift term has density evolution exactly . Therefore, under reversed time , the density evolution corresponds to the drift
Switching back to forward time and adding the diffusion term gives the reverse SDE
Step 4: Substitute the VP coefficients. With and , we have , 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:
For the VP type this is
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 , and the drift of the probability flow ODE is . They differ by .
Step 2: Verify the continuity equation of the ODE. For an ODE , the density satisfies . Taking :
The right-hand side matches the right-hand side of the Fokker-Planck equation term by term (here the identity 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
is the time sampling distribution and is the loss weight. Common choices:
| Strategy | Approach | Purpose |
|---|---|---|
| Uniform sampling in | Simple, but the log signal-to-noise ratio is unevenly distributed | |
| Uniform in log signal-to-noise ratio | Take uniform points in | Balanced gradient contribution from every noise range |
| Importance sampling | Adjust according to the loss magnitude | Reduce gradient variance |
| Loss weighting | or Min-SNR | Trade off between likelihood and perceptual quality |
7.5 Choosing a Numerical Integrator
| Integrator | Order | Evaluations per step | Suitable for |
|---|---|---|---|
| Euler (DDIM) | 1 | 1 | Few steps, simple implementation |
| Heun (second order) | 2 | 2 | Medium step counts, quality-sensitive |
| Runge-Kutta | 4 | 4 | High precision, acceptable compute |
| DPM-Solver family | Multi-step, high order | 1 to 2 | Thousand-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 and 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 (text, class, depth map, reference image), the goal is to sample from . The mainstream approaches fall into two categories:
- Conditional injection: encode and feed it into the network, letting the network learn directly. This is the standard approach of latent diffusion and text-to-image models (Chapters 9 and 10).
- 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,
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
where 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.
An equivalent way of writing it is .
Derivation: Where the linear combination of classifier-free guidance comes from
Step 1: Define the guided distribution. Let
When , Bayes’ rule exactly recovers ; when , 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 cancels the normalization constant:
Step 3: Write the conditional score in terms of two computable quantities. By Bayes’ rule, . Substituting back:
Step 4: Translate into the noise prediction. Using the conversion of 4.4, , and multiplying both sides by gives
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 (commonly 0.1 to 0.2).
Step 5: The two sides of . What 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 toward its high-score region, cutting off the tails, so diversity drops, colors become oversaturated, and details become over-sharpened. When 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
| Item | Cost / symptom | Explanation |
|---|---|---|
| Two forward passes | Sampling compute doubles | The conditional and empty conditions can be concatenated into one batch for a single forward pass, but memory also doubles |
| too large | Oversaturation, reduced diversity | Common values are 3 to 9; negative prompts can be implemented as a subterm with negative |
| No condition-drop training | The unconditional branch is unusable | Random dropping is required at training time, otherwise CFG fails |
| Different random noise for the conditional and empty conditions | Wrong guidance direction | The two branches must share the same |
| Text encoder not frozen | Language capability is destroyed | Usually 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 ( 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 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.
The diffusion process happens entirely on , and after sampling is finished the result is decoded back to pixels.
9.2 Two-Stage Training
- Train the autoencoder: the encoder and decoder are trained with a reconstruction loss (plus perceptual and adversarial losses), with the goal that after compressing to and restoring it, the human eye cannot tell the difference. A common downsampling factor is , that is, becomes .
- Train the diffusion model: freeze and , and train the denoising network in the 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 , the spatial size of the latent space is 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 forward passes. Hence the sampling cost of a single image is approximately
where is the equivalent computation per pixel per step. With , , and , the equivalent spatial size of the latent space is only , which is of pixel space.
Step 3: The trade-off between quality and compression rate. If is too small, little compute is saved; if 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 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 , which serves as keys and values in every attention layer of the denoising network, with the latent variable as the query:
where , , , is the number of positions after flattening the latent space, and 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 are independent, zero-mean, and unit-variance, then
has mean zero and variance .
Step 2: Without scaling, softmax saturates. The magnitude of the softmax input grows with , 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 , 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 , not to make the numbers “look nice”.
Step 4: The difference between cross-attention and self-attention. In self-attention, all come from the same sequence, and what is modeled is “which positions inside the image are related”; in cross-attention comes from the latent variable and 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
| Pitfall | Symptom | Fix |
|---|---|---|
| Autoencoder reconstruction too blurry | Missing detail and distorted text in generated images | Increase the weights of the perceptual and adversarial terms in the reconstruction loss, or lower the downsampling factor |
| Latent distribution shift | Overall color shift in generated images | Standardize the latent variables (scale by per-channel mean and variance) |
| Too few cross-attention layers | The prompt only affects global style | Add cross-attention at multiple resolution levels |
| Decoder participating in training | Memory explodes, training unstable | Freeze the decoder and call it only at the end of sampling |
| Latent resolution inconsistent with training | Collapse when the sampling size changes | Support 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:
- Time-step embedding: encode the integer into a continuous vector and inject it into every residual block. Sinusoidal positional encoding is commonly used:
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.
-
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.
-
Self-attention layers: usually placed only at the lower-resolution levels (such as and ), 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 , we have
Step 2: See how the error is amplified. If the network has an absolute error when predicting , then the error translated into noise is
As (low noise), this factor tends to infinity: a tiny error is translated into an enormous noise error. Conversely, if the network has an error when predicting , the error translated into is
As (high noise), this factor tends to infinity.
Step 3: Conclusion. The low-noise range suits predicting (or the equivalent quantity of ), and the high-noise range suits predicting ; a single parameterization cannot be stable at both ends. This is why DDPM chose , why some models choose , and why the parameterization tries to compromise.
Step 4: Why the parameterization compromises. Define
It weights the two quantities by their respective “stable regions”: at low noise is large, so mainly reflects ; at high noise is large, so mainly reflects . Hence the prediction error of 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 parameterization is better suited to high-resolution, high-dynamic-range data”.
10.3 Training Engineering Checklist
| Item | Common practice | Note |
|---|---|---|
| Mixed precision | bfloat16 for the backbone, float32 for the cumulative coefficients and the loss | Half precision saves memory and time, but needs high precision in the low-noise range |
| Gradient clipping | Clip the norm at 1.0 | Diffusion training occasionally spikes; clipping prevents occasional exploding gradients |
| EMA | Decay 0.9999, smaller early on | Essential for sampling; reduces noise markedly |
| Learning rate | 1e-4 to 2e-5, with warmup | Lower for large models, higher for small ones |
| Batch size | As large as possible, with gradient accumulation | Diffusion is sensitive to batch variance |
| Data augmentation | Only on , using distribution-preserving transforms such as horizontal flip | Strong augmentation changes the data distribution and must be used carefully |
| Time-step sampling | Uniform, or by log signal-to-noise ratio | Affects how well each noise range is trained |
| Loss monitoring | Track the loss per noise range | Looking 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 and let the samples follow the ordinary differential equation
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 , with the noise and the data:
The training objective is to regress this velocity:
Derivation: Why regressing the "conditional velocity" learns the "marginal velocity"
Step 1: The velocity of the conditional path is known. Given a pair , the path is a straight line and the velocity is constant at , independent of . 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 be . One can show that the velocity field that makes the marginal distribution evolve correctly along the ODE is
Step 3: The least-squares optimum is exactly the conditional expectation. For a fixed , minimize
Differentiating with respect to and setting it to zero gives . 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 and that correspond to , the parameterization of diffusion
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 , the probability flow ODE is written as . 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 is matched independently, the marginal trajectories of the straight-line interpolation path may still be curved. Rectified Flow straightens them iteratively:
- Sample with the current model to obtain pairs ;
- Retrain on these new pairs to regress ;
- 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
| Pitfall | Symptom | Fix |
|---|---|---|
| Time sampling concentrated at both ends | The velocity in the middle range is learned poorly | Use uniform sampling or a logit-normal distribution |
| Arbitrary pairing | Curved trajectories, steps cannot be reduced | Use multi-round straightening of rectified flow, or pair by optimal transport |
| Velocity magnitude not normalized | Training diverges | Standardize the data, and do not add a bounded activation to the output layer |
| Changing the time parameter directly in diffusion code | Color shift in sampling | Make explicit the direction of (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
| Route | Approach | Representative | Cost |
|---|---|---|---|
| A better integrator | Use high-order ODE solvers | DPM-Solver | The lower bound on the step count is limited by curvature |
| A better path | Use straight-line flow matching to straighten the trajectory | Rectified Flow | Requires retraining or straightening iterations |
| Distillation | Have a student model imitate the teacher in fewer steps | Progressive distillation, consistency models | Requires 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 and takes two DDIM steps to reach , the student is trained to predict directly from :
Once training is finished, the student becomes the new teacher, the step count is halved again, and the process repeats for 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”:
The boundary condition 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 can map any point on the trajectory back to the starting point, then for two adjacent points,
Step 2: Approximate the right-hand side with one ODE step. Using the teacher (or the EMA parameters ) to take one step from gives , so the target is
Step 3: Write it as a loss.
where is a distance (L2, or LPIPS plus L2). 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, maps pure noise directly to in a single step; a multi-step alternation (calling 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
| Pitfall | Symptom | Fix |
|---|---|---|
| The teacher is of poor quality | The student’s ceiling is locked | Train the teacher well first, then distill |
| The distillation target contains random noise | The student cannot learn a deterministic mapping | Use a deterministic sampler () during distillation |
| Boundary conditions not enforced | One-step output is all gray | Explicitly add the boundary loss |
| Steps compressed too aggressively | Detail and text break down | 4 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
| Category | Metric | What it measures | Limitation |
|---|---|---|---|
| Distribution distance | FID, KID | The gap between the generated distribution and the real distribution | Depends on Inception features; not applicable to some domains |
| Single-sample quality and diversity | IS, precision, recall | Whether a single image is realistic; how many real modes are covered | IS is insensitive to mode collapse |
| Likelihood | bits/dim, negative log likelihood | How well the probabilistic model fits | Weakly correlated with perceptual quality |
| Cost | NFE, samples per second, memory | Engineering usability | Not 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:
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 , the second-order Fréchet distance is
where is the set of all joint distributions with marginals and . 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 and , the optimal coupling is the affine transform , where satisfies .
Step 3: Expand the expectation.
The second term equals .
Step 4: Take the optimal . The optimal solution is ; substituting it back into the second term and using the cyclic property of the trace gives
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
| Detail | Correct practice | Common mistake |
|---|---|---|
| Sample size | At least the same order as the real set (commonly 10 thousand to 50 thousand) | Computing FID from a few hundred images, with enormous variance |
| Preprocessing | Consistent with how Inception was trained (resizing, normalization) | Feeding images directly, which shifts the features |
| Randomness | Fix the seed, and report the mean and variance over multiple samplings | Reporting only the single best run |
| Fairness of comparison | Same resolution, same sampling steps, same guidance strength | Comparing 4 steps against 1000 steps |
| Text conditioning | Use a fixed prompt set and report every category of metric | Picking 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:
- The likelihood cares about the exact probability of every pixel, whereas the human eye cares about structure and semantics;
- 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 . This assumption has two fatal flaws:
- 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;
- 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 , 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 (an image or a state vector) and the action be . The diffusion policy learns the conditional distribution , and its training objective is exactly the same as the conditional diffusion of Chapter 8:
At sampling time we start from and denoise iteratively to obtain the action .
14.3 Action Chunking and Closed-Loop Execution
There are two key designs in practice:
- Action chunking: generate the next actions at once (for example ) rather than one step. This lowers the inference frequency, improves temporal consistency, and mitigates the jitter caused by “independent sampling at every step”.
- Receding horizon: execute only the first steps (for example ), then re-observe and regenerate. This preserves closed-loop feedback and avoids the cumulative error of open-loop execution.
| Execution style | Approach | Advantage | Disadvantage |
|---|---|---|---|
| Single-step closed loop | Generate one action per step and execute it | Fastest feedback | High inference frequency, jitter |
| Open-loop chunking | Generate steps and execute all of them | Cheap inference, temporal consistency | No feedback, errors accumulate |
| Receding horizon | Generate steps, execute only | Balances consistency and feedback | Requires tuning and |
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
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 , the optimal mean when minimizing is the mean of :
And 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 family | Distribution representation | Training signal | Multimodal | Inference cost | Typical algorithms |
|---|---|---|---|---|---|
| Gaussian policy | Unimodal Gaussian | Policy gradient / maximum likelihood | Weak | One forward pass | PPO, SAC |
| Mixture density network | A finite number of Gaussians | Maximum likelihood | Medium | One forward pass | MDN policy |
| Diffusion policy | Implicit distribution of multi-step denoising | Denoising regression | Strong | Several forward passes | Diffusion Policy |
| Flow matching policy | Velocity field ODE | Velocity regression | Strong | A few integration steps | The action expert of π₀ |
| Autoregressive discrete policy | Discrete token sequence | Cross entropy | Strong | Token by token | RT-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:
- 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);
- 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;
- 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
| Pitfall | Symptom | Fix |
|---|---|---|
| Actions not normalized | Sampled action magnitudes are absurd | Standardize each dimension using dataset statistics |
| Observation conditioning too weak | Generated actions do not correspond to the scene | Use a pretrained vision encoder, and add auxiliary losses |
| Inference frequency inconsistent with training | Jitter on the real robot | Fix the action chunk length and the number of execution steps, and simulate the same latency during training |
| Open loop only | Errors accumulate over long tasks | Use receding horizon, with about half the chunk length |
| Too little data | Multimodality cannot be learned | Diffusion 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:
| Variable | Meaning | Question to answer when switching to a new modality |
|---|---|---|
| Data form | What is being noised | Is it a tensor, a sequence, a point set, a graph, or discrete tokens? How are the dimensions normalized? |
| Conditioning signal | What guides the generation | Class, text, depth map, pose, action history, ligand pocket? Where does the encoder come from? |
| Sampling budget | The acceptable number of network forward passes | Offline 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.
| Scenario | Data form | Conditioning signal | Mainstream approach | Typical sampling budget | Representative method |
|---|---|---|---|---|---|
| Image generation and editing | or latent | Class, text, reference image, mask | Latent diffusion plus classifier-free guidance | 20 to 50 steps | Stable Diffusion family, Imagen, DALL·E 2 |
| Video generation | Text, first frame, camera trajectory | Joint spatiotemporal diffusion, or latent video diffusion | 20 to 100 steps | Video Diffusion, Sora-style spatiotemporal diffusion | |
| Audio, speech, and music | Waveform or mel spectrogram | Text, speaker, score | Mel-spectrogram diffusion plus a vocoder, or waveform diffusion | 10 to 50 steps | DiffWave, WaveGrad, AudioLDM |
| 3D and scenes | Multiple views, point cloud, implicit field, triplane | A single image, text, sparse views | Multi-view diffusion plus reconstruction, or native 3D diffusion | 30 to 100 steps | Zero-1-to-3, DreamGaussian, 3D latent diffusion |
| Molecules and protein structures | Atomic coordinates plus atom types | Pocket, properties, sequence | Equivariant diffusion (coordinate noising with a rotation-equivariant network) | 50 to 500 steps | GeoDiff, DiffDock, RFdiffusion |
| Medical images | 2D slices, 3D volumes | Segmentation mask, low-dose input, modality | Conditional diffusion for reconstruction and cross-modality translation | 10 to 50 steps | Low-dose CT diffusion reconstruction, MR cross-modality translation |
| Robot policies | Action chunk | Observation sequence, language instruction | Conditional diffusion policy plus action chunking plus receding horizon | 1 to 10 steps (often distilled) | Diffusion Policy, consistency policy |
| Data augmentation and simulation | Images, sensor data, trajectories | Labels, scene parameters | Unconditional or conditional diffusion for augmentation | 20 to 50 steps (can be offline and batched) | Diffusion augmentation, synthetic-data pipelines |
| Time-series forecasting and imputation | Multivariate sequence | History window, covariates | Conditional diffusion for whole-segment generation or masked imputation | 10 to 100 steps | Time-series diffusion imputation, trajectory prediction |
15.1 Image Generation and Editing
Task form. Unconditional generation learns ; text-to-image learns ; editing, given a source image and a mask , 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 image into a 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.
| Pitfall | Symptom | Fix |
|---|---|---|
| Guidance strength too large | Saturation explodes and details smear | Keep the guidance strength between 3 and 8, with dynamic thresholding or truncated sampling |
| Latent variance compressed | Small text and texture are lost | Use a gentler downsampling factor, or restandardize the variance in the latent space |
| Text encoder too weak | Long sentences and negations have no effect | Switch to a stronger text encoder, and preprocess with “prompt rewriting” |
| Mask boundary not blended | Visible seams after editing | Refill the known region after each denoising step, and feather the mask |
| Reporting only FID | Metrics look good but the semantics are wrong | Add 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 , where is a sequence of 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.
| Pitfall | Symptom | Fix |
|---|---|---|
| Per-frame metrics only | High score but flickering | Add optical-flow consistency and manual inspection |
| Fully connected temporal attention | Memory grows with the square of the frame count | Use local windows or block attention |
| First-frame condition too strong | Later frames do not budge and the video is almost static | Lower the weight of the first-frame condition, or add noise to it |
| Training clips too short | Long videos drift or the scene jumps | Use 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 ; speech enhancement and denoising is ; music generation is .
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.
| Pitfall | Symptom | Fix |
|---|---|---|
| Crude phase handling | Metallic sound, crackling | Use the complex spectrum or model the waveform directly; do not run diffusion only on the magnitude spectrum |
| Sequences that are too long | Memory and latency unacceptable | Segmented generation plus overlapping cross-fading |
| Conditioning not aligned with duration | Speaking-rate drift, drawn-out vowels | Provide duration or alignment conditions explicitly (such as phoneme duration prediction) |
| Only objective metrics | Metrics are good but it sounds bad | MOS-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 ; text-to-3D is . 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.
| Pitfall | Symptom | Fix |
|---|---|---|
| Inconsistent viewpoints | Multi-view images do not stitch together | Share cross-view information in the attention layers, and feed the camera poses explicitly |
| Equivariance broken | The result collapses when the orientation changes | Use equivariant networks and equivariant noise, not ordinary convolutions |
| Reconstruction error masks generation error | Metrics are good but the shape is odd | Evaluate “geometry” and “texture” separately |
| Memory too tight | High resolution is impossible | Use 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 ; molecular docking is ; protein backbone design is .
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.
| Pitfall | Symptom | Fix |
|---|---|---|
| No equivariant constraint | Inconsistent results after rotation, unstable training | Equivariant network plus equivariant noise |
| Physical validity ignored | Absurd bond lengths, overlapping atoms | Add auxiliary losses or post-processing for bond lengths and repulsion |
| Only optimizing RMSD | Generating structures that “match but do not look real” | Add physical energy terms and diversity metrics |
| Discrete and continuous mixed improperly | Atom types jump around | Design 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 ; Magnetic Resonance (MR) cross-modality translation is ; 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.
| Pitfall | Symptom | Fix |
|---|---|---|
| Hallucinated lesions | Generating structures that do not exist | Add data-consistency terms, check consistency across multiple samples, and keep human review |
| Pixel-level metrics only | Metrics are good but diagnostic value is low | Add downstream task metrics and physician ratings |
| Data bias | Fails on a certain device or population | Multi-center validation, stratified evaluation by device |
| Privacy and compliance | Data cannot be shared | Federated 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 ; 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.
| Pitfall | Symptom | Fix |
|---|---|---|
| Inference too slow | Control frequency drops to single digits | Action chunking plus distillation plus half-precision inference |
| Action chunk too long | Sluggish reactions | Shorten the chunk length and pair it with receding horizon |
| Observation conditioning too weak | Grabbing at nothing, hitting objects | Strengthen the vision encoder and add auxiliary tasks (such as predicting future frames) |
| Testing only success cases | Frequent failures on the real robot | Systematically 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.
| Pitfall | Symptom | Fix |
|---|---|---|
| Synthetic distribution too narrow | Downstream performance drops instead of rising | Constrain the conditional distribution with real-data statistics, and check distribution coverage |
| Labels misaligned with images | Detection boxes do not match | Check consistency after layout-conditional generation |
| Test-set leakage | Inflated evaluation | Strictly isolate synthetic samples from the real evaluation samples |
| Visual inspection only | Bias goes unnoticed | Do 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 ; missing-value imputation is ; 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 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.
| Pitfall | Symptom | Fix |
|---|---|---|
| Noising the raw magnitude directly | Large values dominate the loss | Standardize or log-transform first, then normalize symmetrically |
| Time-step conditioning ignored | Trajectory drift over long forecast windows | Feed the forecast step index explicitly as a condition |
| Reporting only point error | Multimodality is averaged away | Distribution metrics and multi-sample metrics must be reported |
| Sequence too short | Periodicity cannot be learned | Use 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
| Method | Forward process | Sampling process | Typical NFE | Main advantage | Main cost | When to choose it |
|---|---|---|---|---|---|---|
| DDPM | Discrete -step Markov chain | Discrete reverse Markov chain, noise added at every step | 1000 (can be reduced to 100 to 250) | Cleanest concept, most stable training, easy to reproduce | Extremely slow sampling | Learning the principles, small-scale experiments |
| DDIM | Same training objective as DDPM | Non-Markovian, deterministic update | 20 to 50 | Accelerates without retraining, invertible | Quality drops when steps are too few | Needing both speed and quality on the same weights |
| Score SDE (VP/VE) | Continuous-time noising | Reverse SDE or probability flow ODE | Hundreds of steps for the SDE, tens for the ODE | Unified theory, any integrator can be used | Requires tuning the discretization and the integrator | Continuous-time modeling, writing a new integrator |
| DPM-Solver | Continuous time | High-order exponential integrator | 10 to 20 | Good few-step quality, no retraining | Many implementation details | An existing continuous-time model that needs few-step generation |
| Conditional guidance (classifier / CFG) | Same as the base model | Adds a condition gradient to the score | Same as the base model | Significantly improves condition alignment | Too-strong guidance sacrifices diversity | Text-to-image, action-conditioned generation |
| Latent-space diffusion | Noising in the compressed latent space | Same as the base model | 20 to 50 | Resolution and quality rise sharply for the same compute | Needs an autoencoder, details are lossy | High-resolution images and video |
| Flow matching (CFM) | Straight-line interpolation path, no fixed forward chain | Velocity field ODE integration | 1 to 20 | Straighter path, better few-step results, simple training target | Needs a pairing or coupling design | Fast sampling needed (such as a VLA action head) |
| Rectified flow (Reflow) | Iteratively straightened path | One-step or multi-step straight ODE | 1 to 4 | Can be compressed to very few steps | Requires multiple rounds of retraining | Deployment with strict latency requirements |
| Consistency model / LCM | Distilled from a pretrained diffusion model | One step or a few steps mapping to | 1 to 4 | Extremely fast, acceptable quality | Complex training, slightly reduced diversity | Real-time interaction, on-device deployment |
| Diffusion policy | Noising the action chunk | Conditional denoising plus receding horizon | 1 to 10 | Strong multimodal expressiveness, stable training | Slow inference, large data requirement | Fine 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 -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 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:
| Goal | Recommended path | Roughly covered chapters |
|---|---|---|
| Just want to know what diffusion is | Chapter 0 plus Chapter 1 plus the sampling pseudocode in 5.1 | 0, 1, 5 |
| Want to train an image model hands-on | 2, 3, 5, 8, 9, 10 | Forward process, loss, DDPM, CFG, latent space, architecture |
| Want to accelerate to few-step deployment | 6, 7, 11, 12, 13 | DDIM, continuous time, flow matching, distillation, metrics |
| Want to build a robot policy | 14 plus 15.7 plus the flow matching of Chapter 11 | Diffusion 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
- 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.)
- Ho, Jain, Abbeel. Denoising Diffusion Probabilistic Models. NeurIPS 2020. (The original DDPM paper, the main basis of Chapter 5 here.)
- Nichol, Dhariwal. Improved Denoising Diffusion Probabilistic Models. ICML 2021. (Cosine noise schedule, learned variance, importance sampling.)
- 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
- Hyvärinen. Estimation of Non-Normalized Statistical Models by Score Matching. JMLR 2005. (The original form of explicit score matching.)
- Vincent. A Connection Between Score Matching and Denoising Autoencoders. Neural Computation 2011. (Implicit score matching, the core of Chapter 4 here.)
- Song, Ermon. Generative Modeling by Estimating Gradients of the Data Distribution. NeurIPS 2019. (Annealed Langevin sampling.)
- 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
- Song, Meng, Ermon. Denoising Diffusion Implicit Models. ICLR 2021. (DDIM, Chapter 6 here.)
- 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.)
- Liu, Gong, Liu. Flow Straight and Fast: Learning to Generate and Transfer Data with Rectified Flow. ICLR 2023. (Rectified flow.)
- Lipman, Chen, Ben-Hamu, Nickel, Le. Flow Matching for Generative Modeling. ICLR 2023. (Conditional flow matching.)
- Salimans, Ho. Progressive Distillation for Fast Sampling of Diffusion Models. ICLR 2022. (Progressive distillation.)
- Song, Dhariwal, Chen, Sutskever. Consistency Models. ICML 2023. (Consistency models.)
- 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
- Dhariwal, Nichol. Diffusion Models Beat GANs on Image Synthesis. NeurIPS 2021. (Classifier guidance, architecture ablations.)
- Ho, Salimans. Classifier-Free Diffusion Guidance. 2022. (CFG, Chapter 8 here.)
- Rombach, Blattmann, Lorenz, Esser, Ommer. High-Resolution Image Synthesis with Latent Diffusion Models. CVPR 2022. (Latent-space diffusion, Chapter 9 here.)
- Zhang, Rao, Agrawala. Adding Conditional Control to Text-to-Image Diffusion Models. ICCV 2023. (ControlNet, a spatial-conditioning bypass.)
- Peebles, Xie. Scalable Diffusion Models with Transformers. ICCV 2023. (A Transformer backbone replacing the U-Net.)
Parameterization, weighting, and training details
- Salimans, Ho. Progressive Distillation for Fast Sampling of Diffusion Models. ICLR 2022. (The same paper as reference 13; its discussion of and parameterizations is frequently cited.)
- 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.)
- 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
- 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.)
- Bińkowski, Sutherland, Arbel, Gretton. Demystifying MMD GANs. ICLR 2018. (KID.)
- Kynkäänniemi, Karras, Laine, Lehtinen. Improved Precision and Recall Metric for Assessing Generative Models. NeurIPS 2019. (Precision/recall.)
Diffusion policies and embodied intelligence
- Janner, Du, Tenenbaum, Levine. Planning with Diffusion for Flexible Behavior Synthesis. ICML 2022. (Diffusion Planner, using diffusion for trajectory planning.)
- Chi, Feng, Du, et al. Diffusion Policy: Visuomotor Policy Learning via Action Diffusion. RSS 2023. (Diffusion policy, Chapter 14 here.)
- 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.)
- Black, Brown, Driess, et al. π₀: A Vision-Language-Action Flow Model for General Robot Control. 2024. (A flow matching action expert.)
Surveys
- Yang, Zhang, Song, et al. Diffusion Models: A Comprehensive Survey of Methods and Applications. ACM Computing Surveys 2023. (The survey with the broadest coverage.)
- 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.
| Abbreviation | Full English name | Explanation |
|---|---|---|
| AC | Actor-Critic | A framework that uses a value function to assist policy updates |
| CFG | Classifier-Free Guidance | Training both a conditional and an unconditional branch and amplifying their difference at sampling time |
| CFM | Conditional Flow Matching | Training a generative model by regressing a conditional velocity field |
| CG | Classifier Guidance | Using the gradient of a noise-robust classifier as conditional guidance |
| CLIP | Contrastive Language-Image Pretraining | A pretrained encoder that aligns images and text |
| CRPS | Continuous Ranked Probability Score | Measuring the distance between a predictive distribution and the true value |
| CT | Computed Tomography | Computed tomography scanning |
| DDIM | Denoising Diffusion Implicit Models | Non-Markovian deterministic sampling for diffusion models |
| DDPM | Denoising Diffusion Probabilistic Models | The standard discrete form of diffusion models |
| DPM-Solver | Diffusion Probabilistic Model Solver | A high-order integrator aimed at few-step sampling |
| DSM | Denoising Score Matching | Estimating the score from the denoising direction of noised data |
| ELBO | Evidence Lower Bound | The variational lower bound on the log likelihood |
| EMA | Exponential Moving Average | Smoothing current parameters with historical parameters |
| FAD | Fréchet Audio Distance | Moving FID onto audio features |
| FID | Fréchet Inception Distance | Comparing the distributional gap between two sets of image features |
| FM | Flow Matching | Directly regressing the velocity field from noise to data |
| GAN | Generative Adversarial Network | A generator and a discriminator trained adversarially |
| IL | Imitation Learning | Learning a policy from demonstrations |
| IS | Importance Sampling | Estimating the expectation of a new distribution with samples from an old one |
| KID | Kernel Inception Distance | An unbiased substitute for FID in the small-sample regime |
| KL | Kullback-Leibler Divergence | A measure of the difference between two probability distributions |
| LCM | Latent Consistency Model | Moving consistency distillation into the latent space |
| MAE | Mean Absolute Error | Mean absolute error |
| MDP | Markov Decision Process | The standard mathematical framework for sequential decision making |
| MOS | Mean Opinion Score | Human perceptual rating of audio quality |
| MR | Magnetic Resonance | Magnetic resonance imaging |
| NeRF | Neural Radiance Field | A differentiable rendering field that represents volume density and color with a network |
| NFE | Number of Function Evaluations | The number of network forward passes needed for sampling |
| ODE | Ordinary Differential Equation | Ordinary differential equation |
| PF ODE | Probability Flow ODE | An ordinary differential equation with the same marginal distributions as the SDE but without the stochastic term |
| POMDP | Partially Observable Markov Decision Process | Partially observable Markov decision process |
| Reflow | Rectified Flow | Straightening the generative path by multiple rounds of retraining |
| RL | Reinforcement Learning | Optimizing a policy by trial-and-error interaction with an environment |
| RMSD | Root Mean Square Deviation | The root mean square of per-atom coordinate distances |
| SDE | Stochastic Differential Equation | A differential equation containing a stochastic term |
| SNR | Signal-to-Noise Ratio | The ratio of signal power to noise power |
| U-Net | — | A U-shaped encoder–decoder network, a multiscale backbone with cross-level skip connections |
| VAE | Variational Autoencoder | A latent-variable generative model trained with a variational lower bound |
| VE SDE | Variance Exploding SDE | A stochastic differential equation whose noise variance diverges over time |
| VLA | Vision-Language-Action | A model that maps observations and instructions directly to actions |
| VP SDE | Variance Preserving SDE | A stochastic differential equation whose total variance stays bounded |
| WER | Word Error Rate | The 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 , whereas these notes uniformly write ), 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…
Want to leave a note? Sign in first — comments are open to every signed-in reader.