◆ AI All-in-One

Level 3 In-Depth AI · Generative AI

Diffusion Models

A diffusion model learns to turn noise into data by reversing a simple process that slowly drowns data in noise. Training teaches a network to predict the noise that was added. Generation starts from pure static and removes a little noise at a time until an image (or sound, or video) appears.

Level
●●●●● Intermediate
Reading
16 min
To learn it well
1.5 hours to read, an afternoon to practise
↗ Plan a path here

Read first

What Generative Models DoConvolutional Neural Networks

This leads to

Diffusion TransformersLatent Diffusion and Stable Diffusion
The full path from zero — 17 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Vectors
  4. Derivatives and Slopes
  5. How Machines Learn
  6. Probability Distributions
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. Convolutional Neural Networks
  17. What Generative Models Do
  18. Diffusion Models

Read them roughly in this order. See it on the concept map →

Why it matters

Since 2022 almost every impressive image generator has been a diffusion model or a close relative: DALL·E 2 and 3, Imagen, Midjourney, Stable Diffusion, and most open models since. The same idea now drives video generators (Video Generation), music and sound effects (Music and Voice Generation), 3-D shapes, robot motion planning, and molecule and protein design.

Diffusion models won because they combine three things earlier methods couldn't. They make high-quality samples like GANs. They cover the whole data distribution like likelihood-based models, with no mode collapse. And they train stably with one simple regression loss, which lets them scale to billions of images. Their cost is speed: generating takes many network evaluations instead of one.

This chapter builds the idea from scratch, with a working diffusion model on 2-D points that you can train on a laptop. The next chapters build on it: Normalizing Flows and Flow Matching (a simpler cousin), Latent Diffusion and Stable Diffusion (Stable Diffusion), Diffusion Transformers and Text-to-Image in Practice.

The intuition

Drop some ink into a glass of water. At first you see a sharp swirl. A minute later it is a blurry cloud. An hour later the water is evenly tinted, and every trace of the original shape is gone. This spreading-out is called diffusion in physics, and it gives the method its name.

Destroying structure is easy. Now imagine a film of the ink spreading, and run it backwards: an even tint gathers itself into a cloud, then into a sharp swirl. If you could learn to play that film backwards, you could start from any glass of evenly tinted water and produce a swirl.

A diffusion model does exactly this, with noise instead of ink:

  1. Forward process (fixed, no learning). Take a real image and add a small amount of random static, again and again, for say 1,000 steps. By the end it is pure static, and the original image can't be recovered.
  2. Reverse process (learned). Train a neural network to undo one small step: given a slightly noisy image, and how noisy it is, guess what the noise was so it can be subtracted.
  3. Generate. Start from fresh static and apply the network over and over. Each step removes a little noise and adds a little structure, until a clean image appears that never existed before.

Why is removing a little noise learnable when generating an image from scratch is so hard? Because each step is a small, local edit. When an image is only slightly noisy, the network can see what it should look like and only has to clean it up. When it is very noisy, the network only has to get the rough layout right ("sky at the top, something dark in the middle"), because later steps will fill in the details. One huge, impossible jump becomes a thousand small, easy ones.

Top: forward process on real data. Bottom: reverse process run by the trained network. t = 0 (data) signal 1.00noise 0.00 t = 50 signal 0.99noise 0.17 t = 100 signal 0.95noise 0.32 t = 250 signal 0.72noise 0.69 t = 500 signal 0.28noise 0.96 t = 1000 signal 0.01noise 1.00 forward q: add a little Gaussian noise at every step (fixed, nothing learned) reverse p_θ: start from pure noise, the network removes a little noise per step new samples pure noise x_t = signal · x₀ + noise · ε, with signal = √ᾱ_t and noise = √(1 − ᾱ_t); linear schedule, β from 0.0001 to 0.02, T = 1000
Fig. 1 Diffusion on 2-D points shaped like two moons. Top: the forward process adds noise to real data. The numbers give how much of the original signal and how much noise make up each point. By t = 1000 it is pure noise. Bottom: the reverse process, run by the network trained in the code below, starts from pure noise on the right and removes a little noise at each step. The moons reappear on the left as brand-new samples.

