Destroy images with noise, learn to denoise, and generate in small steps
The previous chapter trained a U-Net to answer a question about an existing image: which pixels belong to cells? This chapter asks a network for something that looks very different. It should create a new image that nobody has drawn before. The method we study, the diffusion model, is the basis of many current image, audio, and video generators (Sohl-Dickstein et al. 2015; Ho et al. 2020).
Its recipe is short. Take training images and destroy them gradually by adding random noise. Train a network to predict the noise that was added. Then start from pure noise and remove a little predicted noise at a time until an image appears. Making this precise needs three ingredients: a forward process that defines the corruption, a denoising network trained with a regression loss, and a reverse process that turns the network into a sampler.
We build all three on CPU. Our model generates \(16\times16\) images that contain one bright disk. The equations, training loop, and samplers have the same structure as in much larger systems; the data, network, and training budget are tiny so that every step can be inspected. The disks are synthetic shapes, not biomedical observations, and a short CPU run demonstrates a working algorithm rather than realistic image generation.
23.1 Learning goals
After studying this chapter, a student should be able to:
W07-01: explain the forward noising process and the denoising training objective;
W07-02: condition a U-Net on diffusion timesteps;
W07-03: implement a small reverse sampler; and
W07-04: separate training quality from sampling-cost choices.
Along the way you will also learn why generation needs randomness, why a denoiser that minimizes squared error produces blurry averages, and why many small steps succeed where one large step fails.
We assume gradients, stochastic optimization, convolutions, and the encoder, decoder, and skip connections of the U-Net chapter. Gaussian random numbers are introduced where we need them. The main route requires neither maximum likelihood nor previous work with stochastic processes.
The lab keeps one trained model fixed and studies how few network evaluations a sampler needs. The optional additional material derives the equations that this chapter uses as recipes, and adds a small experiment on conditional generation.
TipYour route through the week
When
What you do
Before Session 1
Read up to Learning to denoise and describe how the pixel baseline fails, about 30 minutes.
Session 1, 90 minutes
Forward process, noise schedule, the noise-prediction objective, and the one-dimensional example.
Between sessions
Trace one timestep-conditioned block and check the direct noising equation, about 30 minutes.
Session 2, 90 minutes
Reverse sampling, training, and the diagnosis of training quality versus sampler.
After Session 2
Complete the lab: compare sampling budgets with one checkpoint, about 3 hours.
All cells run in order on CPU without downloading data or weights.
23.2 From predicting to generating
23.2.1 A different kind of task
Every model so far received an input and was trained toward a known correct output. Generation has no such pairing.
Task
Input
Output
Is there one correct output?
Classification (Lesson 5)
An image
Class scores
Yes, the label.
Segmentation (Lesson 6)
An image
A mask
Yes, the annotated mask.
Generation (this lesson)
Random numbers
A new image
No. Many different images are acceptable.
A generative model is a procedure for drawing new examples that resemble the training data without copying them. Two requirements pull in different directions:
Fidelity: each individual sample should look as if it could have come from the data.
Diversity: taken together, the samples should cover the variety in the data.
A model that always returns one perfect training image has fidelity without diversity. Random pixels have diversity without fidelity. A neural network is a deterministic function, so the variety has to enter from outside: we feed in random numbers and ask the model to turn them into an image.
Our generator will be unconditional. It produces images without an input image, a mask, a class label, or a text prompt, so we cannot request a particular object. Later we describe how conditioning adds that control.
23.2.2 The running example
We use 256 training images and 64 validation images. Each contains one smooth disk whose center and radius vary. Brightness \(u\in[0,1]\) is rescaled to \(x=2u-1\in[-1,1]\), so that the background is \(-1\) and the disk is \(+1\). The noise we add later is centered at zero with variance one, and this rescaling puts image values on a comparable scale. Batches are channel-first with shape (N, 1, 16, 16). Validation images come from a separate random stream and never enter a parameter update.
import mathimport matplotlib.pyplot as pltimport torchfrom torch import nnfrom torch.nn import functional as Ffrom dlbook.diffusion import make_disksfrom dlbook.plotting import show_plottorch.set_num_threads(1)PAGE_WIDTH =6.3# figure width in inches; fits the printed page as welltrain = make_disks(n=256, seed=7)valid = make_disks(n=64, seed=8)assert train.shape == (256, 1, 16, 16)assert train.min() >=-1and train.max() <=1print("Training batch:", tuple(train.shape))print("Validation batch:", tuple(valid.shape))def show_row(axes, images, title=""):"""Draw one row of images in the fixed display range [-1, 1]."""for ax, image inzip(axes, images): ax.imshow(image[0].detach().numpy(), cmap="gray", vmin=-1, vmax=1) ax.set_xticks([]) ax.set_yticks([]) axes[0].set_ylabel(title, fontsize=8)
23.2.3 An insufficient baseline: treat every pixel separately
Before building anything sophisticated, try the simplest generator we can think of. For each pixel position, estimate a mean and a standard deviation from the training images. Then generate each pixel independently with those statistics. This baseline knows where brightness tends to occur. Does it know which pixels belong together?
Figure 23.1: Training images, the mean image repeated eight times, and samples whose pixels are drawn independently. Matching the statistics of every single pixel does not produce a coherent disk. Values outside the image range are saturated for display only.
Predict and diagnose — 5 minutes. Which row has diversity? Which has coherent boundaries? Why would a report of average brightness miss the failure? Write down one property that a better model must learn before you continue.
The two failed rows fail in opposite ways. Independent sampling discards the dependencies between pixels: a bright pixel should make its neighbors more likely to be bright, and a disk in one corner should make a second disk elsewhere unlikely. The mean image has smooth structure but no diversity, and it is not even a valid example, because no training image contains a faint blur. Keep the mean image in mind. It will return as the best possible answer to a badly posed question.
23.2.4 The plan: many small denoising problems
Why not train a network that maps random numbers directly to an image in one pass? The difficulty is supervision. For a given random input, which image should be the target? Nothing in the data pairs noise with images.
Diffusion models create the pairing themselves. If we add a known amount of noise to a training image, we obtain a noisy image together with the clean image and the noise that explains it. That is an ordinary supervised example. Generation then runs the idea backward, starting from pure noise and denoising a little at a time.
23.3 The forward process: destroy an image on purpose
23.3.1 Add a little Gaussian noise, many times
A standard Gaussian random number has mean zero and variance one. We write \(z\sim\mathcal N(0,I)\) for a vector whose entries are independent standard Gaussian numbers. torch.randn draws such vectors.
Let \(x_0\) be a clean image, treated as a vector with \(D=256\) entries. The forward process produces a sequence \(x_1,x_2,\ldots,x_T\) of increasingly noisy versions:
Each step does two things. It shrinks the previous image by the factor \(\sqrt{1-\beta_t}\), and it adds fresh noise with variance \(\beta_t\). The numbers \(\beta_1,\ldots,\beta_T\) form the noise schedule. We choose them; nothing in the forward process is learned.
The two square roots are matched on purpose. If the entries of \(x_{t-1}\) have variance one, then the entries of \(x_t\) have variance \((1-\beta_t)\cdot1+\beta_t=1\). Noise replaces signal without letting the overall scale grow.
beta_demo =0.1g_demo = torch.Generator().manual_seed(3)previous = torch.randn(100_000, generator=g_demo) # entries with variance onecurrent = (math.sqrt(1- beta_demo) * previous+ math.sqrt(beta_demo) * torch.randn(100_000, generator=g_demo))print(f"Variance before the step: {previous.var():.3f}")print(f"Variance after the step: {current.var():.3f}")assertabs(current.var() -1) <0.02
Variance before the step: 0.995
Variance after the step: 0.995
The subscript \(t\) is a diffusion timestep. It is not an optimizer update and not a layer number. Three different counters appear in this chapter, and confusing them is the most common source of errors:
Counter
Meaning
Value here
Diffusion timestep \(t\)
Noise level of an image, from \(0\) (clean) to \(T\) (pure noise)
\(T=64\)
Optimizer update
One gradient step on the network weights
600, later 1200
Network evaluation
One forward pass during sampling
64 per generated batch
23.3.2 Jump directly to any noise level
Simulating the chain step by step would be wasteful. Write \(\alpha_t=1-\beta_t\) and let \(\bar\alpha_t=\alpha_1\alpha_2\cdots\alpha_t\) be the running product, with \(\bar\alpha_0=1\). After two steps,
The two noise terms are independent Gaussians. Their sum is again Gaussian, and the variances add: \(\alpha_2\beta_1+\beta_2=\alpha_2(1-\alpha_1)+(1-\alpha_2)=1-\alpha_1\alpha_2\). Repeating the argument for more steps gives the direct noising equation:
Here \(\epsilon\) stands for the combined noise of all steps up to \(t\), not for the last increment \(z_t\). The equation says that \(x_t\) is a blend: the clean image scaled by \(\sqrt{\bar\alpha_t}\) plus noise with variance \(1-\bar\alpha_t\). We call \(\bar\alpha_t\) the signal level. It is the share of the variance budget that the image still holds, and \(1-\bar\alpha_t\) is the share held by noise. Their ratio \(\bar\alpha_t/(1-\bar\alpha_t)\) is the signal-to-noise ratio. With Equation 23.2 we can create a training example at any \(t\) without computing the earlier states. The additional material proves the equation by induction.
23.3.3 Choose a schedule that really ends in noise
Generation will start from pure Gaussian noise. That only makes sense if the forward process ends there: \(\bar\alpha_T\) must be close to zero, so that \(x_T\) is almost exactly \(\epsilon\) whatever the clean image was.
The original DDPM experiments used \(T=1000\) steps with \(\beta_t\) rising linearly from \(10^{-4}\) to \(0.02\)(Ho et al. 2020). Suppose we copy those endpoints but use only 64 steps because we have a CPU budget.
T =64linear_beta = torch.linspace(1e-4, 0.02, T)linear_terminal = (1- linear_beta).prod()print(f"Copied linear schedule: signal level at t = T is {linear_terminal:.3f}")print(f"Multiplier on the clean image at t = T: {linear_terminal.sqrt():.3f}")
Copied linear schedule: signal level at t = T is 0.523
Multiplier on the clean image at t = T: 0.723
More than half of the signal level survives. A sampler that starts from pure noise would begin somewhere the network never saw during training. This failure is purely algebraic; it would occur with any network.
We instead prescribe a curve for the signal level itself. The cosine schedule(Nichol and Dhariwal 2021) sets
with a small offset \(s=0.008\) and \(\beta_t\) capped at \(0.999\). Because the curve is defined in terms of \(t/T\), it reaches essentially zero at \(t=T\) for any number of steps.
u = torch.arange(T +1, dtype=torch.float64) / Tf = torch.cos((u +0.008) /1.008* math.pi /2).square()target_abar = f / f[0]step_beta = (1- target_abar[1:] / target_abar[:-1]).clamp(max=0.999)beta = torch.cat((torch.zeros(1), step_beta)) # index 0 represents clean dataalpha =1- betaabar = alpha.cumprod(0) # recomputed after capping betabeta, alpha, abar = beta.float(), alpha.float(), abar.float()assert abar[0] ==1and abar[-1] <1e-5print(f"Cosine schedule: signal level at t = T is {abar[-1]:.2e}")def q_sample(x0, t, epsilon):"""Direct noising: blend clean images with noise at the levels in t.""" a = abar[t].reshape(-1, 1, 1, 1) # one scalar per image; broadcastsreturn a.sqrt() * x0 + (1- a).sqrt() * epsilon
Cosine schedule: signal level at t = T is 5.93e-07
Do not take Equation 23.2 on trust. The next cell simulates the chain one step at a time for all training images and compares what it added with what the shortcut predicts.
g_chain = torch.Generator().manual_seed(5)x = train.clone()for step inrange(1, 25): # 24 sequential steps of the forward process z = torch.randn(x.shape, generator=g_chain) x = alpha[step].sqrt() * x + beta[step].sqrt() * zadded = x - abar[24].sqrt() * train # what the chain added to the imageadded_mean, added_var = added.mean(), added.var()print(f"Chain at t = 24: added noise has mean {added_mean:+.4f}")print(f" and variance {added_var:.4f}")print(f"Direct equation: mean 0 and variance {1- abar[24]:.4f}")assertabs(added_mean) <0.02andabs(added_var - (1- abar[24])) <0.02
Chain at t = 24: added noise has mean -0.0022
and variance 0.3149
Direct equation: mean 0 and variance 0.3158
Figure 23.2: The same clean image at five noise levels, each drawn directly with independent noise, and the signal level \(\bar\alpha_t\) of two schedules. The images compare noise levels; they are not one trajectory of the chain.
Checkpoint. Explain why \(\bar\alpha_T\) near zero matters. Does it mean that every pixel of \(x_T\) is close to zero? No: the signal vanishes, but the noise still has variance close to one.
23.4 Learning to denoise
23.4.1 A regression task whose targets come for free
When we manufacture a noisy image with Equation 23.2, we know everything about it: the clean image \(x_0\), the timestep \(t\), and the noise \(\epsilon\) we drew. We can therefore train a network \(\epsilon_\theta(x_t,t)\) to predict that noise by ordinary regression:
The expectation is over training images, timesteps, and fresh noise. A predictor that always answers zero has expected loss one, because each noise entry has variance one. That gives the loss values a reference point.
NoteAlgorithm 1 — one training update
Draw a minibatch of clean images \(x_0\) from the training set.
Draw one timestep \(t\) per image, uniformly from \(\{1,\ldots,T\}\).
Draw noise \(\epsilon\sim\mathcal N(0,I)\) with the shape of the batch.
Form the noisy inputs \(x_t=\sqrt{\bar\alpha_t}\,x_0+\sqrt{1-\bar\alpha_t}\,\epsilon\).
Take a gradient step on the mean squared error between \(\epsilon\) and \(\epsilon_\theta(x_t,t)\).
Three properties of this procedure are worth stating early.
No labels are needed. The data supply their own targets, as in the self-supervised pretraining mentioned in Lesson 6.
Training never runs the sampler. Each update is one forward and one backward pass at randomly chosen noise levels. We do not backpropagate through a chain of 64 denoising steps.
One network serves all noise levels. The same weights must handle a nearly clean image and nearly pure noise, which is why the timestep is an input.
This recipe is the denoising diffusion probabilistic model, or DDPM, of Ho et al. (2020). The simple loss is a reweighted version of a likelihood bound. It is not the negative log-likelihood of an image, and its value should not be reported as one. The additional material explains the connection.
23.4.2 Noise and clean image are two views of one prediction
Solving Equation 23.2 for the clean image turns any noise prediction into a clean-image estimate:
Given \(x_t\) and \(t\), knowing the noise is the same as knowing the clean image. Asking “which noise was added?” is therefore the same question as “which clean image is hidden in here?”.
That question usually has no certain answer. Different pairs of clean image and noise can produce the same noisy image. Faced with such ambiguity, a predictor trained with squared error does something specific: its best possible output is the average of all answers that are compatible with its input, weighted by how plausible each one is. This is the conditional mean. A one-dimensional example makes the consequence visible.
23.4.3 What the best possible denoiser does: a one-dimensional example
Replace images by single numbers. Let the “dataset” consist of only two values, \(x_0=-1\) and \(x_0=+1\), each with probability one half. The forward process is unchanged. After \(t\) steps, \(x_t\) is \(\pm\sqrt{\bar\alpha_t}\) plus Gaussian noise.
For this dataset the conditional mean has a closed form, derived in the additional material:
No network is involved. This is the answer that a perfectly trained denoiser would give. We check it against a simulation: among many noisy values close to \(0.3\), what was the average clean value?
def exact_clean(x, t):"""Conditional mean E[x_0 | x_t] for data that are -1 or +1.""" a = abar[t]return torch.tanh(a.sqrt() * x / (1- a))g_1d = torch.Generator().manual_seed(53)n =200_000x0_1d = torch.where(torch.rand(n, generator=g_1d) <0.5, -1.0, 1.0)t_mid =32eps_1d = torch.randn(n, generator=g_1d)xt_1d = abar[t_mid].sqrt() * x0_1d + (1- abar[t_mid]).sqrt() * eps_1dnear = (xt_1d >0.25) & (xt_1d <0.35)formula = exact_clean(xt_1d[near], t_mid).mean()print(f"t = {t_mid}: {near.sum().item()} noisy values lie near 0.3")print(f" average clean value behind them: {x0_1d[near].mean():+.3f}")print(f" formula, averaged over the same values: {formula:+.3f}")assertabs(x0_1d[near].mean() - formula) <0.04# Squared error rewards hedging: compare with answering the nearer data point.mse_mean = (x0_1d - exact_clean(xt_1d, t_mid)).square().mean()mse_sign = (x0_1d - xt_1d.sign()).square().mean()print(f" squared error of the conditional mean: {mse_mean:.3f}")print(f" squared error of 'pick the nearer one': {mse_sign:.3f}")
t = 32: 6845 noisy values lie near 0.3
average clean value behind them: +0.405
formula, averaged over the same values: +0.393
squared error of the conditional mean: 0.457
squared error of 'pick the nearer one': 0.647
A noisy value of \(0.3\) at \(t=32\) came from \(+1\) in roughly seven cases out of ten and from \(-1\) otherwise. The best squared-error answer is the weighted average, about \(+0.4\). That value is not a data point. A rule that always commits to the nearer data point returns valid values, yet its squared error is larger. Squared error rewards hedging.
grid = torch.linspace(-2.5, 2.5, 501)levels = (4, 16, 32, 48, 64)fig, axes = plt.subplots(1, 2, figsize=(PAGE_WIDTH, 2.8))for t_level in levels: a = abar[t_level]# The noisy value follows two Gaussians centered at -sqrt(a) and +sqrt(a). peaks =sum(torch.exp(-(grid - sign * a.sqrt()) **2/ (2* (1- a)))for sign in (-1.0, 1.0)) density = peaks / (2* torch.sqrt(2* math.pi * (1- a))) axes[0].plot(grid, density, label=f"t = {t_level}") axes[1].plot(grid, exact_clean(grid, t_level), label=f"t = {t_level}")axes[0].set(xlabel="noisy value $x_t$", ylabel="density", ylim=(0, 2.1))axes[1].set(xlabel="noisy value $x_t$", ylabel="best estimate $E[x_0\\,|\\,x_t]$")axes[1].legend(fontsize=7)fig.tight_layout()show_plot(fig)
Figure 23.3: The two-point dataset under the forward process. Left: the distribution of the noisy value \(x_t\) changes from two sharp peaks into one Gaussian. Right: the best squared-error estimate of the clean value. With little noise it decides confidently; with much noise it retreats to the data average, zero.
Read the right panel from low to high noise. At \(t=4\) the estimate jumps from \(-1\) to \(+1\): there is hardly any doubt about the origin. At \(t=64\) the curve is flat at zero. Whatever the input, the best guess is the average of the dataset, because the input carries no information.
Two conclusions carry over to images.
One-shot denoising of pure noise returns the mean image. For our disks, that is the blurry average from Figure 23.1. A perfectly trained noise predictor cannot generate a sharp disk in a single jump from \(t=T\).
The answer depends on the noise level. The input \(x_t=0.5\) deserves an estimate near \(+1\) at \(t=4\) and near \(0\) at \(t=64\). A denoiser must be told \(t\).
23.5 The reverse process: generate in small steps
23.5.1 Why a small step succeeds where a big jump fails
If jumping from noise to data fails, try a much more modest question. The chain is at \(x_t\); where was it one step earlier?
Suppose for a moment that we knew the clean image \(x_0\). Then the answer would be an exact Gaussian distribution, with a mean that mixes the clean image and the current state, and a small variance:
The additional material derives both coefficients by completing a square. At first you can read them as a recipe: move from \(x_t\) a little toward the clean image, and remain uncertain by an amount \(\tilde\beta_t\).
We do not know \(x_0\). The honest description of the previous state is therefore a mixture: one such Gaussian for every clean image that could explain \(x_t\), weighted by how plausible that image is. In the two-point example the mixture has exactly two components, one for \(x_0=-1\) and one for \(x_0=+1\). We evaluate them at one state, \(x_{32}=0.3\).
t_step, x_now =32, torch.tensor(0.3)a, a_prev = abar[t_step], abar[t_step -1]# Plausibility of x_0 = +1 given the current value.weight_plus = torch.sigmoid(2* a.sqrt() * x_now / (1- a))# Coefficients of x_0 and x_t in the mean, and the variance, of one step back.c0 = beta[t_step] * a_prev.sqrt() / (1- a)ct = alpha[t_step].sqrt() * (1- a_prev) / (1- a)variance = beta[t_step] * (1- a_prev) / (1- a)# Means of the previous value for x_0 = -1 and for x_0 = +1.mean_minus, mean_plus =-c0 + ct * x_now, c0 + ct * x_nowdef bell(values, mean, var):"""Gaussian density with the given mean and variance.""" normalizer = torch.sqrt(2* math.pi * var)return torch.exp(-(values - mean) **2/ (2* var)) / normalizervalues = torch.linspace(-0.6, 1.2, 400)mixture = (weight_plus * bell(values, mean_plus, variance)+ (1- weight_plus) * bell(values, mean_minus, variance))single = bell(values, c0 * exact_clean(x_now, t_step) + ct * x_now, variance)print(f"Plausibility of the clean value +1: {weight_plus:.2f}")print(f"One step back: the two means are {mean_minus:+.3f} and {mean_plus:+.3f},")print(f" each with standard deviation {variance.sqrt():.3f}")print("Jump to the clean value: the two possibilities are -1 and +1 exactly")
Plausibility of the clean value +1: 0.70
One step back: the two means are +0.212 and +0.346,
each with standard deviation 0.211
Jump to the clean value: the two possibilities are -1 and +1 exactly
One step back, the two means lie closer together than one standard deviation. For the jump to the clean value, the two possibilities are two units apart and have no spread at all.
fig, axes = plt.subplots(1, 2, figsize=(PAGE_WIDTH, 3.0))axes[0].plot(values, mixture, label="Exact: two Gaussians")axes[0].plot(values, single, linestyle="--", label="One Gaussian")axes[0].set(title="One small step: t = 32 to 31", ylim=(0, 2.7), xlabel="previous value $x_{31}$", ylabel="density")axes[0].title.set_fontsize(10)axes[0].legend(fontsize=7, loc="upper left")axes[1].bar([-1, 1], [float(1- weight_plus), float(weight_plus)], width=0.12, label="Exact: two clean values")axes[1].axvline(float(exact_clean(x_now, t_step)), color="C1", linestyle="--", label="One prediction")axes[1].set(title="One giant jump: t = 32 to 0", xlim=(-1.6, 1.6), ylim=(0, 1), xlabel="clean value $x_0$", ylabel="probability")axes[1].title.set_fontsize(10)axes[1].legend(fontsize=7, loc="upper left")fig.tight_layout()show_plot(fig)
Figure 23.4: Two questions asked at the same state, \(x_{32}=0.3\), of the two-point example. Left: where was the chain one step earlier? The exact answer is a mixture of two Gaussians that almost coincide, so a single Gaussian approximates it well. Right: what was the clean value? The exact answer consists of two separate values, and a single prediction at their average is neither.
For a small step, the components for different clean images sit almost on top of each other. Replacing the mixture by one Gaussian centered at the weighted average loses very little. For a giant jump, the components are the data points themselves, and their average lies in between, where there is no data.
Because \(\tilde\mu_t\) is linear in \(x_0\), the weighted average of the component means is obtained by inserting the average clean image, which is exactly what a trained denoiser estimates. This gives the DDPM reverse step: estimate \(\hat x_0\) from the network with Equation 23.4, insert it into Equation 23.6, and sample
predict the noise \(\epsilon_\theta(x_t,t)\) and form \(\hat x_0\);
compute the mean \(\tilde\mu_t(x_t,\hat x_0)\);
set \(x_{t-1}=\tilde\mu_t+\sqrt{\tilde\beta_t}\,z\) with fresh \(z\sim\mathcal N(0,I)\). At \(t=1\) add no noise; \(\tilde\beta_1=0\).
Return \(x_0\).
The fresh noise in step 2c is not a nuisance to be minimized. Each mean is an average over possibilities, and averages are less spread out than the things they average. The added noise restores the spread that the forward process has at that level, and over many steps it is what finally breaks the tie between the possible clean images. The noise draws are new random numbers. They are not the forward noise of any training image, and the sampler never sees a training image.
23.5.2 Watch the sampler work with a perfect denoiser
We can run Algorithm 2 on the two-point example right now, with exact_clean in place of a network. No learning error is involved, so this experiment isolates the sampling rule.
def sample_two_point(n, seed):"""Algorithm 2 for the two-point data, with the exact conditional mean.""" g = torch.Generator().manual_seed(seed) x = torch.randn(n, generator=g) # x_T: pure noise path = [x.clone()]for step inrange(T, 0, -1): clean = exact_clean(x, step) a, previous = abar[step], abar[step -1] mean = (beta[step] * previous.sqrt() * clean+ alpha[step].sqrt() * (1- previous) * x) / (1- a) variance = beta[step] * (1- previous) / (1- a) x = meanif step >1: x = x + variance.sqrt() * torch.randn(n, generator=g) path.append(x.clone())return x, torch.stack(path)final_1d, path_1d = sample_two_point(4000, seed=59)start_1d = path_1d[0]one_jump = exact_clean(start_1d, T).abs().max()share_plus = (final_1d >0).float().mean()off_data = (final_1d.abs() -1).abs().max()same_sign = ((start_1d >0) == (final_1d >0)).float().mean()print(f"One jump from pure noise: all estimates within ±{one_jump:.4f} of zero")print(f"64 small steps: {share_plus:.1%} of samples end at +1, the rest at -1")print(f" largest distance of a sample from its data point: {off_data:.1e}")print(f" final sign equals the sign of the starting noise: {same_sign:.1%}")assert off_data <1e-3assert0.45< share_plus <0.55
One jump from pure noise: all estimates within ±0.0027 of zero
64 small steps: 49.5% of samples end at +1, the rest at -1
largest distance of a sample from its data point: 4.6e-06
final sign equals the sign of the starting noise: 49.6%
fig, axes = plt.subplots(1, 2, figsize=(PAGE_WIDTH, 2.9), sharey=True, gridspec_kw={"width_ratios": [3, 1]})steps_axis = torch.arange(T, -1, -1)for index inrange(40): color ="C0"if final_1d[index] >0else"C1" axes[0].plot(steps_axis, path_1d[:, index], color=color, alpha=0.55, linewidth=0.8)axes[0].invert_xaxis()axes[0].set(xlabel="timestep t (sampling runs left to right)", ylabel="value $x_t$")axes[1].hist(final_1d.numpy(), bins=41, range=(-2.05, 2.05), orientation="horizontal")axes[1].set(xlabel="number of samples")fig.tight_layout()show_plot(fig)
Figure 23.5: Algorithm 2 on the two-point dataset with the exact denoiser. Left: 40 of 4000 trajectories, colored by where they end. Right: all 4000 final values. Every sample is a valid data point, and both values appear about equally often.
Three observations:
Every sample ends on a data point, although every single prediction along the way was an average. Small steps with fresh noise turn a hedging predictor into a decisive sampler.
The two data points appear in the right proportion. The sampler reproduces the diversity of the data, not just one mode.
The outcome is decided gradually. With this schedule the sign of the starting noise has almost no say; trajectories commit at intermediate noise levels, where the tanh curve in Figure 23.3 begins to steepen.
For images we cannot write down the conditional mean. There are far too many possible clean images to enumerate. Estimating it from examples is the job of a neural network.
23.6 The denoising network: a U-Net that knows the noise level
23.6.1 What changes relative to segmentation
The network must map a noisy image to an output of the same shape, combine broad context (where is the disk?) with fine detail (where exactly is its edge?), and do so at every noise level. The first two requirements are what the U-Net was designed for. We reuse its encoder, decoder, and skip connections and change the parts that concern the task.
Segmentation U-Net (Lesson 6)
Denoising U-Net (this lesson)
Input
An image
A noisy image \(x_t\)and its timestep \(t\)
Output
One foreground logit per pixel
One noise value per pixel
Output range
Passed through a sigmoid in the loss
Unbounded; no sigmoid
Target
An annotated mask
The noise \(\epsilon\) we drew
Loss
Binary cross-entropy plus soft Dice
Mean squared error
Weights
Possibly transferred
Trained from scratch
A U-Net is an architecture. Whether it segments or denoises is decided by the input, the target, and the loss. Reusing the design does not mean reusing segmentation weights.
23.6.2 Tell the network the timestep
The same pixel value can be a dark object at low noise or an uninformative draw at high noise, and Figure 23.3 showed that the right answer changes with \(t\). We encode the relative time \(\tau=t/T\) by five smooth features and transform them with a small MLP into a time embedding:
Feeding the bare integer \(t\) would also be possible, but sines and cosines give the MLP smooth, bounded inputs that distinguish nearby timesteps. This particular choice is small and sufficient for our model. Larger diffusion models use the same idea with many more frequencies, borrowed from the positional encodings of Transformers (Vaswani et al. 2017; Ho et al. 2020), which we meet in Lesson 10.
23.6.3 Inject time into every block
Each convolutional block receives the embedding. A linear layer projects \(e(t)\) to one number per channel, and that number is added to every spatial position of the block’s feature map. The network can thereby shift its features depending on the noise level, at every resolution.
def time_features(t, steps): tau = t.float() / stepsreturn torch.stack((tau, torch.sin(math.pi * tau), torch.cos(math.pi * tau), torch.sin(2* math.pi * tau), torch.cos(2* math.pi * tau)), 1)class TimeBlock(nn.Module):"""Two 3x3 convolutions, a time-dependent shift, and a residual shortcut."""def__init__(self, channels_in, channels_out, time_dim=32):super().__init__()self.conv1 = nn.Conv2d(channels_in, channels_out, 3, padding=1)self.norm1 = nn.GroupNorm(4, channels_out)self.time = nn.Linear(time_dim, channels_out)self.conv2 = nn.Conv2d(channels_out, channels_out, 3, padding=1)self.norm2 = nn.GroupNorm(4, channels_out)self.shortcut = nn.Conv2d(channels_in, channels_out, 1)def forward(self, x, embedding):# (N, C) -> (N, C, 1, 1): one shift per channel, broadcast over H and W. h =self.norm1(self.conv1(x)) +self.time(embedding)[:, :, None, None] h =self.norm2(self.conv2(F.silu(h)))return F.silu(h +self.shortcut(x))class TinyTimeUNet(nn.Module):def__init__(self, steps=64, width=8):super().__init__()self.steps = stepsself.embedding = nn.Sequential( nn.Linear(5, 32), nn.SiLU(), nn.Linear(32, 32))self.enc1 = TimeBlock(1, width)self.enc2 = TimeBlock(width, 2* width)self.middle = TimeBlock(2* width, 4* width)self.dec2 = TimeBlock(6* width, 2* width)self.dec1 = TimeBlock(3* width, width)self.output = nn.Conv2d(width, 1, 1)def forward(self, x, t): e =self.embedding(time_features(t, self.steps)) s1 =self.enc1(x, e) s2 =self.enc2(F.avg_pool2d(s1, 2), e) h =self.middle(F.avg_pool2d(s2, 2), e) h = F.interpolate(h, size=s2.shape[-2:], mode="nearest") h =self.dec2(torch.cat((h, s2), 1), e) h = F.interpolate(h, size=s1.shape[-2:], mode="nearest") h =self.dec1(torch.cat((h, s1), 1), e)returnself.output(h) # unbounded noise predictiontorch.manual_seed(17)model = TinyTimeUNet(steps=T)probe = torch.zeros(2, 1, 16, 16)probe_times = torch.tensor([1, T])output = model(probe, probe_times)assert output.shape == probe.shapeassertnot torch.allclose(output[0], output[1]) # same image, different tprint("Trainable parameters:", sum(p.numel() for p in model.parameters()))
Trainable parameters: 35513
Stage
Feature shape, omitting batch
Receives the time embedding?
First encoder block
\(8\times16\times16\)
Yes
Second encoder block
\(16\times8\times8\)
Yes
Bottleneck
\(32\times4\times4\)
Yes
First decoder block, after concatenating the skip
\(16\times8\times8\)
Yes
Second decoder block, after concatenating the skip
\(8\times16\times16\)
Yes
Output projection
\(1\times16\times16\)
Through the preceding blocks
Some details differ from the Lesson 6 model and are common in diffusion networks:
Group normalization normalizes groups of channels within each example. Unlike batch normalization it does not mix statistics across a batch, which matters here because one batch contains images at very different noise levels.
SiLU is the smooth activation \(a\mapsto a\cdot\operatorname{sigmoid}(a)\).
The output has no sigmoid. Gaussian noise can be negative or larger than one. Bounding the output would make the target unreachable.
Two kinds of shortcut coexist. The long U-Net skips concatenate encoder features into the decoder and carry spatial detail. The short residual connection inside each block adds its input to its output and eases optimization, as in ResNets.
Note what the skips do not carry. During sampling, every encoder feature is computed from the current noisy state. No clean training image enters the network.
23.7 Training across all noise levels
The training loop is Algorithm 1 in code. We use Adam with learning rate \(0.002\) and batches of 32. Each batch contains images at 32 independently chosen noise levels.
BATCH_SIZE =32g_train = torch.Generator().manual_seed(19)optimizer = torch.optim.Adam(model.parameters(), lr=0.002)history = []def train_updates(count):"""Run `count` further updates of Algorithm 1 on the shared model.""" model.train()for _ inrange(count): index = torch.randint(len(train), (BATCH_SIZE,), generator=g_train) x0 = train[index] # step 1 t = torch.randint(1, T +1, (BATCH_SIZE,), generator=g_train) # step 2 epsilon = torch.randn(x0.shape, generator=g_train) # step 3 xt = q_sample(x0, t, epsilon) # step 4 loss = F.mse_loss(model(xt, t), epsilon) # step 5 optimizer.zero_grad() loss.backward() optimizer.step() history.append(loss.item())train_updates(600)recent =sum(history[-50:]) /50print(f"Mean training noise MSE over the last 50 updates: {recent:.4f}")
Mean training noise MSE over the last 50 updates: 0.0231
A single average hides how the error is distributed over noise levels. We therefore evaluate on the validation images at five fixed timesteps and with fixed corruptions. To give the numbers meaning, two trivial predictors go through exactly the same evaluation: one always answers zero, the other returns its own input. The helper denoising_errors in src/dlbook/diffusion.py applies the direct noising equation with a fixed seed and returns the squared error per image.
from dlbook.diffusion import cosine_schedule, denoising_errorsschedule = cosine_schedule(T)torch.testing.assert_close(schedule.abar, abar) # same schedule as built aboveclass ZeroNoise(nn.Module):def forward(self, x, t):return torch.zeros_like(x)class CopyInput(nn.Module):def forward(self, x, t):return xevaluation_times = (1, 16, 32, 48, 64)def validation_errors(predictor):"""Mean noise MSE on the validation images at each evaluation time.""" per_image = denoising_errors(predictor, valid, schedule, times=evaluation_times)return per_image.mean(1)errors = {"Always zero": validation_errors(ZeroNoise()),"Copy the input": validation_errors(CopyInput()),"Network, 600 updates": validation_errors(model)}print("Validation noise MSE at t =", evaluation_times)for name, values in errors.items():print(f" {name:22s}", " ".join(f"{value:.4f}"for value in values))
Validation noise MSE at t = (1, 16, 32, 48, 64)
Always zero 1.0130 0.9971 1.0019 0.9915 1.0095
Copy the input 1.8499 1.1504 0.5438 0.1403 0.0000
Network, 600 updates 0.1197 0.0275 0.0214 0.0155 0.0066
Figure 23.6: Training noise error averaged over blocks of 25 updates, and validation noise error at fixed timesteps for the network and two trivial predictors. The difficulty of the task depends on the noise level, so each level needs its own reference.
Stop and interpret. At \(t=T\) the input is almost exactly the noise, so copying the input is nearly perfect. The network’s small error at high noise is therefore no achievement, and it says little about generated images. At \(t=1\) the noise is a faint perturbation on top of an image that occupies the full value range; predicting it precisely is hard, and both trivial predictors are poor. Compare each level with its own baselines, and do not read the curve as “the model learned most at large timesteps”.
23.8 Sampling new images
Now implement Algorithm 2 for images. We add one practical safeguard. After a short training run the estimate \(\hat x_0\) can leave the valid image range, especially at high noise, where Equation 23.4 divides by a small number. We clip\(\hat x_0\) to \([-1,1]\) and compute the mean from the clipped estimate with Equation 23.6. This is a sampling heuristic that uses our knowledge of the data range; the shorter formula Equation 23.8 would silently ignore the clipping.
@torch.no_grad()def sample_ddpm(model, initial_noise, seed=31):"""Algorithm 2 with a clipped clean estimate; also returns some states.""" model.eval() g = torch.Generator().manual_seed(seed) x = initial_noise.clone() snapshots = {T: x.clone()}for step inrange(T, 0, -1): t = torch.full((len(x),), step, dtype=torch.long) predicted_noise = model(x, t) a, previous = abar[step], abar[step -1] x0_hat = (x - (1- a).sqrt() * predicted_noise) / a.sqrt() x0_hat = x0_hat.clamp(-1, 1) mean = (beta[step] * previous.sqrt() * x0_hat+ alpha[step].sqrt() * (1- previous) * x) / (1- a) variance = beta[step] * (1- previous) / (1- a) x = meanif step >1: # no fresh noise in the final step x = x + variance.sqrt() * torch.randn(x.shape, generator=g)if step -1in (48, 32, 16, 0): snapshots[step -1] = x.clone()return x, snapshotsg_start = torch.Generator().manual_seed(37)initial = torch.randn((64, 1, 16, 16), generator=g_start)generated_600, snapshots = sample_ddpm(model, initial)assert generated_600.shape == initial.shapeassert torch.isfinite(generated_600).all()# The packaged sampler used by the lab is the same algorithm.from dlbook.diffusion import sample_ddpm as packaged_ddpmpackaged = packaged_ddpm(model, initial, schedule, seed=31)torch.testing.assert_close(generated_600, packaged)
Figure 23.7: Five states from each of the first four sampling trajectories after 600 updates. No clean target was supplied. Intermediate states are saturated to the display range.
Figure 23.8: Sixteen validation images and the first 16 of 64 generated images after 600 updates. The draws are shown in their original order; none were selected after inspection.
Return to the first experiment. Neighboring pixels are now coordinated, and the disks appear at varied positions and sizes. The model has learned dependencies that independent pixels could not express, and it retained diversity that the mean image lacked. But look at every draw, including the failures. Some images are faint, too small, or empty. A generator that sometimes returns an empty image does not match the data, in which every image contains a disk.
23.9 Diagnose before you tune: training or sampler?
Something is wrong, and there are two suspects. The sampler might contain an error in its coefficients. Or the network might simply be undertrained. These call for different repairs, and looking at pictures cannot tell them apart. We test each suspect in isolation.
Step 1: turn the impression into a number. For each image, compute the fraction of pixels brighter than mid-gray. An empty image scores zero.
def bright_area(images):"""Fraction of pixels above mid-gray (x > 0), one value per image."""return (images >0).float().mean((1, 2, 3))def report(name, images): area = bright_area(images) empty = (area ==0).sum().item()print(f"{name:24s} bright area {area.mean():.3f} ± "f"{area.std(unbiased=False):.3f} empty images: {empty} of {len(images)}")report("Validation images", valid)report("Generated, 600 updates", generated_600)
Validation images bright area 0.068 ± 0.020 empty images: 0 of 64
Generated, 600 updates bright area 0.044 ± 0.029 empty images: 10 of 64
Step 2: test the sampler without the network. Replace the network by an oracle that is told one clean image and returns exactly the noise that explains the current state. If the sampler’s algebra is right, it must recover that image from any starting noise. A wrong coefficient would show up here, independent of any training.
class Oracle(nn.Module):"""Not a learned model: knows one clean image, returns its implied noise."""def__init__(self, clean):super().__init__()self.clean = cleandef forward(self, x, t): a = abar[t].reshape(-1, 1, 1, 1)return (x - a.sqrt() *self.clean) / (1- a).sqrt()target = valid[:1]recovered, _ = sample_ddpm(Oracle(target), initial[:8])deviation = (recovered - target).abs().max()print(f"Largest deviation from the oracle's image, 8 starts: {deviation:.1e}")assert deviation <1e-4
Largest deviation from the oracle's image, 8 starts: 4.7e-06
The sampler passes. Notice also what the oracle cannot do: it reproduces one given image and generates nothing new. A correct sampler is necessary, not sufficient.
Step 3: change only the training budget. Keep the data, architecture, optimizer state, sampler, starting noise, and reverse-noise seed. Continue training the same model for 600 further updates and sample again.
train_updates(600) # same model, optimizer, and random stream: 1200 in totalgenerated_1200, _ = sample_ddpm(model, initial)errors["Network, 1200 updates"] = validation_errors(model)report("Validation images", valid)report("Generated, 600 updates", generated_600)report("Generated, 1200 updates", generated_1200)print("Validation noise MSE at t =", evaluation_times)for name in ("Network, 600 updates", "Network, 1200 updates"):print(f" {name:22s}", " ".join(f"{value:.4f}"for value in errors[name]))
Validation images bright area 0.068 ± 0.020 empty images: 0 of 64
Generated, 600 updates bright area 0.044 ± 0.029 empty images: 10 of 64
Generated, 1200 updates bright area 0.071 ± 0.027 empty images: 0 of 64
Validation noise MSE at t = (1, 16, 32, 48, 64)
Network, 600 updates 0.1197 0.0275 0.0214 0.0155 0.0066
Network, 1200 updates 0.0793 0.0228 0.0188 0.0130 0.0014
Figure 23.9: The first 16 draws after 600 and after 1200 updates. Images in the same column of adjacent rows share the starting noise and all reverse-noise draws; only the network weights differ.
In our reference run, about one draw in six is empty after 600 updates and none is after 1200, and the average bright area moves close to that of the validation images. Your numbers can differ slightly between machines. The sampler was identical in both rows of each pair, so the improvement is a training effect. In the reference run the validation noise error also fell at each of the five timesteps, but by amounts that look unremarkable: a modest change in denoising error can separate a generator that often fails from one that rarely does.
One run with one initialization is thin evidence. The number of empty images varies considerably between initialization seeds, so a careful comparison repeats the whole experiment several times and reports every run.
This is the distinction behind learning outcome W07-04. Three dials are separate:
Dial
Examples
Changing it requires
Training quality
Data, architecture, loss, number of updates
Retraining
Sampling rule
DDPM step, clipping, how much fresh noise
Nothing but new sampling runs
Sampling cost
Number of network evaluations per image
Nothing but new sampling runs
A controlled experiment changes one dial and fixes the others. From here on we keep the 1200-update weights. The lab retrains exactly this checkpoint in a fresh kernel, freezes it, and turns only the third dial.
23.10 Sampling with fewer network evaluations
DDPM sampling calls the network once per timestep: 64 network function evaluations (NFE) per batch here, and a thousand for a model trained with \(T=1000\). Sampling cost, unlike training cost, is paid again for every generated image, so reducing it matters.
A tempting shortcut is to visit only every fourth timestep and keep everything else. It fails for a reason you can now state: the coefficients in Equation 23.6 describe the step from \(t\) to \(t-1\). After one such update the state has the noise level of \(t-1\), but the shortcut labels it \(t-4\). The network then receives an image whose actual noise level contradicts its time label.
Denoising diffusion implicit models (DDIM) provide an update that is valid for jumps (J. Song et al. 2021). The idea follows from Equation 23.2. At time \(t\), the network’s prediction splits the current state into an estimated clean image \(\hat x_0\) and an estimated noise \(\hat\epsilon\). To move to an earlier time \(s<t\), recombine the same two parts with the signal and noise levels of \(s\):
No fresh noise is added, so this sampler is deterministic: the starting noise alone determines the image. The jump may skip any number of timesteps, because the update refers only to the two noise levels involved.
DDPM (Algorithm 2)
Deterministic DDIM
Network and weights
The trained noise predictor
The same, unchanged
Training schedule and time labels
As trained
As trained, using a subset of the timesteps
Fresh noise per step
Yes, except at the end
No
Randomness comes from
Starting noise and all later draws
Starting noise only
Network evaluations
\(T\)
Any number from \(1\) to \(T\)
DDIM changes the sampling rule and the sampling cost and leaves training untouched. How far the number of evaluations can be reduced before the images change is an empirical question about a particular model. The lab lets you watch the naive shortcut fail, implement Equation 23.9, and compare 64, 16, and 4 evaluations with one frozen checkpoint.
23.11 Judging a generator
23.11.1 No paired ground truth
In segmentation, each prediction had a reference mask, and Dice measured their overlap. A generated image has no reference. Comparing it pixel by pixel with an arbitrary validation image measures nothing useful, since a perfectly good disk at a different position would score badly. Using the same starting noise in two samplers gives a controlled comparison, but neither result becomes the truth.
Evaluation therefore compares sets of images and asks several questions, none of which a single number answers.
Question
Evidence in this chapter
What it cannot establish alone
Does the denoiser generalize?
Validation noise error at fixed timesteps
Sample fidelity or diversity
Does each sample look like data?
Unselected sample grids; bright-area statistics
A precise population-level estimate
Do samples cover the variety?
Spread of positions and sizes across many draws
Coverage of rare cases
Are samples new, or copies?
Distance to the nearest training image
That distant samples are good
What does a sample cost?
Network evaluations per image
Wall-clock time on every device
23.11.2 Are the samples copies of the training set?
A generator could score well on fidelity by memorizing training images. A simple check compares each generated image with its nearest training image. The validation set supplies the reference: it tells us how close a genuinely new image from the same distribution typically comes to the training set.
def nearest_training_image(images):"""Euclidean distance to, and index of, the closest training image.""" distances = torch.cdist(images.flatten(1), train.flatten(1)) # (N, 256)return distances.min(dim=1)valid_distance, _ = nearest_training_image(valid)generated_distance, neighbor = nearest_training_image(generated_1200)print("Distance to the nearest training image: smallest / median / largest")for name, distance in [("Validation images", valid_distance), ("Generated images", generated_distance)]: low, middle, high = distance.min(), distance.median(), distance.max()print(f" {name:18s}{low:.2f} / {middle:.2f} / {high:.2f}")
Distance to the nearest training image: smallest / median / largest
Validation images 0.33 / 1.70 / 3.26
Generated images 0.69 / 1.76 / 5.36
Figure 23.10: The first eight generated images after 1200 updates and, below each, its nearest training image in Euclidean distance.
If the generator copied its training data, the generated distances would be close to zero, far below those of the validation images. If it produced images unlike any data, they would be much larger. In our reference run the typical distances are similar: generated disks resemble training disks about as much as fresh disks do. The largest generated distances exceed the largest validation distance, which points to a few unusual samples.
Inspect — 5 minutes. Display the eight generated images with the largest distances. Do they look wrong? Compare the positions of their disks with the positions in the training set, and decide whether “looks like a disk” is enough to say that a sample follows the data distribution.
This check is useful and limited. It uses pixel distance, which is meaningful for our simple shapes and much less so for photographs, and it can only detect near-duplicates.
23.11.3 Metrics used for real image generators
For natural images, pixel statistics such as our bright area are too crude. A widely used summary is the Fréchet inception distance (FID)(Heusel et al. 2017). It passes a large set of real images and a large set of generated images through a pretrained classification network, summarizes each set by the mean and covariance of the resulting feature vectors, and reports a distance between the two summaries. Lower is better.
FID rewards both fidelity and diversity, but it compresses them into one number, depends on the feature network and on the number of samples, and says nothing about any individual image. Careful reports therefore add separate fidelity and coverage measures, checks for memorization, and unselected sample grids. The habits from this chapter apply unchanged: fix seeds, show all draws, compare distributions with held-out data, and state the cost.
23.12 From sixteen pixels to modern image generators
Our model and a current text-to-image system share the forward process, the noise-prediction objective, and the idea of iterative sampling. Three additions account for most of the difference in what they can do.
23.12.1 Conditioning: asking for a particular image
To control what is generated, the denoiser receives an additional input \(c\) that describes the desired content and becomes \(\epsilon_\theta(x_t,t,c)\). The condition can be a class label, another image, or a text embedding. Training is Algorithm 1 with one change: each training image is presented together with its own label or caption.
The network takes in \(c\) much as it takes in \(t\). A class label can be embedded as a vector and added to the time embedding. Text is processed by a separate language model into a sequence of vectors, which the denoiser reads through attention layers, a mechanism we study from Lesson 10 onward.
23.12.2 Guidance: trading diversity for adherence
A conditional model often follows its condition only loosely. Classifier-free guidance strengthens the effect at sampling time (Ho and Salimans 2022). During training, the condition is replaced by an empty placeholder \(\varnothing\) for a fraction of the examples, so that one network learns both a conditional and an unconditional prediction. During sampling, the two are extrapolated:
With \(w=1\) this is the conditional prediction. With \(w>1\) the sampler moves further in the direction that distinguishes “matching the condition” from “any image”. Samples then match the condition more reliably and usually become less varied. Guidance is thus a dial on the sampling rule in the sense of the table above: it needs no retraining. Papers differ in how they parameterize the weight, so check the convention before comparing values. The additional material trains a small conditional model on our disks and measures this trade-off.
23.12.3 Latent diffusion: denoise a compressed representation
Running a U-Net many times over millions of pixels is expensive. Latent diffusion first trains an autoencoder that compresses an image into a much smaller grid of features, a latent, and can decode it again (Rombach et al. 2022). The diffusion model is then trained and sampled entirely in latent space, and the decoder runs once at the end. In the original Stable Diffusion configuration, for example, a \(512\times512\) color image corresponds to a \(64\times64\) latent with four channels. The diffusion algorithm is unchanged; only the space in which it operates differs.
The U-Net is not essential either. Many recent systems replace it by a Transformer that operates on patches of the latent (Peebles and Xie 2023), connecting this chapter to Lessons 10 and 13.
23.12.4 Explore interactively: inside a text-to-image model
Diffusion Explainer visualizes how Stable Diffusion turns a text prompt into an image. Use it to connect the three additions above to what you built.
Find the denoising network and the timestep in the diagram. Which quantities play the roles of \(x_t\), \(t\), and \(\epsilon_\theta\) from this chapter?
Change the guidance scale and compare the results. Relate what you see to Equation 23.10.
Locate the step that converts the final latent into an image. Why is it applied only once?
The tool replays precomputed results for a fixed set of prompts; it does not train or run a model in your browser. Open the link in a separate tab if the embedded view does not load or needs more space.
Credit: Seongmin Lee and colleagues, Polo Club of Data Science at Georgia Tech, Diffusion Explainer.
23.12.5 Where diffusion sits among generative models
Diffusion is one of several families of deep generative models. Autoregressive models, which we meet with GPT in Lesson 11, generate one element at a time. Generative adversarial networks train a generator against a second network that tries to tell its samples from data. Variational autoencoders learn an encoder and a decoder around a simple latent distribution. These families differ in training stability, sampling cost, and whether they provide likelihoods; Prince (2023) compares them in more detail. Diffusion models became the dominant approach for images after they matched and then exceeded the sample quality of adversarial networks (Dhariwal and Nichol 2021), using a training objective that is a plain regression. Their main price is slow, iterative sampling.
23.13 Generalization, limitations, and responsible use
The experiment is small. Sixteen-by-sixteen disks have three degrees of freedom: two coordinates and a radius. Our results show that the algorithm works and how to diagnose it. They are not evidence about natural or medical images, and a short run on one seed does not establish a ranking of design choices.
A generator reproduces its training distribution, including its flaws. Whatever is frequent in the data becomes frequent in the samples; whatever is rare or absent stays rare or absent. Biases in a training collection are inherited, and strong guidance, which trades variety for typical examples, may accentuate them.
Generated data contain no new measurements. Synthetic images can be useful, for example to balance classes or to share examples when the originals are restricted. But they are drawn from a model fitted to the original data. They cannot reveal a pattern that those data did not contain, and using them as if they were independent observations overstates the evidence. In digital health this matters twice: synthetic patients are not additional patients, and an evaluation must still rest on real, independently collected cases.
Models can memorize. Large diffusion models have been shown to reproduce individual training images, including photographs of people (Carlini et al. 2023). “Generated” therefore does not imply “anonymous”. For sensitive data, test for near-duplicates of training examples and treat a trained generator as carefully as the data it was fitted to.
Samples can deceive. Realistic synthetic images and videos can be used to mislead. When you publish generated material, label it as generated and document the model, the data it was trained on, and the sampling settings.
Sampling costs compute. Every image requires repeated passes through a large network. The number of evaluations is a design decision with a quality trade-off, as the lab shows on a small scale.
23.14 Chapter summary
Generation has no paired target. A generator turns random numbers into new examples and must achieve both fidelity and diversity. Sampling pixels independently loses the dependencies between pixels; the mean image loses diversity.
The forward process destroys images in a controlled way. Each step shrinks the image and adds Gaussian noise. The direct noising equation reaches any noise level in one computation, and the schedule must drive the signal level to zero at \(t=T\).
Training is noise regression. Sample an image, a timestep, and noise; ask the network to predict the noise. No labels are needed, and the sampler is never run during training. The simple loss is not a likelihood.
A squared-error denoiser returns the conditional mean. From pure noise, that is the average of the data. One large jump therefore yields a blur, not a sample.
Small steps with fresh noise turn a denoiser into a sampler. One step back is well approximated by a Gaussian whose mean uses the current clean estimate. Repeating such steps commits gradually to one clean image and reproduces the variety of the data.
The denoising network is a U-Net that receives the timestep. A time embedding is added inside every block. The output is unbounded and has no sigmoid.
Training quality, sampling rule, and sampling cost are separate dials. Test the sampler with an oracle, compare checkpoints with identical random numbers, and change one dial at a time. DDIM reduces the number of network evaluations without retraining.
Evaluation compares sets of images. Inspect unselected draws, compare simple statistics with held-out data, check for copies, and report cost. Large systems add conditioning, guidance, and latent spaces to the same core algorithm.
23.15 Review questions
23.15.1 Check the foundations
Write the single-step forward update and the direct noising equation. What do \(\beta_t\), \(\alpha_t\), and \(\bar\alpha_t\) mean, and which of them is the signal level?
Why are the coefficients \(\sqrt{1-\beta_t}\) and \(\sqrt{\beta_t}\) chosen together? What would happen to the scale of \(x_t\) if the image were not shrunk?
List the three random choices in one training update. Why can the targets be constructed without manual labels?
Distinguish a diffusion timestep, an optimizer update, and a network evaluation. How many of each occur when we train for 1200 updates and then generate 64 images with DDPM?
Why does a noise-prediction network have no sigmoid at its output, and why does it need the timestep although input and output always have the same shape?
23.15.2 Explain and diagnose
A colleague copies \(\beta_1=10^{-4}\) and \(\beta_T=0.02\) from a paper that used \(T=1000\), but sets \(T=50\). Without running code, explain what goes wrong and at which stage it becomes visible.
For the two-point dataset, sketch the best clean estimate as a function of \(x_t\) at low, medium, and high noise. Why is its value at the highest noise level not a valid data point?
Use Figure 23.4 to explain why DDPM takes many small steps. What does the fresh noise in each step contribute?
A model has very low validation noise error at \(t=T\). Explain why this says little about its samples. Which baseline makes the point?
Samples from your model are sometimes empty. Describe two experiments that distinguish a faulty sampler from an undertrained network, and state what each one holds fixed.
Someone speeds up sampling by visiting every fourth timestep in the DDPM loop without other changes. Which quantity disagrees with which? How does the DDIM update avoid the problem?
23.15.3 Design and evaluate
You may change either the number of training updates or the number of sampling evaluations. Design a comparison for each that changes only one dial. Which controls are shared, and which resource does each experiment spend?
Why is the mean squared error between a generated image and a validation image not a quality measure? Propose two pieces of evidence that are meaningful for our disks and one that would be needed for natural images.
The nearest-training-image distances of your samples are much smaller than those of validation images. What does this suggest, and why would it matter for a model trained on patient images?
A conditional model is sampled with guidance weights \(w=1\) and \(w=4\). Predict the difference in how well samples match the condition and in their variety. Why does changing \(w\) not require retraining?
A team proposes to enlarge a small clinical image dataset with samples from a diffusion model trained on that same dataset, and then to report test accuracy on a mixture of real and generated images. Identify two problems with this plan.
23.16 Selected further reading
These resources follow the chapter’s progression: understand the algorithm, implement it, then connect it to other viewpoints.
23.16.1 Foundational papers
Denoising Diffusion Probabilistic Models — Ho, Jain, and Abbeel (2020). The paper behind Algorithms 1 and 2. Read Sections 2 and 3 next to this chapter and identify the forward process, the simple loss, and the two algorithm boxes. Compare its \(T=1000\) linear schedule with our 64-step cosine schedule.
Deep Unsupervised Learning using Nonequilibrium Thermodynamics — Sohl-Dickstein and colleagues (2015). The origin of the idea of destroying structure gradually and learning to reverse the process. Read the introduction for the motivation, and the description of the reverse trajectory for the argument that small steps make the reverse process simple.
Improved Denoising Diffusion Probabilistic Models — Nichol and Dhariwal (2021). Source of the cosine schedule. Look at its comparison of how quickly the linear and cosine schedules destroy an image.
Denoising Diffusion Implicit Models — Song, Meng, and Ermon (2021). Source of the deterministic sampler used in the lab. Focus on how the same trained network supports samplers with different numbers of steps.
23.16.2 Tutorials and visual explanations
What are Diffusion Models? — Lilian Weng. A thorough written overview with consistent notation, from the forward process to guidance, latent diffusion, and faster samplers. Use it as a reference once you have worked through this chapter.
The Annotated Diffusion Model — Hugging Face blog (2022). A step-by-step PyTorch implementation of DDPM on real images. Compare its network, schedule, and sampler with ours and list what was added for the larger problem.
Understanding Deep Learning, Chapter 18 — Simon Prince (Prince 2023). A textbook treatment at a similar level, including the derivation of the training objective.
Guidance: a cheat code for diffusion models — Sander Dieleman. An accessible explanation of classifier guidance and classifier-free guidance and of the trade-off they control.
These topics extend the chapter; none is a prerequisite for the lab.
23.17.1 Scores and continuous time
Predicting noise is equivalent to estimating the direction in which the probability of a noisy image increases fastest, the score. In the limit of infinitely many steps the forward process becomes a stochastic differential equation, and sampling means solving a differential equation backward in time (Y. Song et al. 2021). Yang Song’s article Generative Modeling by Estimating Gradients of the Data Distribution introduces this view with many figures. The additional material verifies the noise–score relation numerically.
23.17.2 Flow matching
Related methods train a network to predict a velocity that transports noise to data along simple paths and then sample by integrating that velocity (Lipman et al. 2023). Investigate how the training target and the sampler differ from the ones in this chapter, and what stays the same.
23.17.3 Faster samplers
Beyond DDIM, improved numerical solvers reduce the number of evaluations further, and distillation trains a second network to reproduce in one or a few steps what the original sampler needs many steps for. Lilian Weng’s overview above includes a section on faster sampling and distillation. Ask of each method which dial it turns: sampling rule, sampling cost, or training.
23.17.4 Guidance and control
Classifier guidance (Dhariwal and Nichol 2021) and classifier-free guidance (Ho and Salimans 2022) steer sampling toward a condition. Explore how the guidance weight affects fidelity and variety, and what happens to the images when the weight becomes very large.
23.17.5 Diffusion models in medical imaging
Diffusion models are studied in medicine for image generation, reconstruction, segmentation, denoising, and anomaly detection, among other tasks (Kazerouni et al. 2023). For any such application, determine what the model was trained on, how memorization was assessed, and whether the evaluation uses independent real cases.
23.18 What to watch
Use these videos to reinforce the explanations, then return to the chapter or the code to check your understanding.
But how do AI images and videos actually work? — Welch Labs, guest video on 3Blue1Brown. A visual account of diffusion, text conditioning, and guidance. After watching, explain in your own words why removing the fresh noise from the sampling steps leads to blurry results, and connect that to the conditional mean.
Diffusion Models | Paper Explanation | Math Explained — Outlier. Walks through the DDPM equations, including the direct noising formula and the reverse step. Pause at each derivation and locate the corresponding equation in this chapter.
When following an implementation, identify three things explicitly: what the network predicts, which schedule defines the noise levels, and which sampler is used with how many evaluations. Implementations differ in all three, and results are only comparable when they are stated.
Kazerouni, Amirhossein, Ehsan Khodapanah Aghdam, Moein Heidari, et al. 2023. “Diffusion Models in Medical Imaging: A Comprehensive Survey.”Medical Image Analysis 88: 102846. https://arxiv.org/abs/2211.07804.
Lipman, Yaron, Ricky T. Q. Chen, Heli Ben-Hamu, Maximilian Nickel, and Matthew Le. 2023. “Flow Matching for Generative Modeling.”International Conference on Learning Representations. https://arxiv.org/abs/2210.02747.
Nichol, Alexander Quinn, and Prafulla Dhariwal. 2021. “Improved Denoising Diffusion Probabilistic Models.”Proceedings of the 38th International Conference on Machine Learning, Proceedings of machine learning research, vol. 139: 8162–71. https://arxiv.org/abs/2102.09672.
Peebles, William, and Saining Xie. 2023. “Scalable Diffusion Models with Transformers.”Proceedings of the IEEE/CVF International Conference on Computer Vision, 4195–205. https://arxiv.org/abs/2212.09748.
Rombach, Robin, Andreas Blattmann, Dominik Lorenz, Patrick Esser, and Björn Ommer. 2022. “High-Resolution Image Synthesis with Latent Diffusion Models.”Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, 10684–95. https://arxiv.org/abs/2112.10752.
Sohl-Dickstein, Jascha, Eric Weiss, Niru Maheswaranathan, and Surya Ganguli. 2015. “Deep Unsupervised Learning Using Nonequilibrium Thermodynamics.”Proceedings of the 32nd International Conference on Machine Learning, Proceedings of machine learning research, vol. 37: 2256–65. https://proceedings.mlr.press/v37/sohl-dickstein15.html.
Song, Jiaming, Chenlin Meng, and Stefano Ermon. 2021. “Denoising Diffusion Implicit Models.”International Conference on Learning Representations. https://arxiv.org/abs/2010.02502.
Song, Yang, Jascha Sohl-Dickstein, Diederik P. Kingma, Abhishek Kumar, Stefano Ermon, and Ben Poole. 2021. “Score-Based Generative Modeling Through Stochastic Differential Equations.”International Conference on Learning Representations. https://iclr.cc/virtual/2021/poster/3177.
Vaswani, Ashish et al. 2017. “Attention Is All You Need.”Advances in Neural Information Processing Systems.