26.6 Score Matching and Diffusion Models

We know how to turn Gaussian noise into data: integrate the reverse-time SDE or the probability-flow ODE. Both ask for one thing in return, the score ∇log⁡pt\nabla\log p_t of the noised data at every point they visit. For the two-mode mixture of the previous section a formula supplied it. Images come with samples and no formula. Here the samples are 4,096 draws from that mixture, standing in for a training set of images. We have to learn a field that we cannot evaluate at even a single point.

Fitting a density by maximum likelihood and differentiating it does not help, because a flexible density, the exponential of a network's output, needs a normalizing constant, an integral over all of space. Aapo Hyvärinen observed in 2005 that the score needs no normalizer, and that an integration by parts removes the unknown data score from the objective (Hyvärinen, 2005). Pascal Vincent noticed something simpler still (Vincent, 2011). The score of noised data is the average, over the clean points that could have produced a noisy point, of the direction back to the clean point. That direction is known for every training pair, so ordinary least squares learns the score from samples alone.

Diffusion models are trained this way: their standard loss, "predict the noise you added", is this regression with a particular weighting. Their two best-known samplers, DDPM and DDIM, bring no new equations either: each discretizes one we already have. A one-dimensional Gaussian turns each claim into a number we can check by hand before the mixture tests it.

No network is trained in this section. We learn the score at one noise level by least squares, with a model small enough to be solved exactly. The samplers are then analyzed on the exact score of the mixture, so that each error we measure is the sampler's own: first at a single noise level, which turns out not to be enough, then at all levels at once. Once, near the end, a sampler runs on scores fitted by least squares at every level. Networks and their errors are the business of Chapter 17, which builds on three results from here: Vincent's theorem, the identification of DDPM with the variance-preserving SDE of Section 26.4, and that of DDIM with Euler's method. The proof of Hyvärinen's identity and the subsection on guidance can be skipped on a first reading.

26.6.1 Learning the Score#

We want a vector field sθ\mathbf{s}_{\boldsymbol{\theta}}, in practice a network with dd inputs and dd outputs, that approximates the score of the data, and we can only draw samples. The first task is an objective that compares the model with the true field and that we can evaluate from samples.

26.6.1.1 A Normalizer-Free Objective#

A neural network defines a density most flexibly through an energy: an energy-based model is pθ(x)=e−Eθ(x)/Zθp_{\boldsymbol{\theta}}(\mathbf{x}) = e^{-E_{\boldsymbol{\theta}}(\mathbf{x})}/Z_{\boldsymbol{\theta}} with a network EθE_{\boldsymbol{\theta}} and the normalizer Zθ=∫e−Eθ(x) dxZ_{\boldsymbol{\theta}} = \int e^{-E_{\boldsymbol{\theta}}(\mathbf{x})}\, d\mathbf{x} (LeCun et al., 2006). Maximum likelihood needs ∇θlog⁡Zθ\nabla_{\boldsymbol{\theta}} \log Z_{\boldsymbol{\theta}}, a dd-dimensional integral that changes with every update of θ\boldsymbol{\theta}. The score in x\mathbf{x} does not see it: ZθZ_{\boldsymbol{\theta}} is a constant in x\mathbf{x}, so ∇xlog⁡pθ=−∇xEθ\nabla_{\mathbf{x}} \log p_{\boldsymbol{\theta}} = -\nabla_{\mathbf{x}} E_{\boldsymbol{\theta}}.

So we compare fields instead of densities. With ∇log⁡p\nabla\log p the score of the data, the explicit score-matching objective is the mean squared distance between the two fields, weighted by where the data are:

JESM(θ)=12 Ex∼p[ ∥sθ(x)−∇log⁡p(x)∥2].(26.6.1)J_{\mathrm{ESM}}(\boldsymbol{\theta}) = \tfrac{1}{2}\, \mathbb{E}_{\mathbf{x} \sim p} \left[\, \left\| \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}) - \nabla \log p(\mathbf{x}) \right\|^2 \right]. \tag{26.6.1}

It is zero exactly when the model field equals the data score wherever the data have mass. When sθ\mathbf{s}_{\boldsymbol{\theta}} is the score of a density qq, this is the Fisher divergence of Section 25.5.1, which also discusses what such a divergence can and cannot see. Here sθ\mathbf{s}_{\boldsymbol{\theta}} may be any vector field, because a network with dd outputs need not be the gradient of anything. The objective has removed the normalizer, but it still contains ∇log⁡p\nabla \log p, the one field we do not know. Hyvärinen's integration by parts removes it.

Proposition (Hyvärinen's identity). Let pp be a smooth positive density and sθ\mathbf{s}_{\boldsymbol{\theta}} a smooth vector field, with p(x) sθ(x)→0p(\mathbf{x})\, \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}) \to \mathbf{0} as ∥x∥→∞\|\mathbf{x}\| \to \infty and all the expectations below finite. Then

JESM(θ)=Ex∼p[ 12∥sθ(x)∥2+∇⋅sθ(x)]+C,(26.6.2)J_{\mathrm{ESM}}(\boldsymbol{\theta}) = \mathbb{E}_{\mathbf{x} \sim p} \left[\, \tfrac{1}{2} \| \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}) \|^2 + \nabla \cdot \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}) \right] + C, \tag{26.6.2}

where ∇⋅sθ=∑i∂si/∂xi\nabla \cdot \mathbf{s}_{\boldsymbol{\theta}} = \sum_i \partial s_i / \partial x_i is the divergence and C=12Ep∥∇log⁡p∥2C = \tfrac12\mathbb{E}_p\|\nabla\log p\|^2 does not depend on θ\boldsymbol{\theta}.

Proof. Expand the square in (26.6.1). The term 12E∥∇log⁡p∥2\tfrac12 \mathbb{E}\|\nabla \log p\|^2 is the constant CC, the term 12E∥sθ∥2\tfrac12 \mathbb{E}\|\mathbf{s}_{\boldsymbol{\theta}}\|^2 appears unchanged in (26.6.2), and it remains to transform the cross term. In one dimension,

−Ex∼p[sθ(x) (log⁡p)′(x)]=−∫sθ(x) p′(x)p(x) p(x) dx=−∫sθ(x) p′(x) dx,-\mathbb{E}_{x \sim p}\left[ s_{\boldsymbol{\theta}}(x)\, (\log p)'(x) \right] = -\int s_{\boldsymbol{\theta}}(x)\, \frac{p'(x)}{p(x)}\, p(x)\, dx = -\int s_{\boldsymbol{\theta}}(x)\, p'(x)\, dx,

and integrating by parts with the boundary term [sθ p]−∞∞=0\left[ s_{\boldsymbol{\theta}} \, p \right]_{-\infty}^{\infty} = 0 leaves +∫sθ′(x) p(x) dx=Ep[sθ′]+\int s_{\boldsymbol{\theta}}'(x)\, p(x)\, dx = \mathbb{E}_p[s_{\boldsymbol{\theta}}']. This is Stein's identity Ep[sθ′+sθ (log⁡p)′]=0\mathbb{E}_p[s_{\boldsymbol{\theta}}' + s_{\boldsymbol{\theta}}\, (\log p)'] = 0 of Section 25.5.2: the derivative has moved from the unknown density onto the model. In dd dimensions, apply the same step to each coordinate ii, with sis_i in place of sθs_{\boldsymbol{\theta}} and ∂ip\partial_i p in place of p′p', integrating over xix_i first; Fubini's theorem allows this under the stated integrability. Summed over ii, the cross term becomes Ep[∑i∂isi]=Ep[∇⋅sθ]\mathbb{E}_p[\sum_i \partial_i s_i] = \mathbb{E}_p[\nabla \cdot \mathbf{s}_{\boldsymbol{\theta}}]. ■\blacksquare

Every term on the right of (26.6.2) is an expectation under pp of something we can evaluate for a given model, so a sample average estimates it, with no ZθZ_{\boldsymbol{\theta}} and no ∇log⁡p\nabla \log p. The right-hand side is called implicit score matching.

A Gaussian shows that the identity works. Let the data be x∼N(0,v)x \sim \mathcal{N}(0, v), whose score is −x/v-x/v, and take the one-parameter model sw(x)=−x/ws_w(x) = -x/w. Then 12sw2+sw′=x2/(2w2)−1/w\tfrac12 s_w^2 + s_w' = x^2/(2w^2) - 1/w, so the implicit objective is J(w)=v/(2w2)−1/wJ(w) = v/(2w^2) - 1/w. Its derivative −v/w3+1/w2-v/w^3 + 1/w^2 vanishes at w=vw = v: the objective never saw the data score and still returns the variance. The constant agrees as well. At the minimum J(v)=−1/(2v)J(v) = -1/(2v), and C=12E[x2/v2]=1/(2v)C = \tfrac12\mathbb{E}[x^2/v^2] = 1/(2v), so the explicit objective is J(v)+C=0J(v) + C = 0 there, as it must be when the model matches the data.

In practice the expectation is a sample average. Let us replace vv in JJ by the mean of x2x^2 over 10,000 draws from N(0,2)\mathcal{N}(0, 2) and minimize over a grid of ww. The minimizer is then that sample mean, whose standard error is v2/104≈0.03v\sqrt{2/10^4} \approx 0.03, so we should see 22 give or take a few hundredths.

rng = np.random.default_rng()
v = 2.0
x = rng.normal(0.0, np.sqrt(v), 10000)        # data x ~ N(0, v)
w = np.linspace(0.5, 4.0, 701)                # model s_w(x) = -x / w
J_ism = (x**2).mean() / (2 * w**2) - 1 / w    # E[s_w^2 / 2 + s_w']
print(f'implicit score matching picks w = {w[J_ism.argmin()]:.2f}  (v = {v})')
implicit score matching picks w = 1.98  (v = 2.0)

We do. The two terms of (26.6.2) pull against each other, and the Gaussian shows how. The divergence term −1/w-1/w rewards a field that points inward at the samples, a sink where the data are, and rewards it more the steeper the sink. The squared norm x2/(2w2)x^2/(2w^2) stops the field from growing without bound. The balance sits at the true variance.

Implicit score matching has two limits. The proof needs the boundary term to vanish. For data on a bounded interval it does not, and the implicit objective then picks the wrong field. The second limit is cost. The divergence is the trace of the Jacobian, ∇⋅sθ=tr⁡ (∂sθ/∂x)\nabla \cdot \mathbf{s}_{\boldsymbol{\theta}} = \operatorname{tr}\, (\partial \mathbf{s}_{\boldsymbol{\theta}} / \partial \mathbf{x}). Computing it exactly takes one reverse-mode pass per row of the Jacobian, dd passes in all, and dd is in the millions for images. Hutchinson's estimator (Section 26.3.3) replaces the trace by one vector-Jacobian product per random direction, but it adds variance. Denoising score matching avoids the trace altogether.

26.6.1.2 Denoising Score Matching#

We want an objective without the trace, and we want the score where a sampler will need it, which includes points near but not on the data. Matching the score of noised data meets both requirements. Perturb each sample with Gaussian noise of scale σ\sigma:

x~=x+σϵ,ϵ∼N(0,I),pσ(x~∣x)=N(x~; x, σ2I).\begin{aligned} \tilde{\mathbf{x}} &= \mathbf{x} + \sigma \boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}), \\ p_\sigma(\tilde{\mathbf{x}} \mid \mathbf{x}) &= \mathcal{N}(\tilde{\mathbf{x}};\, \mathbf{x},\, \sigma^2 \mathbf{I}). \end{aligned}

The noised marginal pσ(x~)=∫pσ(x~∣x) p(x) dxp_\sigma(\tilde{\mathbf{x}}) = \int p_\sigma(\tilde{\mathbf{x}} \mid \mathbf{x})\, p(\mathbf{x})\, d\mathbf{x} is the data density blurred by a Gaussian, and it approaches pp as σ\sigma shrinks. Its score is as unknown as the data score. The score of the conditional, however, follows from the logarithm of a Gaussian density:

∇x~log⁡pσ(x~∣x)=x−x~σ2=−ϵσ.(26.6.3)\nabla_{\tilde{\mathbf{x}}} \log p_\sigma(\tilde{\mathbf{x}} \mid \mathbf{x}) = \frac{\mathbf{x} - \tilde{\mathbf{x}}}{\sigma^2} = -\frac{\boldsymbol{\epsilon}}{\sigma}. \tag{26.6.3}

This vector points from the noisy observation back to the clean sample that produced it, and we know it for every pair we generate. Denoising score matching (DSM) uses it as a regression target:

JDSM(θ)=12 Ex∼p, x~∼pσ(⋅∣x)[ ∥sθ(x~)−∇x~log⁡pσ(x~∣x)∥2].(26.6.4)\begin{aligned} J_{\mathrm{DSM}}(\boldsymbol{\theta}) &= \tfrac12\,\mathbb{E}_{\mathbf{x} \sim p,\ \tilde{\mathbf{x}} \sim p_\sigma(\cdot \mid \mathbf{x})} \\ &\quad \left[\, \left\| \mathbf{s}_{\boldsymbol{\theta}}(\tilde{\mathbf{x}}) - \nabla_{\tilde{\mathbf{x}}} \log p_\sigma(\tilde{\mathbf{x}} \mid \mathbf{x}) \right\|^2 \right]. \end{aligned} \tag{26.6.4}

The loss asks the network to predict, from the noisy point alone, the direction back to a clean point that it cannot see. The target depends on the clean point, while the score we want depends only on the noisy one. Least squares connects the two, because it fits the target's conditional mean. The following lemma states that fact. It is elementary, and this section and the next both rest on it; the next applies it to a velocity.

