Mathematics behind Diffusion Models
It was personally quite a struggle to understand how diffusion works. Fortunately, several resources---especially Luo (2022) and Weng (2021)---made the learning process a lot easier. In this blog post, I’ve distilled my personal notes from these resources on understanding diffusion models, and I hope this can help others going through the same struggle I did!
What are Diffusion Models?
The concept of diffusion-based generative modelling was actually proposed early in 2015 by Sohl-Dickstein et al. who were inspired by non-equilibrium thermodynamics. The idea behind it as described by Sohl-Dickstein et al. (2015) is this:
The essential idea, inspired by non-equilibrium statistical physics, is to systematically and slowly destroy structure in a data distribution through an iterative forward diffusion process. We then learn a reverse diffusion process that restores structure in data, yielding a highly flexible and tractable generative model of the data.
Half a decade later, Ho et al. (2020) proposed Denoising Diffusion Probabilistic Models (DDPMs), which improved upon the previous method by introducing significant simplifications to the training process. Soon after, a 2021 paper by OpenAI demonstrated DDPMs’ superior performance in image synthesis tasks compared to Generative Adversarial Networks (GANs). Since then, notable diffusion-based generative models have been released such as DALL-E, Stable Diffusion and Imagen. I’ll be covering the concept underlying diffusion models, mainly focusing on DDPMs.
To better understand this, let’s focus on the forward diffusion process and reverse diffusion process separately.
Forward Diffusion Process

In the forward trajectory, we want to gradually “corrupt” the training images. As such, we iteratively apply Gaussian noise to images sampled from the true data distribution, i.e. , in over steps to produce a sequence of noisy samples .
The diffusion process is fixed to a Markov chain which simply means that each step is only dependent on the previous one (memoryless). Specifically, at each step, we apply Gaussian noise with variance to to produce a latent variable of the same dimension. As such, each transition is parameterized as a diagonal Gaussian distribution that uses the output of the previous state as its mean:
Note:
- is known as the “diffusion rate” and it can be sampled according to a variance schedule , which means the amount of noise applied at each time step is not necessarily constant
- is the identity matrix. We use the identity matrix because our images are multi-dimensional and we want each dimension to be independent of each other
The posterior after steps, conditioned on the original data distribution, can be represented as a product of single step conditionals as such:
As , is equivalent to an isotropic Gaussian distribution, losing all information about the original sample distribution.
Reverse Diffusion Process

