28 / 33 · Diffusion Models
Score matching and Langevin dynamics
Learn the gradient of the log-density instead of the density: the score, Hyvärinen's score matching, its sliced and denoising versions, sampling with Langevin dynamics, why one noise level is not enough, and how noise-conditional scores and annealing lead to the same model as DDPM.
On this page 13
The DDPM note arrived at a model by bounding the likelihood of a noising chain and simplifying the bound until it became a regression on noise. This note arrives at the same model from the other side. Instead of a density, learn its gradient, the score; instead of a decoder, sample by following the score with a little noise added, Langevin dynamics. The two routes meet: the network that predicts the noise in DDPM is, up to a known scale, the score of the noised data.
Notation. is the data density on and its score; is the model. is the data after adding Gaussian noise of scale . is the trace of the Jacobian of .
Why the score#
Many models define a density only up to a constant, like the energy-based models of an earlier note: with an energy and a normalizer that cannot be computed in high dimension. Maximum likelihood needs and its gradient. The score does not:
depends on but not on , so it disappears. The score of a Gaussian is : a vector pointing back to the mean, longer the farther away. In general the score points toward higher density, and it carries all the information about where is positive and smooth on a connected region, such as all of : two such densities with the same score everywhere differ by a constant factor, which normalization fixes. On two separated components the score fixes each piece only up to its own constant, and says nothing about how the mass splits between them; Gaussian smoothing removes the problem, because a noised density is positive on all of . When the score is parameterized through an energy, , fitting it therefore trains an energy-based model without its normalizer and without samples from the model (energy-based models). An unrestricted network is a different object: a vector field whose Jacobian need not be symmetric, so it need not be the gradient of any scalar function. It is an approximate score with no energy behind it, which is how diffusion models use it.
Fitting a score: Hyvärinen’s trick#
The natural loss is the Fisher divergence, the mean squared distance between the two scores under the data:
It needs the true score, which is unknown. Hyvärinen (2005) removes it by integration by parts. In one dimension, expand the square; the cross term is
using and assuming at infinity. The square of the true score does not depend on . In dimensions the same step per coordinate gives
an expectation over data that involves only the model.
Worked example. Fit a Gaussian score with to the data . Then and the objective is . Setting the derivative in to zero gives ; the derivative in gives , so . Score matching recovers the sample mean and variance, the maximum likelihood estimates for a Gaussian, without ever touching the normalizing constant.
The cost is the trace term. For a network , needs backward passes, one per diagonal entry of the Jacobian: fine for , impossible for an image with .
Two cheaper objectives#
Sliced score matching (Song et al., 2019) projects onto random directions with :
In expectation over this is the objective above, because and . One Jacobian–vector product replaces backward passes.
Denoising score matching (Vincent, 2011) avoids input derivatives of the model in the loss, with no Jacobian and no trace, by fitting the score of noised data; training still needs the parameter gradient , as any loss does. Draw and perturb it with any kernel whose score is known; the noised data have the density . The objective
differs from the Fisher divergence to only by a constant (Song and Ermon, 2019, Eq. 2). Expand both squares. The terms have the same expectation, the terms without are constants, and the cross terms agree because , so
The usual kernel is Gaussian, with , which gives the density of the notation. Its score is , and the objective becomes
Another way to see why it works: a squared-error regression learns a conditional mean: the minimizer is , and this conditional mean is exactly , a fact known as Tweedie’s formula.
Worked example. Data and . Then , whose score is . Directly: and are jointly Gaussian with , so and : the regression target, averaged, is the score of the noised data.
The price of denoising score matching is that it estimates the score of , not of . Small keeps them close but makes the targets large and noisy; large blurs the data. The way out, below, is to use many values of at once.
Sampling with Langevin dynamics#
Given a score, Langevin dynamics produces samples:
The drift climbs the density, the noise keeps the chain from collapsing onto the modes. For small step sizes and many steps the distribution of approaches ; under regularity conditions it becomes exactly as and the number of steps grows without bound (Song and Ermon, 2019, §2.2, citing Welling and Teh, 2011). Without the noise term the update is gradient ascent on and ends at a mode, not at a sample.
Worked example. For , and the update is . Its stationary variance solves , so
With the chain settles at variance 1.026 instead of 1; with at 1.143. The discretization bias is of order , and smaller steps buy accuracy with more steps; a Metropolis–Hastings correction would remove the bias, at the cost of evaluating the density, which is what the score was meant to avoid.
Shrinking the step during the run. The bias also vanishes if the step size decreases along the chain, but only if it decreases slowly. Welling and Teh (2011), Eq. 2, require
for example with . The first condition lets the chain travel any distance from its start; the second makes the steps, and with them the discretization error, go to zero. A geometric decay breaks the first condition: the steps add up to , and the chain freezes before it has mixed. In the Gaussian example the starting point survives in with the factor . With and the steps add up to at most , and after ten steps the factor is still : the chain has barely left its start.
Temperature. Some samplers scale the noise by a temperature , . Since , this is the plain sampler for the density proportional to with step . A temperature below therefore concentrates the samples near the modes. In the Gaussian example the stationary variance becomes : with and it is , close to the variance of .
Why one noise level fails#
Two problems appear as soon as the data are more than a blob (Song and Ermon, 2019).
The score is unknown where there are no data. Score matching weights its error by , so in regions of low density the learned score is barely trained, and a chain started there, as every chain started from noise is, follows arbitrary arrows. When the data lie near a low-dimensional manifold, as images do, almost all of space is such a region, and the score of the data itself is not even defined off the manifold.
Langevin dynamics cannot balance separated modes. Take . Near each mode the score is that of one Gaussian and does not depend on the weights; the weights show only in the gap, where the score at is , but the density there is about and chains rarely visit. A chain falls into the mode nearest to its start and stays. With the exact score, 4000 chains started uniformly on end with 0.52 of them in the left mode after 2000 steps of size 0.05, close to the share that started on the left, not the true 0.8.
Noise addresses both problems. The noised density is positive everywhere, so its score is defined everywhere, and at large the noised training points spread over a much wider region, so the network is trained where chains from noise begin; it is still trained only where noised samples actually land. For large , also fills the gap between the modes, so that the weights are visible to a chain. How much this helps depends on the choices: the noise levels must overlap, each must get enough steps of a suitable size, and a learned score adds its own approximation error. The mixture example below uses the exact score.
Noise fills the gap between the modes
Noise-conditional scores and annealing#
Song and Ermon (2019) train one network for many noise levels at once. Choose a geometric sequence , condition the network on the level, and minimize a weighted sum of denoising objectives:
The weight makes the terms comparable: the target has size , so each weighted term is of order one. Sampling, annealed Langevin dynamics, runs a few Langevin steps at the largest noise level, where the chain moves freely, then continues at the next level from where it stopped, down to the smallest, with step sizes that shrink with the noise. For images the paper uses levels from to , 100 steps per level and .
Two details make the training work. The network sees the level. In the NCSN of Song and Ermon every normalization layer has a learned scale and shift for each level, a conditional instance normalization (App. A.1). In a small fully connected network the level can simply select a learned vector that is added to each hidden layer, . Diffusion networks receive their timestep in the same ways (DDPM note). One level per example. The sum over levels has terms, and for the weighted per-level losses . So the average of the sampled per-level losses, one level drawn per training example, is an unbiased estimate of : the objective up to the constant factor , which scales the gradient but does not move the minimizer (multiply by to estimate itself), as the random timestep does for DDPM. For example, four geometric levels from to are : , , and . The figure below shows the fields such a network has to learn at these four levels.
The score field at four noise levels
In the mixture example, annealing through ten levels from to , 100 steps each, with the exact score of each , ends with 0.79 of the chains in the left mode, against the true 0.8.
Without noise, Langevin loses the mode weights
The same model as DDPM#
DDPM trains a network to predict the noise in (forward process). The score of this perturbation kernel is
so denoising score matching at level regresses onto . Writing turns the DSM loss into , and the weight , the variance of the noise, is the weighting above. The DDPM objective is noise-conditional denoising score matching with the noise variance as weight, and the DDPM sampling step is a Langevin-like step with the learned score. Song et al. (2021) make the correspondence exact in continuous time: both models discretize a stochastic differential equation that adds noise, and generation runs its time reversal, whose drift contains the score .
What changed#
| Likelihood (VAE, flows) | Score matching | |
|---|---|---|
| What is learned | a density or a bound on it | the gradient of the log-density |
| Normalizing constant | needed, or avoided by the architecture | never needed |
| Training signal | log-likelihood or ELBO | Fisher divergence, via a trace, random projections, or denoising |
| Sampling | one decoder pass | many Langevin steps |
| Weak spot | the architecture restricts the model | regions without data; separated modes, mitigated by noise levels |
Limitations#
- Many sampling steps. Annealed Langevin runs hundreds to thousands of network evaluations per sample; faster samplers are the subject of later work.
- Discretization bias. Unadjusted Langevin with a finite step samples a slightly wrong distribution, as the variance 1.026 instead of 1 shows. A decreasing step removes the bias only if the steps still add up to infinity.
- The noise schedule is a design choice. The largest level must cover the distances between modes, the smallest must be below the detail that matters, and the steps between levels must overlap.
- No likelihood for free. A score model does not give directly; it can be computed through the probability flow ODE of Song et al. (2021), at the cost of solving it.
Summary#
- The score does not depend on the normalizing constant and, where is positive on a connected region, determines up to it.
- Hyvärinen’s integration by parts turns the Fisher divergence into ; sliced score matching estimates the trace with random projections; denoising score matching regresses onto the score of a perturbation kernel, for Gaussian noise, and learns the score of the noised data.
- Langevin dynamics samples with the score; its step size trades bias against the number of steps, a decaying step must sum to infinity, and a temperature samples instead of .
- One noise level fails in empty regions and between modes; noise-conditional scores with annealing mitigate both when the levels and step sizes suit the data. The network receives the level in every layer and is trained with one random level per example.
- DDPM’s noise prediction is noise-conditional denoising score matching: .
Notebook#
The score matching notebook of the HSE-LAMBDA Deep Generative Models repository works on a two-dimensional Swiss roll and is based on the ACIDS-IRCAM diffusion tutorial (cell 1; cell numbers count every cell, markdown included, from 1). It has no saved outputs, so it documents the procedure rather than results.
- Cell 5: 10,000 points of a Swiss roll with noise 0.5, the first and third coordinates divided by 10.
- Cells 7–12: standard score matching with a two-layer Softplus network, the exact Jacobian built by one backward pass per output coordinate, and 2000 full-batch Adam steps.
- Cells 13–14:
plot_gradientsdraws the score as arrows on a grid over , each rescaled to , the length rule of the score-field figure, so that the huge scores far from the data stay readable. Cells 19, 23, 27 and 32–33 reuse the same plot. - Cells 15–19: gradient ascent with the score (20 steps of ) against Langevin dynamics (10 steps from , multiplied by 0.9 after each step), both from the fixed point ; the text says the start is drawn from . Cell 17 credits the convergence of Langevin dynamics to Welling and Teh (2011).
sample_langevin(cell 18) has atemperatureargument, default 1, that scales the noise. Its geometric decay of the step breaks the condition : the ten steps add up to , so the chain barely moves from its start. - Cells 20–23: sliced score matching on the first 1000 points. The random directions are normalized to unit length, so , and both terms are averaged over the coordinates: the Jacobian term becomes , with expectation , and the second term is the mean of rather than , with expectation . Both carry the same factor , so the objective is proportional to Hyvärinen’s and has the same minimizer.
- Cells 24–27: denoising score matching. The markdown of cell 24 gives the general objective for any perturbation kernel before the Gaussian one; the code uses and 5000 steps. At this noise level the targets are of size and points off the roll get almost no training signal, which is the failure that motivates the next cells.
- Cells 28–33: a noise-conditional network with the four levels , , and and the -weighted loss (
anneal_power = 2).ConditionalLinearadds a learned vector per level, annn.Embedding(4, 128)initialized uniformly on , to the output of each of the two hidden linear layers, the additive variant described above. Each of the 5000 full-batch steps draws one level per point withtorch.randint. Cell 32 plots the learned score field at each level. Annealed Langevin sampling is not implemented, and the last plot assigns a random noise level to every grid point, so its arrows mix four different fields.
Next#
Diffusion and score models work in pixel space: every step of the reverse chain processes the full image, and most of its bits describe details no one perceives. The next note runs the same process in the latent space of an autoencoder and adds the conditioning that turns it into text-to-image generation.
References#
- A. Hyvärinen. Estimation of Non-Normalized Statistical Models by Score Matching. Journal of Machine Learning Research, 6, 2005.
- P. Vincent. A Connection Between Score Matching and Denoising Autoencoders. Neural Computation, 23(7), 2011.
- Y. Song, S. Garg, J. Shi, S. Ermon. Sliced Score Matching: A Scalable Approach to Density and Score Estimation. UAI, 2019.
- Y. Song, S. Ermon. Generative Modeling by Estimating Gradients of the Data Distribution. NeurIPS, 2019. Noise-conditional score networks and annealed Langevin dynamics.
- Y. Song, J. Sohl-Dickstein, D. P. Kingma, A. Kumar, S. Ermon, B. Poole. Score-Based Generative Modeling through Stochastic Differential Equations. ICLR, 2021.
- B. Efron. Tweedie’s Formula and Selection Bias. Journal of the American Statistical Association, 106(496), 2011.
- M. Welling, Y. W. Teh. Bayesian Learning via Stochastic Gradient Langevin Dynamics. ICML, 2011. Eq. 2 (step-size conditions).
- G. O. Roberts, R. L. Tweedie. Exponential Convergence of Langevin Distributions and Their Discrete Approximations. Bernoulli, 2(4), 1996.