Lemma (regression to the conditional mean). Let (X,Y)(X, Y) be jointly distributed with E∥Y∥2<∞\mathbb{E}\|Y\|^2 \lt \infty, and let m(X)=E[Y∣X]\mathbf{m}(X) = \mathbb{E}[Y \mid X]. Then for every measurable v\mathbf{v} with E∥v(X)∥2<∞\mathbb{E}\|\mathbf{v}(X)\|^2 \lt \infty,

E∥v(X)−Y∥2=E∥v(X)−m(X)∥2+E∥Y−m(X)∥2.(26.6.5)\mathbb{E} \left\| \mathbf{v}(X) - Y \right\|^2 = \mathbb{E} \left\| \mathbf{v}(X) - \mathbf{m}(X) \right\|^2 + \mathbb{E} \left\| Y - \mathbf{m}(X) \right\|^2. \tag{26.6.5}

The second term does not involve v\mathbf{v}: minimizing a least-squares loss against the noisy target YY is the same problem as minimizing it against the conditional mean m(X)\mathbf{m}(X), up to an additive constant.

Proof. Insert ±m(X)\pm\mathbf{m}(X) and expand. The cross term is 2 E[(v(X)−m(X))⊤(m(X)−Y)]2\, \mathbb{E}\left[ (\mathbf{v}(X) - \mathbf{m}(X))^\top (\mathbf{m}(X) - Y) \right]. By the tower rule E[Z]=E[E[Z∣X]]\mathbb{E}[Z] = \mathbb{E}[\mathbb{E}[Z \mid X]] (Section 24.2) we may first average over YY with XX fixed, and E[m(X)−Y∣X]=0\mathbb{E}[\mathbf{m}(X) - Y \mid X] = \mathbf{0} makes the cross term vanish. ■\blacksquare

