AI Logic

Architectures

Score SDE

Updated:

Architecture of Score SDE. The left side shows the flow that turns data x(0) into noise x(T) with the forward SDE and returns it with the reverse SDE that uses the score. The right side shows how the score at time t is learned, the three SDEs (VE, VP, and sub-VP), and the two ways of generating: predictor-corrector and the probability flow ODE

Background and overview

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)\boldsymbol{x}(t) at time t∈[0,T]t \in [0, T] evolves according to the following SDE (an Itô stochastic differential equation) (equation 5).

dx=f(x,t) dt+g(t) dwd\boldsymbol{x} = \boldsymbol{f}(\boldsymbol{x}, t)\,dt + g(t)\,d\boldsymbol{w}

f\boldsymbol{f} is the drift coefficient (change in a fixed direction), gg is the diffusion coefficient (noise strength), and w\boldsymbol{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)\boldsymbol{x}(0) is the data and x(T)\boldsymbol{x}(T) follows a tractable prior such as a normal distribution. The distribution of x(t)\boldsymbol{x}(t) at time tt is written pt(x)p_t(\boldsymbol{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β€‰βˆ‡xlog⁑pt(x)] dt+g(t) dwΛ‰d\boldsymbol{x} = \big[\boldsymbol{f}(\boldsymbol{x}, t) - g(t)^2\,\nabla_{\boldsymbol{x}} \log p_t(\boldsymbol{x})\big]\,dt + g(t)\,d\bar{\boldsymbol{w}}

wΛ‰\bar{\boldsymbol{w}} is a Wiener process running backward in time, and dtdt is a negative infinitesimal time step. βˆ‡xlog⁑pt(x)\nabla_{\boldsymbol{x}} \log p_t(\boldsymbol{x}) is called the score. Since the score points in "the direction of higher probability", the reverse SDE moves x\boldsymbol{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)\boldsymbol{x}(T).

Learning the score

The score is approximated by a time-dependent network sΞΈ(x,t)\boldsymbol{s}_\theta(\boldsymbol{x}, t). Training uses the following objective, which extends denoising score matching to continuous time (equation 7).

ΞΈβˆ—=arg⁑min⁑θ Et{Ξ»(t) Ex(0)Ex(t)∣x(0)[βˆ₯sΞΈ(x(t),t)βˆ’βˆ‡x(t)log⁑p0t(x(t)∣x(0))βˆ₯22]}\theta^* = \arg\min_\theta\ \mathbb{E}_t\Big\{\lambda(t)\,\mathbb{E}_{\boldsymbol{x}(0)}\mathbb{E}_{\boldsymbol{x}(t) \mid \boldsymbol{x}(0)}\Big[\big\|\boldsymbol{s}_\theta(\boldsymbol{x}(t), t) - \nabla_{\boldsymbol{x}(t)} \log p_{0t}(\boldsymbol{x}(t) \mid \boldsymbol{x}(0))\big\|_2^2\Big]\Big\}

tt is sampled uniformly from [0,T][0, T], and Ξ»(t)\lambda(t) is a positive weight. p0t(x(t)∣x(0))p_{0t}(\boldsymbol{x}(t) \mid \boldsymbol{x}(0)) is the distribution obtained by adding noise to x(0)\boldsymbol{x}(0) up to time tt; if f\boldsymbol{f} is affine in x\boldsymbol{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)\boldsymbol{s}_{\theta^*}(\boldsymbol{x}, t) equals the true score βˆ‡xlog⁑pt(x)\nabla_{\boldsymbol{x}} \log p_t(\boldsymbol{x}).

For example, for a normal distribution of the same form as DDPM, N(Ξ±Λ‰t x(0),(1βˆ’Ξ±Λ‰t)I)\mathcal{N}(\sqrt{\bar{\alpha}_t}\,\boldsymbol{x}(0), (1 - \bar{\alpha}_t)\boldsymbol{I}), the target score is βˆ’Ο΅/1βˆ’Ξ±Λ‰t-\boldsymbol{\epsilon}/\sqrt{1 - \bar{\alpha}_t}. In other words, predicting the score is the same as predicting the added noise Ο΅\boldsymbol{\epsilon}, and DDPM training is included in this form.

Three SDEs

The paper gives the following three concrete SDEs (Section 3.4).

SDEEquationOver timeDiscretization
VE SDE (variance exploding)dx=d[Οƒ2(t)]dt dwd\boldsymbol{x} = \sqrt{\frac{d[\sigma^2(t)]}{dt}}\,d\boldsymbol{w} (eq. 9)Variance keeps growingSMLD (NCSN)
VP SDE (variance preserving)dx=βˆ’12Ξ²(t)x dt+Ξ²(t) dwd\boldsymbol{x} = -\frac{1}{2}\beta(t)\boldsymbol{x}\,dt + \sqrt{\beta(t)}\,d\boldsymbol{w} (eq. 11)Stays at 1 if the data variance is 1DDPM
sub-VP SDEdx=βˆ’12Ξ²(t)x dt+Ξ²(t)(1βˆ’eβˆ’2∫0tΞ²(s) ds) dwd\boldsymbol{x} = -\frac{1}{2}\beta(t)\boldsymbol{x}\,dt + \sqrt{\beta(t)\big(1 - e^{-2\int_0^t \beta(s)\,ds}\big)}\,d\boldsymbol{w} (eq. 12)Variance always smaller than VPNewly proposed in the paper

In the experiments, Οƒ(t)\sigma(t) of the VE SDE is the limit of a geometric sequence starting at Οƒmin⁑=0.01\sigma_{\min} = 0.01, and Ξ²(t)\beta(t) of the VP SDE is a function that increases linearly from Ξ²Λ‰min⁑=0.1\bar{\beta}_{\min} = 0.1 to Ξ²Λ‰max⁑=20\bar{\beta}_{\max} = 20 (t∈[0,1]t \in [0, 1]) (Appendix C). The latter is the continuous-time version of DDPM's Ξ²\beta schedule (10βˆ’410^{-4} to 0.020.02 over 1000 steps).

Generation

The learned score defines the reverse SDE; x(T)\boldsymbol{x}(T) is drawn from the prior, and the SDE is solved numerically from t=Tt = T to 00. The paper presents the following three kinds of solvers (Section 4).

  1. 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.
  2. 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".
  3. Probability flow ODE: every diffusion process has a deterministic process with the same distribution ptp_t at each time, expressed by the following ordinary differential equation (equation 13).
dx=[f(x,t)βˆ’12g(t)2β€‰βˆ‡xlog⁑pt(x)] dtd\boldsymbol{x} = \Big[\boldsymbol{f}(\boldsymbol{x}, t) - \frac{1}{2}g(t)^2\,\nabla_{\boldsymbol{x}} \log p_t(\boldsymbol{x})\Big]\,dt

Since the probability flow ODE uses no randomness, x(0)\boldsymbol{x}(0) and x(T)\boldsymbol{x}(T) correspond one to one. This makes it possible to encode images into the latent variable x(T)\boldsymbol{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 tt 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 tt 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, βˆ‡xlog⁑pt(x∣y)=βˆ‡xlog⁑pt(x)+βˆ‡xlog⁑pt(y∣x)\nabla_{\boldsymbol{x}} \log p_t(\boldsymbol{x} \mid \boldsymbol{y}) = \nabla_{\boldsymbol{x}} \log p_t(\boldsymbol{x}) + \nabla_{\boldsymbol{x}} \log p_t(\boldsymbol{y} \mid \boldsymbol{x}), so simply adding the gradient for the condition y\boldsymbol{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)\boldsymbol{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)\boldsymbol{x}(0) \to \boldsymbol{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)

SDEPredictorP1000P2000C2000PC1000
VE (SMLD)Ancestral sampling4.984.8820.433.62
VE (SMLD)Reverse diffusion4.794.7420.433.60
VE (SMLD)Probability flow15.4110.5420.433.51
VP (DDPM)Ancestral sampling3.243.2419.063.21
VP (DDPM)Reverse diffusion3.213.1919.063.18
VP (DDPM)Probability flow3.593.2319.063.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)

ModelFIDIS
StyleGAN2-ADA2.929.83
NCSN25.328.87
DDPM3.179.46
DDPM++ cont. (deep, VP)2.419.68
NCSN++ cont. (VE)2.389.83
NCSN++ cont. (deep, VE)2.209.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)