Key idea A diffusion model learns to remove noise. Training: take real data, add a random amount of noise, and teach a network to predict the noise that was added. Generation: start from pure noise and subtract the predicted noise a little at a time, for many steps.

How it works

We'll use the notation of the DDPM paper (Ho, Jain and Abbeel, 2020), which most code follows. A data example, such as an image flattened into numbers, is x0\mathbf{x}_0. The subscript counts noise steps: x0\mathbf{x}_0 is clean, x1\mathbf{x}_1 slightly noisy, and so on up to xT\mathbf{x}_T, which is pure noise. TT is the number of steps, typically 1,000.

1. The forward process and the noise schedule

At each step we shrink the current image slightly and add a little fresh Gaussian noise:

xt=1−βt  xt−1+βt  ϵt,ϵt∼N(0,I)\mathbf{x}_t = \sqrt{1 - \beta_t}\; \mathbf{x}_{t-1} + \sqrt{\beta_t}\; \boldsymbol{\epsilon}_t, \qquad \boldsymbol{\epsilon}_t \sim \mathcal{N}(\mathbf{0}, \mathbf{I})
  • βt\beta_t ("beta") is a small number, such as 0.0001 at the start and 0.02 at the end. It controls how much noise step tt adds. The list β1,…,βT\beta_1, \dots, \beta_T is the noise schedule, chosen by hand, not learned.
  • ϵt\boldsymbol{\epsilon}_t ("epsilon") is fresh random noise: one independent draw from a standard Gaussian for every number in the image.
  • The factor 1−βt\sqrt{1-\beta_t} slightly shrinks the image so that the total size of the numbers stays about the same. Noise is added, signal is shrunk, and the overall spread stays near 1.

Stepping 500 times to reach x500\mathbf{x}_{500} would be slow. Luckily, adding Gaussian noise many times in a row is the same as adding one bigger dose of Gaussian noise. Multiply all the shrink factors together:

αˉt=∏s=1t(1−βs)\bar{\alpha}_t = \prod_{s=1}^{t} (1 - \beta_s)

αˉt\bar{\alpha}_t ("alpha-bar t") is the product of (1−βs)(1-\beta_s) over all steps up to tt. It starts near 1 and falls towards 0. Then you can jump straight from clean data to any step:

xt=αˉt  x0+1−αˉt  ϵ,ϵ∼N(0,I)\mathbf{x}_t = \sqrt{\bar{\alpha}_t}\; \mathbf{x}_0 + \sqrt{1 - \bar{\alpha}_t}\; \boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})

This is the most important equation in the chapter. A noisy example is just a weighted mix of the clean example and pure noise. αˉt\sqrt{\bar{\alpha}_t} is the signal weight and 1−αˉt\sqrt{1-\bar{\alpha}_t} is the noise weight. Their squares always add up to 1.

For the standard linear schedule (β\beta rising evenly from 0.0001 to 0.02 over 1,000 steps), the code below computes:

Step tt Signal αˉt\sqrt{\bar\alpha_t} Noise 1−αˉt\sqrt{1-\bar\alpha_t} What you'd see
1 1.000 0.010 the image, imperceptibly grainy
100 0.947 0.321 clearly noisy, content obvious
250 0.724 0.690 half and half
500 0.280 0.960 mostly static, faint shapes
1000 0.006 1.000 pure static

Worked example. Take one number of a clean example, x0=1.5x_0 = 1.5, and one noise draw, ϵ=−0.4\epsilon = -0.4. At step 500: x500=0.280×1.5+0.960×(−0.4)=0.420−0.384=0.036x_{500} = 0.280 \times 1.5 + 0.960 \times (-0.4) = 0.420 - 0.384 = 0.036. The original 1.5 is almost hidden. Only 0.42 of the total comes from the data.

