VerifiedarXiv:1907.0560031 min
Diffusion · Generative models

NCSN: Generative Modeling by Estimating Gradients of the Data Distribution

A network learns which way data density rises at each noise level; a noisy walk that follows those directions turns random pixels into images.

Song and Ermon's 2019 model trains with a regression loss, with no adversary and no normalizing constant, and set a record inception score of 8.87 for unconditional CIFAR-10 models.

Explaining the paperGenerative Modeling by Estimating Gradients of the Data DistributionYang Song, Stefano Ermon · Stanford · NeurIPS 2019 · arXiv:1907.05600 ↗

Start from a 32×32 color image of uniform random pixels. Take 100 small steps at each of ten noise levels, from σ = 1 down to σ = 0.01; every step moves the pixels a little toward higher density of the noised data at that level and adds a little fresh Gaussian noise. After 1,000 steps the static is a CIFAR-10-like image.

In 2019 most image generators fell into two families. Likelihood-based models, such as the variational autoencoder, autoregressive models and normalizing flows, train by maximizing the probability the model assigns to the data. That probability has to be normalized, so it sums to one over every possible image, and getting there forces either a restricted architecture or a surrogate loss such as the evidence lower bound. Generative adversarial networks skip the probability and train a generator against a discriminator. Their training can be unstable, and the GAN loss cannot be used to compare two GAN models.

Song and Ermon learn a different object: the score, a function that returns, for any image, a vector of the same shape pointing in the direction that makes the image more probable. A few ideas explain the method: what the score is and why it never involves the normalizing constant; how Langevin dynamics turns a score into samples; three ways that plan fails on real images; why adding Gaussian noise at ten different scales repairs all three; and how one network is trained on all ten scales with a regression loss and then sampled by walking the scales from large to small.

The score of a density

Write p(x)p(\mathbf{x}) for the density of the data, where x\mathbf{x} is an image flattened into a vector. The score is the gradient of its logarithm with respect to the input:

s(x)=∇xlog⁡p(x)\mathbf{s}(\mathbf{x}) = \nabla_{\mathbf{x}} \log p(\mathbf{x})
(1)

For a 32×32 color image, x\mathbf{x} has D=3072D = 3072 entries and so does s(x)\mathbf{s}(\mathbf{x}): one number per pixel channel, saying how much brightening that channel would raise the log-density. The paper calls this the Stein score, the gradient with respect to the data point. The older Fisher score is a gradient with respect to a model's parameters and is a different quantity.

The score does not depend on the normalizing constant. Any model density can be written as an unnormalized function p~(x)\tilde p(\mathbf{x}) divided by ZZ, the integral of p~\tilde p over all of image space. Computing ZZ means integrating over 3072 dimensions, which nobody can do for a neural network. Taking the log turns the division into a subtraction, and log⁡Z\log Z does not depend on x\mathbf{x}, so its gradient is zero:

∇xlog⁡p(x)=∇xlog⁡p~(x)−∇xlog⁡Z=∇xlog⁡p~(x)\nabla_{\mathbf{x}} \log p(\mathbf{x}) = \nabla_{\mathbf{x}} \log \tilde{p}(\mathbf{x}) - \nabla_{\mathbf{x}} \log Z = \nabla_{\mathbf{x}} \log \tilde{p}(\mathbf{x})∇xlog⁡p(x)=∇xlog⁡p~(x)−∇xlog⁡Z=∇xlog⁡p~(x)\begin{aligned} \nabla_{\mathbf{x}} \log p(\mathbf{x}) &= \nabla_{\mathbf{x}} \log \tilde{p}(\mathbf{x}) - \nabla_{\mathbf{x}} \log Z \\ &= \nabla_{\mathbf{x}} \log \tilde{p}(\mathbf{x}) \end{aligned}

A one-dimensional Gaussian with mean μ\mu and standard deviation ss shows what the score looks like. Its log-density is a downward parabola minus the constant log⁡(2π s)\log(\sqrt{2\pi}\,s), and the constant disappears under the derivative:

ddxlog⁡N(x;μ,s2)=−x−μs2\frac{d}{dx}\log \mathcal{N}(x;\mu,s^2) = -\frac{x-\mu}{s^2}

At x=2x = 2 under a standard Gaussian the score is −2-2: it points back toward the mean, with a size proportional to the distance from it. For an energy-based model with p~=e−E(x)\tilde p = e^{-E(\mathbf{x})}, the score is −∇E(x)-\nabla E(\mathbf{x}), one backward pass through the energy network, while ZZ stays out of reach.

Figure 1 draws the score of a density made of six clusters blurred by Gaussian noise of width σ\sigma. Watch the arrows as you drag σ\sigma: at small values they point to the nearest cluster, and at large values the clusters merge into one broad bump and the arrows point toward its center.

Figure 1 · the score field
σ = 1.00
Teal arrows are the score ∇log⁡pσ\nabla\log p_\sigma of six data clusters blurred by noise of width σ\sigma. Drag σ\sigma: small values give arrows toward the nearest cluster, large values give arrows toward the overall center.

Two questions remain: how to turn a score into samples, and how to estimate the score from a dataset that comes with no arrows attached. The sampling answer is decades older, and the training choices depend on it, so it comes first.

Sampling with Langevin dynamics

Given the exact score, the obvious procedure is gradient ascent: start somewhere and repeatedly step along the score. Every starting point then climbs to the nearest peak of log⁡p\log p and stops, so the output is a handful of most-likely images. Sampling means something else: visiting each region in proportion to its probability and never settling.

Langevin dynamics adds fresh Gaussian noise to every gradient step. From an initial point x~0\tilde{\mathbf{x}}_0 drawn from a prior and a step size ϵ>0\epsilon > 0, it repeats

