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 DistributionStart 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 for the density of the data, where is an image flattened into a vector. The score is the gradient of its logarithm with respect to the input:
For a 32×32 color image, has entries and so does : 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 divided by , the integral of over all of image space. Computing means integrating over 3072 dimensions, which nobody can do for a neural network. Taking the log turns the division into a subtraction, and does not depend on , so its gradient is zero:
A one-dimensional Gaussian with mean and standard deviation shows what the score looks like. Its log-density is a downward parabola minus the constant , and the constant disappears under the derivative:
At under a standard Gaussian the score is : it points back toward the mean, with a size proportional to the distance from it. For an energy-based model with , the score is , one backward pass through the energy network, while stays out of reach.
Figure 1 draws the score of a density made of six clusters blurred by Gaussian noise of width . Watch the arrows as you drag : 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.
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 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 drawn from a prior and a step size , it repeats
The factor is on the score term only; the noise is scaled by . As and the number of steps , the distribution of becomes under regularity conditions. For finite and a Metropolis–Hastings accept/reject step would correct the error; the paper assumes the error is negligible when is small and is large, and skips it.
Run (2) on a standard Gaussian, whose score is , with . The update becomes
Without the noise term, each step multiplies 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 , 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 does.
Figure 2 runs a swarm of chains on a density with several wells. It writes the step as , which is (2) with and an extra multiplier on the noise. At the chains pile onto the peaks and stop. At they spread over every well and keep moving. Above 1 they overshoot: multiplying the noise by makes the chain sample, for small steps, , a flattened version of .
With Langevin dynamics in hand, a generative model needs only a network 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 is 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 and four fifths around :
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 whose components have disjoint supports, with . On the support of the second term is zero, the log-density is , and the constant has zero gradient:
The same holds on the support of . The score is identical for every value of , 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 and with unit variance, the left one holding a fraction of the mass. With the added noise at 0, drag 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 to 3 or more: the bumps overlap and the score where the data lies depends on .
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 to every data point. The noised data have density
which is convolved with a Gaussian. Because a Gaussian is positive everywhere, so is , and its score is defined at every point: the manifold problem is gone at any . Large spreads training samples into the empty regions, so they get training signal. And when 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 the score exists only in a thin band around the curve; drag up and the band widens until the field covers the whole frame and points toward the curve from everywhere.
A small alone does not work, and the paper tests it. The baseline uses a single level , the same score network, and plain Langevin dynamics with and 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,
but the true score is the unknown. Hyvärinen's score matching (2005) removes it. Expanding the square gives three terms: , a term that does not depend on , and a cross term with the unknown score in it. In one dimension the cross term yields to integration by parts, because :
assuming at infinity. The derivative of the unknown density has moved onto the network. In 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
which equals the squared-error loss up to a constant. The multiplies only the squared norm; the trace term has no factor. Each diagonal entry of the Jacobian 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 with , such as a standard normal,
so is an unbiased estimate of the trace, and one forward-mode derivative computes it. The objective keeps the full 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 instead of the clean one. Noise a clean image yourself, with (a standard Gaussian vector, not the Langevin step size ), and the score of the noised image given its clean source is known in closed form:
This vector points from the noised image back to its source, scaled by . It becomes the regression label. For one noise level, the paper's per-level loss is
The plus sign inside the norm comes from subtracting the label . One noised image 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 , and Vincent showed that this average is , the score of the noised density.
Let the data be a standard Gaussian and take , so is a Gaussian with variance 2 and its score at is . The clean values that could have produced follow a Gaussian with mean 0.5 and variance 0.5. Their labels have mean 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 , and the readout reports the cosine between them.
The network therefore learns , which is close to only when is small. At large 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): equals , 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) , which takes the noise level as a second input and approximates for every in a fixed set. Neighbouring levels have similar score fields, which one network can share. The levels form a geometric sequence:
is large enough to deal with the three failures and is small enough to leave the data almost unchanged. For images the paper uses levels from to , 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 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:
Because (8) is a positively weighted sum of denoising objectives, a network with enough capacity minimizes it by matching 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 has expected squared norm , which is 3072 at and about 31 million at , so the smallest level would dominate. The paper observed that trained networks have and chose . Multiplying (6) by gives
where is a standard normal vector and has a norm that does not depend on , 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.
A training step at level 5, , on a batch of 128 images of shape [3, 32, 32]: draw of the same shape, form , and set the label to . The label's squared norm is about ; the weight 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 , and averages over the batch. Gradients flow into the one set of weights 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 adversaryThe network receives the level as an integer index , 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 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 , run Langevin steps with the network's score for that level, then use the result as the starting point for , and so on down to . At level the update is
This is (2) with the level- score and a level-dependent step . The denominator is , the smallest level, so the last level uses and earlier levels use larger steps. With the paper's , the first level has and per-step noise per pixel, and the last has and per-step noise 0.0045, a little more than one 8-bit gray level (1/255 = 0.0039).
Why ? The paper fixes the ratio of the score step to the noise step. The score step has size about , and with that is proportional to . The noise step has size proportional to . Their ratio is proportional to , which is the constant when . The third tab of Figure 6 shows 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 scaling as .
For images the paper runs steps per level from uniform noise, 1,000 network evaluations in total, and reports that results are robust to and that anywhere from to 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 equal to twice step_size, so its step_lr = 2e-5 corresponds to , 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 callsFigure 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.
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 and the exact score. Its text gives the ladder in two places with different values: Section 4.3 says and , and Appendix B.1 says and , with and for annealed Langevin and , 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, , 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 xResults 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 model | inception ↑ | FID ↓ |
|---|---|---|
| NCSN (unconditional) | 8.87 ± 0.12 | 25.32 |
| ProgressiveGAN (unconditional) | 8.80 ± 0.05 | – |
| SNGAN (unconditional) | 8.22 ± 0.05 | 21.7 |
| MoLM (unconditional) | 7.90 ± 0.10 | 18.9 |
| BigGAN (class-conditional) | 9.22 | 14.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 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 . 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 , 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 about as large as the largest distance between two training images, and parameterizing the network as . The 2019 paper uses 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.
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
- 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.pyand the sampler inrunners/anneal_runner.py. - 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.
- 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).
- Sliced score matching: Yang Song, Sahaj Garg, Jiaxin Shi and Stefano Ermon, Sliced Score Matching (UAI 2019).
- The mixing analysis: Li Wenliang, Danica Sutherland, Heiko Strathmann and Arthur Gretton, Learning Deep Kernels for Exponential Family Densities (ICML 2019).
- 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).
- 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).
How could this explainer be improved? Found an error, or something unclear? I read every message.