0 0.5 1 0 250 500 750 1000 step t coefficient 0.95 0.72 0.28 signal √ᾱ_tshare of the clean data left noise √(1 − ᾱ_t)share of pure noise linear schedulecosine schedule Linear (DDPM): the signal ismostly gone by t ≈ 600.Cosine: noise is added moreevenly across the steps.
Fig. 2 The noise schedule: how much signal (blue) and noise (grey) make up the noisy example at each step. Solid lines show the linear schedule used in DDPM and in the code below, with the values from the table marked. Dashed lines show the cosine schedule (Nichol and Dhariwal, 2021), which destroys information more evenly and wastes fewer steps on near-pure noise.

2. The training objective: predict the noise

We want a network that can undo noise. The DDPM paper found that the simplest way to train it works best: show the network a noisy example and ask it what noise was added. The network is called the denoiser and written ϵθ(xt,t)\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t). It takes the noisy example xt\mathbf{x}_t and the step number tt, and outputs a guess of ϵ\boldsymbol{\epsilon}, with the same shape as the input. θ\theta is its weights.

One training step:

  1. Pick a real example x0\mathbf{x}_0 from the data.
  2. Pick a random step tt between 1 and TT.
  3. Draw noise ϵ∼N(0,I)\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}) and make xt=αˉt x0+1−αˉt ϵ\mathbf{x}_t = \sqrt{\bar{\alpha}_t}\,\mathbf{x}_0 + \sqrt{1 - \bar{\alpha}_t}\,\boldsymbol{\epsilon}.
  4. Ask the network for its guess and compute the squared error:
L(θ)=∥ϵ−ϵθ(xt,t)∥2L(\theta) = \big\lVert \boldsymbol{\epsilon} - \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t) \big\rVert^2
  1. Take a Gradient Descent step on θ\theta.

∥⋅∥2\lVert \cdot \rVert^2 is the squared length of a vector: the sum of squared differences, number by number. That's it: a plain mean squared error regression. There is no adversary and no balancing act. You can't game this loss, because the noise is random and fresh every time. The only way to predict it is to understand what real data looks like, so you can tell which part of xt\mathbf{x}_t is data and which is noise.

Predicting the noise is equivalent to predicting the clean data. Once you have ϵ^\hat{\boldsymbol{\epsilon}}, the forward equation rearranges to an estimate of the clean example:

x^0=xt−1−αˉt  ϵ^αˉt\hat{\mathbf{x}}_0 = \frac{\mathbf{x}_t - \sqrt{1-\bar\alpha_t}\;\hat{\boldsymbol{\epsilon}}}{\sqrt{\bar\alpha_t}}

Some models predict x0\mathbf{x}_0 directly, or a mix of the two called v\mathbf{v} ("v-prediction"). Others predict the score function, the direction in which the data becomes more probable, which is proportional to −ϵ-\boldsymbol{\epsilon}. These are different parametrisations of the same idea. The DDPM paper also showed that this loss is a simplified, reweighted version of a VAE-style ELBO (Variational Autoencoders), which is why diffusion counts as a likelihood-based model.

3. Sampling: remove the noise step by step

To generate, start with pure noise xT∼N(0,I)\mathbf{x}_T \sim \mathcal{N}(\mathbf{0}, \mathbf{I}) and go backwards, t=T,T−1,…,1t = T, T-1, \dots, 1. At each step:

xt−1=1αt(xt−βt1−αˉt ϵθ(xt,t))+σtz\mathbf{x}_{t-1} = \frac{1}{\sqrt{\alpha_t}} \left( \mathbf{x}_t - \frac{\beta_t}{\sqrt{1 - \bar{\alpha}_t}}\, \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t) \right) + \sigma_t \mathbf{z}