Proposition (Vincent's theorem). Let the noising kernel pσ(x~∣x)p_\sigma(\tilde{\mathbf{x}} \mid \mathbf{x}) be differentiable in x~\tilde{\mathbf{x}}, with gradient and integral over x\mathbf{x} interchangeable (both hold for the Gaussian kernel), and let the DSM target and sθ(x~)\mathbf{s}_{\boldsymbol{\theta}}(\tilde{\mathbf{x}}) have finite second moments. Then

JDSM(θ)=12 Ex~∼pσ[ ∥sθ(x~)−∇log⁡pσ(x~)∥2]+C,J_{\mathrm{DSM}}(\boldsymbol{\theta}) = \tfrac12\,\mathbb{E}_{\tilde{\mathbf{x}} \sim p_\sigma} \left[\, \left\| \mathbf{s}_{\boldsymbol{\theta}}(\tilde{\mathbf{x}}) - \nabla \log p_\sigma(\tilde{\mathbf{x}}) \right\|^2 \right] + C,

with CC independent of θ\boldsymbol{\theta}. The right-hand side is the explicit objective (26.6.1) for pσp_\sigma, so denoising and explicit score matching on the noised data have the same minimizers and the same gradients.

Proof. Apply the lemma with X=x~X = \tilde{\mathbf{x}} and Y=∇x~log⁡pσ(x~∣x)Y = \nabla_{\tilde{\mathbf{x}}} \log p_\sigma(\tilde{\mathbf{x}} \mid \mathbf{x}). It remains to identify the conditional mean of YY, and the identification is the content of the theorem: the marginal score is the posterior mean of the conditional scores. Writing the posterior p(x∣x~)p(\mathbf{x} \mid \tilde{\mathbf{x}}) by Bayes' rule and then exchanging gradient and integral,

E[Y∣x~]=∫∇x~ pσ(x~∣x)pσ(x~∣x)  pσ(x~∣x) p(x)pσ(x~) dx=∇x~∫pσ(x~∣x) p(x) dxpσ(x~)=∇log⁡pσ(x~).\begin{aligned} \mathbb{E}\left[ Y \mid \tilde{\mathbf{x}} \right] &= \int \frac{\nabla_{\tilde{\mathbf{x}}}\, p_\sigma(\tilde{\mathbf{x}} \mid \mathbf{x})}{p_\sigma(\tilde{\mathbf{x}} \mid \mathbf{x})} \; \frac{p_\sigma(\tilde{\mathbf{x}} \mid \mathbf{x})\, p(\mathbf{x})}{p_\sigma(\tilde{\mathbf{x}})}\, d\mathbf{x} \\ &= \frac{\nabla_{\tilde{\mathbf{x}}} \int p_\sigma(\tilde{\mathbf{x}} \mid \mathbf{x})\, p(\mathbf{x})\, d\mathbf{x}}{p_\sigma(\tilde{\mathbf{x}})} = \nabla \log p_\sigma(\tilde{\mathbf{x}}). \end{aligned}

■\blacksquare

The proof used no property of the Gaussian beyond differentiability, and none of the data distribution: for a finite training set the integral is a sum, and the theorem returns the score of the blurred training set. That has a sobering consequence. A network that reached the minimum at every noise level, and a sampler that followed its score without error, would return the training points and nothing else (Exercise 3 takes the limit σ→0\sigma\to0). A model that produces new samples therefore owes them to a regression that stops short of its minimum, not to the objective; Section 17.10 lists what is known about when it does. Gaussian noise is chosen because its conditional score (26.6.3) is the noise itself, scaled by −1/σ-1/\sigma. Predicting the score and predicting the noise ϵ\boldsymbol{\epsilon} are therefore the same task, and a network ϵθ\boldsymbol{\epsilon}_{\boldsymbol{\theta}} that predicts the noise defines the score model sθ=−ϵθ/σ\mathbf{s}_{\boldsymbol{\theta}} = -\boldsymbol{\epsilon}_{\boldsymbol{\theta}}/\sigma. This noise-prediction form is the one diffusion models use.

Example: the Gaussian. Let the data be x∼N(0,v)x \sim \mathcal{N}(0, v) again, noised at level σ\sigma. The noised marginal is pσ=N(0,v+σ2)p_\sigma = \mathcal{N}(0, v + \sigma^2), with score −x~/(v+σ2)-\tilde x/(v + \sigma^2). Bayes' rule for two Gaussians gives the posterior of the clean point,

x∣x~  ∼  N(vv+σ2 x~, vσ2v+σ2),x \mid \tilde x \;\sim\; \mathcal{N}\Big(\frac{v}{v + \sigma^2}\,\tilde x,\ \frac{v \sigma^2}{v + \sigma^2}\Big),

a shrinkage of the noisy point toward the data mean, with a spread that does not depend on x~\tilde x. Every claim of this subsection becomes a formula. The conditional mean of the target Y=(x−x~)/σ2Y = (x - \tilde x)/\sigma^2 is (vv+σ2−1)x~/σ2=−x~/(v+σ2)\big(\tfrac{v}{v + \sigma^2} - 1\big)\tilde x/\sigma^2 = -\tilde x/(v + \sigma^2), the marginal score, as Vincent's theorem says. The best possible mean squared error, the second term of (26.6.5), is the posterior variance of the target, Var(x∣x~)/σ4=1σ2−1v+σ2\textrm{Var}(x \mid \tilde x)/\sigma^4 = \tfrac{1}{\sigma^2} - \tfrac{1}{v + \sigma^2}. With v=1v = 1 and σ=0.5\sigma = 0.5 the floor is 4−0.8=3.24 - 0.8 = 3.2, and the posterior mean of the clean point is 0.8 x~0.8\,\tilde x. A Monte Carlo run on 100,000 pairs checks both numbers.

x, eps = rng.standard_normal((2, 100000))             # v = 1
xt, y = x + 0.5 * eps, -eps / 0.5                      # sigma = 0.5; DSM target y
print(f'mean squared error of the conditional mean -xt/1.25: {((y + xt / 1.25)**2).mean():.3f}'
      '  (floor 3.2)')
print(f'least-squares slope of x on xt: {(xt * x).mean() / (xt**2).mean():.3f}  (0.8)')
mean squared error of the conditional mean -xt/1.25: 3.186  (floor 3.2)
least-squares slope of x on xt: 0.800  (0.8)

The best regression function has mean squared error 3.23.2 on the targets, not 00, because many clean points explain one noisy point and the regression can only return their average. Here a loss of 3.23.2 is a perfect fit, and a loss of zero is impossible. The slope 0.800.80 is the shrinkage factor v/(v+σ2)v/(v+\sigma^2). Neither observation is special to the Gaussian.

The slope is an instance of Tweedie's formula, which Robbins published and credited to Tweedie (Robbins, 1956; Efron, 2011). Rearranging Vincent's identity E[(x−x~)/σ2∣x~]=∇log⁡pσ(x~)\mathbb{E}[(\mathbf{x} - \tilde{\mathbf{x}})/\sigma^2 \mid \tilde{\mathbf{x}}] = \nabla \log p_\sigma(\tilde{\mathbf{x}}) gives

E[x∣x~]=x~+σ2 ∇log⁡pσ(x~).(26.6.6)\mathbb{E}[\mathbf{x} \mid \tilde{\mathbf{x}}] = \tilde{\mathbf{x}} + \sigma^2\, \nabla \log p_\sigma(\tilde{\mathbf{x}}). \tag{26.6.6}

The best denoiser under squared error moves the noisy point one step of size σ2\sigma^2 up the score of the noised data (Figure 26.6.1). For the Gaussian it reads x~−σ2x~/(v+σ2)=0.8 x~\tilde x - \sigma^2 \tilde x/(v + \sigma^2) = 0.8\,\tilde x, the slope just measured.

Figure 26.6.1:

Tweedie's formula for the mixture 12N(−2,0.52)+12N(2,0.52)\tfrac12\mathcal{N}(-2, 0.5^2) + \tfrac12\mathcal{N}(2, 0.5^2) noised at σ=0.5\sigma = 0.5. A noisy observation x~\tilde{x} lies in the low-density valley of the noised density pσp_\sigma. The posterior of the clean point is bimodal but asymmetric, and the step x~+σ2∇log⁡pσ(x~)\tilde{x} + \sigma^2 \nabla \log p_\sigma(\tilde{x}) lands on its mean x^0=E[x∣x~]\hat{x}_0 = \mathbb{E}[x \mid \tilde{x}], the optimal denoiser.

The floor is general as well. At the optimum the mean squared error 2JDSM2J_{\mathrm{DSM}} equals E∥Y−m(X)∥2\mathbb{E}\|Y - \mathbf{m}(X)\|^2, the average posterior variance of the target and the Bayes risk of the regression. To compute it, apply the lemma (26.6.5) to the field v=0\mathbf{v} = \mathbf{0}, which gives E∥Y∥2=E∥m(X)∥2+E∥Y−m(X)∥2\mathbb{E}\|Y\|^2 = \mathbb{E}\|\mathbf{m}(X)\|^2 + \mathbb{E}\|Y - \mathbf{m}(X)\|^2. The target Y=−ϵ/σY = -\boldsymbol{\epsilon}/\sigma has E∥Y∥2=d/σ2\mathbb{E}\|Y\|^2 = d/\sigma^2 in dd dimensions, and its conditional mean is the score, so

E∥Y−∇log⁡pσ(x~)∥2=dσ2−Ex~∼pσ∥∇log⁡pσ(x~)∥2.(26.6.7)\mathbb{E}\left\| Y - \nabla \log p_\sigma(\tilde{\mathbf{x}}) \right\|^2 = \frac{d}{\sigma^2} - \mathbb{E}_{\tilde{\mathbf{x}} \sim p_\sigma} \left\| \nabla \log p_\sigma(\tilde{\mathbf{x}}) \right\|^2 . \tag{26.6.7}

For the Gaussian this is 1σ2−1v+σ2\tfrac{1}{\sigma^2} - \tfrac{1}{v + \sigma^2} again. An observed loss also contains the fit's own error, so it should be compared with this floor, not with zero.

The floor also says what goes wrong at a very small noise level. For data with a smooth density it grows like d/σ2d/\sigma^2 as σ→0\sigma \to 0. The target −ϵ/σ-\boldsymbol{\epsilon}/\sigma becomes large, while the score it averages to keeps a finite mean square. A single small noise level therefore gives a poorly conditioned regression, whose targets are mostly noise.

Tweedie's formula says where the best denoiser sends a noisy point. Differentiating it once more says how fast that answer changes with the noisy point, and this turns out to limit how sharply a noised density can curve. We need the bound only once, in the last subsection, where a sampler is steered toward a class, but the proof takes a few lines here, while the posterior is in front of us.

Proposition (curvature of a noised density). For any data distribution and any σ>0\sigma > 0,

∇2log⁡pσ(x~)=−Iσ2+1σ4 Cov[x∣x~],(26.6.8)\nabla^2 \log p_\sigma(\tilde{\mathbf{x}}) = -\frac{\mathbf{I}}{\sigma^2} + \frac{1}{\sigma^4}\, \textrm{Cov}\left[ \mathbf{x} \mid \tilde{\mathbf{x}} \right], \tag{26.6.8}

so no eigenvalue of −∇2log⁡pσ-\nabla^2 \log p_\sigma exceeds 1/σ21/\sigma^2.

Proof. By Tweedie's formula (26.6.6), ∇log⁡pσ(x~)=(E[x∣x~]−x~)/σ2\nabla \log p_\sigma(\tilde{\mathbf{x}}) = (\mathbb{E}[\mathbf{x} \mid \tilde{\mathbf{x}}] - \tilde{\mathbf{x}})/\sigma^2, so it remains to differentiate the posterior mean E[x∣x~]=∫x p(x∣x~) dx\mathbb{E}[\mathbf{x} \mid \tilde{\mathbf{x}}] = \int \mathbf{x}\, p(\mathbf{x} \mid \tilde{\mathbf{x}})\, d\mathbf{x}. The posterior depends on x~\tilde{\mathbf{x}} through Bayes' rule, which gives ∇x~log⁡p(x∣x~)=∇x~log⁡pσ(x~∣x)−∇log⁡pσ(x~)=(x−E[x∣x~])/σ2\nabla_{\tilde{\mathbf{x}}} \log p(\mathbf{x} \mid \tilde{\mathbf{x}}) = \nabla_{\tilde{\mathbf{x}}} \log p_\sigma(\tilde{\mathbf{x}} \mid \mathbf{x}) - \nabla \log p_\sigma(\tilde{\mathbf{x}}) = (\mathbf{x} - \mathbb{E}[\mathbf{x} \mid \tilde{\mathbf{x}}])/\sigma^2. Differentiating under the integral with ∇p=p ∇log⁡p\nabla p = p\, \nabla \log p, the Jacobian of the posterior mean is

∫x (x−E[x∣x~])⊤σ2 p(x∣x~) dx=1σ2 Cov[x∣x~].\int \mathbf{x}\, \frac{(\mathbf{x} - \mathbb{E}[\mathbf{x} \mid \tilde{\mathbf{x}}])^\top}{\sigma^2}\, p(\mathbf{x} \mid \tilde{\mathbf{x}})\, d\mathbf{x} = \frac{1}{\sigma^2}\, \textrm{Cov}\left[ \mathbf{x} \mid \tilde{\mathbf{x}} \right].

Subtracting the Jacobian I\mathbf{I} of x~\tilde{\mathbf{x}} and dividing by σ2\sigma^2 gives (26.6.8). A covariance is positive semidefinite, which gives the bound. ■\blacksquare

A noised density cannot curve more sharply than its own noise: none of its peaks is narrower than the Gaussian that blurred it. For Gaussian data the right-hand side of (26.6.8) is −1σ2+vσ2(v+σ2)=−1v+σ2-\tfrac{1}{\sigma^2} + \tfrac{v}{\sigma^2 (v + \sigma^2)} = -\tfrac{1}{v + \sigma^2}, the curvature of log⁡N(0,v+σ2)\log \mathcal{N}(0, v + \sigma^2), as it should be.

26.6.1.3 A Least-Squares Score in One Dimension#

The Gaussian has a linear score, which a one-parameter model can represent. Does least squares on noisy pairs also recover a curved score? The data are the mixture of the previous section, p=12N(−2,0.52)+12N(2,0.52)p = \tfrac12 \mathcal{N}(-2, 0.5^2) + \tfrac12 \mathcal{N}(2, 0.5^2), noised at σ=0.5\sigma = 0.5. Noising adds σ2\sigma^2 to each component's variance, so pσp_\sigma is again a mixture, with component variance 0.25+0.25=0.50.25 + 0.25 = 0.5. As derived in Section 26.5.3, a symmetric mixture with means ±μ\pm\mu and common component variance vv has the score (μtanh⁡(μx/v)−x)/v(\mu \tanh(\mu x/v) - x)/v. With μ=2\mu = 2 and v=0.5v = 0.5 the target curve is

∇log⁡pσ(x~)=4tanh⁡(4x~)−2x~.\nabla \log p_\sigma(\tilde x) = 4 \tanh(4 \tilde x) - 2 \tilde x .

Near each mode it is close to −(x~∓2)/0.5-(\tilde x \mp 2)/0.5, the linear score of a single component. Between the modes it rises from about −2.9-2.9 at x~=−0.45\tilde x = -0.45 to +2.9+2.9 at x~=0.45\tilde x = 0.45, pushing points out of the valley.

The model is not a network. It is a linear combination of 17 fixed features, sixteen Gaussian bumps of width 0.60.6 centered on [−4.5,4.5][-4.5, 4.5] plus the identity xx. We choose it because fitting the DSM loss (26.6.4) is then ordinary least squares on the pairs (x~,−ϵ/σ)(\tilde x, -\epsilon/\sigma), which np.linalg.lstsq solves exactly: any gap between the fit and the score is sampling error, with no optimizer to blame. Noise costs nothing to draw, so each of the 4,096 clean points is noised four times. We fit the model on these 16,384 pairs, compare it with the analytic score, and evaluate both far outside the data, at x=8x = 8. The printed mean squared errors are 2JDSM2J_{\mathrm{DSM}}, the quantity the regression lemma splits.

n, sigma = 4096, 0.5
def mixture_score(q, var, means=(-2.0, 2.0), ws=(0.5, 0.5)):   # analytic score, any level
    logw = np.stack([np.log(w) - (q - mu)**2 / (2 * var) for mu, w in zip(means, ws)])
    r = np.exp(logw - logw.max(0))                              # responsibilities, stable softmax
    return (r * np.stack([(mu - q) / var for mu in means])).sum(0) / r.sum(0)
def noisy_pairs(n, rng):                                        # n points of p, four noisings each
    x = np.repeat(rng.normal(4.0 * rng.integers(0, 2, n) - 2.0, 0.5), 4)   # x ~ p, the mixture
    eps = rng.standard_normal(x.size)
    return x + sigma * eps, -eps / sigma                        # the (input, target) pairs
centers = np.linspace(-4.5, 4.5, 16)
def features(q):                                                # identity + 16 bumps, width 0.6
    return np.column_stack([q, np.exp(-(q[:, None] - centers)**2 / 0.72)])
def fit(xt, y):                                                 # least squares = the regression
    return np.linalg.lstsq(features(xt), y, rcond=None)[0]
xt, y = noisy_pairs(n, rng)
w_ls = fit(xt, y)
s_hat = lambda q: features(q) @ w_ls
g = np.linspace(-8, 8, 16001); dg = g[1] - g[0]
p_sigma = 0.5 * (np.exp(-(g + 2)**2) + np.exp(-(g - 2)**2)) / np.sqrt(np.pi)  # var 0.5 each
floor = 1 / sigma**2 - (p_sigma * mixture_score(g, 0.5)**2).sum() * dg
excess = (p_sigma * (s_hat(g) - mixture_score(g, 0.5))**2).sum() * dg
print(f'mean squared error: fit {((s_hat(xt) - y)**2).mean():.2f}, exact score '
      f'{((mixture_score(xt, 0.5) - y)**2).mean():.2f}, population floor {floor:.2f}')
print(f'excess risk {excess:.3f}; fit at x = 8: {s_hat(np.array([8.0]))[0]:+.1f}, '
      f'exact score {4 * np.tanh(32) - 16:.0f} (no pairs there)')
grid = np.linspace(-4, 4, 201)
d2l.plot([xt[:600], grid, grid], [y[:600], 4 * np.tanh(4 * grid) - 2 * grid, s_hat(grid)],
         'noisy input', 'target and score', fmts=('.', '-', '--'),
         legend=['pairs', 'score of p_sigma', 'least-squares fit'], figsize=(5.5, 3))
mean squared error: fit 2.10, exact score 2.11, population floor 2.11
excess risk 0.012; fit at x = 8: +1.6, exact score -12 (no pairs there)

The plot shows all that the regression sees: a cloud of targets −ϵ/σ-\epsilon/\sigma that spreads over several units at every x~\tilde x. Through the cloud runs its conditional mean, the score of pσp_\sigma, and the least-squares fit lies on it. The printout follows the regression lemma. The population floor (26.6.7), here 1σ2−Epσ(∇log⁡pσ)2\tfrac{1}{\sigma^2} - \mathbb{E}_{p_\sigma}(\nabla\log p_\sigma)^2 computed by quadrature, is 2.112.11. It is the mean squared vertical spread of the cloud around the curve. The fit and the exact score both print a mean squared error within a tenth of this floor, and they agree with each other to about a hundredth. Neither need land on 2.112.11, because each is an average over one sample of pairs, and such an average moves from one sample to the next. What separates the fit from the score is the excess risk, the first term of the lemma. It is around 0.010.01, under one percent of the floor.

The last number shows the limit of the method. No noisy pair lands beyond ∣x~∣≈5|\tilde x| \approx 5, so at x=8x = 8 the fit is whatever the basis extrapolates to. The printed value may fall near the exact −12-12 or far from it, and one fit cannot tell us which to expect. Let us therefore repeat the experiment twenty times, each time with fresh data and fresh noise. We record the exact score's mean squared error, to see how far one sample moves it, and the fit at two points: at x=1x = 1, on the flank of the right mode, where pairs are plentiful, and at x=8x = 8, where there are none.

runs = [noisy_pairs(n, rng) for _ in range(20)]                 # 20 fresh draws of data and noise
errs = np.array([((mixture_score(xt_r, 0.5) - y_r)**2).mean() for xt_r, y_r in runs])
W = np.array([fit(xt_r, y_r) for xt_r, y_r in runs])            # (20, 17) fitted weights
print(f'exact score over 20 draws: mean squared error {errs.mean():.2f}, sd {errs.std():.3f}')
for q in (1.0, 8.0):
    s_q = W @ features(np.array([q]))[0]
    print(f'fit at x = {q:.0f} over 20 draws: from {s_q.min():+.1f} to {s_q.max():+.1f} '
          f'(exact score {4 * np.tanh(4 * q) - 2 * q:+.1f})')
exact score over 20 draws: mean squared error 2.12, sd 0.047
fit at x = 1 over 20 draws: from +1.9 to +2.1 (exact score +2.0)
fit at x = 8 over 20 draws: from -12.6 to +27.0 (exact score -12.0)

Over the twenty draws the exact score's mean squared error has a standard deviation of 0.030.03 to 0.050.05. One sample of pairs therefore gives the floor to a few hundredths and no better (Exercise 3 obtains the same figure from a single sample). At x=1x = 1 the twenty fits stay within about two tenths of the exact score +2.0+2.0. At x=8x = 8 they are spread over tens of units and take both signs: in some draws the fitted score is positive and points away from the data. The regression has no opinion about a place where it saw no pairs, and it returns a number there all the same. Least squares constrains the fit only where pairs fall, so a sampler that starts far from the data meets an arbitrary field there.

26.6.2 Sampling with a Score#

The samplers of the previous section need the score at every noise level of a forward process. With the score at one level only, or the exact score of pp itself, we can still draw samples, by a method that needs no forward process at all. It carries the name of Paul Langevin, who in 1908 described a particle in a fluid by a force plus random kicks.

26.6.2.1 Langevin Dynamics#

Picture a particle that drifts uphill on the log-density and is jostled by noise. The drift pulls it toward high density, and the noise keeps it from collapsing onto a mode. Langevin dynamics is the SDE

dX=12∇log⁡p(X) dt+dW,(26.6.9)d\mathbf{X} = \tfrac{1}{2} \nabla \log p(\mathbf{X})\, dt + d\mathbf{W}, \tag{26.6.9}

whose drift is half the score and whose noise is a standard Brownian motion W\mathbf{W}. The claim is that pp is its stationary law.

For the Gaussian p=N(0,v)p = \mathcal{N}(0, v), with score −x/v-x/v, we already know this. Then (26.6.9) reads dX=−X2v dt+dWdX = -\tfrac{X}{2v}\, dt + dW, an Ornstein–Uhlenbeck process. An OU process dX=−θX dt+g dWdX = -\theta X\, dt + g\, dW has the stationary law N(0,g2/(2θ))\mathcal{N}(0, g^2/(2\theta)) (Section 26.4.3), and here θ=1/(2v)\theta = 1/(2v) and g=1g = 1 give the variance vv. The proposition extends this to smooth targets whose score grows at most linearly.

Proposition (stationarity). Let pp be a smooth positive density whose score ∇log⁡p\nabla \log p is locally Lipschitz and grows at most linearly, so that (26.6.9) has a unique solution that does not explode and its Fokker–Planck equation has a unique solution for each initial density. If X0∼p\mathbf{X}_0 \sim p, then Xt∼p\mathbf{X}_t \sim p for all t≥0t \ge 0.

Proof. For an SDE dX=b dt+dWd\mathbf{X} = \mathbf{b}\, dt + d\mathbf{W} with unit diffusion, the density qtq_t of Xt\mathbf{X}_t solves the Fokker–Planck equation ∂tq=−∇⋅(q b)+12Δq\partial_t q = -\nabla \cdot (q\, \mathbf{b}) + \tfrac12 \Delta q (Section 26.5.2). Substitute b=12∇log⁡p\mathbf{b} = \tfrac12 \nabla \log p and q=pq = p, and use p ∇log⁡p=∇pp\, \nabla \log p = \nabla p:

−∇⋅(12 p ∇log⁡p)+12Δp=−12∇⋅(∇p)+12Δp=0.-\nabla \cdot \left( \tfrac{1}{2}\, p\, \nabla \log p \right) + \tfrac{1}{2} \Delta p = -\tfrac{1}{2} \nabla \cdot (\nabla p) + \tfrac{1}{2} \Delta p = 0.

So qt≡pq_t \equiv p solves the equation with the initial density pp. Uniqueness turns "pp solves the equation" into "the law of Xt\mathbf{X}_t is pp". ■\blacksquare

The drift transports mass up the log-density at exactly the rate at which the noise spreads it out. Stationarity says nothing yet about a chain started elsewhere, and a sampler always starts elsewhere. For targets like those of the proposition, smooth and positive with a score that grows at most linearly, the law of Xt\mathbf{X}_t does converge to pp from every starting point (Roberts and Tweedie, 1996). We do not prove it. How long the convergence takes is another matter, and the experiment below measures it.

To sample, we discretize. The Euler–Maruyama step of (26.6.9) with step hh is the Langevin sampler

x←x+h2 s(x)+h ξ,ξ∼N(0,I),\mathbf{x} \leftarrow \mathbf{x} + \tfrac{h}{2}\, \mathbf{s}(\mathbf{x}) + \sqrt{h}\, \boldsymbol{\xi}, \qquad \boldsymbol{\xi} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}),