x~t=x~t−1+ϵ2 ∇xlog⁡p(x~t−1)+ϵ ztzt∼N(0,I)\tilde{\mathbf{x}}_t = \tilde{\mathbf{x}}_{t-1} + \frac{\epsilon}{2}\,\nabla_{\mathbf{x}} \log p(\tilde{\mathbf{x}}_{t-1}) + \sqrt{\epsilon}\,\mathbf{z}_t \qquad \mathbf{z}_t \sim \mathcal{N}(\mathbf{0},\mathbf{I})x~t=x~t−1+ϵ2 ∇xlog⁡p(x~t−1)+ϵ ztzt∼N(0,I)\begin{gathered} \tilde{\mathbf{x}}_t = \tilde{\mathbf{x}}_{t-1} + \frac{\epsilon}{2}\,\nabla_{\mathbf{x}} \log p(\tilde{\mathbf{x}}_{t-1}) + \sqrt{\epsilon}\,\mathbf{z}_t \\ \mathbf{z}_t \sim \mathcal{N}(\mathbf{0},\mathbf{I}) \end{gathered}
(2)

The factor 12\tfrac12 is on the score term only; the noise is scaled by ϵ\sqrt{\epsilon}. As ϵ→0\epsilon \to 0 and the number of steps T→∞T \to \infty, the distribution of x~T\tilde{\mathbf{x}}_T becomes pp under regularity conditions. For finite ϵ\epsilon and TT a Metropolis–Hastings accept/reject step would correct the error; the paper assumes the error is negligible when ϵ\epsilon is small and TT is large, and skips it.

Run (2) on a standard Gaussian, whose score is −x-x, with ϵ=0.1\epsilon = 0.1. The update becomes

xt=0.95 xt−1+0.316 ztx_t = 0.95\,x_{t-1} + 0.316\,z_t

Without the noise term, each step multiplies xx by 0.95, and after 100 steps any start has shrunk to 0.006 of its size: every chain sits at the mode. With the noise, the chain settles to a stationary variance of ϵ/(1−0.952)=1.026\epsilon / (1 - 0.95^2) = 1.026, which matches the target's variance of 1 except for a 2.6% excess. That excess is the finite-step error a Metropolis–Hastings step would remove, and it shrinks as ϵ\epsilon does.

Figure 2 runs a swarm of chains on a density with several wells. It writes the step as τ s+2τ k z\tau\,\mathbf{s} + \sqrt{2\tau}\,k\,\mathbf{z}, which is (2) with τ=ϵ/2\tau = \epsilon/2 and an extra multiplier kk on the noise. At k=0k = 0 the chains pile onto the peaks and stop. At k=1k = 1 they spread over every well and keep moving. Above 1 they overshoot: multiplying the noise by kk makes the chain sample, for small steps, p1/k2p^{1/k^2}, a flattened version of pp.

Figure 2 · sampling vs. optimizing
k = 1.00
Chains follow the score toward the data while Gaussian noise of size kk pushes them around. Drag kk to 0 to get gradient ascent (chains freeze on peaks), to 1 for Langevin sampling, and above 1 for a cloud wider than the data.

With Langevin dynamics in hand, a generative model needs only a network sθ(x)≈∇xlog⁡p(x)\mathbf{s}_{\boldsymbol\theta}(\mathbf{x}) \approx \nabla_{\mathbf{x}} \log p(\mathbf{x}) plugged into (2). Section 3 of the paper shows three ways this fails on real images.

Why the plain version fails

The score is undefined on a manifold. A 32×32 color image has 3072 coordinates, but images that look like anything occupy a much lower-dimensional surface inside that space, the data manifold. This is the manifold hypothesis. Off the surface the density is zero, so log⁡p\log p is −∞-\infty and its gradient does not exist. Even on the surface, the gradient in the full 3072-dimensional space is not defined, because the density has no extent in the directions that leave it. The standard fitting method has a second problem here: Hyvärinen's consistency result for score matching (Theorem 2 of the 2005 paper) assumes densities that are positive everywhere. The paper shows the symptom in its Figure 1: a ResNet trained with sliced score matching on raw CIFAR-10 has a loss that first decreases and then fluctuates irregularly, while the same network trained on images with Gaussian noise of variance 0.0001 (standard deviation 0.01) added converges.

Empty regions get no training signal. Every score-matching loss is an average over training images. Where the data density is near zero, no training images land, and the network's output there is whatever its inductive bias produces. The paper's toy example is a two-dimensional mixture with one fifth of the mass around (−5,−5)(-5,-5) and four fifths around (5,5)(5,5):

pdata=15 N((−5,−5),I)+45 N((5,5),I)p_{\text{data}} = \tfrac15\,\mathcal{N}\big((-5,-5),\mathbf{I}\big) + \tfrac45\,\mathcal{N}\big((5,5),\mathbf{I}\big)

A score network fit to it with sliced score matching is reliable only close to the two modes. Langevin chains start from random noise, so they begin in the regions where the estimate is unreliable.

The score does not contain the mode weights. Take a mixture p=π p1+(1−π) p2p = \pi\,p_1 + (1-\pi)\,p_2 whose components have disjoint supports, with π∈(0,1)\pi \in (0,1). On the support of p1p_1 the second term is zero, the log-density is log⁡π+log⁡p1\log \pi + \log p_1, and the constant log⁡π\log\pi has zero gradient:

∇xlog⁡p(x)=∇x(log⁡π+log⁡p1(x))=∇xlog⁡p1(x)\nabla_{\mathbf{x}} \log p(\mathbf{x}) = \nabla_{\mathbf{x}}\big(\log\pi + \log p_1(\mathbf{x})\big) = \nabla_{\mathbf{x}} \log p_1(\mathbf{x})∇xlog⁡p(x)=∇x(log⁡π+log⁡p1(x))=∇xlog⁡p1(x)\begin{aligned} \nabla_{\mathbf{x}} \log p(\mathbf{x}) &= \nabla_{\mathbf{x}}\big(\log\pi + \log p_1(\mathbf{x})\big) \\ &= \nabla_{\mathbf{x}} \log p_1(\mathbf{x}) \end{aligned}

The same holds on the support of p2p_2. The score is identical for every value of π\pi, so a sampler that only reads the score cannot produce the right fraction of samples in each component; the fraction it produces depends on where the chains started. The paper checks this with the exact ground-truth score of the toy mixture (its Figure 3b), so the failure does not come from a badly trained network. Real modes are rarely fully disjoint; they share support through regions of tiny density. Then Langevin dynamics is correct in theory, but needs a very small step and a very large number of steps to move mass between modes, which the paper calls slow mixing. Its analysis follows Wenliang et al. (2019).