Symbol by symbol:

  • αt=1−βt\alpha_t = 1 - \beta_t is the one-step shrink factor, without the bar.
  • ϵθ(xt,t)\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t) is the network's guess of the noise in the current example.
  • βt1−αˉt\frac{\beta_t}{\sqrt{1-\bar\alpha_t}} scales that guess down to the share of noise belonging to this one step. We only remove one step's worth, not all of it.
  • 1αt\frac{1}{\sqrt{\alpha_t}} undoes the slight shrinking of the forward step.
  • σtz\sigma_t \mathbf{z} adds a little fresh noise (z∼N(0,I)\mathbf{z} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}), with σt2=βt\sigma_t^2 = \beta_t in the simplest choice). That may seem odd, but it keeps the process random so that different runs give different samples, and it corrects small errors. It is skipped on the final step.

After TT steps, x0\mathbf{x}_0 is a new sample. The bottom row of the chain picture shows this happening with real numbers.

The denoiser network: a U-Net

For 2-D points a small MLP is enough. For images the classic denoiser is a U-Net (Ronneberger and colleagues, 2015, originally for medical Image Segmentation). It is a convolutional network shaped like a U. The left half shrinks the image step by step to capture the overall layout. The right half grows it back to full size to output a noise estimate per pixel. Skip connections carry fine detail across the U from each left-side level to the matching right-side level. Two additions make it a diffusion denoiser:

  • Time conditioning. The step tt is turned into a vector (a sinusoidal embedding, like the Positional Encodings of Transformers) and added inside every block, so the same network knows whether to make big layout decisions (high noise) or fine touch-ups (low noise).
  • Attention layers at the coarser resolutions let distant parts of the image coordinate. In text-to-image models, cross-attention layers also let the image look at the words of the prompt (Latent Diffusion and Stable Diffusion).

DDPM's CIFAR-10 U-Net had about 36 million parameters. Stable Diffusion 1.5's U-Net has about 860 million. Newer models replace the U-Net with a Transformer (Diffusion Transformers).

Faster sampling: DDIM and friends

A thousand network evaluations per image is slow. DDIM (Song, Meng and Ermon, 2020) showed that the same trained network can be sampled with a deterministic update that jumps across many steps at once. It predicts x^0\hat{\mathbf{x}}_0, then re-noises it to the next, much lower noise level, with no fresh randomness. On our 2-D model:

Sampler Network evaluations Samples within 0.1 of real data
DDPM 1,000 95%
DDIM 50 91%
DDIM 10 77%
(pure noise, for comparison) 0 31%

In practice image models use 20–50 steps with improved solvers (DPM-Solver, Euler, Heun). Distilled models such as SDXL Turbo and the "LCM" models get down to 1–4 steps. In the Hugging Face diffusers library these samplers are called schedulers, and you can swap them without retraining.

In code

A complete DDPM on 2-D points in PyTorch: forward noising, an MLP denoiser, training by noise prediction, and 1,000-step sampling. It runs in about 15 seconds on a CPU.

import torch, torch.nn as nn
from sklearn.datasets import make_moons

torch.manual_seed(0)
X = torch.tensor(make_moons(10_000, noise=0.03, random_state=0)[0], dtype=torch.float32)
X = (X - X.mean(0)) / X.std(0)                      # standardise: mean 0, std 1

# Forward process: noise schedule
T = 1000
beta = torch.linspace(1e-4, 0.02, T)                # noise added at each step
alpha_bar = torch.cumprod(1 - beta, dim=0)          # how much signal survives to step t
for t in [0, 99, 499, 999]:
    print(f"t={t+1:4d}  signal sqrt(a_bar)={alpha_bar[t].sqrt():.3f}  noise sqrt(1-a_bar)={(1-alpha_bar[t]).sqrt():.3f}")

# Denoiser: an MLP that sees (noisy point, t) and predicts the noise
net = nn.Sequential(nn.Linear(3, 128), nn.SiLU(), nn.Linear(128, 128), nn.SiLU(),
                    nn.Linear(128, 128), nn.SiLU(), nn.Linear(128, 2))
