DDPM (Denoising Diffusion Probabilistic Models) is a generative model that creates images by using a neural network to reverse, one step at a time, a process that gradually destroys data by adding noise. Starting from pure noise and repeating an operation that removes a little noise 1000 times produces an image that resembles the training data.
It was introduced in 2020 by Ho, Jain, and Abbeel in the paper "Denoising Diffusion Probabilistic Models". The idea of diffusion models itself had been proposed by Sohl-Dickstein et al. in 2015, but until then it had not been shown that they could produce high-quality images. DDPM turned diffusion models into a practical image generation method through two points.
Having the network predict "the added noise": instead of outputting the mean of each step directly, the network is trained to guess the noise ϵ mixed into the image. The loss then takes the simple form of the squared error between the added noise and the predicted noise.
A simple objective with the loss weights removed: removing the theoretically derived weights was shown to improve image quality greatly.
As a result, it achieved an FID of 3.17 on unconditional generation on CIFAR-10, surpassing many GANs of the time. The paper also showed that this form is equivalent to "denoising score matching over multiple noise levels" and "sampling with Langevin dynamics".
DDPM became the foundation for later diffusion models. DDIM, which made generation faster, Score SDE, which extended it to continuous time, Latent Diffusion, which diffuses after compressing images, and DiT, which made the noise-predicting network a Transformer, all inherit DDPM's training formulation.
Theory
DDPM considers data x0 and T latent variables x1,…,xT of the same size. It consists of two processes: a forward process that adds noise from x0 toward xT, and a reverse process that removes noise from xT back toward x0.
Forward process (diffusion process): adding noise
At each step, the value from the previous step is scaled down slightly and Gaussian noise with variance βt is added (Eq. 2). β1,…,βT are constants fixed in advance and are not learned.
q(xt∣xt−1)=N(xt;1−βtxt−1,βtI)
With αt=1−βt and αˉt=∏s=1tαs, the value at step t can be produced from x0 in a single shot (Eq. 4).
As t grows, αˉt approaches 0, and xT becomes nearly standard Gaussian noise.
Reverse process: removing noise
The reverse process is a Markov chain that starts from xT∼N(0,I) and goes back one step at a time with Gaussian distributions (Eq. 1). Its mean is learned by a network.
pθ(xt−1∣xt)=N(xt−1;μθ(xt,t),σt2I)
The variance σt2 is not learned and is set to σt2=βt (using β~t=1−αˉt1−αˉt−1βt gave almost the same results). The justification for this form is that when βt is small, a single reverse step is also well approximated by a Gaussian.
Training objective: guessing the added noise
As in a VAE, training minimizes a variational upper bound on the negative log-likelihood (Eq. 3). This bound can be rewritten as a sum over steps of the KL divergence between "the true reverse distribution q(xt−1∣xt,x0)" and "pθ(xt−1∣xt)" (Eq. 5). Both are Gaussian, so each term becomes a squared error of the means.
Here DDPM expresses the mean in the following form (Eq. 11). ϵθ is a network that predicts the noise ϵ contained in xt.
μθ(xt,t)=αt1(xt−1−αˉtβtϵθ(xt,t))
The loss at each step then becomes the squared error between the added noise and the predicted noise, multiplied by a per-step weight (Eq. 12). The paper trains with the following simple objective that removes this weight (Eq. 14).
t is embedded with the same formula as the sinusoidal positional encoding and added to each residual block; weights are shared across all steps
Parameters
35.7M for CIFAR-10, 114M for LSUN and CelebA-HQ
A single network handles every step, from images with little noise to images close to pure noise. Which step's problem it is solving is conveyed by the embedded t.
Why it works
The reasons DDPM generates images well can be summarized in three points.
One step at a time, denoising is an easy problem: unlike GANs and VAEs, which produce a whole image in one shot, the network at each step only needs to "estimate the noise from an image with a little noise mixed in". Since βt is small, a single reverse step is also well approximated by a Gaussian, so the hard generation problem is split into 1000 easy denoising problems.
Noise prediction has the same form as score matching: the loss that has the network predict ϵ (Eq. 12) matches "denoising score matching" over multiple noise levels. The generation formula also resembles Langevin dynamics, moving little by little along the gradient of the learned data density while adding random noise. In other words, DDPM can be seen as training a score-based generative model within a variational inference framework. Score SDE extended this view to continuous time.
Removing the weights focuses training on the hard steps: the weights in Eq. 12 are large for low-noise steps (small t). Lsimple removes these weights, which lowers the share of the easy low-noise steps and directs training toward the hard high-noise steps. The paper explains that this is why image quality improved.
Lining up the x^0 estimated from xt at each point during generation shows that the rough shape appears first and the details appear last (Figure 6 of the paper). It proceeds like a painter who starts from a blurred sketch and then adds outlines, colors, and fine patterns in that order.
The forward process of a diffusion model has no parameters, and xT becomes noise nearly unrelated to the data. Since there is no need to learn the counterpart of a VAE encoder, the only thing trained is the noise-predicting network.
Experimental results
In all experiments, the paper used T=1000 with βt increasing linearly from 10−4 to 0.02.
CIFAR-10 (unconditional generation) (excerpt from Table 1; higher Inception Score (IS) and lower FID are better; NLL is in bits per dimension)
Model
IS
FID
NLL (test)
NCSN (score matching)
8.87
25.32
—
SNGAN
8.22
21.7
—
StyleGAN2 + ADA
9.74
3.26
—
Gated PixelCNN (autoregressive)
4.60
65.93
3.03
DDPM (trained with the variational bound L)
7.67
13.51
≤ 3.70
DDPM (trained with Lsimple)
9.46
3.17
≤ 3.75
The model trained with Lsimple had the best FID among unconditional models at the time. Its FID computed against the test data was 5.24. On the other hand, its log-likelihood (NLL) did not reach that of other likelihood-based models such as autoregressive models.
Comparison of reverse-process parameterizations and objectives (Table 2, CIFAR-10)
Predicted quantity
Objective
IS
FID
Mean μ~
L, variance also learned
7.28
23.69
Mean μ~
L, fixed variance
8.06
13.22
Mean μ~
Unweighted squared error
Training unstable
—
Noise ϵ
L, variance also learned
Training unstable
—
Noise ϵ
L, fixed variance
7.67
13.51
Noise ϵ
Lsimple
9.46
3.17
The combination of predicting the noise and the unweighted objective gave the best results. Learning the variance made training unstable.
FID on LSUN (256 × 256) (Table 3)
Model
Bedroom
Church
Cat
ProgressiveGAN
8.34
6.42
37.52
StyleGAN2
—
3.86
6.93
DDPM
6.36
7.89
19.75
DDPM (larger model)
4.90
—
—
On 256 × 256 images, the quality was close to ProgressiveGAN but did not reach StyleGAN2.
The training settings were as follows (Appendix B).
Item
Value
Optimizer
Adam (learning rate 2×10−4; 2×10−5 for 256 × 256 images)
Batch size
128 for CIFAR-10, 64 for larger images
Training length
800K updates for CIFAR-10 (10.6 hours on a TPU v3-8)
Parameter averaging
Exponential moving average (EMA) with decay 0.9999
Keep the following points in mind when using DDPM.
Scale pixels to [−1,1]: the paper linearly scales pixels from 0-255 to [−1,1]. The magnitude of βt is chosen assuming this range.
The βt schedule determines whether xT becomes pure noise: with the paper's settings (linear from 10−4 to 0.02, T=1000), the difference between xT and a standard Gaussian is about 10−5 bits per dimension. If T is made smaller, βt needs to be revised so that xT is sufficiently noisy.
Use the EMA weights for generation: the paper evaluates with an exponential moving average of the parameters (decay 0.9999).
Not suited for likelihood evaluation: although the visual quality of images is high, the log-likelihood is worse than that of other likelihood-based models. According to the paper, more than half of the code length is spent describing imperceptibly fine details.
Generation requires passing through the network T=1000 times. Even in the paper's environment (TPU v3-8), 256 CIFAR-10 images took 17 seconds and 128 images of 256 × 256 took 300 seconds. Generation is much slower than with GANs or VAEs, which produce an image in one shot. To generate faster by skipping steps while keeping the trained model as is, use the generation procedure of DDIM.
Comparison with other methods
The following compares DDPM with other generative models from the same viewpoints.
Diffuses in the latent space of an autoencoder and maps back to an image with the decoder at the end
Same loss as DDPM, in latent space
Lighter than diffusing in pixel space
—
VAEs train stably and also provide a latent space through the encoder. GANs produce high-quality images, but stabilizing training requires careful choice of optimization and architecture, and they can end up producing only part of the data distribution. DDPM trains stably with just a simple squared error and produces high-quality images, at the cost of slow generation.
Rough guidelines for choosing:
To produce high-quality images with stable training: DDPM is a good fit. If generation time is a concern, replace only the generation with DDIM.
For high-resolution images or text-to-image generation: Latent Diffusion, which keeps the computation down, is a good fit.
To generate instantly in one pass, or to give the latent space meaning: GANs and VAEs are also candidates.
PyTorch example
▶Show code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of DDPM from Ho et al. (2020), written to follow the paper's equations.
T = 1000, beta linear from 1e-4 to 0.02 (Section 4). Training is Algorithm 1, generation is Algorithm 2.
The paper's network is a U-Net with residual blocks and self-attention. Here it is a small CNN just to show the shape
"""
T = 1000
betas = torch.linspace(1e-4, 0.02, T) # beta_1, ..., beta_T
alphas = 1.0 - betas # alpha_t = 1 - beta_t
alpha_bars = torch.cumprod(alphas, dim=0) # alpha_bar_t = alpha_1 * ... * alpha_t
def timestep_embedding(t, dim):
"""Embed step t with sinusoids (same formula as the Transformer's positional encoding)"""
half = dim // 2
freqs = torch.exp(-math.log(10000) * torch.arange(half, device=t.device) / half)
args = t.float()[:, None] * freqs[None]
return torch.cat([torch.sin(args), torch.cos(args)], dim=1)
class TinyEpsModel(nn.Module):
"""Predict the added noise epsilon from x_t and t (a U-Net in the paper)"""
def __init__(self, ch=64, t_dim=128):
super().__init__()
self.t_mlp = nn.Sequential(nn.Linear(t_dim, ch), nn.SiLU(), nn.Linear(ch, ch))
self.inp = nn.Conv2d(3, ch, 3, padding=1)
self.body = nn.Sequential(nn.GroupNorm(8, ch), nn.SiLU(), nn.Conv2d(ch, ch, 3, padding=1),
nn.GroupNorm(8, ch), nn.SiLU(), nn.Conv2d(ch, ch, 3, padding=1))
self.out = nn.Conv2d(ch, 3, 3, padding=1)
self.t_dim = t_dim
def forward(self, x, t):
h = self.inp(x)
h = h + self.t_mlp(timestep_embedding(t, self.t_dim))[:, :, None, None] # add the embedding of t
return self.out(h + self.body(h))
def q_sample(x0, t, eps):
"""Eq. 4: form x_t = sqrt(alpha_bar_t) x_0 + sqrt(1 - alpha_bar_t) eps in one shot"""
ab = alpha_bars.to(x0.device)[t - 1].view(-1, 1, 1, 1) # t is 1..T
return ab.sqrt() * x0 + (1 - ab).sqrt() * eps
def loss_simple(model, x0):
"""Eq. 14 (Algorithm 1): squared error between the added noise and the predicted noise"""
t = torch.randint(1, T + 1, (x0.size(0),), device=x0.device) # t ~ Uniform({1, ..., T})
eps = torch.randn_like(x0) # epsilon ~ N(0, I)
return F.mse_loss(model(q_sample(x0, t, eps), t), eps)
@torch.no_grad()
def sample(model, shape, device):
"""Algorithm 2: go back one step at a time from x_T ~ N(0, I) (sigma_t^2 = beta_t)"""
x = torch.randn(shape, device=device)
for t in range(T, 0, -1):
tt = torch.full((shape[0],), t, device=device, dtype=torch.long)
a, ab, b = alphas[t - 1].item(), alpha_bars[t - 1].item(), betas[t - 1].item()
eps = model(x, tt)
mean = (x - b / math.sqrt(1 - ab) * eps) / math.sqrt(a) # mean from Eq. 11
z = torch.randn_like(x) if t > 1 else torch.zeros_like(x) # z = 0 only at the last step
x = mean + math.sqrt(b) * z
return x.clamp(-1, 1)
device = "cuda" if torch.cuda.is_available() else "cpu"
model = TinyEpsModel().to(device)
ema = TinyEpsModel().to(device)
ema.load_state_dict(model.state_dict())
optimizer = torch.optim.Adam(model.parameters(), lr=2e-4) # the paper's CIFAR-10 learning rate
x0 = torch.rand(8, 3, 32, 32, device=device) * 2 - 1 # images with pixels scaled to [-1, 1] (random stand-in here)
model.train()
loss = loss_simple(model, x0)
optimizer.zero_grad()
loss.backward()
optimizer.step()
with torch.no_grad(): # exponential moving average of the parameters (decay 0.9999)
for p_ema, p in zip(ema.parameters(), model.parameters()):
p_ema.mul_(0.9999).add_(p, alpha=1 - 0.9999)
ema.eval()
images = sample(ema, (4, 3, 32, 32), device) # use the EMA weights for generation
FAQ
Q. What does the DDPM network predict?
A.
It takes a noisy image xt and the step t, and predicts the noise ϵ mixed into it. From the predicted noise, the mean of the previous step xt−1 is computed as αt1(xt−1−αˉtβtϵθ). The paper showed that predicting the noise and training with the unweighted loss gives much better image quality than predicting the mean directly (FID 3.17 on CIFAR-10).
Q. Does training also need to go through the 1000 steps in order?
A.
No. With xt=αˉtx0+1−αˉtϵ, the xt of any step can be produced from x0 in one shot. In training, one step t is chosen at random for each data point, and only denoising at that step is learned. The 1000 steps are traversed only during generation.
Q. How are DDPM and VAE similar, and how do they differ?
A.
Both are latent variable models trained with a variational bound on the log-likelihood (in DDPM, an upper bound on the negative log-likelihood). The difference is that a VAE learns an encoder that maps data to latent variables in one shot, whereas DDPM fixes the "noise-adding" forward process and does not learn it. DDPM's latent variables have the same size as the data, and the network learns the 1000-step reverse process.