In the reverse process, we aim to learn a model that can denoise the pure Gaussian noise, i.e. , to recover the original sample image. As mentioned by Sohl-Dickstein et al. (2015),
Estimating small perturbations is more tractable than explicitly describing the full distribution with a single, non-analytically-normalizable, potential function.
Directly describing the original distribution from the pure Gaussian noise can be intractable. Rather, what we can do is train a model (e.g. using a neural network) to approximate such that we can iteratively recover the original data distribution in small time steps. Therefore, the reverse trajectory can also be formulated as a Markov chain and can be represented as such:
where .
Moreover, since follows a Gaussian distribution, if is small, then the reversal of the diffusion process has the identical functional form as the forward process (Feller, 1949), which means that will also be Gaussian. Therefore, to approximate , our model only needs to estimate the Gaussian parameters and for timestep .
Note:
- not only takes in , but also , as inputs because each time step is associated with different noise levels.
Parameterisation of Diffusion Model
In summary, we have defined the forward trajectory as a steady noisification of the sample distribution over time and the reverse trajectory as “tracing back” these steps to recover the original distribution.
But how exactly do we teach a neural network (or other function approximation methods) to approximate the conditional probabilities for each time step in the reverse trajectory? To do so, we need to define a loss function.
Naively, we can use a maximum likelihood objective where we maximize the likelihood assigned to by the model, i.e.
This objective is unfortunately intractable as it requires us to marginalize over all possible trajectories we could have taken from . Rather, we can take inspiration from Variational Autoencoders (VAE) and reformulate the training objective using a variational lower bound (VLB), also known as “evidence lower bound” (ELBO).
Therefore, the last term becomes the VLB of the likelihood assigned to , a proxy objective to maximize. However, this VLB term is still not tractable so further reformulations is needed. Before we proceed, it is important to note that we can rewrite each transition as , where the extra conditioning term is superfluous due to the Markov property. Using Bayes’ rule, we can rewrite each transition as:
This trick will be useful for reducing the variance and derive a more elegant variational lower bound expression. Continuing from where we left off earlier, we have:
- is a constant because has no trainable parameters and is a standard Gaussian. Therefore, we can ignore it.
- is the reconstruction term which predicts the log likelihood of the original data sample given the first-step latent. Since the original data distribution may not be Gaussian, we cannot compute this in closed form. We can approximate and optimise this term using a Monte Carlo estimate.
- measures the KL divergence between the learnt transition step and the ground-truth denoising transition step . can act as a ground-truth signal because it defines how to denoise a noisy image with access to what the final, completely denoised image should be.
Given that the denoising matching term is the only term we are interested in, to maximise the likelihood objective, we will need to minimise the KL divergence between the learnt denoising step and ground-truth denoising step. By Bayes’ Rule, we can reformulate the ground-truth denoising transition step as such:
Using our definition of the forward transition step and the Markov property, we already know that . Let , under the reparameterisation trick used in VAEs, samples can be rewritten as:
where . To express in closed form, we recursively apply the reparameterisation trick. That is, for any ,
where . We can merge two Gaussians in (1) since the sum of two independent Gaussian random variables is a Gaussian with mean being the sum of the two means and variance being the sum of the two variances. We have therefore derived and we can reuse the parameterization trick to yield . Substituting both expressions into the Bayes rule expansion of the ground truth denoising step (intermediate steps have been omitted for brevity):
We have therefore shown that at each step, follows a normal distribution with mean , a function of and , and variance , a function of coefficients. We can further leverage the reparameterization trick to express as :
Following Ho et al. (2020), we can set as a constant at each timestep by modelling the coefficients as fixed hyperparameters. With that, we can rewrite the variance equation as , where:
As we have kept the variance constant, minimizing the KL divergence is simply minimizing the difference between and . Note that we have no choice but to only parameterize the mean of the learnt model as a function of since does not depend on (due to Markov property).
The true denoising transition mean is expressed as:
To optimize the model’s mean , we set it to have the following form:
where is parameterized by a neural network that seeks to predict the source noise that lead to from . As such, the optimization problem simplifies to:
We can formulate our variational lower bound loss function as
Simplification of Loss Term
Empirically, Ho et al. (2020) found that a simplified loss function without the weighting term performs better:
which is basically just the mean squared error between the noise added in the forward process and the noise predicted by the model!

Relation to Score Matching
So far, I have been covering generative models via the “likelihood-based” objective, which seeks to learn a model that assigns a high likelihood to the observed data samples. However, there is another “score-based” interpretation which seeks to model the gradient of the log probability density function, a quantity known as the (Stein) score function. Score-based generative modelling is another rabbit hole on its own, but my goal here today is just to highlight the parallels between denoising diffusion generative modelling and denoising score matching in score-based generative modelling. It would be helpful to understand this before getting into conditional diffusion models in the later section.
Motivation behind Score Matching
In order to build a likelihood-based generative model, given a dataset , one learns a function parameterized by a learnable parameter that best explains the observed data. More specifically, our goal would be to find the that maximises the log probability density function (or probability mass function in the discrete case) of the data:
As you know from Probability Theory 101, for to be a valid p.d.f., we need to make sure it is normalized such that . We can define a valid p.d.f. via
where is the normalizing constant and in this case is often called the energy function.
The fundamental limitation behind likelihood-based models is that can be intractable to compute the normalizing constant , especially if is usually high-dimensional and is highly complex and nonlinear. One way to avoid computing is via approximation methods. For example, in DDPMs, we relied on variational inference and used the ELBO as a surrogate objective to maximise the log likelihood of the data.
Score-based models are motivated by this fundamental limitation and offers an alternative that avoids calculating or approximating the normalization constant by learning the score function of the distribution instead. By taking the derivative of the log of the unnormalized density in Equation 3, we can see that:
where is our score-based model that learns that best approximates .
It is intuitive to see that is independent of the normalization constant . And to train score-based models, we can simply minimize the expected Fisher Divergence between the and the score function:
Intuitively, the Fisher Divergence measures the squared distance between the ground truth score function and the score-based model. This is what is known as score matching. Instead of directly maximizing the likelihood function, score matching instead tries to find a such that the gradient of the model’s log likelihood is approximately the same as the gradient of the data distribution’s log likelihood, circumventing the need to work with the normalization constant.
However, a problem here is that it requires access to dependent on an unknown , which is the same limitation faced by likelihood-based methods. Fortunately, Hyvärinen (2005) showed that by applying multivariate integration by parts, the objective in Equation 4 can be rewritten to not rely on as such:
where denotes the Jacobian of , which is also the Hessian of the log-density function, and denotes the trace of the Jacobian matrix, i.e. the sum of the elements on the main diagonal of the matrix.
Intuitive Interpretation of Score Matching
We can expect the second term, , to be small when the gradients of the score function are close to zero, indicating a local extremum of the log-likelihood. This term is closely related to the maximization of the non-normalized log-likelihood. However, optimizing solely the non-normalized log-likelihood could lead to a trivial solution where the score function is flat, i.e., it has infinite variance and assigns equal probability to all . Such a solution is undesirable because it fails to uniquely describe the observed data distribution.
The first term, , provides information about the overall curvature or sharpness of the extremum. To minimize the Fisher Divergence, we need this term to be negative, indicating that the extremum is a maximum. A more negative trace of the Hessian suggests a sharper maximum of the log-likelihood for the observed data points, , as opposed to a flat maximum. Therefore, the trace term favors steeper maxima that more uniquely reflects the data distribution, compared to a flat maxima where similar probabilities are assigned to all data points. In some sense, this term acts as a proxy for the normalization constant in traditional density estimation. It encourages the learned score function to behave like the gradient of a properly normalized log-density function by penalizing score functions that would correspond to optimizing only the non-normalized density function.
Langevin Dynamics
Okay, now that we have trained a score-based model , how do we even generate samples using it?

