Diffusion Models
After this lesson, you will be able to:
- Describe the forward process (adding noise step by step) and the one-step shortcut that makes training cheap
- Train a network to guess the noise with the simple loss L_simple
- Use the guidance scale to trade variety for prompt-following, and use DDIM to cut sampling from 1000 steps to about 20
- Pick a sampler: DDPM for theory, DDIM for speed, DPM-Solver++ or Euler for production
Before you start
Random speckle added to data, like TV static. Every value is a dice roll.
Adding noise to a clean picture a little at a time until only noise is left.
Removing noise a little at a time, which turns pure noise into a picture.
The network's estimate of the noise inside a noisy picture, written ε_θ.
A whole number that says how much noise has been added. t = 0 is a clean picture and t = T is pure noise.
The recipe that runs the network many times to turn pure noise into a picture.
A number that says how hard the model is pushed to follow your prompt.
A shape where most values sit near the middle. Gaussian noise has this shape.
#The Two-Direction Setup
#The Forward Process: Destroying Information
A worked number shows the size of the change. At step 500 of the linear schedule the picture is multiplied by 0.28 and the noise by 0.96. A pixel of brightness 0.8 and a noise draw of -0.5 become 0.28 x 0.8 + 0.96 x (-0.5) = -0.256. The pixel no longer looks like 0.8.
Drag the slider below to watch the same thing on a whole picture.
Do: Drag the timestep slider from 1000 down to 0.Notice: A digit appears out of noise while the signal bar fills.Why: Each step changes the picture only a little, so the network must run many times.
You can test that equality yourself. The tool below makes a small picture, noises it with t small steps one after another, and also with the single jump, then reports the largest difference over all 768 numbers.
Do: Set the step to 500 and press Jump straight here. Switch between the Linear and Cosine schedules.Notice: On the linear schedule the picture is multiplied by 0.28 and the noise by 0.96, which matches the worked number above, and only 8% of the mix is picture. The jump and the 500 small steps differ by about 1e-15, which is floating-point rounding. Cosine keeps about 49% at the same step.Why: The jump uses the 500 small doses added up with the weights sqrt(beta_s x abar_t / abar_s), so it is the same calculation grouped differently. That is why q(x_t | x_0) is a single Gaussian with mean sqrt(abar_t) x_0 and variance 1 - abar_t. Drawn stand-in, not a trained model: no network runs here.
The table lists the signal fraction ᾱ_t (how much of the picture is left) and the log signal-to-noise ratio log(ᾱ_t / (1 − ᾱ_t)) (how much stronger the picture is than the noise, on a log scale) at T = 1000 for the linear schedule (betas from 1e-4 to 0.02) and the cosine schedule (s = 0.008). By t = 700 the linear schedule has only 0.7 percent of the signal left, while the cosine schedule still has 20 percent.
| t | linear ᾱ_t | linear log-SNR | cosine ᾱ_t | cosine log-SNR |
|---|---|---|---|---|
| 100 | 0.8970 | 2.16 | 0.9721 | 3.55 |
| 200 | 0.6590 | 0.66 | 0.8987 | 2.18 |
| 300 | 0.3964 | -0.42 | 0.7869 | 1.31 |
| 400 | 0.1951 | -1.42 | 0.6475 | 0.61 |
| 500 | 0.0786 | -2.46 | 0.4938 | -0.02 |
| 600 | 0.0259 | -3.63 | 0.3408 | -0.66 |
| 700 | 0.0070 | -4.96 | 0.2031 | -1.37 |
| 800 | 0.0015 | -6.48 | 0.0940 | -2.27 |
| 900 | 0.0003 | -8.20 | 0.0241 | -3.70 |
Move the timestep, the linear beta range and the cosine offset, and watch how the linear schedule sits at abar below 0.01 for about a third of its steps while the cosine schedule spends about 6.5 percent there, with the strip showing how much of the signal is left at each t.
Do: Move the timestep, the linear beta range and the cosine offset.Notice: Linear leaves under 1% of the picture for about a third of its steps. Cosine does so for about 6.5%.Why: Steps spent on pure noise teach the network little, so a good schedule avoids them.
Do: Drag the step slider and watch all three schedules at once.Notice: Linear loses the picture before cosine does.Why: Every step should leave something for the network to learn from, and cosine spreads the loss more evenly.
Do: Drag the timestep slider and watch the picture dissolve, then rebuild.Notice: Early steps change little. Late steps wipe out the structure fast.Why: The rebuild here only replays the forward steps. The next picture steps through a noise guess.
#The Reverse Process: Learning to Denoise
In symbols, the reverse process is parameterized by a neural network θ:
t is injected via sinusoidal embedding + MLP into every block. For text-to-image, the conditioning text is injected via cross-attention.Do: Use the step buttons or Play, and switch between DDPM (20 steps) and DDIM (4 steps).Notice: The noise guess and the picture get cleaner together. DDIM reaches a similar picture in far fewer steps.Why: Each step removes only the guessed noise. Fewer, longer steps need a sampler built for them.
#The Training Objective: L_simple
Training is a guessing game with a known answer. Take a clean image, pick a random step t, and mix in noise that you drew yourself. Ask the network to guess that noise. Because you know the real noise, scoring is easy: the loss is the squared difference between the real noise and the guess.
Ho et al. (2020) showed that this one loss, called L_simple, is enough:
The simplicity is what made diffusion practical. No GAN training instability, no mode collapse, no balance between generator and discriminator. Just minimize MSE.
You train a tiny diffusion model on MNIST with T=1000 timesteps and the training loss converges nicely. You start from pure noise and run exactly ONE reverse step. What do you have?
#The Math: From Variational Bound to L_simple
The derivation is folded away below. You can skip it and still follow the rest of the lesson.
#Classifier-Free Guidance: The Sampling Superpower
diffusers library the argument is guidance_scale and it is exactly this s, so the Stable Diffusion default is guidance_scale=7.5. Push higher for stronger prompt adherence; drop to 3-5 for more varied results. If you read a paper that writes the formula as (1 + w) * eps_c - w * eps_u, its w is our s minus 1.Do: Drag the guidance scale s from 1 to 15 and press reseed.Notice: Around 3 to 8 the four samples follow the prompt and still differ. Near 15 they look alike and burnt.Why: A large s pushes every sample toward the most typical look of the prompt.
#DDIM: Fast Deterministic Sampling
Slide the step count from 2 up to 200 and watch the final histogram close in on the true three-bump density, then set eta to 1 and see fresh noise return.
Do: Slide the step count from 2 up to 200, then set eta to 1.Notice: The histogram closes in on the true three bumps as steps grow. Eta = 1 brings fresh noise back.Why: Fewer steps mean longer jumps, and a long jump trusts one noise guess over a long distance.
#Modern Samplers Cheat Sheet
| Sampler | Steps | Properties |
|---|---|---|
| DDPM | 1000 | Theoretically grounded, slow |
| DDIM | 50 | Deterministic, good baseline |
| Euler / Euler-A | 20-30 | Fast, slightly noisy results |
| DPM-Solver++ (2M) | 15-25 | Default in many production stacks |
| Heun | 25-40 | Higher quality, slower |
| LCM (4 steps) | 4 | Distilled, fastest, mild quality loss |
How the fast samplers relate
#Counting network evaluations
The step counts in the table are only half of the cost, because one step can need more than one pass through the network.
#The Karras EDM unifying framework
#1. Reparameterize: predict the clean image directly
D_θ(x; σ) directly, where σ ∈ ℝ₊ is the current noise level. There are no discrete timesteps — σ is a continuous knob from σ_min ≈ 0.002 to σ_max ≈ 80. This single change makes every previous diffusion variant a special case of EDM by a coordinate change.x = x_0 + σ · n (clean image plus noise of standard deviation σ, with n ~ N(0, I)), and the prediction target is x_0 itself.#2. Four preconditioning functions
F_θ with four σ-dependent scalars so the network always sees unit-variance inputs and always predicts a unit-variance target. The full denoiser is:(target - c_skip · x) / c_out should also have unit variance. Solve that and you get the formulas above.#3. The unified objective
The training loss is a weighted denoising-score-matching loss across all noise levels:
λ(σ) = (σ² + σ_data²) / (σ · σ_data)² is the Karras choice that makes the effective signal-to-noise gradient constant across σ — every noise level contributes the same amount of gradient signal, so the network spends training compute uniformly rather than blowing up on easy low-σ cases.#4. Noise schedule: log-normal σ sampling
log σ ~ N(P_mean, P_std²) with P_mean = -1.2, P_std = 1.2 for natural images. Plotting that distribution puts most of the training mass right around σ ≈ 0.3 — the "interesting" mid-noise regime where most of the perceptual structure is decided. Karras et al. report this as a clear gain, and EDM2 keeps it. Other models choose differently: SDXL trains on the discrete DDPM schedule, and SD3 and FLUX draw their time variable from a logit-normal distribution (see the flow matching lesson).#5. Heun's 2nd-order sampler: halving the discretization error
σ_i = (σ_max^(1/ρ) + (i / (N-1)) · (σ_min^(1/ρ) - σ_max^(1/ρ)))^ρ with ρ = 7. This polynomial spacing concentrates steps where the model is most sensitive (low σ near the end of sampling).#6. Where EDM-style parameterization shows up
#Hands-On: Train a Tiny Diffusion Model
alpha_bar at the last step), and the DDIM loop takes the final jump to the clean estimate.This exercise calls input(). Python here can't pause to ask you, so type the answers below before running — one value per line, in the order the program asks for them.
Tests: Check that alpha_bar at the last step is below 0.01, that the loss falls during training, and that at least 85 percent of both DDPM and DDIM samples land within 0.8 of a cluster centre.
The same loop on real images needs a deep-learning library and a GPU, so it does not run on this page. Copy it to Google Colab:
# Copy to Colab: needs torch and torchvision, so it cannot run on this page.
# Minimal diffusion training loop on MNIST (a few minutes on a Colab GPU).
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
# --- 1. Hyperparameters ---
T = 200
device = "cuda" if torch.cuda.is_available() else "cpu"
# Scale the betas to the step count, so the chain still ends at pure noise.
# (0.02 is the value for T = 1000; with fewer steps each step must add more noise.)
betas = torch.linspace(1e-4, 0.02 * 1000 / T, T).to(device)
alphas = 1.0 - betas
alpha_bar = torch.cumprod(alphas, dim=0)
print(f"alpha_bar at t = T-1: {alpha_bar[-1].item():.5f} (should be close to 0)")
# --- 2. Tiny U-Net (single down-up block) ---
class TimeEmbed(nn.Module):
def __init__(self, dim):
super().__init__()
self.lin1 = nn.Linear(1, dim)
self.act = nn.SiLU()
self.lin2 = nn.Linear(dim, dim)
def forward(self, t):
return self.lin2(self.act(self.lin1(t.unsqueeze(-1).float() / T)))
class TinyUNet(nn.Module):
def __init__(self, ch=32):
super().__init__()
self.t_embed = TimeEmbed(ch)
self.down = nn.Sequential(nn.Conv2d(1, ch, 3, padding=1), nn.SiLU(), nn.Conv2d(ch, ch, 3, padding=1, stride=2))
self.mid = nn.Sequential(nn.Conv2d(ch, ch, 3, padding=1), nn.SiLU())
self.up = nn.Sequential(nn.ConvTranspose2d(ch, ch, 3, padding=1, output_padding=1, stride=2), nn.SiLU(), nn.Conv2d(ch, 1, 3, padding=1))
def forward(self, x, t):
h = self.down(x)
h = h + self.t_embed(t).unsqueeze(-1).unsqueeze(-1)
h = self.mid(h)
return self.up(h)
# --- 3. Forward sampling: get (x_t, eps) given (x_0, t) ---
def q_sample(x_0, t, eps=None):
if eps is None:
eps = torch.randn_like(x_0)
sqrt_ab = torch.sqrt(alpha_bar[t]).view(-1, 1, 1, 1)
sqrt_1mab = torch.sqrt(1.0 - alpha_bar[t]).view(-1, 1, 1, 1)
return sqrt_ab * x_0 + sqrt_1mab * eps, eps
# --- 4. Training: several passes over MNIST (about 3,000 steps) ---
model = TinyUNet().to(device)
opt = torch.optim.AdamW(model.parameters(), lr=2e-4)
ds = datasets.MNIST("/tmp/mnist", train=True, download=True,
transform=transforms.Compose([transforms.Resize(16), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]))
loader = DataLoader(ds, batch_size=128, shuffle=True, num_workers=0)
MAX_STEPS = 3000
step = 0
print("Training tiny diffusion model on MNIST...")
while step < MAX_STEPS:
for x_0, _ in loader:
if step >= MAX_STEPS:
break
x_0 = x_0.to(device)
t = torch.randint(0, T, (x_0.size(0),), device=device)
x_t, eps = q_sample(x_0, t)
loss = torch.mean((eps - model(x_t, t)) ** 2)
opt.zero_grad(); loss.backward(); opt.step()
if step % 500 == 0:
print(f"step {step}: loss = {loss.item():.4f}")
step += 1
# --- 5. DDPM sampling (all T steps, starting from N(0, I)) ---
@torch.no_grad()
def ddpm_sample(model, n=8):
x = torch.randn(n, 1, 16, 16, device=device)
for t in reversed(range(T)):
t_batch = torch.full((n,), t, device=device, dtype=torch.long)
eps_pred = model(x, t_batch)
coef = (1 - alphas[t]) / torch.sqrt(1 - alpha_bar[t])
mean = (1.0 / torch.sqrt(alphas[t])) * (x - coef * eps_pred)
x = mean + torch.sqrt(betas[t]) * torch.randn_like(x) if t > 0 else mean
return x.clamp(-1, 1)
# --- 6. DDIM sampling with ~20 steps, including the final jump to x_0 ---
@torch.no_grad()
def ddim_sample(model, n=8, num_steps=20):
x = torch.randn(n, 1, 16, 16, device=device)
ts = torch.linspace(T - 1, 0, num_steps).round().long().tolist()
for i, t in enumerate(ts):
t_batch = torch.full((n,), t, device=device, dtype=torch.long)
eps_pred = model(x, t_batch)
ab_t = alpha_bar[t]
ab_prev = alpha_bar[ts[i + 1]] if i + 1 < len(ts) else torch.tensor(1.0, device=device)
x0_hat = (x - torch.sqrt(1 - ab_t) * eps_pred) / torch.sqrt(ab_t)
x = torch.sqrt(ab_prev) * x0_hat + torch.sqrt(1 - ab_prev) * eps_pred
return x.clamp(-1, 1) # after the last step x is the estimate of x_0
samples = ddpm_sample(model, n=4)
fast = ddim_sample(model, n=4)
print(samples.shape, fast.shape) # both: (4, 1, 16, 16), values in [-1, 1]#Key Takeaways
- Diffusion = forward noising + learned reverse denoising. The forward process is fixed Gaussian noise addition; the reverse process is a U-Net (or DiT) trained to predict the noise that was added at each step
- L_simple is the entire training objective. Pick random t, sample noise ε, construct x_t, predict ε from x_t — pure MSE loss, no GAN instability, no balance to maintain
- The reparameterization x_t = √(ᾱ_t)·x_0 + √(1-ᾱ_t)·ε is the practical shortcut. It lets you sample any timestep in one shot, making training dataset-efficient and embarrassingly parallel
- Classifier-free guidance is the most important sampling trick. Train one model that handles both conditional and unconditional, then linearly extrapolate at sampling. The CFG scale s (guided = unconditional + s × (conditional − unconditional), so s = 1 is plain conditional) is the knob every user adjusts
- DDIM and modern samplers cut steps from 1000 to 20-50 with little quality loss. DPM-Solver++, Euler-A, and Heun all solve the same probability-flow ODE more efficiently. LCM and Turbo distill further to 1-4 steps with mild quality cost
#Quick Check
Why does the simplified DDPM loss L_simple work despite the original formulation involving a complex variational bound?