which needs only a score s\mathbf{s}, exact or learned. The discretized chain does not inherit the stationarity of the SDE. For the Gaussian the step is the linear recursion x←(1−h2v) x+h ξx \leftarrow (1 - \tfrac{h}{2v})\, x + \sqrt{h}\, \xi, whose stationary variance VV solves V=(1−h2v)2V+hV = (1 - \tfrac{h}{2v})^2 V + h. Hence V=v/(1−h/(4v))V = v/(1 - h/(4v)), and the sampler overstates the variance by about h/4h/4 (Exercise 1 measures this).

A Gaussian has one mode, and one mode hides the difficulty. Let us give the sampler the lopsided mixture of Section 26.5.5, p=0.8 N(−2,0.52)+0.2 N(2,0.52)p = 0.8\, \mathcal{N}(-2, 0.5^2) + 0.2\, \mathcal{N}(2, 0.5^2), and let us give it the exact score of pp, not a fit, so that whatever goes wrong is the sampler's doing. A fifth of the mass of pp lies right of zero, and EX2=4+0.25=4.25\mathbb{E}X^2 = 4 + 0.25 = 4.25 whatever the weights. We run 10,000 chains for 2,000 steps of size h=0.01h = 0.01, three times: from a broad start N(0,32)\mathcal{N}(0, 3^2), from the left mean, and from the right mean. Before reading the output, guess what fraction of the broad start ends right of zero, and how many chains started in one mode end in the other.

def langevin(q, h, steps, var=0.25, ws=(0.8, 0.2)):   # var: component variance of p
    for _ in range(steps):
        xi = rng.standard_normal(q.shape)
        q = q + 0.5 * h * mixture_score(q, var, ws=ws) + np.sqrt(h) * xi
    return q
warm = langevin(rng.normal(0.0, 3.0, 10000), 0.01, 2000)
print(f'broad start: P(X > 0) = {(warm > 0).mean():.3f}, '
      f'E[X^2] = {(warm**2).mean():.2f}  (truth 0.2, 4.25)')
for start, w in ((-2.0, 0.8), (2.0, 0.2)):              # every chain in one mode
    q = langevin(np.full(10000, start), 0.01, 2000)
    print(f'all chains at {start:+.0f} (weight {w}): '
          f'{(np.sign(q) != np.sign(start)).mean():.3f} end on the other side')
broad start: P(X > 0) = 0.476, E[X^2] = 4.23  (truth 0.2, 4.25)
all chains at -2 (weight 0.8): 0.005 end on the other side
all chains at +2 (weight 0.2): 0.020 end on the other side

Of the 10,000 chains started in the heavy mode, about one in two hundred has ended on the other side. Of those started in the light mode, about one in forty or fifty has. In the valley the density is tiny and the drift points back to the mode the chain came from. Crossing needs a rare run of noise in one direction, and the waiting time grows exponentially with the height of the barrier in −log⁡p-\log p.

The two fractions differ, as they should. In equilibrium as much mass flows from left to right as from right to left, so the light mode, with a quarter of the heavy mode's mass, must give up its chains four times as readily. The sampler has its rates in about the right ratio. They are far too small. A system with two states forgets its initial proportions at the sum of its two rates, and the two printed fractions add up to about 0.030.03 per run. An error in the proportions therefore shrinks by a factor ee only every 2,000/0.03≈67,0002{,}000/0.03 \approx 67{,}000 steps, more than thirty times the length of our run.

This changes how the first line must be read. The second moment matches 4.254.25 to within a few hundredths, the sampling error of 10,000 chains (the step-size bias h/4≈0.0025h/4 \approx 0.0025 is far below it). Each chain has equilibrated inside the mode it fell into. But almost half of the chains end right of zero, where pp has a fifth of its mass. The start is symmetric, each chain slides into the mode on its side of the valley, and hardly any leaves. The proportions are those of the start, not of pp (Section 17.1 measures the same blindness with a learned score on three modes).

The time a chain needs to forget where it started is its mixing time. Slow mixing is a property of the SDE itself, so a smaller step does not cure it. A smaller step removes only the discretization bias.

26.6.2.2 Limits of a Single Noise Level#

A score at one noise level has now failed in three ways. Where no noisy pair landed, the learned score is arbitrary. With the correct score, Langevin dynamics hardly ever crosses the valley between the modes. And its samples have the proportions of its start: almost half of the mass in a mode that holds a fifth. The third failure is not the sampler's alone. Where a mixture of well-separated modes has mass, its score is almost that of the nearest mode, whatever the weights (Section 25.5.1): at low noise the score hardly records the proportions.

The reverse sampler of Section 26.5.5 met the same lopsided mixture from an equally symmetric start and returned four fifths of the mass to the left. It had what Langevin dynamics lacks, the score at every noise level. Its proportions were settled at intermediate noise, where the two components still overlap and their pulls already differ, so that the weights decide where a particle goes.

A decreasing sequence of noise levels addresses all three limits. At a large σ\sigma the noised density has no valley, and the noisy pairs cover the whole region a sampler visits. For the symmetric mixture, pσp_\sigma has component variance 0.25+σ20.25 + \sigma^2 and is unimodal once its component standard deviation reaches the distance 22 from the center to each mean (Exercise 4 of the previous section), that is, for σ≥1.94\sigma \ge 1.94. Unequal weights close the valley sooner. As σ\sigma shrinks the detail returns, and a sampler that has already spread its mass across both modes only needs to refine it.

Annealed Langevin dynamics (Song and Ermon, 2019) runs the sampler down such a sequence, each level with its own score. Exercise 2 frees chains from a single mode this way, and Section 17.2 shows that such a sequence recovers unequal weights. Levels chosen one by one leave two questions open: how to space them, and how to move from one to the next. A forward process settles both. It supplies a continuum of noise levels, and its reverse is the sampler.

26.6.3 Scores Across Noise Levels#

From here on the model is one field sθ(x,t)\mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}, t) that takes the noise level as a second input and is trained at every level at once, by the loss of the next subsection. The samplers are the two we started from, the reverse-time SDE of Section 26.5.5 and the probability-flow ODE of Section 26.5.4.3.

26.6.3.1 Forward Processes and the Noise-Conditional Loss#

DSM needs the conditional law of the noised point given the clean one, and it needs that law to be Gaussian so that the target is explicit. Every SDE whose drift is linear in x\mathbf{x} and whose noise amplitude does not depend on x\mathbf{x} has Gaussian transition kernels, as Section 26.4.3 showed for the OU process. The two standard forward processes of Section 26.4 are of this kind, and their kernels can be written once for both as

pt(xt∣x0)=N(αtx0, σt2I),i.e.xt=αtx0+σtϵ.p_t(\mathbf{x}_t \mid \mathbf{x}_0) = \mathcal{N}(\alpha_t \mathbf{x}_0,\ \sigma_t^2 \mathbf{I}), \qquad\textrm{i.e.}\qquad \mathbf{x}_t = \alpha_t \mathbf{x}_0 + \sigma_t \boldsymbol{\epsilon}.

The coefficient αt\alpha_t shrinks the signal and σt\sigma_t scales the noise. The two processes differ only in these two numbers.

  • The variance-exploding (VE) SDE dX=ddtσ2(t)  dWd\mathbf{X} = \sqrt{\tfrac{d}{dt}\sigma^2(t)}\; d\mathbf{W}, with σ2(t)\sigma^2(t) increasing and σ(0)=0\sigma(0) = 0, adds noise without shrinking the data: αt=1\alpha_t = 1 and σt=σ(t)\sigma_t = \sigma(t). It is the continuous version of the sequence of noise levels that annealed Langevin dynamics descends.
  • The variance-preserving (VP) SDE is an Ornstein–Uhlenbeck process with a time-dependent rate,
dX=−12β(t) X dt+β(t)  dW,d\mathbf{X} = -\tfrac12 \beta(t)\, \mathbf{X}\, dt + \sqrt{\beta(t)}\; d\mathbf{W},

with αt=e−12∫0tβ(r) dr\alpha_t = e^{-\frac12 \int_0^t \beta(r)\, dr} and σt2=1−αt2\sigma_t^2 = 1 - \alpha_t^2, so that unit-variance data keep unit variance at every tt (Section 26.4).

The rest of the section works with the VP process. The VE process returns once, as the coordinates in which DDIM turns out to be simple.

With a Gaussian kernel at every tt, the conditional score is −ϵ/σt-\boldsymbol{\epsilon}/\sigma_t, and DSM applies at each level. Averaging over levels with a weight w(t)>0w(t) > 0 gives the noise-conditional DSM loss

L(θ)=12 Et w(t)  Ex0, ϵ[ ∥sθ(αtx0+σtϵ,t)+ϵσt∥2],(26.6.10)\mathcal{L}(\boldsymbol{\theta}) = \tfrac12\, \mathbb{E}_{t}\, w(t)\; \mathbb{E}_{\mathbf{x}_0,\, \boldsymbol{\epsilon}} \left[\, \left\| \mathbf{s}_{\boldsymbol{\theta}}(\alpha_t \mathbf{x}_0 + \sigma_t \boldsymbol{\epsilon}, t) + \frac{\boldsymbol{\epsilon}}{\sigma_t} \right\|^2 \right], \tag{26.6.10}

with tt drawn uniformly from the training range. Each draw of (t,x0,ϵ)(t, \mathbf{x}_0, \boldsymbol{\epsilon}) is one regression pair. This loss is what the rest of the section uses. The choice of the weight, to which we turn now, is a detail on a first reading.

The weight decides which levels the network serves best, not what it learns. For any positive ww the population minimizer is s(⋅,t)=∇log⁡pt\mathbf{s}(\cdot, t) = \nabla \log p_t at every tt, by Vincent's theorem at each level, provided the network can represent it. What the weight changes is the size of each level's contribution. By (26.6.7) the floor at level tt is d/σt2−E∥∇log⁡pt∥2d/\sigma_t^2 - \mathbb{E}\|\nabla \log p_t\|^2, which grows like d/σt2d/\sigma_t^2 at small σt\sigma_t. An unweighted loss is therefore dominated by its least noisy levels.

Two weights are standard. The discrete-time model of the next subsection uses w(t)=σt2w(t) = \sigma_t^2, which cancels this growth, so that every level contributes a loss of the same order.

The likelihood weighting w=g2w = g^2, the squared diffusion coefficient of the forward SDE, is the weight under which the score error controls a likelihood. The squared error of the score under this weight, integrated over the levels, bounds the KL divergence from the data to the model that the reverse-time SDE defines, apart from a term for the mismatch between pTp_T and the Gaussian the sampler starts from (Exercise 7). The loss we can compute contains the floor on top of this error, and under the likelihood weighting the floor is troublesome. For the VP process g2=βg^2 = \beta, and the weighted floor grows like d/td/t as t→0t \to 0, so its integral down to t=0t = 0 is infinite. Training therefore starts at a small time ε>0\varepsilon > 0 (Exercise 4).

Generation needs nothing new. The two samplers run with the learned field in place of the exact score. For a forward SDE dX=f(X,t) dt+g(t) dWd\mathbf{X} = \mathbf{f}(\mathbf{X}, t)\, dt + g(t)\, d\mathbf{W} on [0,T][0, T], we start from the Gaussian that approximates pTp_T and integrate either the reverse-time SDE (Section 26.5.5) or the probability-flow ODE (Section 26.5.4.3) from t=Tt = T down to 00:

dX=[f−g2 sθ(X,t)] dt+g dWˉ,dxdt=f−12g2 sθ(x,t),(26.6.11)d\mathbf{X} = \big[\mathbf{f} - g^2\, \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{X}, t)\big]\, dt + g\, d\bar{\mathbf{W}}, \qquad \frac{d\mathbf{x}}{dt} = \mathbf{f} - \tfrac12 g^2\, \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}, t), \tag{26.6.11}

where Wˉ\bar{\mathbf{W}} is a Brownian motion running backward in time. For VP, f=−12βx\mathbf{f} = -\tfrac12 \beta \mathbf{x} and g2=βg^2 = \beta.

A generative model is thus a triple: a forward process, a learned score, and a sampler. Figure 26.6.2 shows the three at work in two dimensions, the companion of the forward and reverse densities of Figure 26.5.5.

Figure 26.6.2:

A two-moons distribution under the VP forward process at t/T=0t/T = 0, 0.020.02, and 11 (top row, left to right), approaching an isotropic Gaussian. The bottom row traverses the same marginals in reverse, right to left; short arrows show the direction of the exact score ∇log⁡pt\nabla\log p_t of the noised data. At high noise the score is the pull toward the origin; at low noise it points toward the data.

26.6.3.2 DDPM and the Variance-Preserving SDE#

The Denoising Diffusion Probabilistic Model (DDPM) (Ho et al., 2020) is written in discrete time and looks at first like a separate construction. It has three parts, a noising chain, a loss and a sampler, and each turns out to be something we already have. The chain is a Markov chain of N=1000N = 1000 noising steps with a schedule β1,…,βN∈(0,1)\beta_1, \ldots, \beta_N \in (0, 1),

xt=1−βt  xt−1+βt  ϵt,ϵt∼N(0,I) i.i.d.,(26.6.12)\mathbf{x}_t = \sqrt{1 - \beta_t}\; \mathbf{x}_{t-1} + \sqrt{\beta_t}\; \boldsymbol{\epsilon}_t, \qquad \boldsymbol{\epsilon}_t \sim \mathcal{N}(\mathbf{0}, \mathbf{I})\ \textrm{i.i.d.}, \tag{26.6.12}

which shrinks the state slightly and adds a little noise at each step. In this subsection and the next, tt counts levels, t=0,1,…,Nt = 0, 1, \ldots, N, and level tt stands for the time t Δt\, \Delta of the SDE, with Δ=T/N\Delta = T/N.

