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 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 , in practice a network with inputs and 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 with a network and the normalizer (LeCun et al., 2006). Maximum likelihood needs , a -dimensional integral that changes with every update of . The score in does not see it: is a constant in , so .
So we compare fields instead of densities. With 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:
It is zero exactly when the model field equals the data score wherever the data have mass. When is the score of a density , this is the Fisher divergence of Section 25.5.1, which also discusses what such a divergence can and cannot see. Here may be any vector field, because a network with outputs need not be the gradient of anything. The objective has removed the normalizer, but it still contains , the one field we do not know. Hyvärinen's integration by parts removes it.
Proposition (Hyvärinen's identity). Let be a smooth positive density and a smooth vector field, with as and all the expectations below finite. Then
where is the divergence and does not depend on .
Proof. Expand the square in (26.6.1). The term is the constant , the term appears unchanged in (26.6.2), and it remains to transform the cross term. In one dimension,
and integrating by parts with the boundary term leaves . This is Stein's identity of Section 25.5.2: the derivative has moved from the unknown density onto the model. In dimensions, apply the same step to each coordinate , with in place of and in place of , integrating over first; Fubini's theorem allows this under the stated integrability. Summed over , the cross term becomes .
Every term on the right of (26.6.2) is an expectation under of something we can evaluate for a given model, so a sample average estimates it, with no and no . The right-hand side is called implicit score matching.
A Gaussian shows that the identity works. Let the data be , whose score is , and take the one-parameter model . Then , so the implicit objective is . Its derivative vanishes at : the objective never saw the data score and still returns the variance. The constant agrees as well. At the minimum , and , so the explicit objective is there, as it must be when the model matches the data.
In practice the expectation is a sample average. Let us replace in by the mean of over 10,000 draws from and minimize over a grid of . The minimizer is then that sample mean, whose standard error is , so we should see 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 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 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, . Computing it exactly takes one reverse-mode pass per row of the Jacobian, passes in all, and 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 :
The noised marginal is the data density blurred by a Gaussian, and it approaches as shrinks. Its score is as unknown as the data score. The score of the conditional, however, follows from the logarithm of a Gaussian density:
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:
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 be jointly distributed with , and let . Then for every measurable with ,
The second term does not involve : minimizing a least-squares loss against the noisy target is the same problem as minimizing it against the conditional mean , up to an additive constant.
Proof. Insert and expand. The cross term is . By the tower rule (Section 24.2) we may first average over with fixed, and makes the cross term vanish.
Proposition (Vincent's theorem). Let the noising kernel be differentiable in , with gradient and integral over interchangeable (both hold for the Gaussian kernel), and let the DSM target and have finite second moments. Then
with independent of . The right-hand side is the explicit objective (26.6.1) for , so denoising and explicit score matching on the noised data have the same minimizers and the same gradients.
Proof. Apply the lemma with and . It remains to identify the conditional mean of , and the identification is the content of the theorem: the marginal score is the posterior mean of the conditional scores. Writing the posterior by Bayes' rule and then exchanging gradient and integral,
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 ). 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 . Predicting the score and predicting the noise are therefore the same task, and a network that predicts the noise defines the score model . This noise-prediction form is the one diffusion models use.
Example: the Gaussian. Let the data be again, noised at level . The noised marginal is , with score . Bayes' rule for two Gaussians gives the posterior of the clean point,
a shrinkage of the noisy point toward the data mean, with a spread that does not depend on . Every claim of this subsection becomes a formula. The conditional mean of the target is , 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, . With and the floor is , and the posterior mean of the clean point is . 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 on the targets, not , because many clean points explain one noisy point and the regression can only return their average. Here a loss of is a perfect fit, and a loss of zero is impossible. The slope is the shrinkage factor . 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 gives
The best denoiser under squared error moves the noisy point one step of size up the score of the noised data (Figure 26.6.1). For the Gaussian it reads , the slope just measured.
Tweedie's formula for the mixture noised at . A noisy observation lies in the low-density valley of the noised density . The posterior of the clean point is bimodal but asymmetric, and the step lands on its mean , the optimal denoiser.
The floor is general as well. At the optimum the mean squared error equals , 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 , which gives . The target has in dimensions, and its conditional mean is the score, so
For the Gaussian this is 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 as . The target 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 ,
so no eigenvalue of exceeds .
Proof. By Tweedie's formula (26.6.6), , so it remains to differentiate the posterior mean . The posterior depends on through Bayes' rule, which gives . Differentiating under the integral with , the Jacobian of the posterior mean is
Subtracting the Jacobian of and dividing by gives (26.6.8). A covariance is positive semidefinite, which gives the bound.
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 , the curvature of , 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, , noised at . Noising adds to each component's variance, so is again a mixture, with component variance . As derived in Section 26.5.3, a symmetric mixture with means and common component variance has the score . With and the target curve is
Near each mode it is close to , the linear score of a single component. Between the modes it rises from about at to at , 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 centered on
plus the identity . We choose it because fitting the DSM loss
(26.6.4) is then ordinary least squares on the pairs
, 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 . The
printed mean squared errors are , 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 that spreads over several units at every . Through the cloud runs its conditional mean, the score of , and the least-squares fit lies on it. The printout follows the regression lemma. The population floor (26.6.7), here computed by quadrature, is . 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 , 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 , under one percent of the floor.
The last number shows the limit of the method. No noisy pair lands beyond , so at the fit is whatever the basis extrapolates to. The printed value may fall near the exact 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 , on the flank of the right mode, where pairs are plentiful, and at , 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 to . 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 the twenty fits stay within about two tenths of the exact score . At 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 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
whose drift is half the score and whose noise is a standard Brownian motion . The claim is that is its stationary law.
For the Gaussian , with score , we already know this. Then (26.6.9) reads , an Ornstein–Uhlenbeck process. An OU process has the stationary law (Section 26.4.3), and here and give the variance . The proposition extends this to smooth targets whose score grows at most linearly.
Proposition (stationarity). Let be a smooth positive density whose score 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 , then for all .
Proof. For an SDE with unit diffusion, the density of solves the Fokker–Planck equation (Section 26.5.2). Substitute and , and use :
So solves the equation with the initial density . Uniqueness turns " solves the equation" into "the law of is ".
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 does converge to 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 is the Langevin sampler
which needs only a score , exact or learned. The discretized chain does not inherit the stationarity of the SDE. For the Gaussian the step is the linear recursion , whose stationary variance solves . Hence , and the sampler overstates the variance by about (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, , and let us give it the exact score of , not a fit, so that whatever goes wrong is the sampler's doing. A fifth of the mass of lies right of zero, and whatever the weights. We run 10,000 chains for 2,000 steps of size , three times: from a broad start , 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 .
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 per run. An error in the proportions therefore shrinks by a factor only every steps, more than thirty times the length of our run.
This changes how the first line must be read. The second moment matches to within a few hundredths, the sampling error of 10,000 chains (the step-size bias 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 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 (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 the noised density has no valley, and the noisy pairs cover the whole region a sampler visits. For the symmetric mixture, has component variance and is unimodal once its component standard deviation reaches the distance from the center to each mean (Exercise 4 of the previous section), that is, for . Unequal weights close the valley sooner. As 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 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 and whose noise amplitude does not depend on 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
The coefficient shrinks the signal and scales the noise. The two processes differ only in these two numbers.
- The variance-exploding (VE) SDE , with increasing and , adds noise without shrinking the data: and . 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,
with and , so that unit-variance data keep unit variance at every (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 , the conditional score is , and DSM applies at each level. Averaging over levels with a weight gives the noise-conditional DSM loss
with drawn uniformly from the training range. Each draw of 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 the population minimizer is at every , 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 is , which grows like at small . An unweighted loss is therefore dominated by its least noisy levels.
Two weights are standard. The discrete-time model of the next subsection uses , which cancels this growth, so that every level contributes a loss of the same order.
The likelihood weighting , 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 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 , and the weighted floor grows like as , so its integral down to is infinite. Training therefore starts at a small time (Exercise 4).
Generation needs nothing new. The two samplers run with the learned field in place of the exact score. For a forward SDE on , we start from the Gaussian that approximates and integrate either the reverse-time SDE (Section 26.5.5) or the probability-flow ODE (Section 26.5.4.3) from down to :
where is a Brownian motion running backward in time. For VP, and .
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.
A two-moons distribution under the VP forward process at , , and (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 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 noising steps with a schedule ,
which shrinks the state slightly and adds a little noise at each step. In this subsection and the next, counts levels, , and level stands for the time of the SDE, with .
How is the chain related to the VP-SDE? With the step agrees to first order in with the Euler–Maruyama step 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 , with the integral of taken between those times. Take an interval on which . The mean coefficient of its kernel is and the variance is , the law of (26.6.12) given . For the largest step of the standard schedule, , such an interval has instead of . The DDPM chain is therefore the VP process observed at discrete times, and the law of given is a VP kernel from time . 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 -marginal). Let . Then conditionally on ,
Proof. Induction on ; the case holds with . Assume (26.6.13) at and substitute it into (26.6.12):
with and independent standard Gaussians. A sum of independent Gaussians is Gaussian with the sum of the variances, , and .
In the kernel notation of the previous subsection, DDPM has and . 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 . Parameterize the score model through a noise-prediction network, . Then
so the DDPM simple loss is the noise-conditional DSM loss (26.6.10) with weight . "Predict the noise you added" is denoising score matching with a weight that cancels the growth of the floor: every level contributes a loss of order . (A warning for readers of (Ho et al., 2020): the paper writes for , where our is the signal coefficient , and its simple loss lacks our factor .)
The third part is the sampler. Ancestral sampling steps through the levels from down to ,
without the noise in the last step. To first order in this is , 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 from to over levels. The VP process is built for data of unit variance, so from here on the mixture is standardized: divided by , with modes at and component standard deviation . Before any sampling, let us look at the schedule itself. We print at three levels and, at the first and the last level, the ratio 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 , and the noised law is still bimodal, with modes at and component standard deviation . At , , 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 to , by four orders of magnitude.
26.6.4 Deterministic Sampling and Guidance#
Ancestral sampling calls the network once per level, 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 , the network's noise estimate gives a guess of the clean sample by inverting the marginal (26.6.13),
To move to any earlier level , DDIM rebuilds the sample from this guess and the same noise estimate, with the coefficients of level :
The update is deterministic: no fresh noise enters. Read literally, it moves a sample along the forward curve of the pair . But a network trained by least squares returns the conditional mean , 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 . The rescaled point equals with , 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 , which grows from at the first level to at the last. The schedule only decides which values of the grid visits. On and the bar marks the rescaled point and its noise level; the bar on is DDPM's and means something else.
Proposition (DDIM is Euler's method). In the coordinates the DDIM update (26.6.14) reads
one Euler step of the ODE . If is the exact noise prediction , this ODE is the probability-flow ODE of the VP process, written in the coordinates .
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), is the continuous time of the SDE.
(i) Divide (26.6.14) by and substitute : .
(ii) Change variables in the VP probability-flow ODE of (26.6.11), with and . Let be the density of ; then . Since , the shrinkage terms cancel and . Since , we have , and dividing gives .
(iii) Tweedie's formula for the kernel reads , so , the right-hand side of (ii). Conditioning on is the same as conditioning on .
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 fixed while the exact 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 , every DDIM stride with the exact lands on the probability-flow trajectory, whatever its length. Here , and along a solution of the ratio is constant. An Euler step for a constant right-hand side is exact.
Corollary (Gaussian data shrink). For data the exact flow is the identity, but one DDIM stride with the exact noise prediction multiplies every sample by
which is below for every stride of positive length. The VP process leaves such data as they are: the marginal is at every level, the score is , and the probability-flow drift vanishes, so no sample of the exact flow moves. By Tweedie, , and substituting into (26.6.14) gives the factor. Writing turns it into the cosine of the angle advanced. In the bar coordinates the exact solution is , so 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 , where the noised law at level has modes and component variance , with and 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 , fifty by , and 999 by . 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 to , as a first-order method should. The mixture behaves the same way. Ten strides land on average from the 999-stride result, on a scale where the modes sit at , and the KS statistic is as well. Fifty strides reduce both numbers to about . Figure 26.6.3 draws both experiments.
(a) Each forward pair 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 , 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 and , reweighted so that the left one holds of the mass and the right one .
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 on the features of the noisy point, evaluated at 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 , 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 .
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 . 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 and a heavy mode that is slightly too narrow, about against . 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 . The fit adds one visible error of its own, a light mode of width to where the exact row has about . 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 returns samples of every kind that contains. Often we want one kind only: images of one class, or images that fit a caption. Guidance steers a sampler toward a class 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 be "the right mode", so that we want samples from the class alone, with and . Bayes' rule at noise level , , becomes additive for scores, because the evidence does not depend on :
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 of noisy inputs and scales it by a guidance scale :
With this is Bayes' rule. With 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, , and so needs no classifier, only a conditional and an unconditional score model and , which one network can supply (Section 17.4.4.2):
equivalently , which for extrapolates past the conditional score.
One fact limits the interpretation of . The tilted density is in general not the noised marginal of any clean distribution. The marginal is the law of noised at scale , so by the curvature bound (26.6.8) no eigenvalue of exceeds , whatever the data. Raising the classifier to the power adds curvature, most of it midway between the classes. For the mixture the bound fails there once , where is the variance of a noised class (Exercise 6). This threshold is at the noisiest levels and at . At the bound holds only at about ten of the thousand levels, the least noisy ones, and at 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 . 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 , combined by (26.6.17) at .
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 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 of the exact and . At and there is no mass left to move between modes, so the guidance moves the mode itself, to about and then to between and , away from the class boundary. The width hardly changes and stays within about of .
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 for every . A chain that followed the marginals of one forward process would end on it. At and ours ends about and 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 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, . 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 as its loss. DDIM is Euler's method for the probability-flow ODE in the coordinates , 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 and that a single level could not. Guidance is Bayes' rule on scores, and for it follows densities that curve more sharply than any noised density can.
26.6.6 Exercises#
-
[code] Langevin discretization bias. For the Gaussian target , the Langevin sampler of (26.6.9) with step is the linear recursion .
- Find the step sizes for which the recursion has a stationary distribution, compute its variance, and expand the bias to first order in .
- Treat each mode of the mixture in the cell that defines
langevinas a separate Gaussian with , and predict the stationary at . Compare each predicted bias with the Monte Carlo standard error of an estimate from 10,000 chains. Then runlangevinfor 2,000 steps at each of these step sizes from the initial pointsrng.normal(0.0, 3.0, 10000)ofwarm. From which step size on does the experiment resolve the bias? - The Metropolis-adjusted Langevin algorithm (Roberts and Tweedie, 1996) removes the bias with an accept–reject test that needs the density ratio . Why can a sampler that has only a trained score network not apply this test directly?
-
[code] Annealing out of one mode. In the cell that defines
langevin, chains started in one mode of 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 , here the mixture with component variance , for the decreasing sequence of noise levels .- With equal weights, has no valley for , as
the text found. With the weights and the valley closes
sooner. Count the sign changes of
mixture_scorewithws=(0.8, 0.2)on a fine grid to find the smallest without a valley. Which levels of the sequence have no valley? - Run steps of
langevinat each level of the sequence, passing the component variance asvar, for 10,000 chains started at and again for 10,000 chains started at . Do this once with the fixed step and once with , which equals at . Report the fraction of chains with at the end of each of the four runs. Which step rule forgets the start? Its fraction comes close to the target without reaching it. Compute the mass of to the right of zero at each level, and say at which level the proportions were fixed. - Song and Ermon (2019) scale the step size of each level with . Use the contraction factor of the linear recursion in Exercise 1 to explain why the fixed step fails at the large noise levels.
- With equal weights, has no valley for , as
the text found. With the weights and the valley closes
sooner. Count the sign changes of
-
[code] The Bayes-risk floor. ● The cell that fits
w_lsprints 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.- The text obtains the floor (26.6.7), the Bayes risk of the regression, from the lemma with . Use Tweedie's formula (26.6.6) to show that it also equals , and check that the two expressions agree for . What does the floor do as for data with a smooth density, and what for a training set of distinct points? What does the optimal denoiser of the training set return in that limit?
- 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.
-
Weightings across noise levels. ● Consider the VP-SDE with the linear schedule on , with and , so that and . Let the data in have a smooth density, and assume that stays bounded as . Write for the Bayes risk of the noise-conditional DSM loss (26.6.10) at level , the floor (26.6.7) with in place of .
- Show that as .
- Find the behavior of as for , for the DDPM weighting , and for the likelihood weighting . For which weightings is finite, and which noise levels does each weighting emphasize?
- Training draws uniformly from . For the likelihood weighting, show that the second moment of under this draw grows like . Song et al. (2021) (Section 5.1) instead draw from the density proportional to on and multiply the DSM term at the drawn level by , with the constant . Show that this estimate is unbiased for the likelihood-weighted loss and that its value at the optimum, , stays bounded as .
-
[code] Guidance by noise level. ● In the cell that defines
cfg_sample, raising from to moves the mean of the guided samples from about to between and .- The text claims that at the clean level the tilted density is the
class itself. Check it. At the last level of the chain, in
cfg_sample, the class posterior of the right mode is a logistic function of . Write it, and compute by quadrature the mean of the tilted density proportional to at that level for . How far is each mean from , and how far are the printed means? - Modify
cfg_sampleso that it uses only on the steps , only on , or only on , and on the others. Which band of noise levels produces the shift? Relate the answer to the separation of the two noised classes, where and are the variablesmandv0, and is the noised component variance, the variablevofcfg_sample. - 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?
- The text claims that at the clean level the tilted density is the
class itself. Check it. At the last level of the chain, in
-
Guided densities and noised marginals. ● The guided field (26.6.17) with is the score of the tilted density . Call a density a noised marginal at level if it is the law of , with , for some clean distribution of .
- Apply (26.6.8) to the clean variable to show that a noised marginal has
Conclude that no eigenvalue of exceeds , whatever the clean distribution.
- In
cfg_sample, the two noised classes are , where and are the variablesmandv0, and is the noised component variance. The label names the right class. Show that , where and is the logistic function. - Find the smallest for which violates the bound of
(a) at some . Evaluate it at the levels , , and of
alpha_bar, and find its limit as . What do the values say about the densities that the chain ofcfg_samplefollows at ?
- Score error and likelihood. ●● With the likelihood weighting , 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 have marginals on . In reverse time , the exact reversal and the model are
evaluated at . The first has marginals ; the second, started from a prior at , has marginals . Assume that all densities are smooth and positive and decay fast enough for every integration by parts.
- Write both Fokker–Planck equations in in the form , and identify the velocities and .
- Show that .
- Bound the right-hand side by , integrate over , and obtain
Under which condition on is the bound of the derivative tight?
- Repeat (a) and (b) for the probability-flow ODE with in place of the score. Which term that made (c) possible is missing, and why does the score loss alone no longer bound ?
-
[extended] Learned noise prediction. ●● The cell that defines
fit_epslearns the noise prediction with 17 fixed features and a separate fit at each of levels. A diffusion model has one network for all levels. Build it for the same data, the drawsdraw(size)of the lopsided standardized mixture, under the DDPM schedulebetaandalpha_bar.- In the framework of your tab, train a noise-prediction network
with input and
two hidden layers of tanh units, with Adam at learning rate
for 4,000 steps on batches of fresh draws, on
the simple loss with 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 at several levels , and do the same for the fitted features of the text at the levels they were fitted for. Where is each error largest? - Sample with
ddimfrom the noisezat and , and with the ancestral step of Section 26.6.3.2, the loop ofcfg_samplewith the network's score in place of the guided one. Compare each set of samples withx_exact,x_fitandx_trueby the mass of the light mode, the widths of the two modes, andks. Which sampler is most sensitive to the error of (a), and at which step of that sampler does the error enter? - Retrain with the per-level weights that correspond to and to the likelihood weighting , that is, with the noise loss at level multiplied by , 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 .
- In the framework of your tab, train a noise-prediction network
with input and
two hidden layers of tanh units, with Adam at learning rate
for 4,000 steps on batches of fresh draws, on
the simple loss with uniform over the 1,000 levels. Compute its
root-mean-square error against the exact noise prediction