Figure 3 shows this on a one-dimensional version of the toy mixture: modes at −5-5 and +5+5 with unit variance, the left one holding a fraction π\pi of the mass. With the added noise at 0, drag π\pi across its range. The density bumps change height, and the score curve over the shaded regions, where the data actually lies, stays on the dashed 50/50 curve. Only the place where the score jumps from negative to positive moves, and it sits in the gap, where the density is about 5 millionths of the peak. Then raise σ\sigma to 3 or more: the bumps overlap and the score where the data lies depends on π\pi.

Figure 3 · the score ignores the mode weights
π = 0.20
σ = 0.0
Top: density of the mixture after adding noise of standard deviation σ\sigma. Bottom: its score, with the equal-weight score dashed and the region holding at least 1% of the peak density shaded. Drag π\pi at σ=0\sigma = 0, then increase σ\sigma and drag it again. The readout gives the largest gap between the two curves inside the shaded region.

Adding noise at many scales

All three failures come from the data being concentrated on a thin set with empty space around it. The paper treats them with one operation: add Gaussian noise of standard deviation σ\sigma to every data point. The noised data have density

qσ(x)=∫pdata(t) N(x∣t,σ2I) dtq_\sigma(\mathbf{x}) = \int p_{\text{data}}(\mathbf{t})\,\mathcal{N}(\mathbf{x}\mid \mathbf{t}, \sigma^2\mathbf{I})\,d\mathbf{t}
(3)

which is pdatap_{\text{data}} convolved with a Gaussian. Because a Gaussian is positive everywhere, so is qσq_\sigma, and its score is defined at every point: the manifold problem is gone at any σ>0\sigma > 0. Large σ\sigma spreads training samples into the empty regions, so they get training signal. And when σ\sigma is large compared with the distance between modes, the modes overlap, their weights reappear in the score (the right half of Figure 3), and Langevin chains can move between them.

In Figure 4 the data lie on a one-dimensional curve in the plane. At the smallest σ\sigma the score exists only in a thin band around the curve; drag σ\sigma up and the band widens until the field covers the whole frame and points toward the curve from everywhere.

Figure 4 · noise gives the score full support
σ = 0.06
The data lie on a curve. Drag σ\sigma: near 0 the score is defined only along the curve; larger values give qσq_\sigma full support and a score that points toward the data from every point. Overlapping modes are shown in Figures 3 and 7.

A small σ\sigma alone does not work, and the paper tests it. The baseline uses a single level σ=0.01\sigma = 0.01, the same score network, and plain Langevin dynamics with ϵ=2×10−5\epsilon = 2\times10^{-5} and T=1000T = 1000 steps. That noise removes the manifold problem, but it is far too small to put training signal into the empty regions, and the baseline fails to produce reasonable images. Large noise reaches the empty regions and connects modes but blurs away detail; small noise keeps the detail. NCSN uses a sequence of noise levels from large to small, trained into one network.

How to train a score network

The natural loss is the squared error between the network and the true score,

12 Ep∥sθ(x)−∇xlog⁡p(x)∥22\tfrac12\,\mathbb{E}_{p}\big\lVert \mathbf{s}_{\boldsymbol\theta}(\mathbf{x}) - \nabla_{\mathbf{x}}\log p(\mathbf{x})\big\rVert_2^2

but the true score is the unknown. Hyvärinen's score matching (2005) removes it. Expanding the square gives three terms: 12∥sθ∥2\tfrac12\lVert\mathbf{s}_{\boldsymbol\theta}\rVert^2, a term that does not depend on θ\boldsymbol\theta, and a cross term with the unknown score in it. In one dimension the cross term yields to integration by parts, because p⋅∂xlog⁡p=p′p \cdot \partial_x \log p = p':

Ep[sθ ∂xlog⁡p]=∫sθ(x) p′(x) dx=−∫sθ′(x) p(x) dx=−Ep[sθ′]\mathbb{E}_p\big[s_\theta\,\partial_x \log p\big] = \int s_\theta(x)\,p'(x)\,dx = -\int s_\theta'(x)\,p(x)\,dx = -\mathbb{E}_p\big[s_\theta'\big]Ep[sθ ∂xlog⁡p]=∫sθ(x) p′(x) dx=−∫sθ′(x) p(x) dx=−Ep[sθ′]\begin{aligned} \mathbb{E}_p\big[s_\theta\,\partial_x \log p\big] &= \int s_\theta(x)\,p'(x)\,dx \\ &= -\int s_\theta'(x)\,p(x)\,dx \\ &= -\mathbb{E}_p\big[s_\theta'\big] \end{aligned}