How is the chain related to the VP-SDE? With βt=β((t−1)Δ) Δ\beta_t = \beta((t-1)\Delta)\, \Delta the step agrees to first order in βt\beta_t with the Euler–Maruyama step (1−12βt) xt−1+βt ϵt(1 - \tfrac12 \beta_t)\, \mathbf{x}_{t-1} + \sqrt{\beta_t}\, \boldsymbol{\epsilon}_t of the VP-SDE. More is true, and Section 26.4.4.1 showed it for a constant rate: the step is an exact transition of the VP process, over an interval of almost the same length. Between any two times the VP kernel has the form we wrote from time 00, with the integral of β\beta taken between those times. Take an interval on which ∫β(r) dr=−log⁡(1−βt)\int \beta(r)\, dr = -\log(1 - \beta_t). The mean coefficient of its kernel is e−12∫β=1−βte^{-\frac12 \int \beta} = \sqrt{1 - \beta_t} and the variance is 1−(1−βt)=βt1 - (1 - \beta_t) = \beta_t, the law of (26.6.12) given xt−1\mathbf{x}_{t-1}. For the largest step of the standard schedule, βt=0.02\beta_t = 0.02, such an interval has ∫β=0.0202\int \beta = 0.0202 instead of 0.020.02. The DDPM chain is therefore the VP process observed at discrete times, and the law of xt\mathbf{x}_t given x0\mathbf{x}_0 is a VP kernel from time 00. This is the result of the subsection to remember; the DDPM training loss follows from it in two lines. In DDPM's own notation the marginal can also be verified directly on the chain, without the SDE.

Proposition (the αˉ\bar{\alpha}-marginal). Let αˉt=∏s=1t(1−βs)\bar{\alpha}_t = \prod_{s=1}^{t} (1 - \beta_s). Then conditionally on x0\mathbf{x}_0,

xt=αˉt  x0+1−αˉt  ϵ,ϵ∼N(0,I).(26.6.13)\mathbf{x}_t = \sqrt{\bar{\alpha}_t}\; \mathbf{x}_0 + \sqrt{1 - \bar{\alpha}_t}\; \boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}). \tag{26.6.13}

Proof. Induction on tt; the case t=0t = 0 holds with αˉ0=1\bar\alpha_0 = 1. Assume (26.6.13) at t−1t - 1 and substitute it into (26.6.12):

xt=(1−βt)αˉt−1  x0+(1−βt)(1−αˉt−1)  ϵ′+βt  ϵt,\mathbf{x}_t = \sqrt{(1 - \beta_t) \bar{\alpha}_{t-1}}\; \mathbf{x}_0 + \sqrt{(1 - \beta_t) (1 - \bar{\alpha}_{t-1})}\; \boldsymbol{\epsilon}' + \sqrt{\beta_t}\; \boldsymbol{\epsilon}_t,

with ϵ′\boldsymbol{\epsilon}' and ϵt\boldsymbol{\epsilon}_t independent standard Gaussians. A sum of independent Gaussians is Gaussian with the sum of the variances, (1−βt)(1−αˉt−1)+βt=1−(1−βt)αˉt−1=1−αˉt(1 - \beta_t)(1 - \bar{\alpha}_{t-1}) + \beta_t = 1 - (1 - \beta_t)\bar{\alpha}_{t-1} = 1 - \bar{\alpha}_t, and (1−βt)αˉt−1=αˉt(1 - \beta_t)\bar{\alpha}_{t-1} = \bar{\alpha}_t. ■\blacksquare

In the kernel notation of the previous subsection, DDPM has αt=αˉt\alpha_t = \sqrt{\bar{\alpha}_t} and σt=1−αˉt\sigma_t = \sqrt{1 - \bar{\alpha}_t}. Training therefore never simulates the chain. It jumps to any level in one step by (26.6.13), and because the kernel is Gaussian, DSM applies directly: the conditional score is −ϵ/σt-\boldsymbol{\epsilon}/\sigma_t. Parameterize the score model through a noise-prediction network, sθ(xt,t)=−ϵθ(xt,t)/σt\mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}_t, t) = -\boldsymbol{\epsilon}_{\boldsymbol{\theta}}(\mathbf{x}_t, t) / \sigma_t. Then

∥sθ(xt,t)+ϵσt∥2=1σt2∥ϵ−ϵθ(xt,t)∥2,\left\| \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}_t, t) + \frac{\boldsymbol{\epsilon}}{\sigma_t} \right\|^2 = \frac{1}{\sigma_t^2} \left\| \boldsymbol{\epsilon} - \boldsymbol{\epsilon}_{\boldsymbol{\theta}}(\mathbf{x}_t, t) \right\|^2,

so the DDPM simple loss 12Et,x0,ϵ∥ϵ−ϵθ(xt,t)∥2\tfrac12\mathbb{E}_{t, \mathbf{x}_0, \boldsymbol{\epsilon}} \| \boldsymbol{\epsilon} - \boldsymbol{\epsilon}_{\boldsymbol{\theta}}(\mathbf{x}_t, t) \|^2 is the noise-conditional DSM loss (26.6.10) with weight w(t)=σt2=1−αˉtw(t) = \sigma_t^2 = 1 - \bar{\alpha}_t. "Predict the noise you added" is denoising score matching with a weight that cancels the 1/σt21/\sigma_t^2 growth of the floor: every level contributes a loss of order dd. (A warning for readers of (Ho et al., 2020): the paper writes αt\alpha_t for 1−βt1 - \beta_t, where our αt\alpha_t is the signal coefficient αˉt\sqrt{\bar\alpha_t}, and its simple loss lacks our factor 12\tfrac12.)

The third part is the sampler. Ancestral sampling steps through the levels from NN down to 11,

xt−1=xt+βt sθ(xt,t)1−βt+βt  ξ,ξ∼N(0,I),\mathbf{x}_{t-1} = \frac{\mathbf{x}_t + \beta_t\, \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}_t, t)}{\sqrt{1 - \beta_t}} + \sqrt{\beta_t}\; \boldsymbol{\xi}, \qquad \boldsymbol{\xi} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}),

without the noise in the last step. To first order in βt\beta_t this is xt+12βtxt+βtsθ+βt ξ\mathbf{x}_t + \tfrac12 \beta_t \mathbf{x}_t + \beta_t \mathbf{s}_{\boldsymbol{\theta}} + \sqrt{\beta_t}\, \boldsymbol{\xi}, the Euler–Maruyama step of the reverse SDE in (26.6.11) for the VP process. The model was first derived by a different route (Sohl-Dickstein et al., 2015; Ho et al., 2020), as a bound on the log-likelihood of a latent-variable model, the route that Section 17.6 follows; it yields the same regression with a different weight on each level.

The samplers below use the standard schedule, linear in βt\beta_t from 10−410^{-4} to 0.020.02 over N=1000N = 1000 levels. The VP process is built for data of unit variance, so from here on the mixture is standardized: divided by 4.25\sqrt{4.25}, with modes at ±2/4.25=±0.970\pm 2/\sqrt{4.25} = \pm 0.970 and component standard deviation 0.2430.243. Before any sampling, let us look at the schedule itself. We print αˉt\bar\alpha_t at three levels and, at the first and the last level, the ratio (1−αˉt)/αˉt\sqrt{(1 - \bar\alpha_t)/\bar\alpha_t} of noise to signal, which the next subsection uses as its time variable.

N = 1000
beta = np.linspace(1e-4, 0.02, N)                       # the DDPM schedule
alpha_bar = np.cumprod(1.0 - beta)
sigma_bar = np.sqrt((1 - alpha_bar) / alpha_bar)        # noise scale of x_t / sqrt(alpha_bar)
print(f'alpha_bar at t = 10, 100, 1000: {alpha_bar[9]:.3f}, {alpha_bar[99]:.3f}, '
      f'{alpha_bar[-1]:.0e}; sigma_bar from {sigma_bar[0]:.2f} to {sigma_bar[-1]:.0f}')
alpha_bar at t = 10, 100, 1000: 0.998, 0.897, 4e-05; sigma_bar from 0.01 to 157

The signal fades slowly at first and completely in the end. At t=100t = 100, αˉ=0.897\bar{\alpha} = 0.897 and the noised law is still bimodal, with modes at ±0.897⋅0.970=±0.92\pm\sqrt{0.897} \cdot 0.970 = \pm 0.92 and component standard deviation 0.897⋅0.2432+0.103=0.39\sqrt{0.897 \cdot 0.243^2 + 0.103} = 0.39. At t=Nt = N, αˉN≈4×10−5\bar\alpha_N \approx 4 \times 10^{-5}, and the sample is a standard Gaussian whatever the data were. From the first level to the last the ratio of noise to signal grows from 0.010.01 to 157157, by four orders of magnitude.

26.6.4 Deterministic Sampling and Guidance#

Ancestral sampling calls the network once per level, N=1000N = 1000 times per sample. Can the same network produce samples with far fewer calls? DDIM does it, and the reason is a fact about ODE solvers. We prove it on exact scores, then run DDIM once on fitted ones, and finally ask what a sampler follows when it is steered toward a class.

26.6.4.1 Denoising Diffusion Implicit Models#

The probability-flow ODE is deterministic and smooth, so a coarse grid of levels should suffice to integrate it. Denoising diffusion implicit models (DDIM) (Song et al., 2021) realize this with an update that reuses the trained noise-prediction network and skips levels. At level tt, the network's noise estimate gives a guess of the clean sample by inverting the marginal (26.6.13),

x^0=xt−1−αˉt  ϵθ(xt,t)αˉt.\hat{\mathbf{x}}_0 = \frac{\mathbf{x}_t - \sqrt{1 - \bar{\alpha}_t}\; \boldsymbol{\epsilon}_{\boldsymbol{\theta}}(\mathbf{x}_t, t)}{\sqrt{\bar{\alpha}_t}}.

To move to any earlier level t′<tt' \lt t, DDIM rebuilds the sample from this guess and the same noise estimate, with the coefficients of level t′t':

