Chapter 2: Mathematical Foundations
Master the essential mathematical toolkit underpinning diffusion models: Gaussian distributions, Markov chains, KL divergence, variational inference, stochastic differential equations, and Langevin dynamics. These foundations are critical for understanding both the theory and implementation of modern diffusion-based generative models.
- Topics
- 3
- Videos
- 3
- Min read
- 19
Chapter Overview
Diffusion models rest on a surprisingly elegant mathematical framework. At their core, they define a forward process that gradually destroys data by adding Gaussian noise, and a learned reverse process that reconstructs data from pure noise. Understanding why this works---and how to train it efficiently---requires fluency in several branches of mathematics.
We begin with Gaussian distributions, the building block of the noise process. Every step of diffusion adds Gaussian noise, and the remarkable closure properties of Gaussians make the entire forward process analytically tractable. Next, Markov chains formalize the sequential structure: each noising step depends only on the previous state, enabling efficient factorization of joint distributions.
KL divergence measures how one probability distribution differs from another, and it is the natural loss function for training generative models. Variational inference provides the framework for optimizing intractable likelihoods by maximizing a tractable lower bound (the ELBO), which is exactly how diffusion models are trained.
Finally, the continuous-time perspective connects diffusion models to stochastic differential equations and Langevin dynamics. Score-based generative models use the score function (gradient of the log-density) to reverse the noising process, unifying denoising diffusion with classical MCMC sampling.
This chapter covers:
- Gaussian Distributions: Properties that make the forward process analytically tractable
- Markov Chains: The sequential structure underlying discrete diffusion steps
- KL Divergence: The divergence measure used to train the reverse process
- Variational Inference: Deriving the ELBO training objective
- Stochastic Differential Equations: Continuous-time formulation of diffusion
- Langevin Dynamics: Score-based sampling and its connection to diffusion models
Chapter Roadmap
Click any topic to jump in
Gaussian Distributions
Properties of Gaussians and reparameterization — the building block of diffusion.
Sequential structure and optimization target
Markov Chains
Transition kernels and stationary distributions — the sequential structure of diffusion.
KL Divergence
Measuring distribution distance — the objective connecting forward and reverse processes.
Topics
3 topics in this chapter
Before we can add noise to an image, we need to say precisely what noise means --- and in diffusion models the answer is always the same distribution: the Gaussian. This topic opens the mathematical-foundations chapter because everything downstream depends on it. Chapter 1 argued that diffusion models generate by reversing a gradual noising process; that process adds Gaussian noise at every step, and the reverse network predicts Gaussian parameters. Why does one distribution get to play both roles? Because Gaussians have algebraic properties no other distribution shares: they stay Gaussian under addition, under linear maps, under conditioning, and under marginalization. Those closure properties are what make the entire forward process solvable in closed form --- you can jump straight to any noise level without simulating the steps in between, a fact we will exploit constantly. This topic builds that toolkit: the univariate and multivariate density, closure under affine transformations, and the reparameterization trick that makes sampling differentiable. Master these and the DDPM equations in later chapters read as routine algebra rather than magic.
Definition
A Gaussian (normal) distribution is the distribution over specified entirely by a mean vector and covariance matrix . It is closed under affine transformation, marginalization, and conditioning --- properties that make the diffusion forward process analytically tractable at every timestep.
In this topic
- 1Univariate and Multivariate Gaussian
- 2Closure Under Linear Transformations
- 3The Reparameterization Trick
Univariate and Multivariate Gaussian
The univariate Gaussian is parameterized by a mean and variance ; the density peaks at and its width scales with . The multivariate generalization replaces the scalar mean with a vector and the variance with a covariance matrix , whose off-diagonal entries encode correlations between dimensions. In diffusion models the covariance is almost always isotropic, , so noise is added independently and equally to every dimension. This is deliberate: correlated noise would bias the forward process toward certain directions in data space, breaking the symmetry that later lets a single scalar schedule describe corruption.
The Gaussian is the maximum entropy distribution for a given mean and variance — it makes the fewest assumptions beyond those two moments. In diffusion, isotropic noise treats all dimensions equally, which is essential: the forward process should not favor any direction in data space. The normalization constant ensures the density integrates to 1 over .
Write the PDF of a 2D isotropic Gaussian with mean and variance .
Closure Under Linear Transformations
Any affine transformation of a Gaussian random variable is again Gaussian: if then has mean and covariance . This is the property that makes diffusion tractable. The forward step is an affine combination of a Gaussian input and independent Gaussian noise, so is Gaussian too. Applying closure repeatedly collapses the whole chain, letting us write in closed form for any --- no need to iterate through intermediate steps, which is what makes training on random timesteps possible.
Closure means the family of Gaussians is preserved under affine maps: if , then . In DDPM, is affine in both and . Since both are Gaussian, is Gaussian with analytically computable moments — no simulation needed to characterize the distribution at any timestep.
If and where is independent, what is the distribution of ?
The Reparameterization Trick
Sampling from is not differentiable with respect to and : the randomness sits between the parameters and the output, blocking gradient flow. The reparameterization trick rewrites the sample as with fixed noise , moving the stochasticity to an input that carries no parameters. Now the sample is a deterministic, differentiable function of and , so gradients pass straight through it. This is what makes end-to-end training of both VAEs and diffusion models possible; without it the sampling step would break backpropagation entirely.
Sampling is a stochastic operation with no gradient through or . The trick decomposes sampling into a deterministic differentiable path (multiply and add) plus fixed randomness (). The pathwise gradient and enable backpropagation through the sampling step — critical for training both VAEs and diffusion models.
Show how to compute gradients of with respect to using the reparameterization trick.
Theory Exercise
Problem:
In the DDPM forward process, where . Derive this closed-form expression starting from the single-step transition .
Hints:
- Write x_t in terms of x_{t-1} and noise using the reparameterization trick
- Recursively substitute x_{t-1} in terms of x_{t-2}, and so on down to x_0
- Use the fact that a sum of independent Gaussians is Gaussian, with variances adding
- Check that the coefficients squared sum to 1 at each step (variance preservation)
Related Problems on PixelBank
The previous topic gave us Gaussian noise; this one gives us the structure that strings the noise together. The diffusion forward process is a Markov chain: each noisy state depends only on the state one step before it, never on the full history. That single restriction is what makes the process analyzable, because it lets the joint distribution over all timesteps factor into a product of simple transition kernels rather than one intractable -dimensional object. This topic builds the vocabulary of Markov chains you need to read every later derivation: transition probabilities and the Markov property that defines them, the stationary distribution that a chain converges to, and the ergodicity and mixing-time results that say how fast it gets there. Those last two matter concretely --- they justify why running the forward process for steps leaves you with essentially pure noise, the fixed starting point the reverse process samples from. Without the Markov property, none of the closed-form posteriors in the coming chapters would exist.
Definition
A Markov chain is a sequence of random variables in which each state depends only on its immediate predecessor: . This property factors the joint distribution into a product of transition kernels, and under mild conditions the chain converges to a unique stationary distribution.
In this topic
- 1Transition Probabilities
- 2Stationary Distribution
- 3Ergodicity and Mixing Time
Transition Probabilities
A Markov chain is fully described by its transition kernel , the probability of moving to state from the current state. The Markov property asserts : the future is conditionally independent of the past given the present. Multiplying the kernels along the chain gives the factorized joint . In DDPM each transition is a small Gaussian perturbation, so the entire forward trajectory is a product of Gaussian conditionals --- the representation that made closure so powerful in the previous topic.
The Markov property means the future is conditionally independent of the past given the present. For the joint distribution, this yields , factoring an exponentially complex joint into simple transitions. In DDPM, each transition is a known Gaussian, making the entire forward process analytically tractable.
Write the joint distribution for a 2-step Markov chain and explain how the Markov property simplifies it.
Stationary Distribution
A stationary (or invariant) distribution is one that a single step of the chain leaves unchanged: , so is a left eigenvector of the transition matrix with eigenvalue 1. For the DDPM forward process the stationary distribution is the standard normal : after enough variance-preserving noising steps, any starting data converges to it regardless of where it began. This is exactly why the reverse process can begin from --- the forward chain has forgotten the input entirely, so pure noise is a faithful sample of the chain's endpoint.
A distribution is stationary if — it is a left eigenvector of the transition matrix with eigenvalue 1. For the DDPM forward process, the stationary distribution is : applying the noising step to standard normal noise returns standard normal noise. The spectral gap of the transition operator controls how fast convergence occurs.
Consider a 2-state Markov chain with transition matrix . Find the stationary distribution.
Ergodicity and Mixing Time
An ergodic Markov chain converges to its stationary distribution from any starting state. The mixing time is the number of steps needed for the chain to be within a small total variation distance of stationary. In diffusion models, the number of forward steps must exceed the mixing time to ensure . Typical DDPM uses , which is far beyond the mixing time of the Gaussian noising chain.
The total variation distance decays exponentially with rate determined by the spectral gap. Mixing time tells us how many steps are needed for the chain to forget its initial state. DDPM uses steps with , ensuring with negligible total variation error.
If a noise schedule has , how close is to pure noise?
Theory Exercise
Problem:
Show that the reverse of a Markov chain is also a Markov chain. Specifically, given the forward chain , derive the form of the reverse transition using Bayes' theorem.
Hints:
- Apply Bayes' theorem: q(x_{t-1} | x_t, x_0) = q(x_t | x_{t-1}, x_0) * q(x_{t-1} | x_0) / q(x_t | x_0)
- By the Markov property, q(x_t | x_{t-1}, x_0) = q(x_t | x_{t-1})
- All three distributions in Bayes' theorem are Gaussian---use the Gaussian product formula
- The result is a Gaussian whose mean is a linear combination of x_t and x_0
Related Problems on PixelBank
Gaussians gave us the noise and Markov chains gave us the structure; now we need the ruler that measures whether the reverse process is doing its job. That ruler is the Kullback-Leibler divergence. It answers a question that runs through all of generative modeling: given two probability distributions, how far apart are they? In diffusion models the answer appears everywhere. The training objective (the ELBO of the next chapter) is a sum of KL terms; the claim that the forward endpoint is pure noise is a statement that a KL is small; and each denoising step is trained so the model's Gaussian matches the true reverse posterior in KL. This topic develops the tool in three parts: the definition and the crucial fact that KL is asymmetric, the practical split between forward and reverse KL and the mode-covering versus mode-seeking behavior each induces, and the closed form for KL between two Gaussians --- the exact expression that, in the next chapter, collapses the diffusion loss into a simple noise-prediction objective.
Definition
The Kullback-Leibler divergence measures the expected extra information needed to encode samples from using a code built for . It is non-negative, zero only when , and asymmetric --- in general. It is the objective used to train the diffusion reverse process.
In this topic
- 1Definition and Asymmetry
- 2Forward vs Reverse KL
- 3KL Between Gaussians
Definition and Asymmetry
KL divergence measures the expected extra information needed to encode samples drawn from using a code optimized for . Here is the reference distribution the expectation is taken under, and the integrand is the pointwise log-likelihood ratio. It is non-negative by Gibbs' inequality and zero only when almost everywhere. Crucially it is asymmetric: in general, because the expectation weights the ratio by , not . It also blows up to infinity wherever but --- the code cannot describe an event the model thinks impossible --- which drives the mode behavior explored next.
KL divergence measures the expected log-likelihood ratio under . It equals the extra bits needed to code -samples using a code optimized for . The asymmetry arises from the weighting: is infinite if where (missing support), but finite if where (wasted support). This asymmetry determines whether training produces mode-covering or mode-seeking behavior.
Compute and where and .
Forward vs Reverse KL
The two orderings of KL induce opposite behaviors when a model cannot perfectly fit the data. Forward KL, , takes the expectation under the data, so it penalizes the model for putting low probability anywhere the data has mass --- it forces mode-covering, spreading density to include every mode even if that covers empty regions between them. Reverse KL, , weights by the model, so it punishes mass where data is sparse --- encouraging mode-seeking collapse onto one mode. Diffusion models effectively minimize a forward-KL objective through the ELBO, a central reason they cover modes and generate diverse samples rather than collapsing like some GANs.
Forward KL penalizes the model for having zero density where data exists, enforcing mode coverage at the cost of spreading mass into empty regions. Reverse KL penalizes the model for placing mass where no data exists, producing sharp but mode-collapsed fits. The ELBO in diffusion models optimizes a sum of forward KL terms at each timestep, which is why they achieve excellent mode coverage.
A bimodal target distribution has two peaks at and . A unimodal Gaussian model must choose its mean. What happens under forward vs reverse KL?
KL Between Gaussians
When both distributions are Gaussian, KL divergence has a closed form, which is why it is so useful in diffusion training. For isotropic Gaussians and in dimensions the general matrix expression collapses to . The first bracket measures variance mismatch and the second measures mean mismatch. In DDPM the variances are fixed by the noise schedule, so only the mean term survives --- and that term is a scaled squared error, which is exactly how the KL objective reduces to predicting the noise .
For vs in dimensions: . The first term measures variance mismatch; the second measures mean mismatch. In DDPM training, the variance is fixed by the schedule, so the KL reduces to a weighted MSE on means — which further reduces to predicting the noise .
Compute in 1D.
Theory Exercise
Problem:
Derive the relationship where is the cross-entropy and is the entropy. Then explain why minimizing cross-entropy is equivalent to minimizing KL divergence when is fixed.
Hints:
- Write out the definition of cross-entropy: H(p, q) = -E_p[log q(x)]
- Write out the definition of entropy: H(p) = -E_p[log p(x)]
- Subtract and compare with the KL definition
- When p is fixed (the data distribution), H(p) is a constant