19 Diffusion Models
Variational autoencoders, as developed in ch:vae,ch:vae2, learn a latent representation of data in a single encoding step. But what if we replaced that single step with a long chain of small, incremental corruptions, gradually transforming data into pure noise? This idea, rooted in non-equilibrium statistical physics, was first formalised by Sohl-Dickstein et al. [1] and later connected to variational inference by Ho et al. [2]. The result is a family of diffusion models that achieve remarkable sample quality by learning to reverse a carefully designed noise process. In this chapter we derive diffusion models as the natural limit of hierarchical VAEs, following the exposition of [5].
From Hierarchical VAEs to Diffusion Models
The standard VAE compresses an observation into a single latent code and reconstructs from that code. A natural question is whether we can build a richer generative model by stacking multiple latent layers on top of one another, so that each layer captures progressively more abstract features. This is the idea behind hierarchical VAEs, and it turns out that diffusion models emerge as a special case when we push the hierarchy to its logical extreme.
Key Idea.
From VAEs to Hierarchical VAEs In ch:vae,ch:vae2 we built VAEs with a single latent layer: an encoder maps data to a latent code, and a decoder maps back. Hierarchical VAEs extend this by introducing a chain of latent variables , where each layer conditions on all previous layers. The encoder builds up a sequence of increasingly abstract representations, and the decoder reconstructs data by traversing the hierarchy in reverse.
Hierarchical VAE
Consider stacking multiple VAE layers into a fully connected directed acyclic graph (DAG), where each latent variable is conditioned on all preceding variables. The resulting graphical model has edges between every earlier node and every later node, as shown in fig:diff:hvae-dag.
Let denote the parents of in the DAG.\@ The joint distribution factorises according to the graph structure:
Applying the product rule explicitly, the forward joint distribution becomes where each latent variable is conditioned on all preceding variables. Similarly, the backward (generative) joint distribution factorises as where each variable is now conditioned on all subsequent variables.
This fully connected hierarchy captures all possible dependencies, but it raises a practical concern: with latent layers, each conditional depends on up to variables. Can we simplify the model without losing too much expressive power?
The Markov Assumption
The fully connected hierarchical VAE requires each latent variable to condition on the entire history of preceding variables, making both inference and generation computationally expensive. A powerful simplification is to impose a Markov assumption: each variable depends only on its immediate predecessor. This reduces the graphical model from a fully connected DAG to a simple chain.
Under the Markov assumption, the joint distribution simplifies dramatically: Note that this generative model proceeds from to , with each transition depending only on the immediately preceding latent variable. The posterior distribution (denoting as generic ) factorises as
The ELBO for this Markovian hierarchical VAE follows the same derivation as in 15:
Inserting the Markovian joint and posterior into the ELBO yields
Historical Note.
The Thermodynamic Origins of Diffusion Sohl-Dickstein et al. [1] first proposed using diffusion processes from non-equilibrium thermodynamics as a foundation for generative modelling. The key insight was that if one can define a tractable process that gradually destroys structure in data, one can train a model to reverse this destruction. Five years later, Ho et al. [2] showed that this framework, when combined with a simplified training objective and careful noise scheduling, produces image samples rivalling those of GANs.
The Variational Diffusion Model
The Markovian VAE of the previous section still uses learned encoders with latent dimensions potentially smaller than the data dimension. The variational diffusion model (VDM) makes three key simplifications that transform this architecture into a diffusion model.
Key Idea.
Three Simplifications from MVAE to VDM
The latent dimension equals the data dimension: for all .
The encoder is not learned; it is a fixed linear Gaussian.
The Gaussian parameters are chosen so that .
Notice in fig:diff:vdm that every latent variable is now denoted rather than , reflecting the fact that latent and data spaces share the same dimensionality. The forward encoder has no trainable parameters; only the backward decoder is learned. With these changes, the posterior distribution becomes
The Forward Process
Since the encoder is not learned, we must specify its form explicitly. The idea is to add a small amount of Gaussian noise at each step, with the noise level controlled by a variance schedule .
Definition 1 (Forward Process).
The forward process defines each transition as a linear Gaussian: (Forward) where for each . The full forward posterior factorises as At each step, the mean shrinks the previous sample by and adds Gaussian noise with variance . By choosing the schedule appropriately, the distribution converges to for large .
ELBO for the Variational Diffusion Model
We now derive the evidence lower bound for the VDM.\@ The derivation follows the same Jensen's inequality argument as in 15, but applied to the -step Markov chain.
Continuing further, we split the logarithm and simplify the expectations: In the last equality, we replaced the joint by the marginals that each term actually depends on.
Theorem 1 (ELBO for VDM (First Form)).
Remark 1 (Interpretation of the Three ELBO Terms).
The three terms in Theorem 1 each have a clear interpretation:
Reconstruction term: measures how well the decoder reconstructs from the first latent step . This term is analogous to the reconstruction term in the standard VAE ELBO.
Prior matching term: penalises deviations of the final noisy distribution from the Gaussian prior. This term has no trainable parameters and vanishes for sufficiently large , since converges to by design.
Consistency term: enforces that the learned backward transition at each step is consistent with the forward transition .
Remark 2 (Issues with the Consistency Term).
The consistency term requires computing an expectation over the joint , which involves two correlated random variables. This is difficult to estimate efficiently. The remedy is to apply Bayes' rule: Note that we added as a condition, which is valid since by the Markov property. As illustrated in fig:diff:bayes-consistency, this yields the true posterior , which runs parallel to . Matching these two distributions will let us rewrite the ELBO in a more tractable form.
Revised ELBO via Bayes' Rule
We now rederive the ELBO, this time applying Bayes' rule to replace with the tractable posterior . Starting again from Jensen's inequality: (NEW ELBO LAST) We now examine the product inside the last term. Separating it into two factors: The second product telescopes, leaving only the boundary terms. Substituting back into :
Theorem 2 (ELBO for VDM (Revised Form)).
(ELBO Revised) The three terms have the following roles:
is the reconstruction term, as before.
is the prior matching term: it compares the final noisy distribution to the standard Gaussian prior.
is the denoising matching term: it measures how well the learned backward step matches the true posterior .
Marginal Distribution
A crucial property of the linear Gaussian forward process is that we can compute the distribution of given in closed form, without iterating through all intermediate steps.
Theorem 3 (Marginal Distribution).
(Marginal)
Proof.
True Posterior
The revised ELBO in Theorem 2 requires the true denoising posterior . We obtain it by applying Bayes' rule and completing the square in the exponent of the resulting Gaussian.
Theorem 4 (True Denoising Posterior).
Proof.
We begin by applying Bayes' rule and substituting the known Gaussian forms from Definition 1 and Theorem 3:
Remark 3 (The Constant ).
The constant term dropped in the proof above is (THE Constant) Since this term depends only on and , both of which are given as conditions, it is treated as a constant with respect to . We will reintroduce when completing the square below.
Continuing the proof by simplifying the coefficient of and completing the square: This completes the proof. The constant that we dropped earlier is precisely the term needed to complete the square.
Remark 4 (Completing the Square).
Remark 5 (Predetermined Variance).
Theorem 4 shows that at each step, given and follows a Gaussian with mean and variance that is predetermined by the schedule . The variance depends only on , not on any trainable parameters. It can be written as , where (Sigma Q) The goal of training is therefore to align the approximate denoiser with the ground-truth posterior . Since both distributions are Gaussian with the same variance, matching them reduces to matching their means.
The Denoising Objective
Now that both and are Gaussian with identical variance , the KL divergence between them simplifies to a function of their means alone.
Theorem 5 (KL Divergence between Gaussians).
The Kullback-Leibler divergence between two Gaussian distributions is
Theorem 6 (Denoising Matching Objective).
When and share the same variance , the denoising matching term reduces to
Proof.
Here is shorthand for and for . The denoiser must therefore learn to predict the mean of the true posterior .
The true mean is given by (Theorem 4):
Definition 2 (True Denoiser Mean).
The approximate denoiser mirrors this formula but replaces the unknown with a learned estimate:
Definition 3 (Approximate Denoiser Mean).
The approximate denoiser uses the mean (Approx MEAN) where is a neural network that attempts to predict from the noisy observation at timestep .
Theorem 7 (-Prediction Loss).
Given the true denoiser mean and the approximate denoiser mean as defined above, the denoising matching objective simplifies to
Proof.
Remark 6 (Interpretation of the -Prediction Loss).
Theorem 7 reveals that optimising the denoising matching term in the ELBO is equivalent to training a neural network to predict the clean data from its noisy version . The time-dependent prefactor weights the loss differently at each noise level, but the core task is always the same: denoise. The model parameters are learned by supervised regression against ground-truth clean samples.
DDPM: Training and Inference
The mathematical machinery of the previous section (the ELBO decomposition, the closed-form posterior, and the -prediction loss) remained largely theoretical until Ho et al. [2] crystallised them into a practical algorithm called the Denoising Diffusion Probabilistic Model (DDPM). Their key contribution was not a new derivation but a concrete recipe: a simple training loop, a matching sampling loop, and a set of design choices (noise schedule, network architecture, loss weighting) that together produce high-quality images rivalling GANs.
The DDPM Loss Function
Combining the per-timestep KL terms from Theorem 2 into a single objective yields the full DDPM loss. Because every term reduces to an -prediction mean-squared error (as shown in the previous section), the summation takes a clean and interpretable form.
Definition 4 (DDPM Loss).
The full DDPM loss sums over all timesteps. It is the negation of the denoising-matching contribution to the ELBO, so minimising it maximises the bound:
Remark 7 (Interpretation of the Loss).
This formulation of the ELBO highlights several critical aspects:
Reconstruction error. Each term within the summation directly relates to the reconstruction error between the predicted data and the original data . This error is scaled inversely by the noise variance , which adjusts the impact of each timestep based on the model's noise schedule.
Noise schedule dependency. The noise schedule is explicitly integrated into the ELBO through the parameters and . The terms involving these parameters adjust how the model weights the importance of errors at different timesteps, effectively shaping the learning trajectory.
Linearity of expectation. The expectation operator is linear, allowing the external factors like the variance scaling and noise parameters to be handled outside of the expectation. This property simplifies the computation and interpretation of the ELBO, making it computationally feasible to handle within the stochastic gradient descent framework typically used to train such models.
In practice, the summation over all timesteps is replaced by an expectation over a uniformly sampled timestep , yielding a stochastic estimate of suitable for mini-batch gradient descent:
Training Algorithm
The training procedure is pleasingly simple: sample a data point, pick a random timestep, corrupt the data with the corresponding noise level, and take a gradient step to make the network's prediction closer to the original clean data.
Algorithm 1 (DDPM Training).
Algorithm 1: DDPM Training [2].
[H]
- repeat
- Sample
- Sample
- Sample
- Take gradient step on
- until converged
An important detail is the choice of , the cumulative product of the variance reduction factors up to timestep . The selection of affects the trajectory of the noise addition and must be carefully calibrated to balance learning efficiency and model stability. We return to this question in Learned Noise Schedules.
Sampling and Inference
After training, the model generates new data by reversing the diffusion process. Starting from pure Gaussian noise , we iteratively apply the learned reverse transition where the mean is given by At each step the network predicts a clean image , which is blended with the current noisy state to produce the mean of the reverse step. Stochasticity enters through the noise term . At the final step () the noise is omitted, producing the deterministic output .
Algorithm 2 (DDPM Sampling).
Algorithm 2: DDPM Sampling [2].
[H]
- Sample
- for
- if , else
- return
Signal-to-Noise Ratio
A unifying lens through which to view the loss, the noise schedule, and the weighting of different timesteps is the signal-to-noise ratio (SNR). Recall that the forward process satisfies . The mean carries the “signal” and the variance carries the “noise” .
Definition 5 (Signal-to-Noise Ratio).
For a Gaussian , the signal-to-noise ratio is . Applied to the forward process , whose mean is , this gives ; for unit-scaled data () this is (SNR)
The SNR starts high at (mostly signal, little noise) and decreases monotonically toward zero as (mostly noise, little signal). A good noise schedule ensures that , so that is nearly pure Gaussian noise, and that the decrease is smooth enough for the network to learn at every noise level.
Theorem 8 (Loss in Terms of SNR).
Proof.
Theorem 8 tells us that the per-timestep loss can be written purely in terms of the SNR drop between consecutive timesteps. In particular, the differential SNR between two consecutive timesteps gives the per-step loss a transparent interpretation: (SNR TIME) Each term is the product of an SNR drop and the network's prediction error at that noise level. Timesteps where the SNR changes rapidly contribute more to the loss, while timesteps where the SNR is nearly constant contribute little. For the standard cosine and linear- schedules the drop is largest at small , so this weighting emphasises the low-noise end of the chain, which is one reason Ho et al. [2] found that discarding the weight altogether improves perceptual sample quality. Minimising is thus synonymous with denoising: the model learns to reverse the noise added during the forward process, reconstructing from with increasing accuracy as training progresses.
Learned Noise Schedules
The noise schedule (equivalently, the SNR schedule) is a design choice that profoundly affects sample quality. Two classical families are:
Variance preserving (VP) [1]: the forward process keeps the total variance of constant at every step; in the parameterisation of Definition 1 this means , where is the variance added at step .
Variance exploding (VE) [3]: the signal coefficient on is held at and only the noise variance grows over time, so . This does not fit the parameterisation of Definition 1 directly; the two are related by the rescaling , which leaves the signal-to-noise ratio unchanged.
Rather than hand-crafting the schedule, Kingma et al. [4] proposed learning it end-to-end by parameterising the SNR directly with a monotonic neural network : (Learned SNR) where is constrained to be monotonically increasing so that the SNR decreases with . From this parameterisation the cumulative signal coefficient follows immediately: (Alpha Sigmoid) where denotes the sigmoid function. Equivalently, . Because is a neural network trained jointly with the denoiser , the model can adapt its noise schedule to the data, yielding tighter variational bounds with no manual tuning.
The Continuous-Time Limit
A natural question is whether using more timesteps always helps. The answer is yes, and the argument is elegant. From (SNR TIME), the loss for evenly-spaced timesteps is with and . Introducing the midpoint and adding and subtracting , we can write (SNR LT) On the other hand, the loss for timesteps splits into two sums: (SNR L2T)
Subtracting (SNR LT) from (SNR L2T) immediately gives
Since and is monotonically decreasing, is positive. Moreover, because , the sample is a less noisy version of compared to . A reasonable denoiser should therefore predict more accurately from than from , implying . Multiplying a positive factor by a negative factor gives : doubling the number of timesteps always decreases the variational bound.
Historical Note.
Kingma et al. [4] formalised this argument and used it to advocate for the continuous-time variational diffusion model (VDM), corresponding to the limit . In the continuous-time limit the discrete sum becomes an integral over , and the loss takes the form (the minus sign is required because is decreasing, so ), which can be estimated with a single uniformly sampled per training step, exactly as in the discrete case, but without any discretisation error in the bound.
Three Parameterisations of the Diffusion Loss
The denoising objective derived in the preceding sections can be equivalently expressed in terms of predicting the original data , the noise , the score , or an energy function . All four viewpoints lead to the same optimum, but they emphasise different aspects of the problem and have motivated distinct lines of research.
Predicting the Original Image (-Prediction)
The most direct parameterisation, analysed in Theorem 7, trains a network to predict the clean data from its noisy observation . The per-timestep loss is This formulation is intuitive: the network literally learns to “see through” the noise and reconstruct the original image. However, the weighting factor in front of the squared error can vary over several orders of magnitude across timesteps, which may complicate optimisation.
Predicting the Noise (-Prediction)
Rather than predicting directly, we can reparameterise the network to predict the noise that was added to produce . Since , knowing is equivalent to knowing , but the loss landscape may differ. We first express the true posterior mean in terms of .
Theorem 9 (True Mean in Terms of Noise).
With , which implies , the true posterior mean satisfies
Proof.
In view of Theorem 9, we define the mean of the approximate reverse process by replacing the unknown true noise with a learned prediction : Substituting this into the KL divergence between the true and approximate posteriors yields the noise-prediction loss.
Theorem 10 (Noise Prediction Loss).
Proof.
The final line shows that, up to a timestep-dependent weight, the -prediction loss is simply the mean-squared error between the true noise and the network's estimate . This is the loss used in the original DDPM paper [2], where Ho et al. [2] further observed that dropping the weighting factor and training with the unweighted objective gives better sample quality in practice, albeit at the cost of no longer optimising a proper variational bound.
Predicting the Score (-Prediction)
A third viewpoint replaces the noise network with a score network that estimates the gradient of the log marginal density . The corresponding loss is We defer the full derivation and the connection to score matching to Score Functions and Diffusion, but note here that it is closely related to -prediction. For the conditional density the identity is exact, , while for the marginal it holds only in conditional expectation, , a consequence of Tweedie's formula (Theorem 11). Consequently, a score network and a noise network carry the same information.
Predicting the Energy
Finally, one may parameterise the model as an energy function whose negative gradient approximates the score. The loss becomes This viewpoint connects diffusion models to the broader family of energy-based models (EBMs). Because the score is , this is mathematically identical to score prediction, but it opens the door to architectures and training tricks developed in the EBM literature.
Summary of Parameterisations
Insight.
All four parameterisations (-prediction, -prediction, score prediction, and energy prediction) are mathematically equivalent: they share the same global optimum and differ only in how the network output is interpreted. The relationships are:
-prediction: the network directly estimates the clean data.
-prediction: the network estimates the noise that was added. Used by DDPM [2].
Score prediction: the network estimates the gradient . Central to score-based generative modelling [3].
Energy prediction: the network defines an energy whose negative gradient gives the score.
They are linked by the identities In practice the choice is largely one of convenience and training stability: -prediction tends to give uniform loss magnitude across timesteps, while -prediction can be more interpretable and is preferred in some recent architectures [4].
Score Functions and Diffusion
So far we have derived the diffusion loss from a purely variational perspective, treating the reverse process as a learned Gaussian and optimising the ELBO. A complementary viewpoint starts from unnormalised probability models and asks: can we train a model without ever computing the intractable normalisation constant? The answer is yes, and the key object is the score function.
Unnormalised Probability Models
Let be a real-valued function defined over the vector space , where denotes the dimensionality of the input space. This function is parameterised by , which represents a set of parameters that govern the behaviour of the function.
Definition 6 (Energy-Based Model).
Given , we can construct a probability distribution over using (Unnormalized) where is the partition function assumed to exist and be finite. Because evaluating is generally intractable, the distribution in (Unnormalized) is called an unnormalised probability model.
Despite the unknown normalisation constant, the unnormalised distribution still encodes the relative likelihood of different values of under the parameterisation . The crucial observation is that the gradient of does not depend on .
Definition 7 (Score Function).
Let be a parameterised density. The score is the gradient of the log-density with respect to the random variable: For the unnormalised model in (Unnormalized), the score reduces to since .
Note that the score does not depend on the intractable partition function ; however, maximum likelihood estimation would, because . This motivates score matching as an alternative training principle, which we develop in Score Matching Methods.
From Denoising to Scores: Tweedie's Formula
Understanding the score function in the context of diffusion models involves applying a classical statistical result known as Tweedie's formula. This formula provides a method for predicting the true posterior mean of a variable from its distribution and the gradient of its log probability.
Theorem 11 (Tweedie's Formula).
For a Gaussian variable , the conditional expectation of the mean given the observation is (Tweedie)
This expression tells us that the expected mean can be adjusted by a term that scales with the variance and the score of .
In diffusion models the forward noising process gives Applying Tweedie's formula with and , we obtain so that the clean data can be recovered in conditional expectation as (Tweedie X0) The conditional expectation matters: a single does not determine , and is precisely what a trained denoiser learns to output. This provides a method to reconstruct from , leveraging the score to adjust for the noise added during the forward process.
Theorem 12 (Score-Based Denoising Mean).
The posterior mean of the reverse transition can be expressed as
Proof.
We have
As expected, an approximation to the denoising transition mean is where is a neural network trained to approximate the score .
Theorem 13 (Score Prediction Loss).
The KL divergence between the forward posterior and the learned reverse transition reduces to a score-matching objective:
Proof.
The Score as Noise
There is a striking algebraic identity connecting the score function to the noise added during the forward process. Recall from (Tweedie X0) and the forward reparameterisation that Equating the numerators and solving gives This shows that the score is proportional to the negative of the noise added to the data, scaled by a factor that depends on . The identity is exact for the conditional score ; for the marginal score it holds with replaced by , consistently with (Tweedie X0).
Insight.
Score, Noise, and Denoising The three views of the learned signal are equivalent:
Score: points toward regions of higher probability density.
Noise: points away from the noise that was added.
Denoising: both representations enable recovery of from via Tweedie's formula.
Predicting the score, predicting the noise, and predicting the clean data are all reparameterisations of the same underlying objective.
Langevin Dynamics
Given access to the score function , we can draw approximate samples from without ever evaluating itself. The idea is to initialise a particle at an arbitrary location and iteratively nudge it in the direction of increasing log-probability, while adding noise to ensure exploration. This is the essence of Langevin dynamics.
Algorithm 3 (Langevin Dynamics Sampling).
Algorithm 3: Langevin Dynamics.
[H]
- Initialise arbitrarily
- for
- Sample
- return
The update rule balances a deterministic “drift” term that pushes toward higher density with a stochastic “diffusion” term that prevents the chain from collapsing to a mode. As the step size and the number of steps (with ), the distribution of converges to [3].
In practice, several challenges complicate Langevin sampling:
Manifold hypothesis. Real data often lives on a low-dimensional manifold embedded in . The score is undefined off the data manifold, so Langevin dynamics may behave poorly in the ambient space.
Low-density regions. Between modes of the density is very small, so the estimated score is unreliable. The chain may get “stuck” before finding the next mode.
Mixing between modes. Even with infinite time, mixing between well-separated modes can be exponentially slow.
Noise-conditional score models, which train a separate score for each noise level, address these issues by providing reliable score estimates at every scale [3].
Historical Note.
Langevin and Brownian Motion Paul Langevin introduced the Langevin equation in 1908 to describe Brownian motion of particles suspended in a fluid. His stochastic differential equation modelled the balance between a viscous drag force and random thermal kicks from surrounding molecules. Over a century later, the same equation drives modern generative modelling: the “drag” is the score function pulling samples toward data, and the “kicks” are injected Gaussian noise that ensures the chain explores the full distribution.
Score Matching Methods
The score function is attractive because it avoids the intractable partition function. But how do we train a model to output accurate scores when we cannot evaluate the true data score ? This section surveys four solutions: Fisher divergence minimisation, implicit (Hyvärinen) score matching, denoising score matching, and sliced score matching.
Fisher Divergence
Definition 8 (Fisher Divergence and Score Matching).
Score matching trains an unnormalised distribution by minimising the Fisher divergence rather than the negative log-likelihood:
The first term inside the norm involves , which is unknown. Apart from density estimation, scores can be used to generate samples via Langevin dynamics as we have seen. Hence, we need effective methods to estimate scores without access to the true data score [3].
Implicit Score Matching
A tractable score-matching objective would be one that depends only on . The following classical result achieves exactly this.
Theorem 14 (Hyvärinen's Theorem).
Under regularity conditions [5],
Proof.
(1D Case) We will prove for 1D case. We have
For the last term, using integration by parts, we have
Substituting the results of integration by parts above into the 1D Fisher divergence (LHS of theorem), we obtain
Proof.
(General case) Expanding the quadratic and dropping the constant term, we have So we just need to show that the inner product term is the negative of where Using integration by parts
Example 1 (Score Matching for a Gaussian).
The probability density function is given by where is a symmetric positive-definite matrix (the inverse of the covariance matrix). Here our parameter Here for Gaussian is well-known, but use this example as illustration. Here is a general -dimensional vector. We have and we obtain and Thus, we obtain the estimate (expectation over samples) in the RHS of Theorem 14 as follows To minimize this with respect to it is enough to compute the gradient (second order convexity) which is zero if and only if is the sample average This is a global minimum because the matrix MM that defines the quadratic form is positive-definite (second order critera for convexity). Similarly, we compute the gradient with respect to which gives which is zero if and only if is the inverse of the sample covariance matrix , which thus gives the score matching estimate.
Remark 8.
Quoting Hyvärinen (2005) [5]: “Interestingly, we see that score matching gives exactly the same estimator as maximum likelihood estimation. In fact, the estimators are identical for any sample (and not just asymptotically). The maximum likelihood estimator is known to be consistent, so the score matching estimator is consistent as well.”
Denoising Score Matching
A different route to tractable score matching starts from a practical observation: if we corrupt data with known noise, the score of the noisy distribution can be computed in closed form. Given a training dataset drawn from a clean distribution, the denoising score matching loss trains a score network by minimising The model learns to predict the negative gradient of the log conditional probability of the noisy data, which for Gaussian noise equals when .
A natural theoretical question is whether this denoising objective is consistent with the original (explicit) score matching loss. Vincent (2011) showed that the two are equivalent up to a constant.
Theorem 15 (Vincent's Theorem).
For up to a constant which is independent of , it holds that:
Proof.
We recall the explicit score matching loss function where the last term is a constant because it is independent of Looking at the second term, we have
(Vincent Expectation) Above, the first equality is by definition of expectation, the second equality is obtained by computing the gradient Substituting in , we have
Sliced Score Matching
Implicit score matching (Theorem 14) removes the dependence on the unknown data score, but it requires computing the trace of the Hessian , which costs backpropagation passes for data of dimension . This is prohibitively expensive for high-dimensional data such as images.
The idea behind sliced score matching [6] draws inspiration from sliced Wasserstein distances: instead of comparing full -dimensional scores, project them onto random directions and compare the resulting one-dimensional quantities.
Definition 9 (Sliced Wasserstein Distance).
The sliced Wasserstein distance is a cheaper approximation of the true Wasserstein distance, computed by averaging the 1D Wasserstein distance of projected point clouds: (Sliced Wasserstein) where is the unit sphere, and contains the indices of all point cloud data. Furthermore, can be re-written as a 1D assignment problem, seeking an optimal assignment of to : (Sliced Wasserstein2)
The 1D assignment problem in can be solved in closed form. Sliced score matching proposes to compute sliced scores analogous to sliced Wasserstein distances.
Definition 10 (Sliced Score Matching).
where is a random projection vector and is a sample from the data distribution.
To eliminate the need for , analogous to Theorem 14, the authors propose approximate sliced score matching [6].
Definition 11 (Approximate Sliced Score Matching).
(Approximate Unbiased Estimator) Analogous to Theorem 14, there is no dependence on the actual data distribution Moreover it leads to a matrix-vector computation rather than a full trace.
To prepare for the proof of equivalence, we list the assumptions from the original paper [6].
Assumption 1 (Regularity of score functions).
The model score function and data score function are both differentiable. They additionally satisfy and
Assumption 2 (Regularity of projection vectors).
The projection vectors satisfy
Assumption 3 (Boundary conditions).
We have the following boundary condition:
Assumption 4 (Identifiability).
The model family is well-specified, i.e., Furthermore, whenever
Assumption 5 (Positiveness).
We have the following positiveness condition:
We will also need the following lemma for integration by parts.
Lemma 1 (Multivariate Integration by Parts).
assuming that and are differentiable. The same applies for all indices of , but for notational simplicity we only write the case here.
Proof.
We can now consider this as a function of alone, all other variables being fixed. Then, integrating over , we have proven the lemma.
Theorem 16 (Sliced Score Matching Equivalence).
Assume and satisfy some regularity conditions (def:diff:sm-assumption1,def:diff:sm-assumption2). Under proper boundary conditions (Assumption 3), we have where is a constant w.r.t.
Proof.
The basic idea of this proof is similar to that of Theorem 14 [6]. First, note that can be expanded to Now what we need to prove is
This can be shown by first observing that
(Sliced LAST)
where we assume . Then, we plan to apply multivariate integration by parts as proved in Lemma 1. We first identify and and integration by parts for each as follows:
(Integration Parts I)
We now have using above, which is due to Lemma 1
Research 1.
Other Score Matching Methods We have seen explicit score matching, implicit score matching, denoising score matching, and finally sliced score matching. What are other ways you may think of for score matching? For example, when there is some structure expected in the distribution, can it be made more specific to such distributions?
Practical Implementation
In the following, let For practical implementation [6], consider a dataset and draw projection vectors independently for each point from We denote all such vectors by For defined in , an unbiased estimator is (Sliced Practical1)
If is known to be a multivariate standard normal or multivariate Rademacher distribution, we may use existing results to conclude
Hence, reduces to the following variance-reduced estimator (SSM-VR): where the last term can be integrated analytically. It was found empirically that this variance-reduced version had better performance [6].
Definition 12 (Hutchinson's Trace Estimator).
Given a matrix Hutchinson's trace estimator approximates the trace of as where are I.I.D. random vectors. Typically, are chosen to be I.I.D. Gaussians or Rademacher vectors with components randomly chosen as Notably, these random vectors have mean 0 and variance 1.
The sliced score matching technique is closely related to randomised trace estimation. In implicit score matching (Theorem 14), one must compute , which requires additional backpropagation passes after computing . Sliced score matching replaces this with a single matrix-vector product , which needs only one additional backpropagation pass regardless of dimension.
A vector-valued deep neural network can be trained as a score model. Substituting into in for , we get (SSM SUM) Minimising the above loss w.r.t. gives optimal , and can be treated as an approximation to the reference score function This is justified with the following identity, obtained by integration by parts as before: From the last term, we observe that if a good collection of random projection vectors are chosen, then
Historical Note.
From Optimal Transport to Score Matching The connection between sliced Wasserstein distances and sliced score matching reveals a deeper link between optimal transport and score-based generative modelling. Both frameworks deal with comparing and transporting distributions, but while optimal transport moves mass between distributions, score matching aligns the gradients of their log-densities. The “slicing” trick, projecting high-dimensional problems onto random one-dimensional subspaces, makes both computationally feasible and bridges these two foundational perspectives.
Exercises
Exercise 1 (Forward Marginal Distribution).
In a diffusion model, the forward process is defined as . Using the Markov property, derive the marginal distribution in closed form. Specifically, show that where . Hint: Use the reparameterisation trick iteratively and combine the noise terms.
Exercise 2 (Noise Schedule Design).
Explain why the noise schedule must be chosen so that . What happens to the distribution in this limit? Discuss the trade-off between using a small number of timesteps (faster sampling) and a large number of timesteps (better approximation of the reverse process). How do methods like DDIM address this trade-off?
Exercise 3 (ELBO Decomposition).
The ELBO for the variational diffusion model decomposes into three types of terms: a reconstruction term, a prior matching term, and denoising matching terms. Write down each term explicitly and explain its role. Why does the prior matching term have no trainable parameters? Under what conditions on and does it vanish?
Exercise 4 (Score of a Gaussian Mixture).
The score function is defined as . Consider a mixture of two Gaussians in one dimension:
Compute the score function explicitly.
Show that at the midpoint , the score is zero.
Describe the behaviour of the score function in the regions near each mode.
(Optional) Consider a two-component mixture in with means , , covariances , , and mixing weights , . Derive and plot the score (gradient field) in Python.
Exercise 5 (Langevin Dynamics Convergence).
Langevin dynamics generates samples from a distribution via the iteration Show that as and (with ), the distribution of converges to . Why is an accurate estimate of the score function crucial for the quality of the generated samples?
Exercise 6 (Denoising Score Matching).
In denoising score matching, instead of computing the intractable directly, we train a neural network by minimising For the Gaussian forward process , compute in closed form and show that it is proportional to the noise that was added during the forward process. Explain how this connects to the -prediction formulation used in DDPM.
Exercise 7 (Computational Cost of Score Matching).
Compare the computational costs of explicit score matching, implicit score matching, and sliced score matching. Explicit score matching requires knowledge of , implicit score matching requires computing (a Hessian trace), and sliced score matching approximates this trace using random projections. For a data dimension and random projection vectors, express the computational cost of each method in terms of the number of backpropagation passes required and explain when sliced score matching offers a significant advantage.
References
-
Deep Unsupervised Learning using Nonequilibrium Thermodynamics
BibTeX
@inproceedings{sohl2015deep, title={Deep Unsupervised Learning using Nonequilibrium Thermodynamics}, author={Sohl-Dickstein, Jascha and Weiss, Eric and Maheswaranathan, Niru and Ganguli, Surya}, booktitle={International Conference on Machine Learning}, pages={2256--2264}, year={2015}, organization={PMLR} }Conference paper
-
Denoising Diffusion Probabilistic Models
BibTeX
@inproceedings{ho2020denoising, title={Denoising Diffusion Probabilistic Models}, author={Ho, Jonathan and Jain, Ajay and Abbeel, Pieter}, booktitle={Advances in Neural Information Processing Systems}, volume={33}, pages={6840--6851}, year={2020} }Conference paper
-
Score-Based Generative Modeling through Stochastic Differential Equations
BibTeX
@inproceedings{song2020score, title={Score-Based Generative Modeling through Stochastic Differential Equations}, author={Song, Yang and Sohl-Dickstein, Jascha and Kingma, Diederik P. and Kumar, Abhishek and Ermon, Stefano and Poole, Ben}, booktitle={International Conference on Learning Representations}, year={2021} }Conference paper
-
Variational Diffusion Models
BibTeX
@inproceedings{kingma2021variational, title={Variational Diffusion Models}, author={Kingma, Diederik and Salimans, Tim and Poole, Ben and Ho, Jonathan}, booktitle={Advances in Neural Information Processing Systems}, volume={34}, pages={21696--21707}, year={2021} }Conference paper
-
Understanding Diffusion Models: A Unified Perspective
BibTeX
@misc{luo2022understanding, title={Understanding Diffusion Models: A Unified Perspective}, author={Calvin Luo}, year={2022}, eprint={2208.11970}, archivePrefix={arXiv}, primaryClass={cs.LG} }Reference
-
Sliced Score Matching: A Scalable Approach to Density and Score Estimation
BibTeX
@inproceedings{song2019sliced, title={Sliced Score Matching: A Scalable Approach to Density and Score Estimation}, author={Song, Yang and Garg, Sahaj and Shi, Jiaxin and Ermon, Stefano}, booktitle={Uncertainty in Artificial Intelligence}, pages={574--584}, year={2020}, organization={PMLR} }Conference paper