Skip to content
LearnAI

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.

⏱ 17 minIntermediate

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.

ANALOGY· Sculpting from a block of static

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 x0x_0, its pixels scaled to the range −1 to 1. The forward process produces noisier versions x1,x2,…,xTx_1, x_2, \dots, x_T (DDPM used T=1000T = 1000). At every step it shrinks the image a little and adds a little Gaussian noise. The amount added at step tt is called βt\beta_t, 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:

xt=αˉt x0+1−αˉt  ε,ε∼N(0,I).x_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\; \varepsilon, \qquad \varepsilon \sim \mathcal{N}(0, I).

Read it as a crossfade. αˉt\bar\alpha_t (“alpha-bar”) falls from 1 at t=0t = 0 to almost 0 at t=Tt = T. The image’s share of the mix is αˉt\sqrt{\bar\alpha_t}; the noise’s share is 1−αˉt\sqrt{1-\bar\alpha_t}. 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, SNR(t)=αˉt/(1−αˉt)\text{SNR}(t) = \bar\alpha_t / (1 - \bar\alpha_t).

INTERACTIVEDiffusion denoising stepper
Direction
Schedule
clean image x₀
noised x_t (t = 300)
00.5102505007501000— signal √ᾱ- - noise √(1−ᾱ)
signal √ᾱ_t
0.887
noise √(1−ᾱ_t)
0.462
SNR ᾱ/(1−ᾱ)
3.7 (6 dB)
RMS diff from x₀
0.235

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.

Forward: drag t and watch a 48×48 image dissolve into Gaussian noise; compare the linear and cosine schedules. Reverse: press Play to denoise from pure noise in 50 steps, with the model's x₀-guess shown alongside.

Things to try:

  1. Forward, linear schedule, t = 250. The scene is already badly degraded (αˉ≈0.52\bar\alpha \approx 0.52). By t≈500t \approx 500 it is essentially gone (αˉ≈0.08\bar\alpha \approx 0.08): the linear schedule destroys information quickly and then spends hundreds of steps on near-pure noise.
  2. Switch to cosine. Now the image survives much longer: at t=500t = 500, αˉ≈0.49\bar\alpha \approx 0.49, 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.
  3. Reverse, step by step. Watch the right panel. At first the “guess of x0x_0” 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:

  1. Take a real training image x0x_0.
  2. Pick a random timestep tt between 1 and TT.
  3. Draw fresh noise ε\varepsilon and form xtx_t with the closed form above.
  4. Ask a network εθ(xt,t)\varepsilon_\theta(x_t, t) to predict ε\varepsilon, and minimize the squared error ∥ε−εθ(xt,t)∥2\lVert \varepsilon - \varepsilon_\theta(x_t, t) \rVert^2 with gradient descentGradient descentRepeatedly nudging the parameters a small step opposite the gradient, so the loss goes downhill..

The network sees the timestep tt 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: x^0=(xt−1−αˉt ε^)/αˉt\hat x_0 = (x_t - \sqrt{1-\bar\alpha_t}\,\hat\varepsilon)/\sqrt{\bar\alpha_t}. Ho et al. found that predicting ε\varepsilon with this simple unweighted loss gave the best samples. Later work also uses x0x_0-prediction or a blend called vv-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 xtx_t, so the loss-minimizing prediction is their average: a blurry blob that captures only the broad layout. At low noise, xtx_t 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 xT∼N(0,I)x_T \sim \mathcal{N}(0, I) and walk backwards. At each step the network predicts the noise, which gives an estimate x^0\hat x_0; the sampler then moves xtx_t 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 x^0\hat x_0, 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.

INTERACTIVEDiffusion on a 2D point cloud
Direction
Data
Sampler
timestep t
1000
ᾱ_t (signal²)
0.000
cloud spread (std)
0.98
N(0, I) has 1.00
mean dist. to data
0.358
lower = on the shape

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.

Each dot is one 'image' with just two pixels. Forward: watch the spiral melt into a round Gaussian blob. Reverse: start from that blob and follow the score arrows back. Compare DDPM's jittery paths with DDIM's smooth ones.

Things to try:

  1. Forward, then drag to the end. Whatever the shape, at t=1000t = 1000 it is a featureless, round blob: N(0,I)\mathcal{N}(0, I). That is why sampling can always start from plain random numbers.
  2. 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.
  3. 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.
  4. 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 p(x)p(x), 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 ∇xlog⁡p(x)\nabla_x \log p(x): 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:

