diffusion, from noise up
here’s the whole idea in one sentence: destroying data is easy, so learn to undo the destruction one small step at a time.
that’s it. no adversary, no clever latent bottleneck. you take a picture, add a little gaussian noise, add a little more, keep going until it’s pure static. then you train a network to walk backwards. once it can, you hand it fresh static and it walks you to a picture that never existed.
i spend most of my time making these models fast enough to serve, so this post goes the whole way: the math, a training loop that fits on a screen, and where the compute actually goes.
the forward process: ruining things on purpose
pick a schedule of small numbers (ddpm uses , with rising linearly from to ). each step shrinks the data a bit and adds noise:
the isn’t decoration. if has unit variance, then has variance . the signal fades while the total energy stays put, so we land on a standard gaussian instead of something that blows up.
here’s what that does to 140 points sitting on a ring of radius 2, using the exact ddpm schedule:
the shortcut: jump to any in one shot
you never actually run that chain step by step. write and . since each step is “scale, then add independent gaussian noise”, the noises stack into a single gaussian:
this one line is why diffusion training is cheap. to make a training example you sample a random , sample , and mix. no simulation.
is the dial. the ratio tells you how much signal survives:
| snr | what it looks like | ||
|---|---|---|---|
| 50 | 0.971 | 33.5 | basically the data |
| 150 | 0.788 | 3.72 | blurry, but obvious |
| 300 | 0.396 | 0.66 | more noise than signal |
| 500 | 0.079 | 0.085 | a ghost |
| 1000 | 0.00004 | ≈ 0 | static |
notice how fast the linear schedule burns through the signal: half the steps are spent in the “a ghost or less” regime. that’s the observation behind the cosine schedule,1 which sets directly so snr falls more evenly and fewer steps are wasted on pure noise.
the reverse process: what we actually want
generation means sampling from . that’s intractable, because it depends on the whole data distribution: given a noisy image, which clean image did it come from?
but if you also know , it’s just algebra with gaussians:
so the reverse step is a gaussian whose mean needs one thing we don’t have at sampling time: . the model’s job is to fill that gap.
the trick: predict the noise
substitute into and it collapses to
everything in there is known except , the noise that was mixed in. so instead of asking a network for an image, ho et al.2 ask it for the noise: . the variational bound on the likelihood turns into a weighted sum of squared errors on , and dropping the weights works better in practice:
a generative model whose loss is mean squared error. that’s a big part of why diffusion trains so stably compared to gans.
why this is secretly a score model
differentiate the log of :
so predicting noise is predicting the score, the direction that makes a sample more likely, up to a scale: . sampling is gradient ascent on log-density with carefully added noise. this is the bridge to the score-based / sde view of diffusion, and it’s why “denoiser”, “score model” and “noise predictor” all name the same network.
the code
the whole thing on a 2d toy. the network sees a noisy point and a sinusoidal embedding of , and outputs a guess for the noise:
import math, torch, torch.nn as nn
T = 1000
betas = torch.linspace(1e-4, 0.02, T)
alphas = 1 - betas
abar = torch.cumprod(alphas, dim=0)
def q_sample(x0, t, eps):
a = abar[t].view(-1, *[1] * (x0.dim() - 1))
return a.sqrt() * x0 + (1 - a).sqrt() * eps
class EpsNet(nn.Module):
def __init__(self, dim=2, hidden=128):
super().__init__()
self.net = nn.Sequential(
nn.Linear(dim + 16, hidden), nn.SiLU(),
nn.Linear(hidden, hidden), nn.SiLU(),
nn.Linear(hidden, hidden), nn.SiLU(),
nn.Linear(hidden, dim),
)
def forward(self, x, t):
freqs = torch.exp(torch.arange(8) * -math.log(1000) / 8)
ang = t[:, None].float() * freqs[None]
return self.net(torch.cat([x, ang.sin(), ang.cos()], dim=-1))
def train_step(model, opt, x0):
t = torch.randint(0, T, (x0.shape[0],))
eps = torch.randn_like(x0)
loss = (model(q_sample(x0, t, eps), t) - eps).pow(2).mean()
opt.zero_grad(); loss.backward(); opt.step()
return loss.item()
and the sampler, which is just the reverse-step mean from above plus fresh noise ():
@torch.no_grad()
def ddpm_sample(model, shape):
x = torch.randn(shape)
for t in reversed(range(T)):
eps = model(x, torch.full((shape[0],), t))
x = (x - betas[t] / (1 - abar[t]).sqrt() * eps) / alphas[t].sqrt()
if t > 0:
x = x + betas[t].sqrt() * torch.randn_like(x)
return x
i trained this on the ring from the figure for 6,000 steps (batch 512, adam, lr , on cpu). pure gaussian noise sits at an average radius of about 1.26. after 1,000 reverse steps, 2,000 samples land at radius 2.01 ± 0.06, right on the ring.
the catch: 1,000 forward passes per sample
that loop calls the network a thousand times. for a 2d toy, fine. for a video model, that’s the bill. this is the part i think about most at work, and nearly every speedup is one of a few moves.
take bigger steps (ddim). song et al.3 noticed the training objective only pins down the marginals , not the step-by-step chain, so you can sample with a different, deterministic chain using the same trained model. predict the clean point, then jump straight to an earlier :
@torch.no_grad()
def ddim_sample(model, shape, steps=50):
ts = torch.linspace(T - 1, 0, steps).long()
x = torch.randn(shape)
for i, t in enumerate(ts):
eps = model(x, torch.full((shape[0],), int(t)))
x0 = (x - (1 - abar[t]).sqrt() * eps) / abar[t].sqrt()
a_next = abar[ts[i + 1]] if i + 1 < steps else torch.tensor(1.0)
x = a_next.sqrt() * x0 + (1 - a_next).sqrt() * eps
return x
on the same toy model, 50 ddim steps give radius 2.01 ± 0.10: a 20× cut in network calls for a slightly fuzzier ring and no retraining. higher-order ode solvers push this further, and distillation can get you down to a handful of steps.
make each step cheaper (latents). run diffusion in an autoencoder’s latent space instead of on pixels.4 with 8× downsampling, a image (786,432 numbers) becomes a latent (16,384 numbers), 48× fewer values per denoising step. video models lean on this even harder, because a time axis multiplies everything.
know what guidance costs. classifier-free guidance5 steers toward the prompt by extrapolating between a conditional and an unconditional prediction:
it works great, and it means two network evaluations per step. that’s a 2× tax hiding inside every “number of steps” you see quoted, and a reason to batch the two passes together.
what to take away
- the forward process is fixed and closed-form, so training is “pick , mix in noise, regress the noise”. that’s why it scales.
- predicting , predicting , and predicting the score are the same thing in different units.
- sampling cost is (steps) × (cost per step) × (guidance passes). every production trick attacks one of those three factors.
next up, i want to write about flow matching, which straightens these noisy paths so you need even fewer steps. if you spot a mistake in the math, tell me. that’s half the reason i write these.
Footnotes
-
nichol & dhariwal, “improved denoising diffusion probabilistic models”, 2021. ↩
-
ho, jain & abbeel, “denoising diffusion probabilistic models”, 2020. ↩
-
song, meng & ermon, “denoising diffusion implicit models”, 2021. ↩
-
rombach et al., “high-resolution image synthesis with latent diffusion models”, 2022. ↩
-
ho & salimans, “classifier-free diffusion guidance”, 2022. ↩