xt′=αˉt′  x^0+1−αˉt′  ϵθ(xt,t).(26.6.14)\mathbf{x}_{t'} = \sqrt{\bar{\alpha}_{t'}}\; \hat{\mathbf{x}}_0 + \sqrt{1 - \bar{\alpha}_{t'}}\; \boldsymbol{\epsilon}_{\boldsymbol{\theta}}(\mathbf{x}_t, t). \tag{26.6.14}

The update is deterministic: no fresh noise enters. Read literally, it moves a sample along the forward curve αˉt x0+1−αˉt ϵ\sqrt{\bar\alpha_t}\,\mathbf{x}_0 + \sqrt{1 - \bar\alpha_t}\,\boldsymbol{\epsilon} of the pair (x^0,ϵθ)(\hat{\mathbf{x}}_0, \boldsymbol{\epsilon}_{\boldsymbol{\theta}}). But a network trained by least squares returns the conditional mean E[ϵ∣xt]\mathbb{E}[\boldsymbol{\epsilon} \mid \mathbf{x}_t], not the noise that produced this sample, and the estimate changes from level to level. What, then, does DDIM integrate, and how large an error does a long stride make?

A change of coordinates answers both questions. Divide by αˉt\sqrt{\bar\alpha_t}. The rescaled point xˉt=xt/αˉt\bar{\mathbf{x}}_t = \mathbf{x}_t/\sqrt{\bar{\alpha}_t} equals x0+σˉtϵ\mathbf{x}_0 + \bar\sigma_t \boldsymbol{\epsilon} with σˉt=(1−αˉt)/αˉt\bar\sigma_t = \sqrt{(1 - \bar{\alpha}_t)/\bar{\alpha}_t}, the ratio of noise to signal that we printed with the schedule. In these coordinates the VP process is a VE process, clean data plus noise of scale σˉ\bar\sigma, which grows from 0.010.01 at the first level to 157157 at the last. The schedule only decides which values of σˉ\bar\sigma the grid visits. On xˉt\bar{\mathbf{x}}_t and σˉt\bar\sigma_t the bar marks the rescaled point and its noise level; the bar on αˉt\bar\alpha_t is DDPM's and means something else.

Proposition (DDIM is Euler's method). In the coordinates (σˉ,xˉ)(\bar\sigma, \bar{\mathbf{x}}) the DDIM update (26.6.14) reads

xˉt′=xˉt+(σˉt′−σˉt) ϵθ(xt,t),(26.6.15)\bar{\mathbf{x}}_{t'} = \bar{\mathbf{x}}_t + (\bar\sigma_{t'} - \bar\sigma_t)\, \boldsymbol{\epsilon}_{\boldsymbol{\theta}}(\mathbf{x}_t, t), \tag{26.6.15}

one Euler step of the ODE dxˉ/dσˉ=ϵθd\bar{\mathbf{x}}/d\bar\sigma = \boldsymbol{\epsilon}_{\boldsymbol{\theta}}. If ϵθ\boldsymbol{\epsilon}_{\boldsymbol{\theta}} is the exact noise prediction ϵ^(xt,t)=E[ϵ∣xt]\hat{\boldsymbol{\epsilon}}(\mathbf{x}_t, t) = \mathbb{E}[\boldsymbol{\epsilon} \mid \mathbf{x}_t], this ODE is the probability-flow ODE of the VP process, written in the coordinates (σˉ,xˉ)(\bar\sigma, \bar{\mathbf{x}}).

Proof. Step (i) is algebra; the substance is in (ii) and (iii), which show that the probability-flow ODE takes this form in the new coordinates. In (ii), tt is the continuous time of the SDE.

(i) Divide (26.6.14) by αˉt′\sqrt{\bar\alpha_{t'}} and substitute x^0=xˉt−σˉtϵθ\hat{\mathbf{x}}_0 = \bar{\mathbf{x}}_t - \bar\sigma_t \boldsymbol{\epsilon}_{\boldsymbol{\theta}}: xˉt′=x^0+σˉt′ϵθ=xˉt+(σˉt′−σˉt)ϵθ\bar{\mathbf{x}}_{t'} = \hat{\mathbf{x}}_0 + \bar\sigma_{t'}\boldsymbol{\epsilon}_{\boldsymbol{\theta}} = \bar{\mathbf{x}}_t + (\bar\sigma_{t'} - \bar\sigma_t)\boldsymbol{\epsilon}_{\boldsymbol{\theta}}.

(ii) Change variables in the VP probability-flow ODE dx/dt=−12βx−12β∇xlog⁡ptd\mathbf{x}/dt = -\tfrac12\beta\mathbf{x} - \tfrac12\beta\nabla_{\mathbf{x}}\log p_t of (26.6.11), with αt=αˉ(t)\alpha_t = \sqrt{\bar\alpha(t)} and αˉ(t)=e−∫0tβ\bar\alpha(t) = e^{-\int_0^t\beta}. Let pˉt\bar p_t be the density of xˉt\bar{\mathbf{x}}_t; then ∇xlog⁡pt=∇xˉlog⁡pˉt/αˉ\nabla_{\mathbf{x}}\log p_t = \nabla_{\bar{\mathbf{x}}}\log\bar p_t/\sqrt{\bar\alpha}. Since dαˉ/dt=−12βαˉd\sqrt{\bar\alpha}/dt = -\tfrac12\beta\sqrt{\bar\alpha}, the shrinkage terms cancel and dxˉ/dt=−β2αˉ∇log⁡pˉtd\bar{\mathbf{x}}/dt = -\tfrac{\beta}{2\bar\alpha}\nabla\log\bar p_t. Since σˉ2=1/αˉ−1\bar\sigma^2 = 1/\bar\alpha - 1, we have dσˉ/dt=β/(2αˉσˉ)d\bar\sigma/dt = \beta/(2\bar\alpha\bar\sigma), and dividing gives dxˉ/dσˉ=−σˉ ∇log⁡pˉ(xˉ)d\bar{\mathbf{x}}/d\bar\sigma = -\bar\sigma\, \nabla \log \bar p(\bar{\mathbf{x}}).

(iii) Tweedie's formula for the kernel N(x0,σˉ2I)\mathcal{N}(\mathbf{x}_0, \bar\sigma^2\mathbf{I}) reads E[x0∣xˉ]=xˉ+σˉ2∇log⁡pˉ\mathbb{E}[\mathbf{x}_0 \mid \bar{\mathbf{x}}] = \bar{\mathbf{x}} + \bar\sigma^2\nabla\log\bar p, so E[ϵ∣xˉ]=(xˉ−E[x0∣xˉ])/σˉ=−σˉ∇log⁡pˉ\mathbb{E}[\boldsymbol{\epsilon} \mid \bar{\mathbf{x}}] = (\bar{\mathbf{x}} - \mathbb{E}[\mathbf{x}_0\mid\bar{\mathbf{x}}])/\bar\sigma = -\bar\sigma\nabla\log\bar p, the right-hand side of (ii). Conditioning on xˉt\bar{\mathbf{x}}_t is the same as conditioning on xt\mathbf{x}_t. ■\blacksquare

DDIM is therefore a first-order solver for the probability-flow ODE, in a clock in which the noise level is the time. Its error is Euler's error: a stride holds ϵθ\boldsymbol{\epsilon}_{\boldsymbol{\theta}} fixed while the exact ϵ^\hat{\boldsymbol{\epsilon}} changes along the trajectory. Two corollaries mark the extremes of this error.

Corollary (a point mass is integrated without error). If the data are a single point x0\mathbf{x}_0, every DDIM stride with the exact ϵ^\hat{\boldsymbol{\epsilon}} lands on the probability-flow trajectory, whatever its length. Here ϵ^=(xˉ−x0)/σˉ\hat{\boldsymbol{\epsilon}} = (\bar{\mathbf{x}} - \mathbf{x}_0)/\bar\sigma, and along a solution of dxˉ/dσˉ=(xˉ−x0)/σˉd\bar{\mathbf{x}}/d\bar\sigma = (\bar{\mathbf{x}} - \mathbf{x}_0)/\bar\sigma the ratio (xˉ−x0)/σˉ(\bar{\mathbf{x}} - \mathbf{x}_0)/\bar\sigma is constant. An Euler step for a constant right-hand side is exact.

Corollary (Gaussian data shrink). For data x0∼N(0,I)\mathbf{x}_0 \sim \mathcal{N}(\mathbf{0}, \mathbf{I}) the exact flow is the identity, but one DDIM stride with the exact noise prediction multiplies every sample by

αˉtαˉt′+(1−αˉt)(1−αˉt′)=cos⁡(ϕt−ϕt′),αˉt=cos⁡2ϕt,\sqrt{\bar\alpha_t \bar\alpha_{t'}} + \sqrt{(1 - \bar\alpha_t)(1 - \bar\alpha_{t'})} = \cos(\phi_t - \phi_{t'}), \qquad \bar\alpha_t = \cos^2\phi_t,

which is below 11 for every stride of positive length. The VP process leaves such data as they are: the marginal is N(0,I)\mathcal{N}(\mathbf{0}, \mathbf{I}) at every level, the score is −x-\mathbf{x}, and the probability-flow drift −12βx−12β(−x)-\tfrac12 \beta \mathbf{x} - \tfrac12 \beta (-\mathbf{x}) vanishes, so no sample of the exact flow moves. By Tweedie, ϵ^(xt,t)=1−αˉt xt\hat{\boldsymbol{\epsilon}}(\mathbf{x}_t, t) = \sqrt{1 - \bar\alpha_t}\, \mathbf{x}_t, and substituting into (26.6.14) gives the factor. Writing αˉt=cos⁡2ϕt\bar\alpha_t = \cos^2\phi_t turns it into the cosine of the angle advanced. In the bar coordinates the exact solution is xˉ∝1+σˉ2\bar{\mathbf{x}} \propto \sqrt{1 + \bar\sigma^2}, so ϵ^=σˉxˉ/(1+σˉ2)\hat{\boldsymbol{\epsilon}} = \bar\sigma\bar{\mathbf{x}}/(1 + \bar\sigma^2) changes along it. Holding it fixed across a stride removes too much signal, by the factor above.

The corollary gives the factor of one stride. Over a sampling run the factors multiply, and we compute the product for 10, 50 and 999 equally spaced strides of the DDPM schedule; 999 strides step through its 1,000 levels one at a time. How much of this error survives on data that are not Gaussian? To see, DDIM runs on the standardized mixture with its exact noise prediction ϵ^=−1−αˉt ∇log⁡pt\hat{\epsilon} = -\sqrt{1 - \bar\alpha_t}\, \nabla \log p_t, where the noised law at level tt has modes ±αˉt m\pm\sqrt{\bar\alpha_t}\, m and component variance αˉtv0+1−αˉt\bar\alpha_t v_0 + 1 - \bar\alpha_t, with m=0.970m = 0.970 and v0=0.2432v_0 = 0.243^2 the clean values. We compare 10 and 50 strides with 999 from the same initial draws in two ways: by the mean distance between paired endpoints, and by the Kolmogorov–Smirnov (KS) statistic of the two samples, the largest gap between their empirical distribution functions.

m, v0 = 2 / np.sqrt(4.25), 0.25 / 4.25                  # standardized: modes +-m, variance v0
def ks(a, b):                                           # two-sample Kolmogorov-Smirnov statistic
    q = np.sort(np.concatenate([a, b]))
    return np.abs(np.searchsorted(np.sort(a), q, 'right') / len(a)
                  - np.searchsorted(np.sort(b), q, 'right') / len(b)).max()
def strides(K):                                         # K equal strides from level N to level 1
    return np.linspace(N - 1, 0, K + 1).round().astype(int)
for K in (10, 50, 999):                                 # the Gaussian corollary
    a = alpha_bar[strides(K)]
    print(f'N(0,1) data, {K:4d} strides: every sample times '
          f'{np.prod(np.sqrt(a[:-1] * a[1:]) + np.sqrt((1 - a[:-1]) * (1 - a[1:]))):.3f}')
def eps_hat(xt, a, ws=(0.5, 0.5)):                      # exact noise prediction of the mixture
    means = (-np.sqrt(a) * m, np.sqrt(a) * m)
    return -np.sqrt(1 - a) * mixture_score(xt, a * v0 + 1 - a, means, ws)
def ddim(z, K, eps_fn):                                 # K DDIM strides from noise z
    xt, idx = z.copy(), strides(K)
    for t1, t2 in zip(idx[:-1], idx[1:]):
        a1, a2 = alpha_bar[t1], alpha_bar[t2]
        e = eps_fn(xt, a1)
        xt = np.sqrt(a2) * (xt - np.sqrt(1 - a1) * e) / np.sqrt(a1) + np.sqrt(1 - a2) * e
    return xt
z = rng.standard_normal(8000)                           # one draw, shared by every stride count
x_ref = ddim(z, 999, eps_hat)
for K in (10, 50):
    x_K = ddim(z, K, eps_hat)
    print(f'mixture, {K:3d} strides vs 999: mean |gap| {np.abs(x_K - x_ref).mean():.3f}, '
          f'KS {ks(x_K, x_ref):.3f}')
N(0,1) data,   10 strides: every sample times 0.832
N(0,1) data,   50 strides: every sample times 0.964
N(0,1) data,  999 strides: every sample times 0.998
mixture,  10 strides vs 999: mean |gap| 0.084, KS 0.078
mixture,  50 strides vs 999: mean |gap| 0.015, KS 0.018

Ten strides shrink unit-variance Gaussian data by the factor 0.8320.832, fifty by 0.9640.964, and 999 by 0.9980.998. These factors are deterministic and measure the Euler error alone, since the noise prediction is exact. Five times as many strides cut the shortfall from 0.170.17 to 0.040.04, as a first-order method should. The mixture behaves the same way. Ten strides land on average 0.080.08 from the 999-stride result, on a scale where the modes sit at ±0.97\pm 0.97, and the KS statistic is 0.080.08 as well. Fifty strides reduce both numbers to about 0.020.02. Figure 26.6.3 draws both experiments.

Figure 26.6.3:

(a) Each forward pair (x0,ϵ)(x_0,\epsilon) of the standardized mixture owns one curve; the blue pair crossed the valley. From the same noise end, DDIM with the exact noise prediction follows the probability-flow ODE (10 strides, dots; 999 strides, one per level, dashed) into the other mode: it never sees the sample's own curve. (b) For unit-variance Gaussian data the exact flow is the identity (dashed); ten DDIM strides with the exact noise prediction shrink every sample by 0.830.83, the Euler error of the Gaussian corollary.

Panel (a) answers the literal reading of the update. The sample travels along the probability-flow trajectory through its noise end, not along the forward curve that produced it. DDIM is the deterministic end of the family of reverse processes (Section 26.5.5), whose members reinject a chosen amount of noise and share the single-time marginals of the forward process, so one trained network serves them all. Section 17.5 chooses among them.

26.6.4.2 DDIM on Fitted Scores#

Every sampler so far was handed the exact score. We now learn one and sample with it, on the data that defeated Langevin dynamics: the two standardized modes at −m-m and +m+m, reweighted so that the left one holds 0.80.8 of the mass and the right one 0.20.2.

The model is the one that worked at a single level, the 17 fixed features, now fitted separately at each of the 50 levels that a 50-stride DDIM run visits. At each level we noise 4,096 clean draws four times and regress the noise ϵ\epsilon on the features of the noisy point, evaluated at 4.25 xt\sqrt{4.25}\, x_t so that the bumps cover the standardized data as they covered the original. A small weight decay (Section 2.7) handles the bumps that no pair reaches at a given level: least squares would leave their weights arbitrary, as it left the fit at x=8x = 8, and the penalty sets them to zero. DDIM then runs twice from the noise of the previous cell, on the exact noise prediction of the lopsided mixture and on the fitted one. If regression at every level learns what a single level could not, both rows will show a light mode of mass 0.20.2.

ws = (0.8, 0.2)                                         # the right mode is the light one
def draw(size):                                         # standardized modes +-m, weights ws
    return rng.normal(np.where(rng.random(size) < ws[0], -m, m), np.sqrt(v0))
x_pairs = np.repeat(draw(4096), 4)                      # four noisy copies per clean point
def fit_eps(a, x_pairs):                                # ridge least squares for eps at one level
    e = rng.standard_normal(x_pairs.size)
    F = features(np.sqrt(4.25) * (np.sqrt(a) * x_pairs + np.sqrt(1 - a) * e))
    return np.linalg.solve(F.T @ F + 1e-6 * e.size * np.eye(17), F.T @ e)
coef = {a: fit_eps(a, x_pairs) for a in alpha_bar[strides(50)[:-1]]}   # the levels DDIM visits
x_exact = ddim(z, 50, lambda q, a: eps_hat(q, a, ws))
x_fit = ddim(z, 50, lambda q, a: features(np.sqrt(4.25) * q) @ coef[a])
x_true = draw(8000)
for name, xs in (('exact', x_exact), ('fitted', x_fit)):
    L, R = xs[xs < 0], xs[xs > 0]
    print(f'{name:6s} scores: light mode {(xs > 0).mean():.3f}, means {L.mean():+.2f} '
          f'{R.mean():+.2f}, widths {L.std():.3f} {R.std():.3f}, KS to p0 {ks(xs, x_true):.2f}')
print(f'truth: light mode 0.2, means {-m:+.2f} {m:+.2f}, widths {np.sqrt(v0):.3f}; '
      f'KS between the clouds {ks(x_exact, x_fit):.2f}')
exact  scores: light mode 0.190, means -0.96 +0.94, widths 0.229 0.234, KS to p0 0.03
fitted scores: light mode 0.199, means -0.95 +0.91, widths 0.232 0.263, KS to p0 0.05
truth: light mode 0.2, means -0.97 +0.97, widths 0.243; KS between the clouds 0.03

They do. Both rows put a fifth of the samples in the light mode, to within a hundredth or two, where Langevin dynamics with the exact score of one level left almost half. The fitted sampler never saw a density, a score or the number 0.20.2. It saw noisy points and the noise that made them.

The two rows start from the same noise, so what they share is the sampler's error and what separates them is the fit's. They share a light mode a few hundredths short of 0.970.97 and a heavy mode that is slightly too narrow, about 0.230.23 against 0.2430.243. With the exact noise prediction the only error is Euler's, so this is the error of fifty strides. It has the size the Gaussian corollary led us to expect, a shrinkage of a few percent, where fifty strides multiplied Gaussian data by 0.9640.964. The fit adds one visible error of its own, a light mode of width 0.250.25 to 0.280.28 where the exact row has about 0.240.24. The two modes differ in nothing but their share of the data, so the excess comes from there. Least squares spends its 17 weights where the pairs are, and only a fifth of the pairs fall in the light mode. The KS statistics agree. Either row is a few hundredths from fresh draws of the data, and the two rows are no further from each other.

A diffusion model does not fit each level separately. Its network takes the level as an input and shares its weights across levels (Exercise 8). The regression, the sampler and the two kinds of error stay the same.

26.6.4.3 Guidance with Bayes' Rule#

A sampler for pp returns samples of every kind that pp contains. Often we want one kind only: images of one class, or images that fit a caption. Guidance steers a sampler toward a class yy by changing the score it follows. Section 17.4 builds guided samplers and measures them on images. Here we keep the two facts that the mixture lets us check by hand: guidance is Bayes' rule on scores, and with a scale above one the sampler follows densities that no noised data could have.

On the standardized mixture with equal weights, let yy be "the right mode", so that we want samples from the class N(m,v0)\mathcal{N}(m, v_0) alone, with m=0.970m = 0.970 and v0=0.2432v_0 = 0.243^2. Bayes' rule at noise level tt, pt(x∣y)∝pt(x) pt(y∣x)p_t(\mathbf{x} \mid y) \propto p_t(\mathbf{x})\, p_t(y \mid \mathbf{x}), becomes additive for scores, because the evidence p(y)p(y) does not depend on x\mathbf{x}:

∇xlog⁡pt(x∣y)=∇xlog⁡pt(x)+∇xlog⁡pt(y∣x).(26.6.16)\nabla_{\mathbf{x}} \log p_t(\mathbf{x} \mid y) = \nabla_{\mathbf{x}} \log p_t(\mathbf{x}) + \nabla_{\mathbf{x}} \log p_t(y \mid \mathbf{x}). \tag{26.6.16}

The conditional score is the unconditional score plus the gradient of a classifier's log-probability, and every sampler of this section runs unchanged with it. Classifier guidance (Dhariwal and Nichol, 2021) takes the second term from a classifier pϕ(y∣x,t)p_{\boldsymbol{\phi}}(y \mid \mathbf{x}, t) of noisy inputs and scales it by a guidance scale γ\gamma:

s~(x,t)=∇log⁡pt(x)+γ ∇log⁡pϕ(y∣x,t),s~=∇log⁡p~t,p~t(x)∝pt(x) pϕ(y∣x,t)γ.\begin{aligned} \tilde{\mathbf{s}}(\mathbf{x}, t) &= \nabla \log p_t(\mathbf{x}) + \gamma\, \nabla \log p_{\boldsymbol{\phi}}(y \mid \mathbf{x}, t), \\ \tilde{\mathbf{s}} &= \nabla \log \tilde p_t,\qquad \tilde p_t(\mathbf{x}) \propto p_t(\mathbf{x})\, p_{\boldsymbol{\phi}}(y \mid \mathbf{x}, t)^{\gamma}. \end{aligned}

With γ=1\gamma = 1 this is Bayes' rule. With γ>1\gamma > 1 the guided field is the score of a tilted density that raises the classifier's probability to a power. Classifier-free guidance (CFG) (Ho and Salimans, 2022) reads (26.6.16) from right to left, ∇log⁡pt(y∣x)=∇log⁡pt(x∣y)−∇log⁡pt(x)\nabla \log p_t(y \mid \mathbf{x}) = \nabla \log p_t(\mathbf{x} \mid y) - \nabla \log p_t(\mathbf{x}), and so needs no classifier, only a conditional and an unconditional score model sθ(x,t,y)\mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}, t, y) and sθ(x,t,∅)\mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}, t, \varnothing), which one network can supply (Section 17.4.4.2):