opt = torch.optim.Adam(net.parameters(), lr=1e-3)
for step in range(5001):
    x0 = X[torch.randint(0, len(X), (512,))]
    t = torch.randint(0, T, (512,))
    eps = torch.randn_like(x0)
    a = alpha_bar[t].unsqueeze(1)
    xt = a.sqrt() * x0 + (1 - a).sqrt() * eps                 # jump straight to step t
    loss = ((net(torch.cat([xt, t.unsqueeze(1) / T], 1)) - eps) ** 2).mean()
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 2500 == 0:
        print(f"step {step}  loss {loss.item():.3f}")

# Sampling: start from pure noise and denoise for T steps
with torch.no_grad():
    x = torch.randn(2000, 2)
    for t in reversed(range(T)):
        eps_hat = net(torch.cat([x, torch.full((2000, 1), t / T)], 1))
        x = (x - beta[t] / (1 - alpha_bar[t]).sqrt() * eps_hat) / (1 - beta[t]).sqrt()
        if t > 0:
            x += beta[t].sqrt() * torch.randn_like(x)
    for name, pts in [("DDPM samples", x), ("pure noise  ", torch.randn(2000, 2))]:
        dist = torch.cdist(pts, X).min(1).values     # distance to the nearest real point
        print(f"{name}: median distance to data {dist.median():.3f}, within 0.1: {(dist < 0.1).float().mean():.0%}")

# t=   1  signal sqrt(a_bar)=1.000  noise sqrt(1-a_bar)=0.010
# t= 100  signal sqrt(a_bar)=0.947  noise sqrt(1-a_bar)=0.321
# t= 500  signal sqrt(a_bar)=0.280  noise sqrt(1-a_bar)=0.960
# t=1000  signal sqrt(a_bar)=0.006  noise sqrt(1-a_bar)=1.000
# step 0  loss 0.968
# step 2500  loss 0.288
# step 5000  loss 0.207
# DDPM samples: median distance to data 0.008, within 0.1: 95%
# pure noise  : median distance to data 0.212, within 0.1: 31%

(Python indexes from 0, so the code's t = 0 is the chapter's step 1.) Notice that the loss does not go to zero. At high noise levels nobody can tell exactly which noise was added, so some error is unavoidable. The loss is useful for comparing runs, but judge the model by its samples.

A DDIM sampler for the same trained network, to append to the script above:

def ddim(n_steps, n=2000):
    ts = torch.linspace(T - 1, 0, n_steps).long()               # e.g. 999, 888, ..., 0
    x = torch.randn(n, 2)
    with torch.no_grad():
        for i, t in enumerate(ts):
            a = alpha_bar[t]
            eps_hat = net(torch.cat([x, torch.full((n, 1), t.item() / T)], 1))
            x0_hat = (x - (1 - a).sqrt() * eps_hat) / a.sqrt()    # predicted clean data
            a_next = alpha_bar[ts[i + 1]] if i + 1 < len(ts) else torch.tensor(1.0)
            x = a_next.sqrt() * x0_hat + (1 - a_next).sqrt() * eps_hat   # re-noise to next level
    return x

for k in [10, 50]:
    d = torch.cdist(ddim(k), X).min(1).values
    print(f"DDIM {k} steps: within 0.1: {(d < 0.1).float().mean():.0%}")
# DDIM 10 steps: within 0.1: 77%
# DDIM 50 steps: within 0.1: 91%

To use a real pretrained image model, the diffusers library wraps all of this, U-Net and scheduler, in a few lines. See Text-to-Image in Practice.

Common pitfalls

  • Forgetting to tell the network the time step. Without tt, the network doesn't know how much noise to expect and does badly at every level.
  • Unnormalised data. The schedule assumes data with a spread of about 1. Images are usually scaled to [−1,1][-1, 1]. If your data has a spread of 100, the "pure noise" at step TT still contains obvious signal, and sampling from N(0,I)\mathcal{N}(\mathbf{0}, \mathbf{I}) starts in the wrong place.
  • Mismatched train and sample schedules. The sampler must use exactly the βt\beta_t and αˉt\bar\alpha_t used in training, and the same indexing. Off-by-one errors in tt give subtly bad samples.
  • Too few sampling steps with a plain DDPM sampler. The DDPM update assumes small steps. Skipping steps needs a sampler designed for it (DDIM, DPM-Solver).
  • The final step leaks noise. Don't add σtz\sigma_t \mathbf{z} on the last step.