assuming sθ p→0s_\theta\,p \to 0 at infinity. The derivative of the unknown density has moved onto the network. In DD dimensions the same step produces the divergence of the network, the trace of its Jacobian, and the objective (Theorem 1 of Hyvärinen's paper) becomes

Epdata(x) ⁣[tr⁡ ⁣(∇xsθ(x))+12∥sθ(x)∥22]\mathbb{E}_{p_{\text{data}}(\mathbf{x})}\!\left[\operatorname{tr}\!\big(\nabla_{\mathbf{x}} \mathbf{s}_{\boldsymbol\theta}(\mathbf{x})\big) + \tfrac{1}{2}\lVert \mathbf{s}_{\boldsymbol\theta}(\mathbf{x})\rVert_2^2\right]
(4)

which equals the squared-error loss up to a constant. The 12\tfrac12 multiplies only the squared norm; the trace term has no factor. Each diagonal entry of the Jacobian ∂sθ,j/∂xj\partial s_{\theta,j} / \partial x_j needs its own backward pass, so the trace of a 3072×3072 Jacobian costs 3072 backward passes per training image. The paper states that score matching does not scale to deep networks and high-dimensional data for this reason, and describes two ways around it.

Sliced score matching (Song, Garg, Shi and Ermon, 2019) replaces the trace with a random projection. For a random vector v\mathbf{v} with E[vv⊤]=I\mathbb{E}[\mathbf{v}\mathbf{v}^\top] = \mathbf{I}, such as a standard normal,

Ev[v⊤A v]=tr⁡(A E[vv⊤])=tr⁡(A)\mathbb{E}_{\mathbf{v}}\big[\mathbf{v}^\top A\,\mathbf{v}\big] = \operatorname{tr}\big(A\,\mathbb{E}[\mathbf{v}\mathbf{v}^\top]\big) = \operatorname{tr}(A)

so v⊤(∇xsθ) v\mathbf{v}^\top (\nabla_{\mathbf{x}}\mathbf{s}_{\boldsymbol\theta})\,\mathbf{v} is an unbiased estimate of the trace, and one forward-mode derivative computes it. The objective keeps the full 12∥sθ∥2\tfrac12\lVert\mathbf{s}_{\boldsymbol\theta}\rVert^2 term. Sliced score matching estimates the score of the unperturbed data, and the NCSN paper puts its cost at about four times that of denoising score matching, because of the forward-mode differentiation.

Denoising score matching (Vincent, 2011) removes the trace by targeting the noised density qσq_\sigma instead of the clean one. Noise a clean image yourself, x~=x+σϵ\tilde{\mathbf{x}} = \mathbf{x} + \sigma\boldsymbol\epsilon with ϵ∼N(0,I)\boldsymbol\epsilon \sim \mathcal{N}(\mathbf{0}, \mathbf{I}) (a standard Gaussian vector, not the Langevin step size ϵ\epsilon), and the score of the noised image given its clean source is known in closed form:

∇x~log⁡qσ(x~∣x)=−x~−xσ2=−ϵσ\nabla_{\tilde{\mathbf{x}}} \log q_\sigma(\tilde{\mathbf{x}}\mid\mathbf{x}) = -\frac{\tilde{\mathbf{x}} - \mathbf{x}}{\sigma^2} = -\frac{\boldsymbol\epsilon}{\sigma}
(5)

This vector points from the noised image back to its source, scaled by 1/σ21/\sigma^2. It becomes the regression label. For one noise level, the paper's per-level loss is

ℓ(θ;σ)=12 Epdata(x) Ex~∼N(x,σ2I)∥sθ(x~,σ)+x~−xσ2∥22\ell(\boldsymbol\theta;\sigma) = \tfrac{1}{2}\,\mathbb{E}_{p_{\text{data}}(\mathbf{x})}\,\mathbb{E}_{\tilde{\mathbf{x}}\sim\mathcal{N}(\mathbf{x},\sigma^2\mathbf{I})}\Big\lVert \mathbf{s}_{\boldsymbol\theta}(\tilde{\mathbf{x}},\sigma) + \frac{\tilde{\mathbf{x}} - \mathbf{x}}{\sigma^2}\Big\rVert_2^2ℓ(θ;σ)=12 Epdata(x) Ex~∼N(x,σ2I)∥sθ(x~,σ)+x~−xσ2∥22\begin{aligned} \ell(\boldsymbol\theta;\sigma) &= \tfrac{1}{2}\,\mathbb{E}_{p_{\text{data}}(\mathbf{x})}\,\mathbb{E}_{\tilde{\mathbf{x}}\sim\mathcal{N}(\mathbf{x},\sigma^2\mathbf{I})} \\ &\quad \Big\lVert \mathbf{s}_{\boldsymbol\theta}(\tilde{\mathbf{x}},\sigma) + \frac{\tilde{\mathbf{x}} - \mathbf{x}}{\sigma^2}\Big\rVert_2^2 \end{aligned}
(6)

The plus sign inside the norm comes from subtracting the label −(x~−x)/σ2-(\tilde{\mathbf{x}}-\mathbf{x})/\sigma^2. One noised image x~\tilde{\mathbf{x}} could have come from many clean images, each giving a different label, so the network cannot fit every label. Squared error is minimized by the average label given x~\tilde{\mathbf{x}}, and Vincent showed that this average is ∇log⁡qσ(x~)\nabla \log q_\sigma(\tilde{\mathbf{x}}), the score of the noised density.

Let the data be a standard Gaussian and take σ=1\sigma = 1, so qσq_\sigma is a Gaussian with variance 2 and its score at x~=1\tilde x = 1 is −1/2-1/2. The clean values that could have produced x~=1\tilde x = 1 follow a Gaussian with mean 0.5 and variance 0.5. Their labels x−x~x - \tilde x have mean −0.5-0.5 and standard deviation 0.71: individually they scatter widely around the score, and their mean is the score.

Figure 5 shows the same thing in two dimensions. The thin teal arrows are individual labels, each pointing back to its own clean source. Drag the probe: the bold amber arrow averages the labels of nearby noised samples, the white arrow is the exact ∇log⁡qσ\nabla\log q_\sigma, and the readout reports the cosine between them.

Figure 5 · denoising labels average to the score
σ = 0.70
Clean data in amber, noised copies in teal with arrows to their sources, the labels (x−x~)/σ2(\mathbf{x}-\tilde{\mathbf{x}})/\sigma^2. Drag the probe to compare the averaged label (bold amber) with the exact score of qσq_\sigma (white).

The network therefore learns ∇log⁡qσ\nabla\log q_\sigma, which is close to ∇log⁡pdata\nabla\log p_{\text{data}} only when σ\sigma is small. At large σ\sigma it learns the score of a heavily smoothed density, the one with full support and connected modes that the sampler needs. The paper picks denoising over sliced score matching because it is slightly faster and targets noised scores directly, and it notes that sliced score matching trains NCSNs equally well.

The same averaging is known as Tweedie's formula, due to Robbins (1956) and Miyasawa (1961) and named by Efron (2011): ∇log⁡qσ(x~)\nabla\log q_\sigma(\tilde{\mathbf{x}}) equals (E[x∣x~]−x~)/σ2(\mathbb{E}[\mathbf{x}\mid\tilde{\mathbf{x}}] - \tilde{\mathbf{x}})/\sigma^2, so the best possible denoiser and the score carry the same information. The NCSN paper does not use this framing. Because of Tweedie's formula, DDPM, which predicts the added noise, trains the same kind of network.

One network for every noise level

The method needs scores at several noise levels. One option is a separate network per level. The paper instead trains a single Noise Conditional Score Network (NCSN) sθ(x,σ)\mathbf{s}_{\boldsymbol\theta}(\mathbf{x},\sigma), which takes the noise level as a second input and approximates ∇xlog⁡qσ(x)\nabla_{\mathbf{x}}\log q_\sigma(\mathbf{x}) for every σ\sigma in a fixed set. Neighbouring levels have similar score fields, which one network can share. The levels form a geometric sequence:

σ1σ2=σ2σ3=⋯=σL−1σL>1σi>0\frac{\sigma_1}{\sigma_2} = \frac{\sigma_2}{\sigma_3} = \cdots = \frac{\sigma_{L-1}}{\sigma_L} > 1 \qquad \sigma_i > 0σ1σ2=σ2σ3=⋯=σL−1σL>1σi>0\begin{gathered} \frac{\sigma_1}{\sigma_2} = \frac{\sigma_2}{\sigma_3} = \cdots = \frac{\sigma_{L-1}}{\sigma_L} > 1 \\ \sigma_i > 0 \end{gathered}
(7)

σ1\sigma_1 is large enough to deal with the three failures and σL\sigma_L is small enough to leave the data almost unchanged. For images the paper uses L=10L = 10 levels from σ1=1\sigma_1 = 1 to σ10=0.01\sigma_{10} = 0.01, on pixels scaled to [0, 1], so each level is 0.599 times the previous one: 1, 0.599, 0.359, 0.215, 0.129, 0.0774, 0.0464, 0.0278, 0.0167, 0.01. Noise of standard deviation 0.01 is almost invisible to the eye. At σ1=1\sigma_1 = 1 the noise is three to four times the spread of uniform pixel values in [0, 1] (standard deviation 0.29), so the image is buried.

The training objective averages the per-level loss (6) over the ladder with a weight per level:

L(θ;{σi})=1L∑i=1Lλ(σi) ℓ(θ;σi)λ(σi)>0\mathcal{L}(\boldsymbol\theta;\{\sigma_i\}) = \frac{1}{L}\sum_{i=1}^{L} \lambda(\sigma_i)\,\ell(\boldsymbol\theta;\sigma_i) \qquad \lambda(\sigma_i) > 0L(θ;{σi})=1L∑i=1Lλ(σi) ℓ(θ;σi)λ(σi)>0\begin{gathered} \mathcal{L}(\boldsymbol\theta;\{\sigma_i\}) = \frac{1}{L}\sum_{i=1}^{L} \lambda(\sigma_i)\,\ell(\boldsymbol\theta;\sigma_i) \\ \lambda(\sigma_i) > 0 \end{gathered}
(8)

Because (8) is a positively weighted sum of denoising objectives, a network with enough capacity minimizes it by matching ∇log⁡qσi\nabla\log q_{\sigma_i} at every level, whatever the weights. The weights decide how much each level contributes to the gradient during training. Without them, the levels differ enormously: the label −ϵ/σ-\boldsymbol\epsilon/\sigma has expected squared norm D/σ2D/\sigma^2, which is 3072 at σ1=1\sigma_1 = 1 and about 31 million at σ10=0.01\sigma_{10} = 0.01, so the smallest level would dominate. The paper observed that trained networks have ∥sθ(x,σ)∥2∝1/σ\lVert\mathbf{s}_{\boldsymbol\theta}(\mathbf{x},\sigma)\rVert_2 \propto 1/\sigma and chose λ(σ)=σ2\lambda(\sigma) = \sigma^2. Multiplying (6) by σ2\sigma^2 gives

σ2 ℓ(θ;σ)=12 E∥σ sθ(x~,σ)+x~−xσ∥22\sigma^2\,\ell(\boldsymbol\theta;\sigma) = \tfrac12\,\mathbb{E}\Big\lVert \sigma\,\mathbf{s}_{\boldsymbol\theta}(\tilde{\mathbf{x}},\sigma) + \frac{\tilde{\mathbf{x}}-\mathbf{x}}{\sigma}\Big\rVert_2^2σ2 ℓ(θ;σ)=12 E∥σ sθ(x~,σ)+x~−xσ∥22\begin{aligned} \sigma^2\,\ell(\boldsymbol\theta;\sigma) &= \tfrac12\,\mathbb{E}\Big\lVert \sigma\,\mathbf{s}_{\boldsymbol\theta}(\tilde{\mathbf{x}},\sigma) \\ &\qquad + \frac{\tilde{\mathbf{x}}-\mathbf{x}}{\sigma}\Big\rVert_2^2 \end{aligned}

where (x~−x)/σ(\tilde{\mathbf{x}}-\mathbf{x})/\sigma is a standard normal vector and σ sθ\sigma\,\mathbf{s}_{\boldsymbol\theta} has a norm that does not depend on σ\sigma, so every level contributes a term of the same order. The choice rests on an empirical observation; the paper does not derive it. Figure 6 plots the ten levels on a log scale. The first two tabs show the squared label size before and after weighting; the third tab belongs to the sampler and is used in the next section. Click a bar or use the slider to read a level's numbers.

Figure 6 · the ten noise levels
σ_5 = 0.129
The paper's image ladder, σ1=1\sigma_1 = 1 to σ10=0.01\sigma_{10} = 0.01 with D=3072D = 3072. Switch tabs to compare the unweighted label size D/σ2D/\sigma^2, the σ2\sigma^2-weighted size, and the sampling step αi\alpha_i with its per-step noise αi\sqrt{\alpha_i}.

A training step at level 5, σ=0.129\sigma = 0.129, on a batch of 128 images of shape [3, 32, 32]: draw ϵ\boldsymbol\epsilon of the same shape, form x~=x+0.129 ϵ\tilde{\mathbf{x}} = \mathbf{x} + 0.129\,\boldsymbol\epsilon, and set the label to −ϵ/0.129=−7.74 ϵ-\boldsymbol\epsilon/0.129 = -7.74\,\boldsymbol\epsilon. The label's squared norm is about 3072/0.0167≈184,0003072/0.0167 \approx 184{,}000; the weight σ2=0.0167\sigma^2 = 0.0167 brings the term back to about 3072. The released code draws a separate level for each image in the batch, sums the squared error over pixels, multiplies by σ2\sigma^2, and averages over the batch. Gradients flow into the one set of weights θ\boldsymbol\theta shared by all levels:

# one NCSN training step (after losses/dsm.py in the official code)
sigmas = geomspace(1.0, 0.01, 10)          # the ladder, sigma_1 ... sigma_10
x      = next_batch()                      # clean images [128, 3, 32, 32] in [0, 1]
i      = randint(0, 10, size=128)          # a random level for EACH image
sigma  = sigmas[i].view(128, 1, 1, 1)
eps    = randn_like(x)
x_t    = x + sigma * eps                   # noised input
target = -(x_t - x) / sigma**2             # = -eps / sigma, the DSM label
s      = s_theta(x_t, i)                   # [128, 3, 32, 32]
sq     = ((s - target)**2).sum(dim=(1, 2, 3))      # squared error per image
loss   = (0.5 * sq * sigma.flatten()**2).mean()    # lambda(sigma) = sigma^2
loss.backward(); adam.step()               # lr 1e-3; no sampling, no adversary

The network receives the level as an integer index ii, and each normalization layer looks up its own learned parameters for that index. Training uses Adam with learning rate 0.001, batch size 128 and 200,000 iterations, with random horizontal flips for CelebA and CIFAR-10. The objective needs no adversarial training, no surrogate loss, no sampling from the model during training, and no architecture restriction for tractability. With λ\lambda and the ladder held fixed, its value can also be used to compare two NCSNs.

The architecture follows from the output: a score is an image-shaped tensor the same size as the input, so the network is a dense-prediction model. The paper combines the U-Net design with dilated convolutions. Concretely it is a 4-cascaded RefineNet (a U-Net variant built from ResNet-style blocks) with pre-activation residual blocks, average pooling instead of max pooling, and batch normalization replaced by CondInstanceNorm++, a modified conditional instance normalization that carries the noise-level input.

Annealed Langevin dynamics

The trained network gives a score at ten noise levels. The sampler has to use the large levels, where chains can move between modes and the network was trained everywhere, and still end at a sample of the nearly clean data. The paper's annealed Langevin dynamics borrows from simulated annealing and annealed importance sampling. In simulated annealing an optimizer starts at a high temperature, where it can jump between basins, and cools slowly so it settles into a good one. Here the noise level plays the temperature. Start at σ1\sigma_1, run TT Langevin steps with the network's score for that level, then use the result as the starting point for σ2\sigma_2, and so on down to σL\sigma_L. At level ii the update is

x~t←x~t−1+αi2 sθ(x~t−1,σi)+αi ztαi=ϵ⋅σi2σL2\tilde{\mathbf{x}}_t \leftarrow \tilde{\mathbf{x}}_{t-1} + \frac{\alpha_i}{2}\,\mathbf{s}_{\boldsymbol\theta}(\tilde{\mathbf{x}}_{t-1},\sigma_i) + \sqrt{\alpha_i}\,\mathbf{z}_t \qquad \alpha_i = \epsilon\cdot\frac{\sigma_i^2}{\sigma_L^2}x~t←x~t−1+αi2 sθ(x~t−1,σi)+αi ztαi=ϵ⋅σi2σL2\begin{gathered} \tilde{\mathbf{x}}_t \leftarrow \tilde{\mathbf{x}}_{t-1} + \frac{\alpha_i}{2}\,\mathbf{s}_{\boldsymbol\theta}(\tilde{\mathbf{x}}_{t-1},\sigma_i) + \sqrt{\alpha_i}\,\mathbf{z}_t \\ \alpha_i = \epsilon\cdot\frac{\sigma_i^2}{\sigma_L^2} \end{gathered}
(9)

This is (2) with the level-ii score and a level-dependent step αi\alpha_i. The denominator is σL2\sigma_L^2, the smallest level, so the last level uses αL=ϵ\alpha_L = \epsilon and earlier levels use larger steps. With the paper's ϵ=2×10−5\epsilon = 2\times10^{-5}, the first level has α1=0.2\alpha_1 = 0.2 and per-step noise 0.2=0.447\sqrt{0.2} = 0.447 per pixel, and the last has α10=2×10−5\alpha_{10} = 2\times10^{-5} and per-step noise 0.0045, a little more than one 8-bit gray level (1/255 = 0.0039).

Why αi∝σi2\alpha_i \propto \sigma_i^2? The paper fixes the ratio of the score step to the noise step. The score step has size about αi2∥sθ∥\tfrac{\alpha_i}{2}\lVert\mathbf{s}_{\boldsymbol\theta}\rVert, and with ∥sθ∥∝1/σi\lVert\mathbf{s}_{\boldsymbol\theta}\rVert \propto 1/\sigma_i that is proportional to αi/σi\alpha_i/\sigma_i. The noise step has size proportional to αi\sqrt{\alpha_i}. Their ratio is proportional to αi/σi\sqrt{\alpha_i}/\sigma_i, which is the constant ϵ/σL=0.447\sqrt{\epsilon}/\sigma_L = 0.447 when αi∝σi2\alpha_i \propto \sigma_i^2. The third tab of Figure 6 shows αi\alpha_i falling by four orders of magnitude while that ratio stays put. The paper notes that other schedules are possible and that this one relies on the same empirical 1/σ1/\sigma scaling as λ\lambda.

For images the paper runs T=100T = 100 steps per level from uniform noise, 1,000 network evaluations in total, and reports that results are robust to TT and that ϵ\epsilon anywhere from 5×10−65\times10^{-6} to 5×10−55\times10^{-5} works. The listing follows Algorithm 1. The released code adds step_size * grad plus Gaussian noise of variance 2 * step_size, which is (9) with αi\alpha_i equal to twice step_size, so its step_lr = 2e-5 corresponds to ϵ=4×10−5\epsilon = 4\times10^{-5}, still inside the working range.

# annealed Langevin dynamics (Algorithm 1), paper's step convention
x = rand(n, 3, 32, 32)                     # uniform noise in [0, 1]
for i, sigma in enumerate(sigmas):         # sigma_1 = 1.0 down to sigma_10 = 0.01
    alpha = eps * sigma**2 / sigmas[-1]**2 # eps = 2e-5: alpha_1 = 0.2, alpha_10 = 2e-5
    for t in range(100):                   # T = 100 steps per level
        z = randn_like(x)
        x = x + (alpha / 2) * s_theta(x, i) + sqrt(alpha) * z
return x                                   # 10 x 100 = 1,000 network calls

Figure 7 runs both samplers on a two-mode mixture with the paper's weights, 20% on the left and 80% on the right, from the same uniform start. Plain Langevin runs at the smallest noise level only; annealed Langevin spends the same total number of steps walking down nine levels. Press Play and watch the first levels: the cloud covers both modes as one broad blob and shifts toward the heavy one. Then switch to plain Langevin, where each chain falls into the nearer basin and stays.

Figure 7 · annealing recovers the mode weights
level 9/9 · σ = 0.42
Two modes holding 20% and 80% of the data. Toggle the sampler, press Play, or scrub the chain; the bar at the bottom shows the fraction of chains on each side, with the target 20/80 dashed. In this page's simulation, plain Langevin ends near half and half and annealed Langevin near 20/80.

The figure's settings are scaled down for a browser: modes 4.9 apart with width 0.42, nine levels from 3.2 to 0.42, 22 steps per level, 220 chains. The paper's own toy run (its Figure 3) uses 1,280 samples started uniformly in [−8,8]2[-8,8]^2 and the exact score. Its text gives the ladder in two places with different values: Section 4.3 says σ1=10\sigma_1 = 10 and σ10=0.1\sigma_{10} = 0.1, and Appendix B.1 says σ1=20\sigma_1 = 20 and σ10=1\sigma_{10} = 1, with T=100T = 100 and ϵ=0.1\epsilon = 0.1 for annealed Langevin and T=1000T = 1000, ϵ=0.1\epsilon = 0.1 for plain Langevin. The paper reports only that plain Langevin gets the relative weights wrong and annealed Langevin recovers them; the near-even split in Figure 7 is this page's simulation, not a number from the paper.

The same sampler fills in missing parts of an image (the paper's Algorithm 2). At each level, the known pixels are noised to that level, y=x+σiz\mathbf{y} = \mathbf{x} + \sigma_i\mathbf{z}, and after every Langevin step they overwrite the corresponding pixels of the chain, so the score network only fills the hole. The hyperparameters are those of image generation, and the hole can have any shape; the paper contrasts this with PixelCNN, which can only fill pixels in raster-scan order.

# inpainting (Algorithm 2): m = 1 on known pixels, 0 on the hole
x = rand_like(img)
for i, sigma in enumerate(sigmas):
    alpha = eps * sigma**2 / sigmas[-1]**2
    y = img + sigma * randn_like(img)      # known pixels, noised to this level
    for t in range(100):
        z = randn_like(x)
        x = x + (alpha / 2) * s_theta(x, i) + sqrt(alpha) * z
        x = x * (1 - m) + y * m            # overwrite the known pixels
return x

Results on CIFAR-10

The paper trains on MNIST, CelebA (center-cropped to 140×140 and resized to 32×32) and CIFAR-10, and reports numbers only for CIFAR-10. The inception score rates how recognizable and varied samples are (higher is better); FID measures the distance between feature statistics of generated and real images (lower is better). Both use 50,000 samples:

CIFAR-10 modelinception ↑FID ↓
NCSN (unconditional)8.87 ± 0.1225.32
ProgressiveGAN (unconditional)8.80 ± 0.05–
SNGAN (unconditional)8.22 ± 0.0521.7
MoLM (unconditional)7.90 ± 0.1018.9
BigGAN (class-conditional)9.2214.73

The 8.87 was a new best inception score for unconditional models, 0.07 above ProgressiveGAN, and higher than most reported class-conditional scores. The FID of 25.32 was not a record. The paper calls it comparable to top models such as SNGAN, and SNGAN and MoLM have lower FIDs in the same table. Class-conditional BigGAN is better on both metrics. The CIFAR-10 and CelebA checkpoints were chosen by computing FID on 1,000 samples from each saved checkpoint (one every 5,000 iterations) and keeping the best; the paper notes ProgressiveGAN used a similar procedure.

Three qualitative checks accompany the numbers. The single-level baseline at σ=0.01\sigma = 0.01 fails to produce reasonable images. Appendix C.2 shows the nearest training images to generated samples, which the paper uses to argue that the model is not memorizing training images. Inpainting with Algorithm 2 gives varied, plausible completions of occluded CelebA and CIFAR-10 images.

From NCSN to diffusion models

NCSN adds noise to images without rescaling them, so the variance of the noised data grows with σ\sigma. DDPM (Ho et al., 2020) shrinks the image as it adds noise, keeping the total variance near 1. The score-SDE paper (Song et al., 2021) showed both are discretizations of stochastic differential equations and named NCSN's version the variance-exploding SDE and DDPM's the variance-preserving SDE; those labels do not appear in the 2019 paper. Predicting the score and predicting the noise differ by a factor of −1/σ-1/\sigma, from (5), and DDIM points out that DDPM's loss with equal weights across levels is the NCSN objective.

Two later details come from the follow-up, NCSNv2 (Song and Ermon, 2020): choosing σ1\sigma_1 about as large as the largest distance between two training images, and parameterizing the network as sθ(x)/σ\mathbf{s}_{\boldsymbol\theta}(\mathbf{x})/\sigma. The 2019 paper uses σ1=1\sigma_1 = 1 and a learned embedding per level. In the other direction, the earlier nonequilibrium thermodynamics paper (Sohl-Dickstein et al., 2015) also generates by reversing a noising process, but it learns a reverse Gaussian chain and has no score and no Langevin sampler; sampling from a learned score with Langevin dynamics is the part NCSN added.

Provenance Verified against primary literatureHow we verify
Hyvärinen (2005), JMLRTheorem 1: integration by parts turns the squared error against the unknown score into E[tr(grad s) + 1/2 ||s||^2] + const, the paper's Eq. (1). Theorem 2: the estimator is consistent when the density is positive everywhere, which fails on a low-dimensional manifold.
Vincent (2011)Denoising score matching. Regressing on the conditional score -(x~ - x)/sigma^2 has the score of the noised density q_sigma as its optimum, not the clean-data score.
Song, Garg, Shi & Ermon (UAI 2019)Sliced score matching: v^T (grad s) v with random v estimates the trace. The NCSN paper puts its cost at about four times that of denoising score matching, from forward-mode autodiff.
Wenliang, Sutherland, Strathmann & Gretton (ICML 2019)Source the NCSN paper credits for its analysis of mixture weights and slow mixing.
Robbins (1956), Miyasawa (1961), Efron (2011)grad log q_sigma(x~) = (E[x | x~] - x~)/sigma^2, so an optimal denoiser gives the score. NCSN does not use this framing; its related-work section only notes that DSM can be derived from Bayes least squares.
ermongroup/ncsn, losses/dsm.py lines 29-38Each image in a batch draws its own level; the squared error is summed over pixels, multiplied by sigma^anneal_power with anneal_power = 2, then averaged over the batch.
ermongroup/ncsn, runners/anneal_runner.py lines 126-140, 203-215Ladder = exp(linspace(log 1, log 0.01, 10)). Sampler: step_size = step_lr * (sigma/sigma_L)^2, x += step_size * grad + sqrt(2 * step_size) * z, with step_lr = 2e-5. models/cond_refinenet_dilated.py conditions on the level index through nn.Embedding(num_classes, ...).
Song & Ermon (2020), NCSNv2Source of the very large sigma_1 (about the largest distance between training images) and the s_theta(x)/sigma parameterization. The 2019 paper used sigma_1 = 1 and a level embedding.
Song et al. (2021), Score-SDERecasts NCSN as a discretized variance-exploding SDE and DDPM as variance-preserving. The VE/VP labels come from that paper.
correctionTwo corrections. (1) A common account blames plain Langevin's wrong mode weights on an inaccurate learned score. The paper's Fig. 3(b) samples with the EXACT ground-truth score and still gets the weights wrong: on the support of one component, grad log(pi p1) = grad log p1, so the score carries no trace of pi and the failure is structural. When the components overlap slightly, Langevin is correct in theory but needs a tiny step and very many steps. (2) The released sampler does not use the paper's step convention. Algorithm 1 takes x += (alpha/2) s + sqrt(alpha) z with alpha_L = eps = 2e-5; runners/anneal_runner.py takes x += step_size * s + sqrt(2 step_size) z with step_size = 2e-5 at the last level, which is alpha_L = 4e-5, twice the paper's value (still inside the 5e-6 to 5e-5 range the paper reports as working).

Questions you might still have

?

Why learn the score of the noised data instead of the clean data?
The clean-data score is undefined off the thin set of real images and has no training signal in the empty regions between clusters. The noised density q_sigma is positive everywhere, so its score is defined and learnable at every point. The smallest level, sigma = 0.01 on pixels in [0, 1], is close enough to the clean data that sampling finishes there.

?

If Langevin dynamics only needs the score, why add random noise on every step?
Without the sqrt(eps) z term the update is gradient ascent on log p, and every chain climbs to the nearest peak and stops. The noise keeps chains moving so they visit regions in proportion to their probability. For a standard Gaussian with eps = 0.1, the noiseless update multiplies x by 0.95 each step and reaches 0.006 of its start after 100 steps; the noisy one settles to a spread of variance 1.026.

?

Why does plain Langevin get the mode weights wrong even with the exact score?
Where one component dominates, the log-density is log pi + log p1, and the gradient of the constant log pi is zero. The score there is the same for any weight, so the split of samples is set by where the chains started. Large noise makes the components overlap, the weight reappears in the score, and annealing carries that split down to small noise.

?

How is NCSN different from DDPM?
Both learn a noise-level-conditioned network with a denoising loss. NCSN adds noise without shrinking the image (variance exploding), predicts the score, and samples with 100 Langevin steps at each of 10 levels. DDPM shrinks the image as it adds noise (variance preserving), predicts the noise, and samples with one learned reverse step per level over 1,000 levels. The score-SDE paper later treated both as discretizations of stochastic differential equations; the DDPM and score-SDE explainers cover those.

?

Was NCSN state of the art?
On inception score among unconditional CIFAR-10 models, yes: 8.87, just above ProgressiveGAN at 8.80, and above most class-conditional models. On FID it was 25.32, called comparable by the paper: SNGAN reports 21.7 and MoLM 18.9 in the same table, and class-conditional BigGAN is ahead on both metrics at 9.22 and 14.73.

?

How expensive is sampling?
Ten levels times 100 steps is 1,000 forward passes of the score network per batch of images. A GAN generator needs one forward pass. Later work on faster samplers, such as DDIM, reduces this cost for diffusion models.

?

Can the trained network be evaluated at a noise level between two rungs of the ladder?
Not in the released code. The network receives the level index i, looked up in a learned embedding table inside each conditional instance norm layer, so only the 10 trained levels exist. NCSNv2 and the score-SDE work moved to conditioning that extends to other noise levels.

Footnotes & further reading

  1. The paper: Yang Song and Stefano Ermon, Generative Modeling by Estimating Gradients of the Data Distribution (Stanford, NeurIPS 2019). Official code; the loss is in losses/dsm.py and the sampler in runners/anneal_runner.py.
  2. Score matching: Aapo Hyvärinen, Estimation of Non-Normalized Statistical Models by Score Matching (JMLR 2005). Theorem 1 is the integration-by-parts identity behind (4); Theorem 2 is consistency, which assumes a density that is positive everywhere.
  3. Denoising score matching: Pascal Vincent, A Connection Between Score Matching and Denoising Autoencoders (Neural Computation, 2011). The denoiser-score identity goes back to Robbins (1956) and Miyasawa (1961) and was named Tweedie's formula by Efron (2011).
  4. Sliced score matching: Yang Song, Sahaj Garg, Jiaxin Shi and Stefano Ermon, Sliced Score Matching (UAI 2019).
  5. The mixing analysis: Li Wenliang, Danica Sutherland, Heiko Strathmann and Arthur Gretton, Learning Deep Kernels for Exponential Family Densities (ICML 2019).
  6. The continuous-time unification: Score-Based Generative Modeling through Stochastic Differential Equations (Song et al., 2021), and the variance-preserving sibling, DDPM (Ho et al., 2020).
  7. The follow-up that revised the noise ladder, the conditioning and the step sizes: Improved Techniques for Training Score-Based Generative Models (NCSNv2, Song & Ermon, 2020).