∇xtlog⁡pt(xt)=−E[ε∣xt]1−αˉt.\nabla_{x_t} \log p_t(x_t) = -\frac{\mathbb{E}[\varepsilon \mid x_t]}{\sqrt{1 - \bar\alpha_t}} .

So a trained εθ\varepsilon_\theta 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 q(xt∣xt−1)=N(1−βt xt−1,βtI)q(x_t \mid x_{t-1}) = \mathcal{N}(\sqrt{1-\beta_t}\, x_{t-1}, \beta_t I). With αt=1−βt\alpha_t = 1 - \beta_t and αˉt=∏s=1tαs\bar\alpha_t = \prod_{s=1}^{t} \alpha_s, composing the Gaussians gives

q(xt∣x0)=N ⁣(αˉt x0, (1−αˉt)I).q(x_t \mid x_0) = \mathcal{N}\!\left(\sqrt{\bar\alpha_t}\, x_0,\ (1 - \bar\alpha_t) I\right).

Training objective (DDPM’s “simple” loss).

L=Ex0, t, ε∥ε−εθ ⁣(αˉt x0+1−αˉt ε, t)∥2.L = \mathbb{E}_{x_0,\, t,\, \varepsilon} \left\lVert \varepsilon - \varepsilon_\theta\!\left(\sqrt{\bar\alpha_t}\, x_0 + \sqrt{1-\bar\alpha_t}\, \varepsilon,\ t\right) \right\rVert^2 .

Reverse step (DDPM). With the prediction ε^=εθ(xt,t)\hat\varepsilon = \varepsilon_\theta(x_t, t),

xt−1=1αt(xt−βt1−αˉt ε^)+σtz,z∼N(0,I).x_{t-1} = \frac{1}{\sqrt{\alpha_t}} \left( x_t - \frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\, \hat\varepsilon \right) + \sigma_t z, \qquad z \sim \mathcal{N}(0, I).

DDIM step from tt to an earlier ss (deterministic):

x^0=xt−1−αˉt ε^αˉt,xs=αˉs x^0+1−αˉs ε^.\hat x_0 = \frac{x_t - \sqrt{1-\bar\alpha_t}\,\hat\varepsilon}{\sqrt{\bar\alpha_t}}, \qquad x_s = \sqrt{\bar\alpha_s}\, \hat x_0 + \sqrt{1-\bar\alpha_s}\, \hat\varepsilon .

Worked example (one pixel). Clean value x0=0.8x_0 = 0.8, noise draw ε=−0.5\varepsilon = -0.5, cosine schedule at t=500t = 500 where αˉ≈0.494\bar\alpha \approx 0.494.

quantityformulavalue
signal weightαˉ\sqrt{\bar\alpha}0.703
noise weight1−αˉ\sqrt{1-\bar\alpha}0.711
noisy pixel0.703⋅0.8+0.711⋅(−0.5)0.703 \cdot 0.8 + 0.711 \cdot (-0.5)0.207
network guessε^\hat\varepsilon−0.40 (a bit off)
implied clean pixel(0.207−0.711⋅(−0.40))/0.703(0.207 - 0.711 \cdot (-0.40)) / 0.7030.699
DDIM jump to t=250t = 250 (αˉ=0.847\bar\alpha = 0.847)0.920⋅0.699+0.391⋅(−0.40)0.920 \cdot 0.699 + 0.391 \cdot (-0.40)0.487

The noise guess was off by 0.1, so the x^0\hat x_0 estimate is off by 0.1⋅0.711/0.703≈0.100.1 \cdot 0.711/0.703 \approx 0.10. At lower noise levels the same error in ε^\hat\varepsilon costs much less, because it is multiplied by a smaller 1−αˉ\sqrt{1-\bar\alpha}: 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.

COMMON MISCONCEPTIONS
  • “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 tt 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

0/5 answered
  1. Q1.With x_t = √ᾱ_t·x₀ + √(1−ᾱ_t)·ε, what happens as t approaches T?

  2. Q2.During DDPM training, what is the network asked to output?

  3. Q3.At very high noise, a well-trained denoiser's guess of x₀ looks like a blurry average. Why?

  4. Q4.What does DDIM change compared with DDPM sampling?

  5. Q5.How is the noise predictor related to the score ∇log p_t(x_t)?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.