Watch out The training loss of a diffusion model never approaches zero and is a weak guide to quality. A model whose loss is still falling can already make good samples, and two models with the same loss can sample very differently. Generate samples regularly during training and look at them, or compute a metric such as FID.

Where it leads

A bit of history

Jascha Sohl-Dickstein and colleagues introduced diffusion models in 2015, inspired by non-equilibrium thermodynamics. The results were modest and the idea was largely overlooked. In 2019 Yang Song and Stefano Ermon independently generated images by following the score function through decreasing noise levels ("score-based models"). In 2020 Jonathan Ho, Ajay Jain and Pieter Abbeel published Denoising Diffusion Probabilistic Models (DDPM). It introduced the simple noise-prediction loss and a U-Net denoiser, and reached a state-of-the-art FID of 3.17 on CIFAR-10. Later in 2020 came DDIM, for faster sampling, and Song and colleagues' SDE paper, which showed that score models and DDPM are the same family.

In 2021, Nichol and Dhariwal's improvements (cosine schedule, learned variances) and Dhariwal and Nichol's Diffusion Models Beat GANs made diffusion the leading approach. Classifier-free guidance (Ho and Salimans) made text conditioning work well. In 2022 DALL·E 2, Imagen and Stable Diffusion brought diffusion to the public. Since 2023 the field has moved towards Transformer denoisers and flow matching.

Try it

  1. Change the schedule to beta = torch.linspace(1e-4, 0.002, T) (ten times less noise) and print αˉT\sqrt{\bar\alpha_T}. Is the final step really pure noise? Train and sample. What goes wrong?
  2. Remove the time input: feed the network only xt (change nn.Linear(3, 128) to nn.Linear(2, 128)). How does the "within 0.1" score change?
  3. Save x every 100 sampling steps and plot the snapshots. At which step do the two moons first become recognisable?

Hint for 1: with too little noise, xT\mathbf{x}_T still contains the moons, but sampling starts from N(0,I)\mathcal{N}(\mathbf{0}, \mathbf{I}), which doesn't match what the network saw in training.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. With the linear schedule, the signal weight at step 500 is 0.280 and the noise weight is 0.960. For a clean value x₀ = 1.5 and noise ε = −0.4, what is x₅₀₀?

  2. What is the diffusion denoiser trained to predict in DDPM?

  3. You remove the time step input from your denoiser. What happens?

  4. You need images faster from a trained DDPM model that normally uses 1,000 steps. What is the right approach?

  5. Your data has a spread of about 100 rather than 1, and samples come out wrong. Why?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Hugging Face Diffusion Models Course

Hugging Face · Intermediate · Free

Theory and hands-on notebooks for training and using diffusion models with the diffusers library.

Tutorial

The Annotated Diffusion Model

Niels Rogge & Kashif Rasul (Hugging Face) · 2022 · Intermediate · Free

A DDPM implemented line by line in PyTorch, with the equations next to the code.

Article

What are Diffusion Models?

Lilian Weng · 2021 · Advanced · Free

The standard written reference on diffusion maths: forward and reverse processes, the noise-prediction loss, DDIM, guidance and latent diffusion. Updated over time.

Book

Understanding Deep Learning

Simon J. D. Prince · 2023 · Intermediate · Free

A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.

Paper

Denoising Diffusion Implicit Models

Song, Meng & Ermon · 2020 · Advanced · Free

DDIM: a deterministic sampler that reuses a DDPM-trained model and needs 10 to 50 times fewer steps.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/diffusion-models.md