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
- Builds on
- 17 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 17 concepts before this one
- What Is AI?
- Probability Basics
- Vectors
- Derivatives and Slopes
- How Machines Learn
- Probability Distributions
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Convolutional Neural Networks
- What Generative Models Do
- 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:
- 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.
- 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.
- 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.
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 . The subscript counts noise steps: is clean, slightly noisy, and so on up to , which is pure noise. 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:
- ("beta") is a small number, such as 0.0001 at the start and 0.02 at the end. It controls how much noise step adds. The list is the noise schedule, chosen by hand, not learned.
- ("epsilon") is fresh random noise: one independent draw from a standard Gaussian for every number in the image.
- The factor 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 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:
("alpha-bar t") is the product of over all steps up to . It starts near 1 and falls towards 0. Then you can jump straight from clean data to any step:
This is the most important equation in the chapter. A noisy example is just a weighted mix of the clean example and pure noise. is the signal weight and is the noise weight. Their squares always add up to 1.
For the standard linear schedule ( rising evenly from 0.0001 to 0.02 over 1,000 steps), the code below computes:
| Step | Signal | Noise | 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, , and one noise draw, . At step 500: . The original 1.5 is almost hidden. Only 0.42 of the total comes from the data.
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 . It takes the noisy example and the step number , and outputs a guess of , with the same shape as the input. is its weights.
One training step:
- Pick a real example from the data.
- Pick a random step between 1 and .
- Draw noise and make .
- Ask the network for its guess and compute the squared error:
- Take a Gradient Descent step on .
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 is data and which is noise.
Predicting the noise is equivalent to predicting the clean data. Once you have , the forward equation rearranges to an estimate of the clean example:
Some models predict directly, or a mix of the two called ("v-prediction"). Others predict the score function, the direction in which the data becomes more probable, which is proportional to . 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 and go backwards, . At each step:
Symbol by symbol:
- is the one-step shrink factor, without the bar.
- is the network's guess of the noise in the current example.
- 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.
- undoes the slight shrinking of the forward step.
- adds a little fresh noise (, with 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 steps, 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 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 , 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 , 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 . If your data has a spread of 100, the "pure noise" at step still contains obvious signal, and sampling from starts in the wrong place.
- Mismatched train and sample schedules. The sampler must use exactly the and used in training, and the same indexing. Off-by-one errors in 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 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
- Guidance. Steering samples towards a class or a text prompt, using classifier-free guidance. See Latent Diffusion and Stable Diffusion and Text-to-Image in Practice.
- Latent diffusion. Run the whole process on a compressed Variational Autoencoders latent instead of pixels, 48 times cheaper for Stable Diffusion. See Latent Diffusion and Stable Diffusion.
- Flow matching. Replace the curved noising path with a straight line and predict a velocity. It is simpler and often faster to sample. See Normalizing Flows and Flow Matching.
- Transformers as denoisers. See Diffusion Transformers, and for video, Video Generation.
- Continuous time. Song and colleagues (2020) described diffusion as a stochastic differential equation, unifying it with score matching and linking it to flows.
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
- Change the schedule to
beta = torch.linspace(1e-4, 0.002, T)(ten times less noise) and print . Is the final step really pure noise? Train and sample. What goes wrong?- Remove the time input: feed the network only
xt(changenn.Linear(3, 128)tonn.Linear(2, 128)). How does the "within 0.1" score change?- Save
xevery 100 sampling steps and plot the snapshots. At which step do the two moons first become recognisable?Hint for 1: with too little noise, still contains the moons, but sampling starts from , which doesn't match what the network saw in training.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Hugging Face Diffusion Models Course
Theory and hands-on notebooks for training and using diffusion models with the diffusers library.
The Annotated Diffusion Model
A DDPM implemented line by line in PyTorch, with the equations next to the code.
What are Diffusion Models?
The standard written reference on diffusion maths: forward and reverse processes, the noise-prediction loss, DDIM, guidance and latent diffusion. Updated over time.
Understanding Deep Learning
A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.
Denoising Diffusion Probabilistic Models
Showed diffusion models could generate images rivalling GANs.
Denoising Diffusion Implicit Models
DDIM: a deterministic sampler that reuses a DDPM-trained model and needs 10 to 50 times fewer steps.
Understanding Diffusion Models: A Unified Perspective
A careful tutorial deriving diffusion from VAEs, and showing how the noise-, data- and score-prediction views are equivalent.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/diffusion-models.md