Score SDE (score-based generative modeling with stochastic differential equations) is a framework that describes the process of gradually adding noise to data as a continuous-time stochastic differential equation (SDE), and generates images by solving the SDE that runs that time backward. The reverse SDE requires only the "score" (the gradient of the log probability density) of the data distribution at each time, so this is learned with a neural network.
It was published by Song et al. in 2020 in the paper "Score-Based Generative Modeling through Stochastic Differential Equations" and accepted at ICLR 2021. At the time, there were two lines of generative models based on noise.
SMLD (score matching with Langevin dynamics, also called NCSN): learns the scores of data blurred with noise at several strengths, and generates images with Langevin dynamics while weakening the noise.
DDPM: learns to trace back a 1000-step noising process one step at a time.
The paper shows that these two are discretizations of different SDEs within the same framework, and calls them collectively "score-based generative models". Extending the framework to continuous time made the following possible.
A choice of generation methods: in addition to general SDE solvers, generation is possible with a "predictor-corrector" sampler that combines an SDE solver with Langevin MCMC, and with the "probability flow ODE", which uses no randomness.
Exact likelihood computation: with the probability flow ODE, the log-likelihood of data can be computed exactly.
Conditional generation: with a model trained unconditionally as is, class-conditional generation, image inpainting, and colorization of grayscale images are possible.
For unconditional generation on CIFAR-10, it achieved an Inception Score of 9.89 and an FID of 2.20, the best values at the time. It was also the first score-based model to generate high-resolution 1024 Γ 1024 images.
Theory
Forward SDE: turning data into noise
The data x(t) at time tβ[0,T] evolves according to the following SDE (an ItΓ΄ stochastic differential equation) (equation 5).
dx=f(x,t)dt+g(t)dw
f is the drift coefficient (change in a fixed direction), g is the diffusion coefficient (noise strength), and w is a standard Wiener process (Brownian motion). This SDE is fixed in advance and has no learned parameters. It is designed so that x(0) is the data and x(T) follows a tractable prior such as a normal distribution. The distribution of x(t) at time t is written ptβ(x).
Reverse SDE: turning noise back into data
The process that traces a diffusion process backward in time is also a diffusion process (Anderson, 1982). It is given by the following reverse SDE (equation 6).
dx=[f(x,t)βg(t)2βxβlogptβ(x)]dt+g(t)dwΛ
wΛ is a Wiener process running backward in time, and dt is a negative infinitesimal time step. βxβlogptβ(x) is called the score. Since the score points in "the direction of higher probability", the reverse SDE moves x little by little toward where data is likely, even while adding noise. The core of this framework is that if the score is known at every time, data can be generated from x(T).
Learning the score
The score is approximated by a time-dependent network sΞΈβ(x,t). Training uses the following objective, which extends denoising score matching to continuous time (equation 7).
t is sampled uniformly from [0,T], and Ξ»(t) is a positive weight. p0tβ(x(t)β£x(0)) is the distribution obtained by adding noise to x(0) up to time t; if f is affine in x, it is a normal distribution and can be written in closed form. With enough data and a sufficiently expressive network, the optimal sΞΈββ(x,t) equals the true score βxβlogptβ(x).
For example, for a normal distribution of the same form as DDPM, N(Ξ±Λtββx(0),(1βΞ±Λtβ)I), the target score is βΟ΅/1βΞ±Λtββ. In other words, predicting the score is the same as predicting the added noise Ο΅, and DDPM training is included in this form.
Three SDEs
The paper gives the following three concrete SDEs (Section 3.4).
In the experiments, Ο(t) of the VE SDE is the limit of a geometric sequence starting at Οminβ=0.01, and Ξ²(t) of the VP SDE is a function that increases linearly from Ξ²Λβminβ=0.1 to Ξ²Λβmaxβ=20 (tβ[0,1]) (Appendix C). The latter is the continuous-time version of DDPM's Ξ² schedule (10β4 to 0.02 over 1000 steps).
Generation
The learned score defines the reverse SDE; x(T) is drawn from the prior, and the SDE is solved numerically from t=T to 0. The paper presents the following three kinds of solvers (Section 4).
General SDE solvers: solve the reverse SDE with methods such as Euler-Maruyama. DDPM sampling corresponds to solving the reverse SDE of the VP SDE with a particular discretization. The paper also proposes a "reverse diffusion sampler" that solves the reverse SDE with the same discretization as the forward one.
Predictor-corrector (PC) samplers: at each time step, first predict the value at the next time with an SDE solver (predictor), then correct it to match the distribution at that time with score-based Langevin MCMC (corrector). SMLD sampling is the special case of "corrector only", and DDPM sampling is the special case of "predictor only".
Probability flow ODE: every diffusion process has a deterministic process with the same distribution ptβ at each time, expressed by the following ordinary differential equation (equation 13).
dx=[f(x,t)β21βg(t)2βxβlogptβ(x)]dt
Since the probability flow ODE uses no randomness, x(0) and x(T) correspond one to one. This makes it possible to encode images into the latent variable x(T), to generate quickly with ODE solvers that adapt their step size automatically, and to compute the log-likelihood exactly.
The deterministic sampling of DDIM is also a relative of the probability flow ODE. The DDIM paper shows that the DDIM ODE is equivalent to the probability flow ODE of the VE SDE.
Network
The score network uses an improved version of the DDPM U-Net. The paper examined the type and number of residual blocks, how skip connections are rescaled, and so on, and built NCSN++ for the VE SDE and DDPM++ for the VP SDE (Section 4.4, Appendix H). The continuous time t is fed to the network with random Fourier feature embeddings (NCSN++).
Why it works
The reasons the Score SDE view is useful can be summarized in three points.
Noise levels can be made infinitely fine: for both SMLD and DDPM, the key to success was using data blurred with noise at many strengths. An SDE extends this to a continuum of infinitely many levels, and during training too, the time t can be sampled continuously. The paper reports that switching from the discrete objective to the continuous-time objective (equation 7) improved FID for every SDE.
Training and generation can be decoupled: training only needs to find the score. For generation, the same score can be used with an SDE solver, predictor-corrector, or the probability flow ODE, chosen to suit the goal. One can use the ODE when speed matters and predictor-corrector when image quality matters.
Conditions can be added just by adding scores: by Bayes' theorem, βxβlogptβ(xβ£y)=βxβlogptβ(x)+βxβlogptβ(yβ£x), so simply adding the gradient for the condition y to the score of the reverse SDE gives conditional generation (equation 14). There is no need to retrain the unconditional model.
As an everyday analogy, the score is "a set of maps, one for each fog density, showing the direction to the summit (where data is likely)". Starting in thick fog (the noisy x(T)) and switching maps as the fog clears, one reaches the summit. The way of walking (SDE or ODE, with or without corrections) can be chosen separately from the maps.
Since the forward SDE has no learned parameters, with enough data and a sufficiently expressive network the encoding by the probability flow ODE (x(0)βx(T)) is uniquely determined by the data distribution alone. This differs from ordinary invertible models, whose encodings change with every training run.
Experimental results
Comparison of samplers (Table 1, CIFAR-10, FID. Same shading means the same computation. P1000/P2000: predictor only for 1000/2000 steps; C2000: corrector only for 2000 steps; PC1000: 1000 predictor steps + 1000 corrector steps)
SDE
Predictor
P1000
P2000
C2000
PC1000
VE (SMLD)
Ancestral sampling
4.98
4.88
20.43
3.62
VE (SMLD)
Reverse diffusion
4.79
4.74
20.43
3.60
VE (SMLD)
Probability flow
15.41
10.54
20.43
3.51
VP (DDPM)
Ancestral sampling
3.24
3.24
19.06
3.21
VP (DDPM)
Reverse diffusion
3.21
3.19
19.06
3.18
VP (DDPM)
Probability flow
3.59
3.23
19.06
3.06
Adding one corrector step to each predictor step (PC1000) doubles the computation, but gave better results than doubling the number of predictor steps (P2000). Corrector only (C2000) was much worse at the same computation.
Image quality (Table 3, unconditional generation on CIFAR-10)
Model
FID
IS
StyleGAN2-ADA
2.92
9.83
NCSN
25.32
8.87
DDPM
3.17
9.46
DDPM++ cont. (deep, VP)
2.41
9.68
NCSN++ cont. (VE)
2.38
9.83
NCSN++ cont. (deep, VE)
2.20
9.89
The best model achieved a better FID than even the best conditional model using labels (StyleGAN2-ADA, FID 2.42).
Likelihood (Table 2, CIFAR-10, negative log-likelihood on uniformly dequantized data, in bits per dimension; lower is better)
Model
NLL
Glow
3.35
Flow++
3.29
DDPM (variational bound)
β€ 3.70
DDPM (exact, via probability flow ODE)
3.28
DDPM cont. (VP)
3.21
DDPM cont. (sub-VP)
3.05
DDPM++ cont. (deep, sub-VP)
2.99
Even for the same DDPM model, computing exactly with the probability flow ODE gave a better value than the variational bound. The sub-VP SDE always gave better likelihoods than the VP SDE.
In addition, solving the probability flow ODE with a solver whose error tolerance can be adjusted reduced the number of score evaluations by more than 90% while maintaining image quality (Figure 3). The paper also shows generation of 1024 Γ 1024 CelebA-HQ images, and class-conditional generation, inpainting, and colorization with an unconditional model (Figure 4).
Practical notes
Keep the following points in mind when using Score SDE.
The choice of SDE shifts the balance between image quality and likelihood: in the paper, the VE SDE tended to give better image quality (FID), and the VP and sub-VP SDEs better likelihood. The best SDE depends on the data and the architecture, so several need to be tried.
Avoid the immediate neighborhood of t=0: the coefficients of the VE SDE are undefined at t=0, so the paper solves over tβ[Ο΅,1] (Ο΅=10β5).
Match the discretization for models trained in continuous time: for VP SDE models trained in continuous time, the paper used Euler-Maruyama as the predictor instead of the DDPM discretization. This is because the DDPM discretization mismatches the variance near tβ0, which degrades FID substantially.
Corrector hyperparameters: in predictor-corrector sampling, the step size of Langevin MCMC is set by the "signal-to-noise ratio" r. The paper uses r=0.16 for the VE SDE and searches for the value per dataset.
Generation with Score SDE is still slower than with GANs (Section 6 of the paper). Predictor-corrector improves image quality but doubles the number of score evaluations. It also adds more generation hyperparameters, such as the solver type, the number of steps, and the corrector step size, which must be tuned to the target quality and speed.
Comparison with other methods
Score SDE and closely related diffusion models are compared from the same viewpoints.
Method
Time
What is learned
Generation
Likelihood
SMLD (NCSN)
Discrete (N noise levels)
Score at each level
Langevin MCMC (corrector only, in Score SDE terms)
Deterministically skips steps (Euler method for an ODE)
β
Score SDE
Continuous
Score at time t
Choose from SDE solvers, predictor-corrector, probability flow ODE
Exact via probability flow ODE
Score SDE explains SMLD and DDPM within one framework and broadens both the generation methods and likelihood computation. What is learned (denoising at each noise level) is not very different from DDPM.
Rough guidelines for choosing:
To understand the theory of diffusion models in a unified way, or to try new generation methods: thinking in the Score SDE framework gives a clearer picture.
To evaluate the log-likelihood exactly: Score SDE, with its probability flow ODE, is a good fit.
To use a pretrained model quickly and cheaply: DDIM sampling is often sufficient.
To produce high-resolution images with little computation: combine with methods that diffuse in a latent space, such as Latent Diffusion.
PyTorch example
βΆShow code
python
import math
import torch
"""
A small implementation of Score SDE by Song et al. (2021), written with the VP SDE (eq. 11).
beta(t) = beta_min + t (beta_max - beta_min), beta_min = 0.1, beta_max = 20, t β [0, 1] (Appendix C).
Training is continuous-time denoising score matching (eq. 7); generation uses Euler-Maruyama for the reverse SDE and the probability flow ODE (eq. 13).
score_model(x, t) is a network that outputs the score from x and the continuous time t (NCSN++ / DDPM++ in the paper)
"""
beta_min, beta_max = 0.1, 20.0
eps_t = 1e-3 # small value to avoid the immediate neighborhood of t = 0 (1e-5 for the VE SDE in the paper)
def beta(t):
return beta_min + t * (beta_max - beta_min)
def marginal(t):
"""p_0t(x(t) | x(0)) = N(mean_coef * x(0), std^2 I) for the VP SDE"""
log_coef = -0.25 * t ** 2 * (beta_max - beta_min) - 0.5 * t * beta_min
mean_coef = torch.exp(log_coef)
std = torch.sqrt(1.0 - torch.exp(2.0 * log_coef))
return mean_coef, std
def score_matching_loss(score_model, x0):
"""Eq. 7: denoising score matching weighted by lambda(t) = std^2"""
t = torch.rand(x0.size(0), device=x0.device) * (1 - eps_t) + eps_t # t ~ U(eps, 1)
z = torch.randn_like(x0)
mean_coef, std = marginal(t)
mean_coef, std = mean_coef.view(-1, 1, 1, 1), std.view(-1, 1, 1, 1)
xt = mean_coef * x0 + std * z
score = score_model(xt, t)
# The target score is -z / std. Multiplying by lambda(t) = std^2 gives ||std * score + z||^2
return ((std * score + z) ** 2).flatten(1).sum(1).mean()
@torch.no_grad()
def reverse_sde_sample(score_model, shape, n_steps=1000, device="cpu"):
"""Solve the reverse SDE (eq. 6) from t = 1 to eps with Euler-Maruyama"""
x = torch.randn(shape, device=device) # x(T) ~ N(0, I) (prior of the VP SDE)
ts = torch.linspace(1.0, eps_t, n_steps, device=device)
dt = ts[0] - ts[1]
for t in ts:
tt = torch.full((shape[0],), t.item(), device=device)
b = beta(t)
drift = -0.5 * b * x - b * score_model(x, tt) # f - g^2 * score (f = -beta x / 2, g^2 = beta)
x = x - drift * dt + torch.sqrt(b * dt) * torch.randn_like(x)
return x
@torch.no_grad()
def probability_flow_sample(score_model, shape, n_steps=1000, device="cpu"):
"""Solve the probability flow ODE (eq. 13) with the Euler method. The only randomness is the initial x(T)"""
x = torch.randn(shape, device=device)
ts = torch.linspace(1.0, eps_t, n_steps, device=device)
dt = ts[0] - ts[1]
for t in ts:
tt = torch.full((shape[0],), t.item(), device=device)
b = beta(t)
drift = -0.5 * b * x - 0.5 * b * score_model(x, tt) # f - (1/2) g^2 * score
x = x - drift * dt
return x
# Usage (score_model is a network that takes x and t and returns a score of the same shape as x)
# loss = score_matching_loss(score_model, x0) # x0: a minibatch of images with pixels scaled to e.g. [-1, 1]
# score_model.eval()
# images = reverse_sde_sample(score_model, (16, 3, 32, 32))
FAQ
Q. What is the "score"?
A.
It is the derivative of the log probability density with respect to the data x, βxβlogp(x). It is a vector that points, at each point of the data space, in "the direction of higher probability". Because it does not depend on the normalizing constant, it is easier to learn than the probability density itself. Predicting the score of a noised image is the same as predicting the added noise, so DDPM training can also be viewed as score learning.
Q. How are Score SDE and DDPM related?
A.
DDPM's noising process is the VP SDE of Score SDE discretized into 1000 steps. DDPM training is equivalent to learning the score, and DDPM sampling corresponds to solving the reverse SDE with a particular discretization. Score SDE organized this relationship in continuous time and added new generation methods, such as predictor-corrector and the probability flow ODE, as well as exact likelihood computation.
Q. What are the benefits of the probability flow ODE?
A.
Because it generates without randomness, the noise x(T) and the image x(0) correspond one to one. This allows images to be encoded into latent variables for interpolation and editing. In addition, the log-likelihood can be computed exactly in the same way as for neural ODEs, and using solvers that adapt their step size automatically greatly reduces the number of score evaluations. DDIM sampling is also a relative of this ODE.