Intuitively, what the model has learnt is a gradient vector field over the density function of and each point in the field indicates the direction and rate of fastest increase (represented by the arrows in the image above). Langevin dynamics provide a Markov Chain Monte Carlo procedure to sample from with access to only . Starting from any arbitrary point (represented by blue dots in image above) sampled from some assumed prior distribution (e.g. Gaussian), we can iteratively perform the following updates to climb towards the modes of the distribution (represented by red lines in image above):
where . The addition of the Gaussian noise helps to introduce stochasticity to the generative process, allowing the samples to converge towards different modes other than the nearest. When is sufficiently small and is sufficiently large, we would produce a sample from under some regularity conditions!
Pitfalls of Naive Score-based Generative Modelling
There are pitfalls involved with this naive approach of sampling via Langevin dynamics. Firstly, in regions where few data points are available for training the model, the estimated score functions can be inaccurate. This is because the model is trained on the Fisher divergence which is an expectation over , i.e.
Because the squared difference is weighted by , the errors are largely ignored in low density regions where is small and results in an inaccurate learned model. Since sampling via Langevin dynamics involves starting from a random location in the high-dimensional space which is likely to be in low density regions (it is unlikely to choose a point that corresponds to an actual sample), an inaccurate score-based model derails the sampling trajectory right from the beginning.
Secondly, the manifold hypothesis poses a problem. The manifold hypothesis postulates that real-world data often lies in a low-dimensional manifold embedded in a high-dimensional space and it has been empirically observed in many datasets. As such, points in the high-dimensional space outside of the low-dimensional manifold would have probability zero and an undefined . This causes the score function to be ill-defined. Moreover, in order to represent the objective using Equation 5, it would require that the support of is over the whole space.
Score-based Generative Modeling with Multiple Noise Perturbations
As it turns out, the above-mentioned pitfalls can be bypassed simply by perturbing data points with Gaussian noise. By injecting small amounts of Gaussian noise into the data, the noised data distribution would have full support and is no longer confined to a low-dimensional manifold. When the noise magnitude is sufficiently large, it would also populate low data density regions and thereby improve the accuracy of the score function.
Song & Ermon (2019) proposed to perturb the data with a increasing sequence of isotropic Gaussian noise to obtain a noise-perturbed distribution
Then, they estimate the score function of the noise-perturbed distribution by training a Noise-Conditioned Score Network (NCSN) to jointly estimate the scores of all perturbed data at different noise levels. The objective then becomes
where is a positive weighing function. After training , we can then produce samples by running Langevin dynamics for each and this method is called annealed Langevin dynamics since the noise scale decreases (anneals) with each time step.
Notice how this procedure is very similar to the one in DDPMs. In fact, their objectives can be reconciled with the same formulation and that is what we’re going to show. For a Gaussian data distribution , the derivative of the log density function is
where . Recall from Equation 1 in DDPM, the posterior of a noised given initial is . As such, we can rewrite the gradient of the log density of each noised sample as:
where refers to the source noise that produces from the original image .
As it turns out, the gradient of the log density function in NCSN and the source noise in DDPM are off by only a constant factor that scales with time (i.e. )! Intuitively, the reason the score function in NCSN points in the opposite (negative) direction of the source noise in DDPM is that the score function indicates the direction in which the log density is maximized, whereas the source noise in DDPM corrupts the image away from its original state. Therefore, moving in the opposite direction of the source noise effectively "denoises" the image and increases the log density of the resulting sample.
With that, we have shown that the -prediction parameterization in DDPM simplifies the diffusion model’s variational bound to an objective that closely resembles denoising score matching in NCSN!
Conditional Generation
As of now, we have only focused on modelling the sample distribution . However, it would be more practical if we could learn a conditional distribution that allows us to generate images conditioned on conditional information which can be a class label, a text encoding in image-text generation, or even a low-resolution image to perform super-resolution on. Conditional generation forms the backbone of state-of-the-art image-to-text models such as DALL-E 2 and Imagen.
An intuitive way to incorporate conditioning information into the generative process would be to condition each transition step on it as such:
This would allow us to learn the model as before, by predicting the source noise . However, this formulation may cause the model to ignore the conditioning information. As such, classifier guidance was introduced to control the amount of weight given to the conditioning information, at the cost of sample diversity. Classifier guidance provides a way to steer the sampling process in the direction of the image space that maximizes the probability of the denoised image belonging to the desired class.
Classifier Guided Diffusion
The first way is to introduce guidance is by training a separate classifier model on noisy samples . At every step of the denoising process, we can then use the gradients of the classifier, i.e. , to guide the denoising process towards an arbitrary input feature, which could be a class label, .
To understand why this works, we can make use of the Bayes rule:
In order to have control over the degree to which the conditional model adheres to the conditioning information, Dhariwal and Nichol (2021) scales the conditioning term by a hyperparameter:
where is called the guidance scale. essentially controls how much our learned conditional model cares about the conditioning information. The greater is, the more likely the generated samples reflect the conditioned information, albeit at the cost of sample diversity. Intuitively, the score function points in the direction of the image space that maximises the likelihood of the resulting image and the classifier gradients points in the direction of the image space that maximises the likelihood of the conditioning information. Combining these gradients together results in a step that balances between both objectives depending on .

