17.1 Denoising and the Score
A network trained by squared error learns the conditional expectation of its target given its input (Section 16.7). When we corrupt a clean data point with isotropic Gaussian noise to form , the optimal least-squares denoiser is therefore the posterior mean . By Tweedie's formula (Robbins, 1956; Miyasawa, 1961; Efron, 2011), this posterior mean is directly determined by the gradient of the log-density of the noised data, , known as the score function. Moreover, Vincent (2011) showed that regressing a network onto the score of the Gaussian perturbation kernel fits without requiring access to the underlying data density .
Learning the score rather than the density itself sidesteps the intractable normalizing constant required by energy-based models, while still providing the vector field needed to generate samples via gradient-based MCMC such as Langevin dynamics. In this section, we first introduce a two-dimensional Gaussian mixture on which the density, score, and posterior mean are exact at every noise level. We use this benchmark to verify Tweedie's formula, examine why a score model trained at any single noise level cannot simultaneously resolve local mode structure and global mode weights, and finally apply single-level denoising to Fashion-MNIST images.
torch.set_float32_matmul_precision('high') # tf32 matmuls on tensor cores17.1.1 The Running Example#
We want one distribution on which every quantity of the chapter is exact at every noise level, so that each learned field and sampler can be checked against the truth. A mixture of Gaussians in the plane will do. Ours has three components with means , and , mixture weights , and a common standard deviation per coordinate. The modes are far apart compared with their width, so the density has deep valleys between them, and the unequal weights give a sampler something to get wrong.
The score of a density is the gradient of its logarithm, , a vector field that points in the direction in which the density grows fastest. For the mixture it reads
Each component pulls the point toward its own mean, and the pulls are averaged with the responsibilities , the posterior probabilities that was drawn from component (Figure 17.1.1). The weights enter only through the responsibilities. Near a mode one responsibility is close to one whatever the weights are, so the weights change the score only in the valleys, where few points lie. The remark looks harmless, but it will decide what a score model can learn.
The score is the gradient of the log-density. Left: a bimodal density in one dimension (top) and its score (bottom), zero at both modes and at the valley between them. Right: the running example, with its density as shaded contours and its score field as arrows that point toward the modes (arrow lengths clipped).
Noise keeps a mixture of Gaussians a mixture of Gaussians. Adding Gaussian noise of standard deviation to a draw adds to the variance of each component, so becomes , and the density, score and posterior mean have closed forms at every noise level. The class below evaluates all three; its argument alpha, a scale on the clean point, stays at one until the next section.
class GaussianMixture:
"""A mixture of isotropic Gaussians, exact at every noise level."""
def __init__(self, means, weights, std, device=None):
self.means = torch.tensor(means, dtype=torch.float32, device=device)
self.weights = torch.tensor(weights, dtype=torch.float32,
device=device)
self.std = std
@staticmethod
def three_modes(device=None):
"""The chapter's running example, with mode weights 0.5/0.3/0.2."""
return GaussianMixture([[-2.5, -1.5], [2.5, -1.5], [0.0, 2.5]],
[0.5, 0.3, 0.2], 0.5, device)
def sample(self, n):
"""n draws from the mixture."""
k = torch.multinomial(self.weights, n, replacement=True)
return self.means[k] + self.std * torch.randn(
n, self.means.shape[1], device=self.means.device)
def _modes(self, x, alpha, sigma):
"""Per-mode log densities, offsets x - alpha mu_k, variances, alpha."""
a, s = (torch.as_tensor(v, dtype=x.dtype, device=x.device)
.reshape(-1, 1, 1) for v in (alpha, sigma))
var = (a * self.std) ** 2 + s ** 2
r = x[:, None] - a * self.means
log_p = (torch.log(self.weights) - (r ** 2).sum(-1) / (2 * var[..., 0])
- x.shape[1] / 2 * torch.log(2 * torch.pi * var[..., 0]))
return log_p, r, var, a
def log_prob(self, x, alpha=1.0, sigma=0.0):
"""log p(x) for x = alpha x0 + sigma eps."""
return torch.logsumexp(self._modes(x, alpha, sigma)[0], 1)
def score(self, x, alpha=1.0, sigma=0.0):
"""The gradient of log p(x) for x = alpha x0 + sigma eps."""
log_p, r, var, _ = self._modes(x, alpha, sigma)
return -(torch.softmax(log_p, 1)[..., None] * r / var).sum(1)
def posterior_mean(self, x, alpha, sigma):
"""E[x0 | x]; finite at alpha = 0 and at sigma = 0."""
log_p, r, var, a = self._modes(x, alpha, sigma)
return (torch.softmax(log_p, 1)[..., None]
* (self.means + a * self.std ** 2 / var * r)).sum(1)Throughout the chapter, samplers on this mixture are judged by the same yardsticks: the mean negative log-likelihood of their points under the true density, and three numbers from summary. The mode weights count each point at its nearest mean. The strays are the fraction of points farther than from every mean. The spread is the mean squared distance of the remaining points to their nearest mean; since it ignores the strays, it can never exceed , and a sampler that is far too wide shows up mainly as strays.
@d2l.add_to_class(GaussianMixture)
def nll(self, x):
"""Mean negative log-likelihood of clean points, in nats."""
return -self.log_prob(x).mean()
@d2l.add_to_class(GaussianMixture)
def summary(self, x):
"""Mode weights by nearest mean, stray fraction, spread of the rest."""
d2 = ((x[:, None] - self.means) ** 2).sum(-1)
near, k = d2.min(1)
inside = near < (3 * self.std) ** 2
weights = torch.bincount(k, minlength=len(self.weights)) / len(x)
return dict(weights=[round(w, 3) for w in weights.tolist()],
stray=round(1 - inside.float().mean().item(), 4),
spread=round(near[inside].mean().item(), 3))To compare 2D point clouds visually alongside these numerical summaries,
scatter_panels plots one or more sample sets side by side on shared axes
(optionally overlaying a reference dataset data in light gray):
def scatter_panels(samples, titles=None, data=None, lim=4.5,
size=3.0):
"""Scatter 2-D point sets side by side on equal, shared axes."""
_, axes = d2l.plt.subplots(1, len(samples), squeeze=False,
figsize=(size * len(samples), size))
for i, (ax, pts) in enumerate(zip(axes[0], samples)):
if data is not None:
ax.scatter(*d2l.numpy(data).T, s=2, c='lightgray')
ax.scatter(*d2l.numpy(pts).T, s=2)
ax.set(xlim=(-lim, lim), ylim=(-lim, lim), aspect='equal')
if titles:
ax.set_title(titles[i])
return axes[0]What should a perfect sampler print? The weights , and , up to sampling noise. In two dimensions the squared distance of a Gaussian draw from its mean is exponentially distributed with mean , so a fraction of the points stray, and the spread of the rest is a little below . We check this on 2,000 draws, the training set of the section's two-dimensional experiments.
torch.manual_seed(0)
mix = d2l.GaussianMixture.three_modes()
data = mix.sample(2000)
print(mix.summary(data), f'NLL {mix.nll(data):.3f}')
d2l.scatter_panels([data], ['2,000 draws']);{'weights': [0.5, 0.317, 0.183], 'stray': 0.012, 'spread': 0.488} NLL 2.504

