A diffusion model learns to turn noise into data. This capstone puts a network, a loss, an optimizer and a sampling loop from the earlier lessons into one working generative model, small enough to run on a CPU in seconds. This lesson pairs with Lecture 23 of CMU's 11-785 (Fall 2026), linked under Watch & read. The course schedule lists that lecture as normalizing flows and diffusion; the previous lesson builds a flow, and this one builds the diffusion half. You build the noising process, the training loss and the sampler in PyTorch, and you test the sampler against a case where the best possible network is known exactly.
Start with the forward process. Choose a number of steps T and a small noise size βₜ for each step. Write αₜ = 1 - βₜ. One step takes the current value x and returns √αₜ · x + √βₜ · ε, where ε is fresh standard normal noise. You never run that loop in training. Independent Gaussians add up to a Gaussian, so the whole chain collapses into one formula. With ᾱₜ = α₀ · α₁ · … · αₜ, the running product:
xₜ = √ᾱₜ · x₀ + √(1 - ᾱₜ) · ε
Here x₀ is always the clean example. The steps are numbered from 0, like the arrays, and xₜ is the result of steps 0 to t, so the noisy value at t = 0 has already taken one small step and is not x₀. The first term is the surviving signal and the second is the accumulated noise. The two squared coefficients sum to 1, so unit-variance data stay at unit variance. The schedule must leave almost no signal at the end, which means ᾱ at the last step has to be close to 0. Check it by computing it:
import numpy as np
betas = np.linspace(1e-4, 0.1, 200)
alpha_bars = np.cumprod(1.0 - betas)
for t in (0, 49, 99, 199):
print(t, alpha_bars[t].round(4), np.sqrt(alpha_bars[t]).round(3), np.sqrt(1 - alpha_bars[t]).round(3))
print(f"{alpha_bars[-1]:.2e}", np.sqrt(betas[0]).round(3))The one-shot formula is exact. This run applies 100 small steps one after another to a constant signal 3, then jumps straight to step 99 with the formula. The two samples and the formula's own prediction agree to about 0.01, which is the sampling error to expect from 50,000 draws:
import numpy as np
rng = np.random.default_rng(0)
betas = np.linspace(1e-4, 0.1, 200)
alpha_bars = np.cumprod(1.0 - betas)
x0 = np.full(50000, 3.0)
x = x0.copy()
for beta in betas[:100]: # 100 small steps, one after another
x = np.sqrt(1 - beta) * x + np.sqrt(beta) * rng.normal(size=x.shape)
jump = np.sqrt(alpha_bars[99]) * x0 + np.sqrt(1 - alpha_bars[99]) * rng.normal(size=x0.shape)
print(x.mean().round(2), x.std().round(2)) # looped
print(jump.mean().round(2), jump.std().round(2)) # one jump
print(round(np.sqrt(alpha_bars[99]) * 3, 2), round(np.sqrt(1 - alpha_bars[99]), 2)) # formulaTraining is then short. Pick a random step t and random noise ε for each example, build xₜ with the formula, and train a network ε̂(xₜ, t) to output the ε you used, with squared error. The network receives t as an input, because the right answer depends on how noisy the input is. That is the whole loss. Knowing ε is as good as knowing x₀: from ε̂ you get x₀ ≈ (xₜ - √(1 - ᾱₜ) · ε̂) / √ᾱₜ. The DDPM paper (linked below) shows this loss is a simplified, reweighted form of the variational bound, which ties it to the VAE lesson.
Sampling runs the chain backward. Start from pure noise x_T and, for t = T - 1 down to 0, take one step:
mean = (xₜ - βₜ / √(1 - ᾱₜ) · ε̂) / √αₜ
xₜ₋₁ = mean + √βₜ · z, with z fresh noise, except at the last step, where the result is the mean itself. The formula is the mean of the reverse Gaussian, written with the noise estimate; the paper derives it, and here it is used as given. The fresh noise keeps the samples spread out. The last step produces the finished sample, so noise added there would only dirty it.
Take four steps with β = 0.1, 0.2, 0.3, 0.4, so ᾱ = 0.9, 0.72, 0.504, 0.3024. For x₀ = 2 and ε = 1 at the last step, x = √0.3024 · 2 + √0.6976 · 1 = 1.935. If a network named ε exactly, (1.935 - √0.6976 · 1) / √0.3024 would return 2 again. Check it:
import numpy as np
ab = np.cumprod(1 - np.linspace(0.1, 0.4, 4))
x_t = np.sqrt(ab[3]) * 2.0 + np.sqrt(1 - ab[3]) * 1.0
print(x_t.round(3), ((x_t - np.sqrt(1 - ab[3]) * 1.0) / np.sqrt(ab[3])).round(3))You can test the sampler without training anything. If the data come from N(m, 1), then xₜ is exactly N(√ᾱₜ · m, 1), and the best possible noise predictor has a closed form: ε*(xₜ, t) = √(1 - ᾱₜ) · (xₜ - √ᾱₜ · m). For unit-variance data the true variance of each reverse step is exactly βₜ, so a sampler driven by ε* must return samples with mean m and spread 1. A failure here is a sampler bug, never a training problem:
import numpy as np
m = 2.0
betas = np.linspace(1e-4, 0.1, 200)
alphas = 1.0 - betas
ab = np.cumprod(alphas)
def eps_star(x, t):
"""The best noise predictor when the data are N(m, 1)."""
return np.sqrt(1 - ab[t]) * (x - np.sqrt(ab[t]) * m)
rng = np.random.default_rng(0)
x = rng.normal(size=20000)
for t in range(199, -1, -1):
mean = (x - betas[t] / np.sqrt(1 - ab[t]) * eps_star(x, t)) / np.sqrt(alphas[t])
noise = rng.normal(size=x.shape)
x = mean + np.sqrt(betas[t]) * noise if t > 0 else mean
print(x.mean().round(2), x.std().round(2))It prints 1.99 and 1.0: mean 2 and spread 1, to within the sampling error of 20,000 draws.
The mistakes people make are small. Adding noise at t = 0 as well is easy to miss: every sample then carries extra noise of standard deviation √β₀, which is 0.01 here. That is far too small to move the mean or spread of a batch, so only a direct test of the last step finds it. On pictures it would be a faint grain. Dropping a square root changes the statistics: the noise scale is √βₜ, not βₜ, and the correction uses √(1 - ᾱₜ). The index trips people too: with arrays starting at 0, step t uses entry t of the schedule.
Normalizing flows, the subject of the previous lesson, take the other route. A flow is an invertible network, so it gets an exact likelihood from the change-of-variables formula, but every layer must be invertible with a cheap determinant. Diffusion gives up the exact likelihood and gets a plain regression target that any network shape can fit.
The tests compare the schedule and the noising with direct formulas, the reverse step with its formula, the whole sampler with the closed-form denoiser, and check that the training loss falls. They do not show that a trained network makes good samples; a falling loss only shows it learned something. The model is a toy on 1-D or 2-D data with a fixed linear schedule and the simplest sampler. Image models add a U-Net or transformer, better schedules and faster samplers.