DDPM: Add Noise Step by Step, Learn to Remove It Step by Step, and Train with a Simple Noise-Prediction Loss
DDPM models generation as fixed forward noising plus learned reverse denoising: the network predicts each step's noise and trains with an unweighted mean squared error, reaching FID 3.17 on CIFAR-10. Code checks the forward closed form, endpoint KL and loss weights on 2D toy data.
On this page
Why this paper matters
Before 2020 generative models mainly followed a few routes: generative adversarial networks (GANs), variational autoencoders (VAEs), autoregressive models and flows. Diffusion probabilistic models had been proposed in 2015, but their sample quality had never been convincing. This paper (Ho, Jain and Abbeel, UC Berkeley, posted in June 2020, NeurIPS 2020) gives a clean training objective and a set of architecture choices, and shows diffusion models can generate high-quality images: FID 3.17 on unconditional CIFAR-10 and sample quality similar to ProgressiveGAN on LSUN 256×256. Later image and video diffusion models mostly kept its noise-prediction objective and its step-by-step denoising sampler.
Method
Forward process (fixed, no parameters). Gaussian noise is added to the data step by step: . With and , the marginal at any step has a closed form:
The paper uses with rising linearly from to . Relative to data scaled to these variances are small, so the forward and reverse processes have approximately the same form, while the signal-to-noise ratio at is as small as possible ( bits/dim).
Reverse process (learned). with fixed variance (using gave similar results). The mean is parameterized through a noise-prediction network :
Training objective. Expanding the variational bound term by term, step equals a weighted noise-prediction error with weight . The paper finds that dropping the weights works better and uses the simplified objective:
Algorithm 1 (training) repeatedly draws , and and takes a gradient step on this loss; Algorithm 2 (sampling) starts from and for down to computes (no noise at the last step).
Network. A U-Net similar to PixelCNN++ with group normalization throughout and self-attention at the 16×16 resolution; the time step enters every residual block through a Transformer sinusoidal embedding and parameters are shared across time steps. The CIFAR-10 model has 35.7 million parameters and the LSUN and CelebA-HQ models have 114 million. Training uses learning rate and batch size 128 (images of 256×256 use and batch size 64), an exponential moving average of the parameters with decay 0.9999, and dropout 0.1 on CIFAR-10.
Experiments and findings
CIFAR-10 (Table 1, excerpt).
| Model | IS | FID | Test codelength (bits/dim) |
|---|---|---|---|
| DDPM, | 9.46 ± 0.11 | 3.17 | ≤ 3.75 |
| DDPM, variational bound, fixed variance | 7.67 ± 0.13 | 13.51 | ≤ 3.70 |
| StyleGAN2 + ADA (unconditional) | 9.74 ± 0.05 | 3.26 | none |
FID is computed against the training set; against the test set it is 5.24. The paper itself notes that its lossless codelengths are not competitive with other likelihood-based models.
Ablation of parameterization and objective (Table 2).
| Prediction target | Training loss | IS | FID |
|---|---|---|---|
| Mean | Variational bound, learned diagonal variance | 7.28 ± 0.10 | 23.69 |
| Mean | Variational bound, fixed variance | 8.06 ± 0.09 | 13.22 |
| Mean | Unweighted mean squared error | unstable | unstable |
| Noise | Variational bound, fixed variance | 7.67 ± 0.13 | 13.51 |
| Noise | Unweighted mean squared error () | 9.46 ± 0.11 | 3.17 |
Also, learning the variances made training unstable and samples worse; predicting is about as good as predicting the mean under the variational bound and much better under the simplified objective.
LSUN 256×256 (Table 3). The FID is 6.36 on Bedroom (4.90 for the large model), 7.89 on Church and 19.75 on Cat. In the same table ProgressiveGAN has 8.34, 6.42 and 37.52, and StyleGAN has 2.65, 4.21 and 8.53.
Progressive lossy compression. Treating the terms of the bound as rate and as distortion, the highest-quality CIFAR-10 model has a rate of 1.78 bits/dim and a distortion of 1.97 bits/dim, a root mean squared error of 0.95 on the 0–255 scale; more than half of the codelength goes to imperceptible details.
Checking it with code
Three things. (1) Noise 1000 times step by step, compare with the closed form , and compute the KL from to a standard Gaussian, against the paper’s roughly bits/dim. (2) Compute the weights the variational bound gives each time step and see how widely they spread. (3) On the “two moons” 2D data, with the paper’s and the same variance schedule, train a DDPM myself (a three-layer, 128-unit MLP noise predictor, 6000 steps), compare the and variational-bound-weight losses with 10 seeds each, and measure the gap between 2000 generated points and 2000 held-out real points with an RBF-kernel MMD². (3) is a toy replication of the conclusion in the last row of the paper’s Table 2: the data is 2D and the network a small MLP, not images and a U-Net.
import math
import statistics as st
import torch
from torch import nn
torch.set_num_threads(1)
# diffusion steps and variance schedule as in the paper:
# beta increases linearly from 1e-4 to 0.02
T = 1000
betas = torch.linspace(1e-4, 0.02, T)
alphas = 1 - betas
abar = alphas.cumprod(0)
# 1) forward process: stepwise noising vs closed form q(x_t | x_0),
# and the KL at the end
g = torch.Generator().manual_seed(0)
x = torch.full((200_000,), 1.0) # worst case x_0 = 1
for t in range(T):
noise = torch.randn(x.shape, generator=g)
x = alphas[t].sqrt() * x + betas[t].sqrt() * noise
print(f"stepwise mean={x.mean():.4f} var={x.var():.4f}")
print(f"closed mean={abar[-1].sqrt():.4f} var={1 - abar[-1]:.4f}")
for x2 in (0.25, 1.0): # mean square of x_0 per dimension
ab = abar[-1]
kl = 0.5 * (1 - ab + ab * x2 - 1 - (1 - ab).log()) / math.log(2)
print(f"abar_T={ab:.2e} E[x0^2]={x2:4.2f} KL={kl:.2e} bits/dim")
# 2) train DDPM on two moons, compare L_simple with the
# variational-bound weights
def moons(n, g):
th = torch.rand(n, generator=g) * math.pi
up = torch.rand(n, generator=g) < 0.5
x = torch.where(up, th.cos(), 1 - th.cos())
y = torch.where(up, th.sin(), 0.5 - th.sin())
return torch.stack([x, y], 1) + 0.08 * torch.randn(n, 2, generator=g)
ref = moons(100_000, torch.Generator().manual_seed(12345))
MEAN, STD = ref.mean(0), ref.std(0)
def data(n, g):
return (moons(n, g) - MEAN) / STD
class Net(nn.Module):
def __init__(self, h=128):
super().__init__()
self.f = nn.Sequential(nn.Linear(2 + 16, h), nn.SiLU(),
nn.Linear(h, h), nn.SiLU(),
nn.Linear(h, h), nn.SiLU(), nn.Linear(h, 2))
def forward(self, x, t): # sinusoidal encoding of t
ang = (t[:, None] / T) * 2 * math.pi * torch.arange(1, 9)
return self.f(torch.cat([x, ang.sin(), ang.cos()], 1))
# weight of the step-t eps-prediction loss in the variational bound
# (paper Eq. (12), with sigma_t^2 = beta_t)
w_vlb = betas**2 / (2 * betas * alphas * (1 - abar))
print(f"variational-bound weights: max/min = {w_vlb.max() / w_vlb.min():.0f}")
def train(weighted, seed, steps=6000):
# seed for initialization, timesteps and noise
torch.manual_seed(10_000 + seed)
# independent seed for the training data
g_data = torch.Generator().manual_seed(seed)
net = Net()
opt = torch.optim.Adam(net.parameters(), lr=1e-3)
for _ in range(steps):
x0 = data(256, g_data)
t = torch.randint(0, T, (256,))
eps = torch.randn_like(x0)
xt = abar[t].sqrt()[:, None] * x0 + (1 - abar[t]).sqrt()[:, None] * eps
loss = ((net(xt, t) - eps) ** 2).sum(1)
loss = (w_vlb[t] * loss if weighted else loss).mean()
opt.zero_grad()
loss.backward()
opt.step()
return net
@torch.no_grad()
def sample(net, n): # paper Algorithm 2
x = torch.randn(n, 2)
for t in reversed(range(T)):
eps = net(x, torch.full((n,), t))
mean = (x - betas[t] / (1 - abar[t]).sqrt() * eps) / alphas[t].sqrt()
x = mean + (betas[t].sqrt() * torch.randn(n, 2) if t > 0 else 0)
return x
def mmd(a, b): # bandwidth: median pairwise distance of the real data
h = torch.cdist(b, b).median()
k = lambda u, v: (-torch.cdist(u, v) ** 2 / (2 * h**2)).exp().mean()
return (k(a, a) + k(b, b) - 2 * k(a, b)).item()
print("\nMMD^2 x 1e3 (lower is better), 10 seeds")
res = {"L_simple": [], "vlb weights": []}
for seed in range(10):
g_test = torch.Generator().manual_seed(20_000 + seed)
real = data(2000, g_test) # held-out real points
for name, weighted in (("L_simple", False), ("vlb weights", True)):
res[name].append(1e3 * mmd(sample(train(weighted, seed), 2000), real))
if seed == 0:
floor = 1e3 * mmd(data(2000, torch.Generator().manual_seed(7)), real)
gauss = 1e3 * mmd(torch.randn(2000, 2), real)
for name, v in res.items():
print(f"{name:12s} {st.mean(v):5.2f}±{st.stdev(v):<5.2f} "
+ " ".join(f"{x:5.2f}" for x in v))
d = [b - a for a, b in zip(res["L_simple"], res["vlb weights"])]
print(f"paired difference (vlb - L_simple): {st.mean(d):+.2f} "
f"± {st.stdev(d) / len(d) ** 0.5:.2f} (s.e.), "
f"L_simple better in {sum(x > 0 for x in d)} of {len(d)} seeds")
print(f"two real samples: {floor:.2f}, N(0, I) vs real: {gauss:.2f}")
Output (CPU, single thread, about 2 minutes):
stepwise mean=0.0048 var=1.0004
closed mean=0.0064 var=1.0000
abar_T=4.04e-05 E[x0^2]=0.25 KL=7.27e-06 bits/dim
abar_T=4.04e-05 E[x0^2]=1.00 KL=2.91e-05 bits/dim
variational-bound weights: max/min = 101
MMD^2 x 1e3 (lower is better), 10 seeds
L_simple 1.16±0.61 1.20 0.51 1.50 0.86 0.93 0.84 2.74 1.04 0.91 1.09
vlb weights 1.33±0.75 2.03 1.52 0.69 0.71 0.34 1.49 2.91 1.01 1.49 1.09
paired difference (vlb - L_simple): +0.17 ± 0.19 (s.e.), L_simple better in 6 of 10 seeds
two real samples: 0.18, N(0, I) vs real: 10.87
How to read these numbers:
- The closed form agrees with stepwise noising. Noising 200,000 samples 1000 times gives mean 0.0048 and variance 1.0004, the closed form gives mean 0.0064 and variance 1.0000; the difference in the mean is within sampling error (standard error about 0.0022).
- The endpoint KL has the order of magnitude the paper states. . If the mean square of per dimension is 0.25 the KL is bits/dim, and if it is 1 it is . The paper’s roughly lies in this range, depending on the data amplitude; I did not recompute it on CIFAR-10.
- The variational-bound weights span a factor of 101. The bound gives the small- terms large weights, and flattens them, which is the paper’s explanation for why it works.
- The toy experiment does not reproduce this difference. The MMD² () is 1.16±0.61 for and 1.33±0.75 for the bound weights, the paired per-seed difference is +0.17±0.19 (standard error), and is better in 6 of 10 seeds, within noise. Both are far better than a standard Gaussian (10.87) but still six or seven times above the noise floor between two real samples (0.18). The paper’s gap (FID 3.17 against 13.51) was measured on images with a U-Net, and 2D toy data cannot say whether that conclusion holds.
Limitations and what to keep in mind
- Slow sampling. 1000 sequential network evaluations; the paper reports 17 seconds for 256 CIFAR-10 images on a TPU v3-8.
- Likelihood is not competitive. The NLL of is slightly worse than that of the variational bound, and the paper admits its lossless codelengths trail other likelihood models.
- Metrics are indirect. FID and IS are indirect measures of sample quality, and the paper’s FID is 3.17 against the training set and 5.24 against the test set, a noticeable difference.
- Verified only on images. The paper mentions combining diffusion models with other generative models, but that is an outlook.
- Limits of the toy experiment. 2D data, a small MLP and 10 seeds check the mechanism only and cannot replace the paper’s image experiments.
What to take from this paper
- The forward process is fixed, so training only has to learn denoising. The closed-form marginal lets any time step be sampled directly.
- Predicting the noise turns the loss into plain regression. This rewrite turns a complicated variational bound into stable supervised learning.
- Dropping the weights is deliberate. It gives up a little likelihood for better samples.
- Sampling is a long chain. Quality is bought with speed, which is where later work focused.
- The link to score matching is the key bridge. Predicting noise is equivalent to estimating the score of noisy data, and the sampler resembles Langevin dynamics.
Further reading
- Paper: Denoising Diffusion Probabilistic Models; code: hojonathanho/diffusion
- Related Wiki on this site: Information theory basics (KL divergence and codelength)
- Glossary: Diffusion model, DDPM
FAQ
- What do DDPM training and sampling do?
- Training draws a data point x0, a time step t and standard Gaussian noise ε, builds the noisy sample x_t = √ᾱ_t·x0 + √(1−ᾱ_t)·ε, and trains the network to predict ε with a mean squared error. Sampling starts from pure Gaussian noise x_T and walks from t=T down to 1, each step computing a mean from the predicted noise and adding Gaussian noise with variance σ_t². The paper uses T=1000, so a sample needs 1000 sequential network evaluations.
- Why predict the noise ε instead of the clean image?
- The paper shows that writing the reverse mean as a function of ε turns each training term into a weighted denoising of the noise, which has the same form as denoising score matching over many noise levels, and the sampler resembles Langevin dynamics. In the ablation of Table 2, predicting ε with the unweighted L_simple works best (FID 3.17), while predicting the mean with an unweighted loss was unstable and gave no usable samples.
- What does L_simple give up compared with the exact variational bound?
- Likelihood gets a little worse: the CIFAR-10 test codelength goes from at most 3.70 to at most 3.75 bits/dim. Sample quality improves a lot, with FID falling from 13.51 to 3.17. The paper's explanation is that the bound gives large weights to the small-t terms, which only teach the network to remove very small noise, and dropping the weights lets the network focus on the harder large-t denoising tasks.
- Why is DDPM sampling slow?
- The reverse process is a Markov chain of length T, and with T=1000 each sample needs 1000 sequential network evaluations. The paper's appendix reports that on a TPU v3-8 a batch of 256 CIFAR-10 images takes 17 seconds and a batch of 128 images with the 256×256 model takes 300 seconds.