The draws print what we predicted. These are the values every sampler on the mixture aims for. The negative log-likelihood needs a word of care. About nats per point is the entropy of the mixture: no density model scores fresh data lower on average, and the points of a correct sampler score about this much under . For a sampler it is a target, not a bound to beat: points crowded at the modes score less, and points in the valleys more.
17.1.2 The Optimal Denoiser#
The regression of the opening has two natural targets, the clean point and a vector that points to it. The identity that links their minimizers is the most important result of this section.
17.1.2.1 Noise and the Regression Target#
Pick a noise level , draw a clean point and standard Gaussian noise , and form the noisy point . Its density is the data density blurred by a Gaussian of width , positive and smooth everywhere even when is not. A denoiser is trained to minimize . Squared error is minimized by the conditional mean of the target given the input, the fact recalled at the start of this section (Section 16.7), so the optimal denoiser is the posterior mean : the average of the clean points that could have produced , each weighted by how likely it is to have done so.
The same regression can aim at a different target. Given the clean point, the noisy point is Gaussian around it, and the score of this conditional density is
a vector pointing from the noisy point back to the clean one. Denoising score matching regresses a vector field onto it (Vincent, 2011):
The minimizer is again a conditional mean, now of the conditional score, and Vincent's theorem identifies it: the score of the noised data is the posterior mean of the conditional score,
The proof is two lines of Bayes' rule. The noisy density is the clean one blurred by the noise, . Differentiate under the integral, write the gradient of the kernel as the kernel times the gradient of its logarithm, and divide by :
The fraction is Bayes' rule for the posterior , so the right-hand side is the posterior mean of the conditional score, which is (17.1.4). Nothing in the two lines used that the noise is Gaussian; the conditions under which the gradient may move inside the integral are in Section 26.6.1.2.
The regression on per-pair targets therefore fits the score of , which we never wrote down. This is the reason the chapter can train generators by regression at all: we cannot evaluate the score of the data, but we can evaluate the score of the noise we added ourselves.
17.1.2.2 Tweedie's Formula#
The two regressions, onto the clean point and onto , have targets related by the map , which is affine once is given, so their minimizers, two conditional means, are related by the same map. Solving for the posterior mean gives Tweedie's formula (Efron, 2011),
The best denoiser takes one step of size up the score of the noisy density (Figure 26.6.1). A denoiser, a score and a noise predictor are therefore three ways of writing one posterior mean:
A network trained to output any one of the three gives the other two.
The smallest case shows what the step does. Let the data be Gaussian, . Then has the score , and Tweedie's formula gives
The denoiser shrinks the noisy offset from the mean by the factor , and the posterior variance per coordinate is . With and the factor is , and the squared error per coordinate falls from to . Away from the valleys the posterior mean of the running example is this shrinkage toward the nearest mean, so over the two coordinates of a point denoising should lower the squared error from to about .
17.1.2.3 A Trained Score#
Does a learned score reach this best denoiser? To find out we need a network, and the chapter uses one small MLP for all its two-dimensional experiments. Besides the point it reads sines and cosines of the noise level (from the next section on, of a time along a path from data to noise). Here the level is fixed and these features do nothing. From the next section on, one network serves every level and must tell nearby levels apart, so the frequencies run from 1 to 64 radians per unit of , and the fastest features complete about ten periods on . The positional encodings of Section 10.4, built for integer token positions in the thousands, would be nearly constant or linear on this interval. The few-step generators of Section 17.8 lower the frequencies again, for a reason given there.
def time_embedding(t, dim, freqs=(1.0, 64.0)):
"""Sines and cosines of t at dim / 2 frequencies, geometric from freqs[0]
to freqs[1] radians per unit of t (t in [0, 1])."""
f = torch.exp(torch.linspace(math.log(freqs[0]), math.log(freqs[1]),
dim // 2, device=t.device))
args = t.float()[:, None] * f
return torch.cat([args.sin(), args.cos()], 1)
class TimeMLP(nn.Module):
"""An MLP on a point x and the time features of one or more times;
time_freqs: see time_embedding."""
def __init__(self, hidden=256, depth=3, *, dim=2, num_times=1,
time_dim=64, time_freqs=(1.0, 64.0)):
super().__init__()
self.time_dim, self.time_freqs = time_dim, time_freqs
self.embed = d2l.make_mlp([time_dim * num_times, hidden, hidden],
nn.SiLU())
self.inp = nn.Linear(dim, hidden)
self.body = nn.Sequential( # depth layers, each after a SiLU
nn.SiLU(), d2l.make_mlp([hidden] * depth + [dim], nn.SiLU()))
def forward(self, x, *ts):
feats = [time_embedding(t, self.time_dim, self.time_freqs) for t in ts]
return self.body(self.inp(x) + self.embed(torch.cat(feats, 1)))One training loop serves the whole chapter: Adam on a fresh minibatch with fresh noise at every step. It also keeps an exponential moving average (EMA) of the weights, which matters from Section 17.4 on; its docstring lists the other options.
def train_regression(model, loss_fn, batch_fn, num_steps, *,
lr=1e-3, cosine=False, ema_half_life=1000,
compiled=True):
"""Adam on loss_fn(model, batch_fn()) -> (model, EMA model, losses).
The learning rate is constant or, with cosine=True, decays to zero along
a cosine. The EMA model averages the weights (d2l.EMA): the weights of
ema_half_life updates ago count half as much as the current ones. On a
GPU, Adam is fused into one kernel and, with compiled=True, the loss and
its gradient run as CUDA graphs: the networks of this chapter are so
small that launching their kernels one at a time would cost more time
than running them."""
params = list(model.parameters())
opt = torch.optim.Adam(params, lr=lr, fused=params[0].is_cuda)
sched = (torch.optim.lr_scheduler.CosineAnnealingLR(opt, num_steps)
if cosine else None)
if compiled and params[0].is_cuda: # loss and gradient as CUDA graphs
loss_fn = torch.compile(loss_fn, mode='reduce-overhead',
dynamic=False)
ema, losses = d2l.EMA(model, ema_half_life), []
for _ in range(num_steps):
loss = loss_fn(model, batch_fn())
opt.zero_grad()
loss.backward()
opt.step()
if sched:
sched.step()
ema.update(model)
losses.append(loss.detach().clone()) # the graph reuses its output
return model, ema.model, torch.stack(losses)For the mixture, a network with two hidden layers of 128 units minimizes (17.1.3) for 2,000 steps, each on 256 of the 2,000 training points with fresh noise, and we keep the trained score as a function of the point alone.
def dsm_loss(net, x, sigma):
"""Denoising score matching at one noise level: regress onto -eps/sigma."""
eps = torch.randn_like(x)
s = net(x + sigma * eps, torch.full((len(x),), sigma))
return 0.5 * ((s + eps / sigma) ** 2).sum(1).mean()
def fit_score(data, sigma, seed=1, num_steps=2000):
"""Train a score network at one noise level and return it as a function."""
torch.manual_seed(seed)
batch_fn = lambda: data[torch.randint(0, len(data), (256,))]
net, _, _ = d2l.train_regression(
d2l.TimeMLP(128, 2), lambda net, x: dsm_loss(net, x, sigma),
batch_fn, num_steps)
return lambda x: net(x, torch.full((len(x),), sigma)).detach()At we noise 20,000 fresh points and compare three guesses of the clean point: the noisy point itself, the exact posterior mean, and Tweedie's step with the trained score.
sigma = 0.3
score = fit_score(data, sigma)
x0 = mix.sample(20000)
xt = x0 + sigma * torch.randn_like(x0)
exact = mix.posterior_mean(xt, 1.0, sigma)
for name, x0_hat in (('noisy point', xt), ('posterior mean', exact),
('Tweedie, trained score', xt + sigma ** 2 * score(xt))):
print(f'{name}: squared error {((x0_hat - x0) ** 2).sum(1).mean():.4f}')noisy point: squared error 0.1782
posterior mean: squared error 0.1317
Tweedie, trained score: squared error 0.1328
The exact posterior mean lowers the squared error from to about , as the Gaussian case predicted, and Tweedie's step with the trained score comes within about one percent of it. After 2,000 steps on 2,000 points the network is a nearly optimal denoiser, and therefore a usable score.
As a score it is a little less good than that sounds. The score enters the denoiser multiplied by , and in expectation the excess error of Tweedie's step over the posterior mean is exactly times the mean squared error of the score; the cross term vanishes because the error of the posterior mean averages to zero given . The gap of about thus stands for a score error of about . A denoiser can look nearly perfect while its score is visibly off, and the score is what a sampler follows.
17.1.2.4 Scores and Normalizers#
Why learn a score rather than a density? A network with a scalar output , called the energy, defines a density through an energy-based model,
The normalizer is what makes learning meaningful: since the total mass is fixed, raising the density on the training points lowers it elsewhere. Unfortunately is an integral over the whole input space that changes with every update, and the gradient of the log-likelihood contains , an expectation that has to be estimated by sampling from the model, in practice with a Markov chain. The score does not see at all, because does not depend on : .
A field is compared with the data by the Fisher divergence, the mean squared distance between the two fields where the data lie:
It contains the unknown data score, which Hyvärinen's identity (Hyvärinen, 2005) removes by integration by parts: up to a constant, equals , an average over data with no normalizer and no chain (Section 26.6.1). Its second term, , the trace of the Jacobian of , costs one backward pass per input dimension, too many for images. Denoising removes that cost as well: by Vincent's theorem, (17.1.3) is the Fisher divergence to up to a constant.
17.1.3 Limits of a Single Noise Level#
A denoiser trained at one noise level gives the score of one blurred distribution, . To sample we want the score of , so the first question is which to choose.
17.1.3.1 Choosing the Noise Level#
A small noise level has two problems. The first is statistical. For data with a smooth density, such as the running example, the target grows like while the score it averages to stays bounded, so at small the target is mostly noise and the network fits it poorly. Even the exact score leaves the variance of the target around its conditional mean in the loss, and in dimensions this floor grows like as shrinks (Section 26.6.1.2). A denoising loss that levels off well above zero is therefore no sign of a bad network.
The second problem matters most for images, which are believed to lie near a low-dimensional set inside pixel space (Bengio et al., 2013). Let us take the extreme case of data on a line in the plane. Noise thickens the line into a band across which is a Gaussian of variance , so the score across the band is at distance from the line (Exercise 3). Its slope, , grows without bound as . Across the band the target equals this score exactly, so the trouble is not noise there: the network must represent a field that turns into a cliff across the data set, while along it the targets are mostly noise.
A large noise level has the opposite problem. The regression is well conditioned, but its answer is the score of , not of . For one Gaussian component in dimensions the two scores are and , and averaging the squared norm of their difference over gives the bias
The bias grows like at first. For and it is at , at and at , and the well-separated mixture has nearly the same values. Divided by the size of the clean score, , it becomes , which depends only on . The smoothed score stays within of the clean one, in root-mean-square terms, while , so we should expect the bias to start to matter near there.
Between the two problems there should be a best level. We train a network at each of seven levels from to , with two seeds, and estimate the Fisher divergence (17.1.8) of each from the clean score on 20,000 test points, next to the bias of the exact smoothed score.
sigmas, seeds = [0.05, 0.1, 0.15, 0.2, 0.3, 0.5, 1.0], (1, 2)
scores = {(sg, seed): fit_score(data, sg, seed)
for seed in seeds for sg in sigmas}
x_test = mix.sample(20000)
target = mix.score(x_test) # the clean score
def score_error(score, x, target):
return 0.5 * ((score(x) - target) ** 2).sum(1).mean().item()
learned = {seed: [score_error(scores[sg, seed], x_test, target)
for sg in sigmas] for seed in seeds}
bias = [score_error(lambda x: mix.score(x, 1.0, sg), x_test, target)
for sg in sigmas]
for seed in seeds:
print(f'trained, seed {seed}:', [round(e, 3) for e in learned[seed]])
print('exact smoothed: ', [round(e, 4) for e in bias])
d2l.plot(sigmas, [*learned.values(), bias], 'sigma',
'error against the clean score', xscale='log', yscale='log',
legend=[f'network, seed {seed}' for seed in seeds]
+ ['exact score of p_sigma'])trained, seed 1: [0.423, 0.189, 0.215, 0.3, 0.409, 1.077, 2.559]
trained, seed 2: [0.541, 0.285, 0.255, 0.252, 0.363, 1.019, 2.532]
exact smoothed: [0.0004, 0.0059, 0.0271, 0.0755, 0.2781, 0.9924, 2.5538]
The learned error traces a U. To the right it follows the bias line, within about from on: the networks fit their blurred targets well, and the targets are wrong. To the left it rises again although the bias vanishes, because the targets are mostly noise, and the second seed changes some errors there by half or more. The best level lies between and , a fifth to two fifths of the component width and around the of the bias rule, at an error of about to . That is the rule for a single level: measure in units of the scale of the data, and take it as small as the network can still fit.
17.1.3.2 Blindness to Mode Weights#
An error of in the Fisher divergence sounds small, but small compared with what? Compare the running example with its equal-weight copy. A model with these wrong weights loses nats of likelihood per point, their Kullback--Leibler divergence. Its score, however, differs from the true one only through the responsibilities in (17.1.1), which differ only in the valleys, where is nearly zero, so the Fisher divergence, an average under , barely sees the difference.
We compute both divergences by quadrature on a grid rather than by sampling, because the Fisher integrand lives in the valleys, where few Monte Carlo draws land, and then repeat the comparison with both mixtures blurred by the same noise.
mix_eq = d2l.GaussianMixture(mix.means.tolist(), [1 / 3] * 3, mix.std)
g = torch.linspace(-9, 9, 721)
grid = torch.stack(torch.meshgrid(g, g, indexing='ij'), -1).reshape(-1, 2)
area = (g[1] - g[0]) ** 2 # of one grid cell
for sigma in (0.0, 0.5, 1.0):
log_p = mix.log_prob(grid, 1.0, sigma)
diff = mix.score(grid, 1.0, sigma) - mix_eq.score(grid, 1.0, sigma)
fisher = area * (log_p.exp() * 0.5 * (diff ** 2).sum(1)).sum()
kl = area * (log_p.exp()
* (log_p - mix_eq.log_prob(grid, 1.0, sigma))).sum()
print(f'sigma = {sigma}: Fisher divergence {fisher:.1e}, KL {kl:.3f} nats')sigma = 0.0: Fisher divergence 1.5e-05, KL 0.069 nats
sigma = 0.5: Fisher divergence 1.4e-03, KL 0.069 nats
sigma = 1.0: Fisher divergence 9.5e-03, KL 0.064 nats
Between the clean mixtures the Fisher divergence is about , four orders of magnitude below the errors of the trained networks, none of which fell below , while the KL divergence is nats. A score model trained near the clean data therefore cannot learn the weights: a field with the wrong weights fits as well as one with the right weights (Section 25.5.1; Exercise 2 of Section 25.5). A score can be excellent near the data and still know nothing about how often each mode occurs.
Noise makes the weights visible. As grows, the components spread into the valleys (Figure 17.1.2), the responsibilities differ where has mass, and the Fisher divergence rises to about at and at , while the KL divergence barely changes. Even at this Fisher divergence is more than ten times smaller than any error in the sweep, so noise alone does not make the weights easy to learn. What it changes first is that chains can cross the valleys.
The running example blurred by Gaussian noise of growing standard deviation ; crosses mark the component means. As grows, the valleys between the modes fill in, until at a single broad bump remains.
17.1.3.3 Sampling with a Score#
A score is enough to draw samples, and the simplest way to do it is more than a century old. Paul Langevin wrote down an equation of this kind in 1908 for a particle in a fluid, pushed by a force and kicked at random by the molecules around it. In discrete form, Langevin dynamics starts from any point and repeats
with a small step size . The drift moves the point up the log-density, and the noise keeps it from collapsing onto a mode. In the continuous-time limit, is the stationary distribution whenever (Section 26.6.2), and a chain run long enough forgets its start. The discrete update is slightly off: for a Gaussian of variance its stationary variance is , a five percent excess for our components at . Nothing in the update refers to a density, so any vector field can drive it, including a trained one that is not the gradient of anything.
@torch.no_grad()
def langevin(score_fn, x, step, num_steps):
"""Langevin steps x <- x + step / 2 * score + sqrt(step) * noise."""
for _ in range(num_steps):
x = x + step / 2 * score_fn(x) + step ** 0.5 * torch.randn_like(x)
return xWe start 2,000 chains from , so that each mode receives about a third of them, and run 2,000 steps at with five fields: the exact score of ; the exact scores of at and at , printed as p_1 and p_0.3; and the two networks of the sweep trained at , used as if they were the score of . The exact field at is the one the networks were trained to imitate, so it tells us which of their behavior is the noise level's and which is their own.
With the exact score of , should the chains end with the weights , and ? They should, if 2,000 steps are long enough for a chain to forget its start. The chains at should sample , whose components have variance per coordinate, five times that of . The calculation for the perfect sampler, with in place of , predicts strays and a spread near , only about twice the data's.
torch.manual_seed(2)
x_init = 3 * torch.randn(2000, 2)
fields = {'p': mix.score, # exact scores of p, p_1, p_0.3
'p_1': lambda x: mix.score(x, 1, 1),
'p_0.3': lambda x: mix.score(x, 1, 0.3),
'net 0.3, seed 1': scores[0.3, 1], # trained at sigma = 0.3
'net 0.3, seed 2': scores[0.3, 2]}
samples = [d2l.langevin(f, x_init, 0.05, 2000) for f in fields.values()]
print(f'{"start":>15}:', mix.summary(x_init))
print(f'{"data":>15}:', mix.summary(data))
for name, x in zip(fields, samples):
print(f'{name:>15}:', mix.summary(x))
d2l.scatter_panels(samples, list(fields), data=data, size=2.3); start: {'weights': [0.308, 0.329, 0.363], 'stray': 0.751, 'spread': 1.051}
data: {'weights': [0.5, 0.317, 0.183], 'stray': 0.012, 'spread': 0.488}
p: {'weights': [0.312, 0.335, 0.354], 'stray': 0.0095, 'spread': 0.501}
p_1: {'weights': [0.498, 0.298, 0.204], 'stray': 0.4245, 'spread': 0.986}
p_0.3: {'weights': [0.329, 0.334, 0.338], 'stray': 0.0435, 'spread': 0.627}
net 0.3, seed 1: {'weights': [0.454, 0.262, 0.284], 'stray': 0.0485, 'spread': 0.625}
net 0.3, seed 2: {'weights': [0.458, 0.289, 0.253], 'stray': 0.0525, 'spread': 0.628}
The exact score of drives every chain into a mode with the right local spread, but the mode weights remain at their initial values ( each). Because the valleys between modes lie 10 to 12 nats above the modes in , the expected Kramers escape time is on the order of steps at (Exercise 6); 2,000 steps cannot mix across modes. Conversely, at the noise fills the valleys, allowing the chains to mix and recover the true weights (), but they sample the wide distribution (with component variance , yielding strays and a spread near ).
The networks trained at approximate the score of (component variance , strays, and spread ). Although the exact score of barely mixes across its 7-to-9-nat barriers in 2,000 steps (shifting the heaviest mode by at most ), the learned networks move more mass between modes because their approximation errors in the data-sparse valleys create artificial drift channels.
Thus, a single noise level faces a fundamental trade-off: small preserves sharp modes but traps chains and leaves the Fisher divergence blind to mode weights, whereas large mixes rapidly across modes but samples a heavily smoothed density. Section 17.2 resolves this by annealing across all noise levels from coarse to fine.
17.1.4 Denoising Images#
Does any of this survive outside the plane? Nothing in the denoising loss depends on the dimension of the data, so it applies to images unchanged. What we lose is the yardstick: the posterior mean of images cannot be computed, so we compare the network with the best denoiser we can compute, a linear one. We use Fashion-MNIST (Section 3.2) with pixel values scaled to , loaded and shown by two small helpers, and noise of standard deviation . The network is four convolutions with 32 channels and SiLU activations, trained by the same loop as the score network for 600 steps with minibatches of 128 images and fresh noise for each. We train it twice, from two seeds, so that whatever it achieves comes with a second run beside it. It predicts the noise , so by (17.1.6) its output divided by is a score of the noisy images in dimensions, obtained without ever writing down a density, and is the denoised image.
def load_fashion_mnist_pm1(binary=False):
"""Fashion-MNIST (X, y, X_test, y_test), images in [-1, 1] or binary."""
data, device = d2l.FashionMNIST(), d2l.try_gpu() # on the GPU if any
def prep(X): # (n, 1, 28, 28) floats or (n, 28, 28) binary pixels
return (X > 127).long() if binary else X[:, None].float() / 127.5 - 1
return (prep(data.train.data).to(device), data.train.targets.to(device),
prep(data.val.data).to(device), data.val.targets.to(device))
def show_gray(imgs, num_rows, num_cols, titles=None, scale=1.0):
"""Show images (n, 1, h, w) in [-1, 1], or binary (n, h, w), in gray."""
imgs = imgs.detach().cpu()
imgs = ((imgs[:, 0] + 1) / 2).clamp(0, 1) if imgs.is_floating_point() \
else imgs.float()
return d2l.show_images(imgs[..., None].expand(-1, -1, -1, 3), num_rows,
num_cols, titles, scale)With those helpers in place, we load the Fashion-MNIST images, define
the noise-prediction objective noise_loss at , and train two
seeds of the four-layer convolutional denoiser for 600 steps with
d2l.train_regression:
X, _, X_test, _ = d2l.load_fashion_mnist_pm1()
sigma = 0.5
def noise_loss(net, x, sigma):
"""Squared error of the predicted noise; the score is -net / sigma."""
eps = torch.randn_like(x)
return ((net(x + sigma * eps) - eps) ** 2).mean()
batch_fn = lambda: X[torch.randint(0, len(X), (128,), device=X.device)]
nets = {}
for seed in (0, 1):
torch.manual_seed(seed)
net = nn.Sequential(nn.Conv2d(1, 32, 3, padding=1), nn.SiLU(),
nn.Conv2d(32, 32, 3, padding=1), nn.SiLU(),
nn.Conv2d(32, 32, 3, padding=1), nn.SiLU(),
nn.Conv2d(32, 1, 3, padding=1)).to(X.device)
nets[seed], _, losses = d2l.train_regression(
net, lambda net, x: noise_loss(net, x, sigma), batch_fn, 600)
print(f'seed {seed}: last training loss {losses[-50:].mean():.3f}')seed 0: last training loss 0.124
seed 1: last training loss 0.121
The loss, the squared error of the predicted noise per pixel, levels off near for both seeds, far above zero. Times it is the squared error of the denoised image, about per pixel; the test below confirms this on images the network has not seen.
Now the reference, the best linear denoiser. If the images were Gaussian with mean and covariance , Tweedie's formula would give the shrinkage of the Gaussian case above, along each eigenvector of with its own factor :
This Wiener filter keeps directions in which the images vary more than the noise and suppresses the others; it is the best affine denoiser for any distribution with this mean and covariance (Exercise 5). We estimate and from the 60,000 training images and compare the per-pixel squared error of the noisy input, the Wiener filter and both networks on 1,000 test images; beside each average the cell prints its standard error over the images. The rows of the figure show clean images, their noisy versions, the filter's output and that of the first network.
Xf = X.reshape(len(X), -1)
mu = Xf.mean(0)
Sigma = (Xf - mu).T @ (Xf - mu) / len(Xf) # (784, 784) pixel covariance
A = torch.linalg.solve(Sigma + sigma ** 2 * torch.eye(784, device=X.device),
Sigma) # (Sigma + sigma^2 I)^-1 Sigma
torch.manual_seed(1)
with torch.no_grad():
x = X_test[:1000]
xt = x + sigma * torch.randn_like(x)
x_lin = (mu + (xt.reshape(1000, -1) - mu) @ A).reshape(x.shape)
x_net = {seed: xt - sigma * net(xt) # Tweedie: xt + sigma^2 * score
for seed, net in nets.items()}
outputs = {'noisy': xt, 'Wiener': x_lin,
**{f'network, seed {seed}': xh for seed, xh in x_net.items()}}
for name, xh in outputs.items(): # error of each of 1,000 images
err = ((xh - x) ** 2).flatten(1).mean(1)
print(f'{name:>16}: per-pixel squared error {err.mean():.4f} '
f'(standard error {err.std() / math.sqrt(len(err)):.4f})')
d2l.show_gray(torch.cat([x[:8], xt[:8], x_lin[:8], x_net[0][:8]]), 4, 8); noisy: per-pixel squared error 0.2493 (standard error 0.0004)
Wiener: per-pixel squared error 0.0447 (standard error 0.0005)
network, seed 0: per-pixel squared error 0.0312 (standard error 0.0004)
network, seed 1: per-pixel squared error 0.0303 (standard error 0.0004)
The noisy input has a per-pixel squared error of , the optimal linear (Wiener) filter achieves , and both four-layer convolutional networks reach ( lower error, separated by more than 20 standard errors). While the Wiener filter shrinks every image toward a single global linear subspace, leaving blurred edges and background grain, the convolutional network projects noisy points toward the nonlinear manifold of garment images (compare Exercise 3). Because the posterior mean averages over all clean images consistent with , however, fine high-frequency texture destroyed by the noise is still replaced by a smooth average. Turning a denoiser into a sharpness-preserving generator requires integrating across noise levels (Section 17.2 and Section 17.3).
17.1.5 Summary#
Minimizing the squared denoising error for recovers the posterior mean . By Vincent's theorem and Tweedie's formula, , so predicting the clean point , the noise , and the score are affine reparameterizations of a single conditional expectation. Learning the score avoids both the intractable normalizing constant of energy-based models and the Jacobian trace of explicit score matching. A single noise level , however, faces a sharp trade-off: small produces high-variance targets, steep gradients near low-dimensional data manifolds, blindness of the Fisher divergence to mode weights, and non-mixing Langevin chains, whereas large mixes rapidly and recovers mode weights but samples only the heavily smoothed density .
17.1.6 Exercises#
- Learning without normalization. Consider the one-dimensional model
with ,
fit to data that take at least two distinct values.
- Maximize over and without normalizing. What does look like away from the data as the objective approaches its supremum?
- Repeat with the normalized model . Which term of the objective prevents the failure of the first part, and what is the maximizer?
- A network energy usually ends in a linear layer with an output bias . Show that the normalized density (17.1.7) does not depend on . What does gradient ascent on alone do to ?
- [code] Estimating the normalizer. A direct way to compute the
normalizer of an energy
is importance sampling (Section 24.8.2): draw
from a proposal and average the
weights , whose mean is
. Take , so that
the target is up to normalization,
and the proposal .
- Derive and show with the moment generating function of a Gaussian that and . Conclude that the relative standard error of the -sample estimate is . How many samples give a relative error of when ?
- Let be the all-ones vector in dimensions, so that the proposal is only one standard deviation off in each coordinate. With , estimate for , report the ratio of the estimate to the true and the effective sample size , and compare both with the predictions of the first part (the effective sample size should be close to ). Why does it exceed its prediction once is large, and what does this imply for it as a diagnostic?
- An image has hundreds of thousands of coordinates. What do your results say about estimating the normalizer of an energy-based model of images, and about training one by maximum likelihood?
- Data on a line. Let the data lie on the first coordinate axis of
, with for a smooth positive
density on , so that has no density on .
- Show that , where is blurred by , and write the score .
- Show that the second component of the score has mean square under and slope in . What happens to both as , and what does this mean for a network that must represent the score at a small noise level?
- Apply Tweedie's formula (17.1.5). What does the optimal denoiser do to each coordinate of , and which geometric operation does it perform?
- Let the data lie on a -dimensional linear subspace of instead. Compute the mean square of the component of the score orthogonal to the subspace.
- Two-point data and the loss floor. Let
in one dimension,
noised at level .
- Compute the posterior mean by Bayes' rule, and show that it equals , as Tweedie's formula (17.1.5) requires.
- What does the optimal denoiser return for ? Why is this the best answer under squared error even though it is not a possible clean value?
- Write the minimum of (17.1.3) as , and show that it is positive for every data distribution that is not concentrated on a single point.
- For the two-point data, write the minimum as a one-dimensional integral over and evaluate it by quadrature for . Multiply each value by to express it in the units of the noise-prediction loss. Explain why this rescaled floor vanishes as , and why it also vanishes as .
- [code] The best linear denoiser.
- Show that the Wiener filter (17.1.10) minimizes among all affine maps for every data distribution with mean and covariance , and that its squared error per pixel is , where are the eigenvalues of .
- Compute this prediction at from
Sigmaand compare it with the printed error ofx_lin. - Count the eigenvalues of
Sigmaabove for , and plot a few of the corresponding eigenvectors as images. What does the filter keep at each noise level?
- [code] Escaping a mode. ● Model the valley between the two lower modes of the running example in one dimension by the equal mixture of and , with potential , wells at , and the barrier at . When the barrier height is large compared with one, Kramers' formula (Kramers, 1940) gives the expected time for the diffusion , the continuous-time limit of (17.1.9), to pass from one well to the other:
- Compute , and , and convert into a number of Langevin steps at .
- Mode 3 of the running example lies about from mode 1 (and from mode 2), closer than the between the two lower modes. Evaluate of the running example along the segment between the two means, read off the barrier height, and estimate the crossing time in the same way. How many of 2,000 chains should cross from mode 1 to mode 3 in 2,000 steps?
- Repeat the first part for at and
, treating the result as an order of magnitude where
is small, and use it to explain the weights of the
chains. How many of 2,000 chains should cross in 2,000
steps at , and does the printed row of
p_0.3agree? The networks trained at move at least twice as much mass. What does that say about the learned field between the modes?