8.3Diffusion: noising & denoising
Destroy images with noise on purpose, train a network to undo one small step of the damage, and you get the engine behind modern image generators.
Generation is hard; denoising is easy
Asking a network to output a photorealistic 512×512 image in one shot is asking it to choose about 786,000 numbers at once, all consistent with each other. In the previous lessons you met two ways to attempt this: VAEsVariational autoencoder (VAE)An autoencoder whose latent space is regularized to be smooth and samplable, so new data can be generated by decoding random latents., which tend to produce blurry averages, and GANsGenerative adversarial network (GAN)A generator and a discriminator trained against each other: the generator tries to fool the discriminator., which produce sharp images but are notoriously hard to train (see GANs).
Diffusion modelsDiffusion modelA generative model trained to reverse a gradual noising process, so it can generate data by denoising pure noise step by step. take a sideways route. Instead of learning to create an image, they learn something much more modest: given a slightly noisy image, how should it look with a little less noise? That is a supervised regression problem with an unlimited supply of training pairs, because you can manufacture noisy images yourself. Chain a few dozen to a thousand of these small cleanups together, starting from pure random noise, and the network has, step by step, generated an image.
The idea was introduced by Sohl-Dickstein and colleagues in 2015 and became practical with Denoising Diffusion Probabilistic Models (DDPMDDPMDenoising Diffusion Probabilistic Models (Ho et al., 2020): train a network to predict the added noise, then sample by denoising step by step., Ho, Jain and Abbeel, 2020). Within two years it powered DALL·E 2, Imagen and Stable Diffusion.
Imagine a restorer handed a photograph that has been left in the rain. They can’t conjure the original from nothing, but they are excellent at one thing: looking at a damaged photo and making it slightly less damaged. Now give that restorer a sheet of pure TV static and tell them, “this is a very, very damaged photo.” They clean it a little. Then again. After many passes, a plausible photograph stands there, one that never existed.
The rain is the forward process (a fixed recipe that adds noise). The restorer is the denoising network. Each pass is one reverse step. And the photo that emerges is a sample: a new image drawn from everything the restorer learned about what photos look like.
The forward process: destroying an image on schedule
Start with a clean image , its pixels scaled to the range −1 to 1. The forward process produces noisier versions (DDPM used ). At every step it shrinks the image a little and adds a little Gaussian noise. The amount added at step is called , and the list of all of them is the noise scheduleNoise scheduleThe recipe that sets how much noise a diffusion model adds at each timestep, e.g. linear or cosine schedules for ᾱ_t..
The key property that makes diffusion practical: you never need to apply those 1000 small steps one after another. Because sums of Gaussians are Gaussian, you can jump straight to any timestep in one line:
Read it as a crossfade. (“alpha-bar”) falls from 1 at to almost 0 at . The image’s share of the mix is ; the noise’s share is . Their squares always add to 1, so the overall variance stays roughly constant, which is why this family is called variance-preserving. A handy single number is the signal-to-noise ratio, .
The noised image is computed in one shot from the closed form x_t = √ᾱ_t·x₀ + √(1−ᾱ_t)·ε; no need to add noise step by step.
Things to try:
- Forward, linear schedule, t = 250. The scene is already badly degraded (). By it is essentially gone (): the linear schedule destroys information quickly and then spends hundreds of steps on near-pure noise.
- Switch to cosine. Now the image survives much longer: at , , and signal and noise are about equal. Nichol and Dhariwal (2021) proposed this cosine schedule precisely so fewer steps are wasted on noise that is already total.
- Reverse, step by step. Watch the right panel. At first the “guess of ” is a flat average color, then a blurry layout (sky on top, dark ground below), and only near the end do edges like the sun and tree sharpen. Diffusion decides composition first and details last.
Training: predict the noise
Here is the whole DDPM training loop, and it is surprisingly short:
- Take a real training image .
- Pick a random timestep between 1 and .
- Draw fresh noise and form with the closed form above.
- Ask a network to predict , and minimize the squared error with gradient descentGradient descentRepeatedly nudging the parameters a small step opposite the gradient, so the loss goes downhill..
The network sees the timestep as an extra input (through an embedding), so a single set of weights handles every noise level. Predicting the noise is equivalent to predicting the clean image, since you can rearrange the closed form: . Ho et al. found that predicting with this simple unweighted loss gave the best samples. Later work also uses -prediction or a blend called -prediction; they are reparameterizations of the same task.
Why does this teach generation? At high noise, many different clean images could have produced the same , so the loss-minimizing prediction is their average: a blurry blob that captures only the broad layout. At low noise, pins down the image almost exactly, so the network learns fine texture. By training on all noise levels at once, one network learns the whole hierarchy, from “where does the sky go” to “what do eyelashes look like”.
Sampling: running the movie backwards
To generate, draw and walk backwards. At each step the network predicts the noise, which gives an estimate ; the sampler then moves a little toward that estimate. DDPM’s sampler is stochastic: each step also adds a small amount of fresh noise, as the math of reversing a noisy process requires. Using all 1000 steps, one image costs 1000 network evaluations.
That is slow, and DDIMDDIMDenoising Diffusion Implicit Models: a deterministic sampler for DDPM-trained models that can skip timesteps, so it needs far fewer steps. (Song, Meng and Ermon, 2020) showed it is unnecessary. DDIM reuses a DDPM-trained network as is, but takes a deterministic path: estimate , then re-noise it to a much lower level using the predicted noise instead of fresh noise. Because the update never needed the in-between steps, you can stride through, say, 50 of the 1000 timesteps. Same model, roughly 20× fewer evaluations, and the same starting noise always gives the same image, which makes it possible to interpolate between noises and edit consistently.
Grey dots: the training data. Orange: samples. Arrows: where the exact denoiser would pull a point at this noise level (they point along the score ∇log p_t). For this toy we can compute the score exactly; a real model learns it.
Things to try:
- Forward, then drag to the end. Whatever the shape, at it is a featureless, round blob: . That is why sampling can always start from plain random numbers.
- Reverse with DDPM, step slowly. For the first half nothing seems to happen except the cloud shrinking. The shape “snaps” into place late, once the noise is small enough for the arrows to point at specific arms of the spiral.
- Turn on the arrows at different t. At high noise every arrow points roughly at the center (the average of all data). At low noise they point to the nearest piece of the shape. That is the coarse-to-fine story again, in two dimensions.
- Switch to DDIM. The trails become smooth curves. Each starting point now maps to exactly one endpoint.
The score view: arrows toward the data
There is a second, equivalent way to describe all this. For any probability distribution , the scoreScore functionThe gradient of the log-density, ∇ₓ log p(x): an arrow at every point that points toward more likely data. Denoisers estimate it. is : an arrow at every point that points toward higher probability. If you knew the score of the data, you could start anywhere and follow the arrows (plus a little noise, a procedure called Langevin dynamics) to land on likely data.
The trouble is that the score of real images is meaningless far from the data, where there are no examples. Song and Ermon (2019) fixed this by learning the score of the noised data at many noise levels, which is smooth and defined everywhere, and annealing from large noise to small. It turns out that the optimal noise predictor and the score are the same object up to a scale:
So a trained is a score estimator, and the arrows in the demo are exactly this quantity. Song et al. (2021) unified both views using stochastic differential equations: DDPM sampling is a discretized reverse-time SDE, and DDIM is a discretization of a deterministic “probability flow” ODE with the same marginals. That ODE view returns in Diffusion Transformers & flow matching, where we straighten its paths.
MATH CORNER · optionalForward closed form, the loss, and one reverse step by hand
Forward process. Each step is . With and , composing the Gaussians gives
Training objective (DDPM’s “simple” loss).
Reverse step (DDPM). With the prediction ,
DDIM step from to an earlier (deterministic):
Worked example (one pixel). Clean value , noise draw , cosine schedule at where .
| quantity | formula | value |
|---|---|---|
| signal weight | 0.703 | |
| noise weight | 0.711 | |
| noisy pixel | 0.207 | |
| network guess | −0.40 (a bit off) | |
| implied clean pixel | 0.699 | |
| DDIM jump to () | 0.487 |
The noise guess was off by 0.1, so the estimate is off by . At lower noise levels the same error in costs much less, because it is multiplied by a smaller : later steps are where fine corrections become cheap and precise.
In code
A minimal DDPM training step and DDIM sampler in PyTorch. model is any network that takes a noisy batch and timesteps and returns a tensor of the same shape (a U-Net or a Transformer in practice).
import torch, math
T = 1000
s = 0.008
t_grid = torch.arange(T + 1) / T
abar = torch.cos((t_grid + s) / (1 + s) * math.pi / 2) ** 2
abar = (abar / abar[0]).clamp(min=1e-4) # cosine schedule; clamp so t = T is not exactly 0
def train_step(model, x0, opt):
t = torch.randint(1, T + 1, (x0.shape[0],))
eps = torch.randn_like(x0)
a = abar[t].view(-1, 1, 1, 1)
xt = a.sqrt() * x0 + (1 - a).sqrt() * eps # jump straight to step t
loss = (model(xt, t) - eps).pow(2).mean() # predict the noise
opt.zero_grad(); loss.backward(); opt.step()
@torch.no_grad()
def ddim_sample(model, shape, steps=50):
x = torch.randn(shape)
ts = torch.linspace(T, 0, steps + 1).long()
for t, s_ in zip(ts[:-1], ts[1:]):
eps = model(x, t.repeat(shape[0]))
x0 = (x - (1 - abar[t]).sqrt() * eps) / abar[t].sqrt()
x = abar[s_].sqrt() * x0 + (1 - abar[s_]).sqrt() * eps
return x
Why it works so well
Diffusion’s advantages over GANs come from that humble regression loss. It is stable: no adversary, no balancing act, the loss just goes down. It covers the whole data distribution, because every training image contributes to the loss at every noise level, so there is no incentive to ignore rare kinds of images (the opposite of mode collapse). And it is flexible at sampling time: you can trade steps for quality, steer the trajectory with guidance, or start part-way from an existing image. The next lesson, Stable Diffusion & classifier-free guidance, shows how to run all of this in a compressed latent space and steer it with text.
The price is speed. Even with good samplers, generation needs tens of network evaluations instead of a GAN’s one. Much of the research since 2020 (better ODE solvers, flow matching, distillationDistillationTraining a smaller 'student' model to imitate a larger 'teacher' model's outputs. into few-step students) is about paying less of that price.
- “The network removes all the noise in one go.” It is trained to predict the noise at any level, but sampling applies that prediction in many small steps, re-evaluating as the picture firms up. A one-shot prediction from pure noise is just a blurry average.
- “Forward diffusion is learned.” The forward process is a fixed formula with no parameters. Only the reverse (denoising) network is trained.
- “Training requires running 1000 noising steps per image.” The closed form jumps to any directly, so each training example costs one network evaluation at one random timestep.
- “DDIM needs a differently trained model.” DDIM is a different sampler for the same DDPM-style network. It changes how predictions are turned into steps, not the training objective.
- “Diffusion models store and stitch together training images.” The ideal denoiser of a tiny dataset would memorize, and large models can occasionally regurgitate heavily duplicated images, but in general they learn a smooth score function and produce new combinations.
Check your understanding
Q1.With x_t = √ᾱ_t·x₀ + √(1−ᾱ_t)·ε, what happens as t approaches T?
Q2.During DDPM training, what is the network asked to output?
Q3.At very high noise, a well-trained denoiser's guess of x₀ looks like a blurry average. Why?
Q4.What does DDIM change compared with DDPM sampling?
Q5.How is the noise predictor related to the score ∇log p_t(x_t)?
Further reading
- paperDenoising Diffusion Probabilistic Models (Ho, Jain, Abbeel, 2020) — The DDPM paper: ε-prediction, the simple loss, linear schedule with T = 1000.
- paperDenoising Diffusion Implicit Models (Song, Meng, Ermon, 2020) — The deterministic, step-skipping sampler.
- paperImproved Denoising Diffusion Probabilistic Models (Nichol & Dhariwal, 2021) — Introduces the cosine noise schedule.
- paperScore-Based Generative Modeling through Stochastic Differential Equations (Song et al., 2021) — Unifies score matching and diffusion; the probability-flow ODE.
- blogWhat are Diffusion Models? (Lilian Weng) — A thorough, math-forward blog walkthrough.
- paperDeep Unsupervised Learning using Nonequilibrium Thermodynamics (Sohl-Dickstein et al., 2015) — Where the diffusion idea began.