ModelNLL
Glow3.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=0t = 0: the coefficients of the VE SDE are undefined at t=0t = 0, so the paper solves over t∈[Ο΅,1]t \in [\epsilon, 1] (Ο΅=10βˆ’5\epsilon = 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β†’0t \to 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" rr. The paper uses r=0.16r = 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.

MethodTimeWhat is learnedGenerationLikelihood
SMLD (NCSN)Discrete (NN noise levels)Score at each levelLangevin MCMC (corrector only, in Score SDE terms)Not computed
DDPMDiscrete (1000 steps)Added noise (equivalent to the score)Ancestral sampling stepping back one step at a time (predictor only)Variational bound
DDIMDiscrete (subsequence)Same as DDPMDeterministically skips steps (Euler method for an ODE)β€”
Score SDEContinuousScore at time ttChoose from SDE solvers, predictor-corrector, probability flow ODEExact 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\boldsymbol{x}, βˆ‡xlog⁑p(x)\nabla_{\boldsymbol{x}} \log p(\boldsymbol{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)\boldsymbol{x}(T) and the image x(0)\boldsymbol{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.

References

  1. Song, Y., Sohl-Dickstein, J., Kingma, D. P., Kumar, A., Ermon, S., & Poole, B. (2021). Score-Based Generative Modeling through Stochastic Differential Equations. ICLR 2021. arXiv:2011.13456.
  2. Ho, J., Jain, A., & Abbeel, P. (2020). Denoising Diffusion Probabilistic Models. NeurIPS 2020. arXiv:2006.11239.