s~(x,t)=sθ(x,t,∅)+γ[sθ(x,t,y)−sθ(x,t,∅)],(26.6.17)\tilde{\mathbf{s}}(\mathbf{x}, t) = \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}, t, \varnothing) + \gamma \left[ \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}, t, y) - \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}, t, \varnothing) \right], \tag{26.6.17}

equivalently (1−γ) s∅+γ sy(1 - \gamma)\, \mathbf{s}_\varnothing + \gamma\, \mathbf{s}_y, which for γ>1\gamma > 1 extrapolates past the conditional score.

One fact limits the interpretation of γ>1\gamma > 1. The tilted density p~t\tilde p_t is in general not the noised marginal of any clean distribution. The marginal ptp_t is the law of αˉt x0\sqrt{\bar\alpha_t}\, \mathbf{x}_0 noised at scale σt\sigma_t, so by the curvature bound (26.6.8) no eigenvalue of −∇2log⁡pt-\nabla^2 \log p_t exceeds 1/σt21/\sigma_t^2, whatever the data. Raising the classifier to the power γ\gamma adds curvature, most of it midway between the classes. For the mixture the bound fails there once γ>1+v0vt/(σt2m2)\gamma > 1 + v_0 v_t/(\sigma_t^2 m^2), where vt=αˉtv0+σt2v_t = \bar\alpha_t v_0 + \sigma_t^2 is the variance of a noised class (Exercise 6). This threshold is 1.06251.0625 at the noisiest levels and 1.091.09 at t=100t = 100. At γ=3\gamma = 3 the bound holds only at about ten of the thousand levels, the least noisy ones, and at γ=10\gamma = 10 at fewer still.

Why should we care? If the tilted densities were the noised marginals of one clean distribution, a reverse chain run on their scores would end on that distribution, as it did for pp. They are not, so nothing tells us in advance where a guided chain ends. Let us look. We run the ancestral chain of Section 26.6.3.2 on exact scores, the unconditional score of the mixture and the class-conditional score, that of the single Gaussian N(αˉt m, vt)\mathcal{N}(\sqrt{\bar\alpha_t}\, m,\ v_t), combined by (26.6.17) at γ∈{1,3,10}\gamma \in \{1, 3, 10\}.

def cfg_sample(gamma, n=8000):                          # ancestral chain with the guided score
    xt = rng.standard_normal(n)
    for t in range(N - 1, -1, -1):
        a, b = alpha_bar[t], beta[t]
        v = a * v0 + 1 - a                              # noised component variance
        s_uncond = mixture_score(xt, v, (-np.sqrt(a) * m, np.sqrt(a) * m))
        s_cond = (np.sqrt(a) * m - xt) / v              # class y = the right mode
        xt = (xt + b * ((1 - gamma) * s_uncond + gamma * s_cond)) / np.sqrt(1 - b)
        if t > 0:
            xt = xt + np.sqrt(b) * rng.standard_normal(n)
    return xt
for gamma in (1.0, 3.0, 10.0):
    xs = cfg_sample(gamma)
    print(f'gamma = {gamma:4.1f}: mass right of 0 {(xs > 0).mean():.3f}, '
          f'mean {xs.mean():.3f}, std {xs.std():.3f}')
print(f'exact conditional: mean {m:.3f}, std {np.sqrt(v0):.3f}')
gamma =  1.0: mass right of 0 1.000, mean 0.973, std 0.243
gamma =  3.0: mass right of 0 1.000, mean 1.027, std 0.234
gamma = 10.0: mass right of 0 1.000, mean 1.070, std 0.236
exact conditional: mean 0.970, std 0.243

At γ=1\gamma = 1 the chain reproduces the class: all the mass lies right of zero, where the unconditional mixture puts only half of it, and the mean and standard deviation are within about 0.010.01 of the exact 0.9700.970 and 0.2430.243. At γ=3\gamma = 3 and 1010 there is no mass left to move between modes, so the guidance moves the mode itself, to about 1.031.03 and then to between 1.071.07 and 1.081.08, away from the class boundary. The width hardly changes and stays within about 5%5\% of 0.240.24.

This is where the broken bound shows. At the clean level the classes are eight standard deviations apart and the classifier is certain, so the tilted density there is the class itself, with mean 0.9700.970 for every γ\gamma. A chain that followed the marginals of one forward process would end on it. At γ=3\gamma = 3 and 1010 ours ends about 0.060.06 and 0.10.1 to its right, because the densities whose scores it follows do not belong to one process. The shift is produced at intermediate levels, where the noised classes overlap (Exercise 5). Guidance with γ>1\gamma > 1 thus moves samples away from the other class, beyond where the class itself sits. A class with a single Gaussian mode has little diversity to lose; on images the loss is measurable (Section 17.4.4.2).

Guided or not, every sampler of this section evaluates the score many times, because its paths curve. The Gaussian corollary showed that even the simplest data bend them in DDIM's clock. We took the forward process for its Gaussian kernels and never asked whether its paths are easy to follow. Which paths from noise to data are straight?

26.6.5 Summary#

A score needs no normalizing constant, and for noised data it is the conditional mean of a target we know for every training pair, −ϵ/σ-\boldsymbol{\epsilon}/\sigma. Least squares on noisy pairs therefore learns it from samples alone, and its loss ends at the posterior-variance floor, not at zero. One noise level is not enough: far from the data the fit is arbitrary, and Langevin dynamics keeps the proportions of its start, with almost half of its samples in a mode that holds a fifth. With scores at every level of a forward process, the two best-known samplers discretize equations we already had. DDPM is the variance-preserving SDE observed at discrete times, with denoising score matching weighted by σt2\sigma_t^2 as its loss. DDIM is Euler's method for the probability-flow ODE in the coordinates (σˉ,xˉ)(\bar\sigma, \bar{\mathbf{x}}), exact for a point mass and too contractive for Gaussian data. Run on scores fitted by least squares at every level, DDIM returned the weights 0.80.8 and 0.20.2 that a single level could not. Guidance is Bayes' rule on scores, and for γ>1\gamma > 1 it follows densities that curve more sharply than any noised density can.