Equation 8 requires that we combine the output of a denoising score-based generative model and the gradients of the classifier. However, recall that denoising score matching has a similar interpretation as -prediction parameterization in DDPM, i.e. . Plugging this into Equation 8 we get:
As such, our new classifier-guided DDPM would take the form:
There are a few things to clarify here:
- Both the classifier and diffusion models are trained on noisy images independently.
- The reason behind training the classifier on the noisy image samples instead of the original images is to allow it to be robust against the distortion introduced by the forward trajectory of the diffusion models. This is also what allows us to apply the gradients of the classifier for guidance on every step of the denoising process.
- In the neural network paradigm, the gradient of the classifier is calculated by backpropagating through the layers of trained classifier from the output logits back to the input image
Classifier-free Guidance
The drawback of the classifier guidance is that it requires the training of two separate models, the diffusion model and the classifier. Moreover, this classifier must be trained on noisy data so it is generally not possible to plug in a pre-trained classifier. As such, Ho & Salimans (2021) introduced classifier-free diffusion guidance, which allows us to jointly train a conditional and unconditional diffusion model using a singular neural network, without learning a separate classifier. This model, denoted , is trained on the labelled data but the conditioning information is discarded periodically to allow the model to generate images unconditionally, i.e. .
To train without a classifier, we have to replace Equation 9 to not rely on its gradient. First, by switching the terms around in Equation 7 we get
Plugging this into Equation 9 we get:
This new equation has no classifier gradient present.
To implement this in a neural network, you can simply concatenate the conditioning information to the end of the flattened image vector and replace the conditioning information with fixed constant values (e.g. zeros) periodically. The neural network would then learn to treat those fixed constant values as the conditioning and perform unconditional generation when inputted with them.
Summary
To wrap up, diffusion models represent a fascinating approach to data generation and denoising tasks in the realm of deep learning. At their core, these models leverage a process called diffusion, which involves progressively applying Gaussian noise to an original sample distribution. The diffusion model then aims to learn the parameters that maximize the Variational Lower Bound (VLB) during the denoising step.
Notably, diffusion models often excel in terms of generalizability and training stability, steering clear of pitfalls like mode collapse commonly encountered by GANs. However, GANs are still considerably more computationally efficient compared to diffusion models. This is due to the fact that GANs can generate an image in a single forward pass but diffusion models rely on a long Markov chain of denoising steps.
Still, diffusion models have proved their incredible capabilities in generating realistic samples. It's highly likely that we'll witness the emergence of even more powerful diffusion-based generative models, pushing the boundaries of generative modeling to new heights in the years ahead!
References
[1] Goodfellow, Ian & Pouget-Abadie, Jean & Mirza, Mehdi & Xu, Bing & Warde-Farley, David & Ozair, Sherjil & Courville, Aaron & Bengio, Y.. (2014). Generative Adversarial Networks. Advances in Neural Information Processing Systems. 3. 10.1145/3422622.
[2] Dhariwal, Prafulla & Nichol, Alex. (2021). Diffusion Models Beat GANs on Image Synthesis.
[3] Zhang, H., Xu, T., Li, H., Zhang, S., Wang, X., Huang, X., & Metaxas, D.N. (2016). StackGAN: Text to Photo-Realistic Image Synthesis with Stacked Generative Adversarial Networks. 2017 IEEE International Conference on Computer Vision (ICCV), 5908-5916.
[4] Xu, T., Zhang, P., Huang, Q., Zhang, H., Gan, Z., Huang, X., & He, X. (2017). AttnGAN: Fine-Grained Text to Image Generation with Attentional Generative Adversarial Networks. 2018 IEEE/CVF Conference on Computer Vision and Pattern Recognition, 1316-1324.
[5] Shoshan, A., Bhonker, N., Kviatkovsky, I., & Medioni, G.G. (2021). GAN-Control: Explicitly Controllable GANs. 2021 IEEE/CVF International Conference on Computer Vision (ICCV), 14063-14073.
[6] Sohl-Dickstein, J., Weiss, E., Maheswaranathan, N. & Ganguli, S.. (2015). Deep Unsupervised Learning using Nonequilibrium Thermodynamics. Proceedings of the 32nd International Conference on Machine Learning, in Proceedings of Machine Learning Research 37:2256-2265
[7] Ho, J., Jain, A., & Abbeel, P. (2020). Denoising Diffusion Probabilistic Models. ArXiv, abs/2006.11239.
[8] Feller, W. (1949). On the Theory of Stochastic Processes, with Particular Reference to Applications.
[9] Weng, Lilian. (2021). What are diffusion models? Lil’Log. https://lilianweng.github.io/posts/2021-07-11-diffusion-models/
[10] Luo, C. (2022). Understanding Diffusion Models: A Unified Perspective. ArXiv, abs/2208.11970.
[11] Karagiannakos, S., Adaloglou, N. (2022). Diffusion models: toward state-of-the-art image generation. https://theaisummer.com/diffusion-models/
[12] Song, Y., & Stefano Ermon. (2019). Generative Modeling by Estimating Gradients of the Data Distribution. ArXiv (Cornell University). https://doi.org/10.48550/arxiv.1907.05600
[13] Dhariwal, P., & Nichol, A. Q. (2021). Diffusion Models Beat GANs on Image Synthesis. Neural Information Processing Systems, 34.
[14] Zeng, F. P., & Wang, O. (2023). Score-Based Diffusion Models. fanpu.io. https://fanpu.io/blog/2023/score-based-diffusion-models/
[15] Hyvärinen, A. (2005). Estimation of Non-Normalized Statistical Models by Score Matching. Journal of Machine Learning Research, 6(24), 695–709. http://jmlr.org/papers/volume6/hyvarinen05a/old.pdf