26.6.6 Exercises#

  1. [code] Langevin discretization bias. For the Gaussian target p=N(0,v)p = \mathcal{N}(0, v), the Langevin sampler of (26.6.9) with step hh is the linear recursion x←(1−h2v) x+h ξx \leftarrow (1 - \tfrac{h}{2v})\, x + \sqrt{h}\, \xi.

    1. Find the step sizes for which the recursion has a stationary distribution, compute its variance, and expand the bias to first order in hh.
    2. Treat each mode of the mixture in the cell that defines langevin as a separate Gaussian with v=0.25v = 0.25, and predict the stationary E[X2]\mathbb{E}[X^2] at h∈{0.01,0.1,0.25,0.5}h \in \{0.01, 0.1, 0.25, 0.5\}. Compare each predicted bias with the Monte Carlo standard error of an estimate from 10,000 chains. Then run langevin for 2,000 steps at each of these step sizes from the initial points rng.normal(0.0, 3.0, 10000) of warm. From which step size on does the experiment resolve the bias?
    3. The Metropolis-adjusted Langevin algorithm (Roberts and Tweedie, 1996) removes the bias with an accept–reject test that needs the density ratio p(x′)/p(x)p(\mathbf{x}') / p(\mathbf{x}). Why can a sampler that has only a trained score network sθ\mathbf{s}_{\boldsymbol{\theta}} not apply this test directly?
  2. [code] Annealing out of one mode. In the cell that defines langevin, chains started in one mode of 0.8 N(−2,0.52)+0.2 N(2,0.52)0.8\, \mathcal{N}(-2, 0.5^2) + 0.2\, \mathcal{N}(2, 0.5^2) stay there, and the broad start leaves almost half of the mass on the right. Annealed Langevin dynamics first runs the sampler on smoothed densities pσp_\sigma, here the mixture with component variance 0.25+σ20.25 + \sigma^2, for the decreasing sequence of noise levels σ=2,1,0.5,0.25,0.1,0\sigma = 2, 1, 0.5, 0.25, 0.1, 0.

    1. With equal weights, pσp_\sigma has no valley for σ≥1.94\sigma \ge 1.94, as the text found. With the weights 0.80.8 and 0.20.2 the valley closes sooner. Count the sign changes of mixture_score with ws=(0.8, 0.2) on a fine grid to find the smallest σ\sigma without a valley. Which levels of the sequence have no valley?
    2. Run 300300 steps of langevin at each level of the sequence, passing the component variance 0.25+σ20.25 + \sigma^2 as var, for 10,000 chains started at −2-2 and again for 10,000 chains started at +2+2. Do this once with the fixed step h=0.01h = 0.01 and once with h=0.04 (0.25+σ2)h = 0.04\, (0.25 + \sigma^2), which equals 0.010.01 at σ=0\sigma = 0. Report the fraction of chains with X>0X > 0 at the end of each of the four runs. Which step rule forgets the start? Its fraction comes close to the target 0.20.2 without reaching it. Compute the mass of pσp_\sigma to the right of zero at each level, and say at which level the proportions were fixed.
    3. Song and Ermon (2019) scale the step size of each level with σ2\sigma^2. Use the contraction factor of the linear recursion in Exercise 1 to explain why the fixed step fails at the large noise levels.
  3. [code] The Bayes-risk floor. ● The cell that fits w_ls prints the mean squared error of the fit and of the exact score, both averages over the same 16,384 noisy pairs, and the population floor by quadrature.

    1. The text obtains the floor (26.6.7), the Bayes risk of the regression, from the lemma with v=0\mathbf{v} = \mathbf{0}. Use Tweedie's formula (26.6.6) to show that it also equals E tr⁡Cov[x∣x~]/σ4\mathbb{E}\, \operatorname{tr} \textrm{Cov}[\mathbf{x} \mid \tilde{\mathbf{x}}] / \sigma^4, and check that the two expressions agree for x∼N(0,vI)\mathbf{x} \sim \mathcal{N}(\mathbf{0}, v \mathbf{I}). What does the floor do as σ→0\sigma \to 0 for data with a smooth density, and what for a training set of nn distinct points? What does the optimal denoiser of the training set return in that limit?
    2. The printed exact-score average is not the floor. Compute its standard error twice: from the 16,384 per-pair squared errors as if they were independent, and from the 4,096 averages over the four noisy copies of each clean point. Why do the two differ, and which one agrees with errs.std(), the standard deviation over twenty fresh draws that the text prints? Is the printed value consistent with the population floor? Then explain why the fit and the exact score, evaluated on the same pairs, differ from each other by far less than this standard error.
  4. Weightings across noise levels. ● Consider the VP-SDE with the linear schedule β(t)=βmin⁡+t (βmax⁡−βmin⁡)\beta(t) = \beta_{\min} + t\, (\beta_{\max} - \beta_{\min}) on [0,1][0, 1], with βmin⁡=0.1\beta_{\min} = 0.1 and βmax⁡=20\beta_{\max} = 20, so that αˉ(t)=exp⁡(−βmin⁡t−12(βmax⁡−βmin⁡)t2)\bar{\alpha}(t) = \exp\big(-\beta_{\min} t - \tfrac12 (\beta_{\max} - \beta_{\min}) t^2\big) and σt2=1−αˉ(t)\sigma_t^2 = 1 - \bar{\alpha}(t). Let the data in Rd\mathbb{R}^d have a smooth density, and assume that E∥∇log⁡pt∥2\mathbb{E} \| \nabla \log p_t \|^2 stays bounded as t→0t \to 0. Write R(t)R(t) for the Bayes risk of the noise-conditional DSM loss (26.6.10) at level tt, the floor (26.6.7) with σt\sigma_t in place of σ\sigma.

    1. Show that R(t)≈d/(βmin⁡t)R(t) \approx d / (\beta_{\min} t) as t→0t \to 0.
    2. Find the behavior of w(t) R(t)w(t)\, R(t) as t→0t \to 0 for w=1w = 1, for the DDPM weighting w=σt2w = \sigma_t^2, and for the likelihood weighting w=g2=β(t)w = g^2 = \beta(t). For which weightings is ∫01w(t) R(t) dt\int_0^1 w(t)\, R(t)\, dt finite, and which noise levels does each weighting emphasize?
    3. Training draws tt uniformly from [ε,1][\varepsilon, 1]. For the likelihood weighting, show that the second moment of w(t) R(t)w(t)\, R(t) under this draw grows like 1/ε1/\varepsilon. Song et al. (2021) (Section 5.1) instead draw tt from the density proportional to β(t)/σt2\beta(t) / \sigma_t^2 on [ε,1][\varepsilon, 1] and multiply the DSM term at the drawn level by c σt2c\, \sigma_t^2, with the constant c=11−ε∫ε1β(r)/σr2 drc = \tfrac{1}{1 - \varepsilon} \int_\varepsilon^1 \beta(r) / \sigma_r^2\, dr. Show that this estimate is unbiased for the likelihood-weighted loss and that its value at the optimum, c σt2 R(t)c\, \sigma_t^2\, R(t), stays bounded as t→0t \to 0.
  5. [code] Guidance by noise level. ● In the cell that defines cfg_sample, raising γ\gamma from 11 to 1010 moves the mean of the guided samples from about 0.970.97 to between 1.071.07 and 1.081.08.

    1. The text claims that at the clean level the tilted density is the class itself. Check it. At the last level of the chain, t=0t = 0 in cfg_sample, the class posterior of the right mode is a logistic function of xx. Write it, and compute by quadrature the mean of the tilted density proportional to pt(x) pt(y∣x)γp_t(x)\, p_t(y \mid x)^{\gamma} at that level for γ∈{1,3,10}\gamma \in \{1, 3, 10\}. How far is each mean from mm, and how far are the printed means?
    2. Modify cfg_sample so that it uses γ=10\gamma = 10 only on the steps t≥500t \ge 500, only on 200≤t<500200 \le t \lt 500, or only on t<200t \lt 200, and γ=1\gamma = 1 on the others. Which band of noise levels produces the shift? Relate the answer to the separation αˉt m/vt\sqrt{\bar{\alpha}_t}\, m / \sqrt{v_t} of the two noised classes, where mm and v0v_0 are the variables m and v0, and vt=αˉt v0+1−αˉtv_t = \bar{\alpha}_t\, v_0 + 1 - \bar{\alpha}_t is the noised component variance, the variable v of cfg_sample.
    3. Kynkäänniemi et al. (2024) find on image models that guidance is harmful at high noise levels, largely unnecessary at low noise levels, and beneficial in between. Which parts of this pattern does the one-dimensional example reproduce, and which can it not exhibit?
  6. Guided densities and noised marginals. ● The guided field (26.6.17) with γ>1\gamma > 1 is the score of the tilted density p~t(x)∝pt(x) pt(y∣x)γ\tilde{p}_t(\mathbf{x}) \propto p_t(\mathbf{x})\, p_t(y \mid \mathbf{x})^{\gamma}. Call a density a noised marginal at level tt if it is the law of αˉt x0+σtϵ\sqrt{\bar{\alpha}_t}\, \mathbf{x}_0 + \sigma_t \boldsymbol{\epsilon}, with σt2=1−αˉt\sigma_t^2 = 1 - \bar{\alpha}_t, for some clean distribution of x0\mathbf{x}_0.

    1. Apply (26.6.8) to the clean variable αˉt x0\sqrt{\bar{\alpha}_t}\, \mathbf{x}_0 to show that a noised marginal ptp_t has
∇2log⁡pt(x)=−Iσt2+αˉtσt4Cov[x0∣xt=x].\nabla^2 \log p_t(\mathbf{x}) = -\frac{\mathbf{I}}{\sigma_t^2} + \frac{\bar{\alpha}_t}{\sigma_t^4} \textrm{Cov}\left[ \mathbf{x}_0 \mid \mathbf{x}_t = \mathbf{x} \right].

Conclude that no eigenvalue of −∇2log⁡pt-\nabla^2 \log p_t exceeds 1/σt21 / \sigma_t^2, whatever the clean distribution.

  1. In cfg_sample, the two noised classes are N(±αˉt m,vt)\mathcal{N}(\pm \sqrt{\bar{\alpha}_t}\, m, v_t), where mm and v0v_0 are the variables m and v0, and vt=αˉt v0+σt2v_t = \bar{\alpha}_t\, v_0 + \sigma_t^2 is the noised component variance. The label yy names the right class. Show that −(log⁡p~t)′′(x)=1/vt+(γ−1) at2 ς(atx) (1−ς(atx))-(\log \tilde{p}_t)''(x) = 1/v_t + (\gamma - 1)\, a_t^2\, \varsigma(a_t x)\, (1 - \varsigma(a_t x)), where at=2αˉt m/vta_t = 2 \sqrt{\bar{\alpha}_t}\, m / v_t and ς(u)=1/(1+e−u)\varsigma(u) = 1 / (1 + e^{-u}) is the logistic function.
  2. Find the smallest γ\gamma for which p~t\tilde{p}_t violates the bound of (a) at some xx. Evaluate it at the levels t=0t = 0, 100100, and 500500 of alpha_bar, and find its limit as t→Nt \to N. What do the values say about the densities that the chain of cfg_sample follows at γ=3\gamma = 3?
  1. Score error and likelihood. ●● With the likelihood weighting w=g2w = g^2, the population score loss bounds the Kullback–Leibler divergence from the data to the model, by Theorem 1 of Song et al. (2021). The paper proves the bound with path measures; this problem derives it from the Fokker–Planck equation of Section 26.5.2, following Lu et al. (2022), who take this route for the SDE (their Proposition C.1) and for the probability-flow ODE (their Theorem 3.1). Let the forward SDE dx=f(x,t) dt+g(t) dWd\mathbf{x} = \mathbf{f}(\mathbf{x}, t)\, dt + g(t)\, d\mathbf{W} have marginals ptp_t on [0,T][0, T]. In reverse time tˉ=T−t\bar t = T - t, the exact reversal and the model are
dx=[−f+g2 ∇log⁡pt]dtˉ+g dBtˉ,dx=[−f+g2 sθ(x,t)]dtˉ+g dBtˉ,(26.6.18)\begin{aligned}d\mathbf{x} &= \left[ -\mathbf{f} + g^2\, \nabla \log p_t \right] d\bar t + g\, d\mathbf{B}_{\bar t}, \\ d\mathbf{x} &= \left[ -\mathbf{f} + g^2\, \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}, t) \right] d\bar t + g\, d\mathbf{B}_{\bar t},\end{aligned} \tag{26.6.18}

evaluated at t=T−tˉt = T - \bar t. The first has marginals ptp_t; the second, started from a prior π\pi at tˉ=0\bar t = 0, has marginals qtq_t. Assume that all densities are smooth and positive and decay fast enough for every integration by parts.

  1. Write both Fokker–Planck equations in tˉ\bar t in the form ∂tˉρ=−∇⋅(ρ u)\partial_{\bar t} \rho = -\nabla \cdot (\rho\, \mathbf{u}), and identify the velocities up\mathbf{u}_p and uq\mathbf{u}_q.
  2. Show that ddtˉDKL(pt ∥ qt)=Ept[(up−uq)⊤∇log⁡(pt/qt)]\frac{d}{d\bar t} D_{\textrm{KL}}(p_t \,\|\, q_t) = \mathbb{E}_{p_t}\left[ (\mathbf{u}_p - \mathbf{u}_q)^\top \nabla \log (p_t / q_t) \right].
  3. Bound the right-hand side by 12g2 Ept∥sθ−∇log⁡pt∥2\tfrac12 g^2\, \mathbb{E}_{p_t} \| \mathbf{s}_{\boldsymbol{\theta}} - \nabla \log p_t \|^2, integrate over tˉ\bar t, and obtain
DKL(p0 ∥ q0)≤DKL(pT ∥ π)+12∫0Tg(t)2 Ept∥sθ(x,t)−∇log⁡pt(x)∥2dt.(26.6.19)\begin{aligned}D_{\textrm{KL}}(p_0 \,\|\, q_0) &\le D_{\textrm{KL}}(p_T \,\|\, \pi) \\ &\quad + \frac12 \int_0^T g(t)^2\, \mathbb{E}_{p_t} \left\| \mathbf{s}_{\boldsymbol{\theta}}(\mathbf{x}, t) - \nabla \log p_t(\mathbf{x}) \right\|^2 dt.\end{aligned} \tag{26.6.19}

Under which condition on qtq_t is the bound of the derivative tight?

  1. Repeat (a) and (b) for the probability-flow ODE with sθ\mathbf{s}_{\boldsymbol{\theta}} in place of the score. Which term that made (c) possible is missing, and why does the score loss alone no longer bound DKL(p0 ∥ q0)D_{\textrm{KL}}(p_0 \,\|\, q_0)?
  1. [extended] Learned noise prediction. ●● The cell that defines fit_eps learns the noise prediction with 17 fixed features and a separate fit at each of 5050 levels. A diffusion model has one network for all levels. Build it for the same data, the draws draw(size) of the lopsided standardized mixture, under the DDPM schedule beta and alpha_bar.

    1. In the framework of your tab, train a noise-prediction network ϵθ(xt,t)\epsilon_{\boldsymbol{\theta}}(x_t, t) with input (xt,t/1000)(x_t, t/1000) and two hidden layers of 6464 tanh units, with Adam at learning rate 3×10−33\times10^{-3} for 4,000 steps on batches of 256256 fresh draws, on the simple loss with tt uniform over the 1,000 levels. Compute its root-mean-square error against the exact noise prediction eps_hat(xt, a, ws) on samples of ptp_t at several levels tt, and do the same for the fitted features of the text at the levels they were fitted for. Where is each error largest?
    2. Sample with ddim from the noise z at K=10K = 10 and K=50K = 50, and with the ancestral step of Section 26.6.3.2, the loop of cfg_sample with the network's score in place of the guided one. Compare each set of samples with x_exact, x_fit and x_true by the mass of the light mode, the widths of the two modes, and ks. Which sampler is most sensitive to the error of (a), and at which step of that sampler does the error enter?
    3. Retrain with the per-level weights that correspond to w=1w = 1 and to the likelihood weighting w=βw = \beta, that is, with the noise loss at level tt multiplied by w(t)/(1−αˉt)w(t) / (1 - \bar{\alpha}_t), and repeat (a) and (b). Exercise 4 predicts which levels each weighting serves: do the errors agree?

    The deliverable is a table of the statistics of (b) for each weighting and sampler, together with a plot of the error of (a) against tt.

Discussions