AI Logic

Architectures

DDPM

Updated:

Structure of DDPM. The left side shows the forward process that adds noise to an image x0 until it reaches xT, and the reverse process that removes noise with a U-Net to go back. The right side shows training that has the network guess the added noise, the generation procedure that repeats 1000 times from xT, and the inside of the noise-predicting U-Net

Background and overview

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 ϵ\boldsymbol{\epsilon} 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\boldsymbol{x}_0 and TT latent variables x1,…,xT\boldsymbol{x}_1, \dots, \boldsymbol{x}_T of the same size. It consists of two processes: a forward process that adds noise from x0\boldsymbol{x}_0 toward xT\boldsymbol{x}_T, and a reverse process that removes noise from xT\boldsymbol{x}_T back toward x0\boldsymbol{x}_0.

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\beta_t is added (Eq. 2). β1,…,βT\beta_1, \dots, \beta_T are constants fixed in advance and are not learned.

q(xt∣xt−1)=N(xt; 1−βt xt−1, βtI)q(\boldsymbol{x}_t \mid \boldsymbol{x}_{t-1}) = \mathcal{N}\big(\boldsymbol{x}_t;\ \sqrt{1 - \beta_t}\,\boldsymbol{x}_{t-1},\ \beta_t \boldsymbol{I}\big)

With αt=1−βt\alpha_t = 1 - \beta_t and αˉt=∏s=1tαs\bar{\alpha}_t = \prod_{s=1}^{t} \alpha_s, the value at step tt can be produced from x0\boldsymbol{x}_0 in a single shot (Eq. 4).

q(xt∣x0)=N(xt; αˉt x0, (1−αˉt)I),xt=αˉt x0+1−αˉt ϵ,  ϵ∼N(0,I)q(\boldsymbol{x}_t \mid \boldsymbol{x}_0) = \mathcal{N}\big(\boldsymbol{x}_t;\ \sqrt{\bar{\alpha}_t}\,\boldsymbol{x}_0,\ (1 - \bar{\alpha}_t)\boldsymbol{I}\big), \qquad \boldsymbol{x}_t = \sqrt{\bar{\alpha}_t}\,\boldsymbol{x}_0 + \sqrt{1 - \bar{\alpha}_t}\,\boldsymbol{\epsilon},\ \ \boldsymbol{\epsilon} \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I})

As tt grows, αˉt\bar{\alpha}_t approaches 0, and xT\boldsymbol{x}_T becomes nearly standard Gaussian noise.

Reverse process: removing noise

The reverse process is a Markov chain that starts from xT∼N(0,I)\boldsymbol{x}_T \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{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)p_\theta(\boldsymbol{x}_{t-1} \mid \boldsymbol{x}_t) = \mathcal{N}\big(\boldsymbol{x}_{t-1};\ \boldsymbol{\mu}_\theta(\boldsymbol{x}_t, t),\ \sigma_t^2 \boldsymbol{I}\big)

The variance σt2\sigma_t^2 is not learned and is set to σt2=βt\sigma_t^2 = \beta_t (using β~t=1−αˉt−11−αˉtβt\tilde{\beta}_t = \frac{1 - \bar{\alpha}_{t-1}}{1 - \bar{\alpha}_t}\beta_t gave almost the same results). The justification for this form is that when βt\beta_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)q(\boldsymbol{x}_{t-1} \mid \boldsymbol{x}_t, \boldsymbol{x}_0)" and "pθ(xt−1∣xt)p_\theta(\boldsymbol{x}_{t-1} \mid \boldsymbol{x}_t)" (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). ϵθ\boldsymbol{\epsilon}_\theta is a network that predicts the noise ϵ\boldsymbol{\epsilon} contained in xt\boldsymbol{x}_t.

μθ(xt,t)=1αt(xt−βt1−αˉt ϵθ(xt,t))\boldsymbol{\mu}_\theta(\boldsymbol{x}_t, t) = \frac{1}{\sqrt{\alpha_t}}\left(\boldsymbol{x}_t - \frac{\beta_t}{\sqrt{1 - \bar{\alpha}_t}}\,\boldsymbol{\epsilon}_\theta(\boldsymbol{x}_t, t)\right)

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).

Lsimple(θ)=Et,x0,ϵ[∥ϵ−ϵθ(αˉt x0+1−αˉt ϵ, t)∥2]L_{\mathrm{simple}}(\theta) = \mathbb{E}_{t, \boldsymbol{x}_0, \boldsymbol{\epsilon}}\Big[\big\|\boldsymbol{\epsilon} - \boldsymbol{\epsilon}_\theta\big(\sqrt{\bar{\alpha}_t}\,\boldsymbol{x}_0 + \sqrt{1 - \bar{\alpha}_t}\,\boldsymbol{\epsilon},\ t\big)\big\|^2\Big]

tt is chosen uniformly from 1 to TT. In substance, it is the mean squared error on the noise.

Training procedure (Algorithm 1)

  1. Take x0\boldsymbol{x}_0 from the training data.
  2. Choose a step tt uniformly from 1 to TT.
  3. Draw noise ϵ∼N(0,I)\boldsymbol{\epsilon} \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I}) and form xt=αˉt x0+1−αˉt ϵ\boldsymbol{x}_t = \sqrt{\bar{\alpha}_t}\,\boldsymbol{x}_0 + \sqrt{1 - \bar{\alpha}_t}\,\boldsymbol{\epsilon}.
  4. Update the network with the gradient of ∥ϵ−ϵθ(xt,t)∥2\|\boldsymbol{\epsilon} - \boldsymbol{\epsilon}_\theta(\boldsymbol{x}_t, t)\|^2, and repeat until convergence.

Generation procedure (Algorithm 2)

  1. Draw xT∼N(0,I)\boldsymbol{x}_T \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I}).
  2. For t=T,…,1t = T, \dots, 1, compute xt−1\boldsymbol{x}_{t-1} with the following formula. z\boldsymbol{z} is a freshly drawn standard Gaussian sample, and only at the last step (t=1t = 1) is z=0\boldsymbol{z} = \boldsymbol{0}.
  3. Output the resulting x0\boldsymbol{x}_0.
xt−1=1αt(xt−1−αt1−αˉt ϵθ(xt,t))+σtz\boldsymbol{x}_{t-1} = \frac{1}{\sqrt{\alpha_t}}\left(\boldsymbol{x}_t - \frac{1 - \alpha_t}{\sqrt{1 - \bar{\alpha}_t}}\,\boldsymbol{\epsilon}_\theta(\boldsymbol{x}_t, t)\right) + \sigma_t \boldsymbol{z}

The noise-predicting network

For ϵθ\boldsymbol{\epsilon}_\theta, a U-Net modeled on the PixelCNN++ backbone is used (Section 4, Appendix B).

ItemDetails
BackboneA U-Net built from Wide ResNet-style residual blocks (ResNet residual connections)
NormalizationGroup Normalization instead of weight normalization
Resolution levels4 levels for 32 × 32 images (32 × 32 to 4 × 4), 6 levels for 256 × 256 images; 2 residual blocks per level
AttentionSelf-attention at the 16 × 16 resolution (scaled dot-product attention)
How step tt is passed intt is embedded with the same formula as the sinusoidal positional encoding and added to each residual block; weights are shared across all steps
Parameters35.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 tt.

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\beta_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 ϵ\boldsymbol{\epsilon} (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 tt). LsimpleL_{\mathrm{simple}} 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\hat{\boldsymbol{x}}_0 estimated from xt\boldsymbol{x}_t 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\boldsymbol{x}_T 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=1000T = 1000 with βt\beta_t increasing linearly from 10−410^{-4} to 0.020.02.

CIFAR-10 (unconditional generation) (excerpt from Table 1; higher Inception Score (IS) and lower FID are better; NLL is in bits per dimension)

ModelISFIDNLL (test)
NCSN (score matching)8.8725.32—
SNGAN8.2221.7—
StyleGAN2 + ADA9.743.26—
Gated PixelCNN (autoregressive)4.6065.933.03
DDPM (trained with the variational bound LL)7.6713.51≤ 3.70
DDPM (trained with LsimpleL_{\mathrm{simple}})9.463.17≤ 3.75

The model trained with LsimpleL_{\mathrm{simple}} 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 quantityObjectiveISFID
Mean μ~\tilde{\boldsymbol{\mu}}LL, variance also learned7.2823.69
Mean μ~\tilde{\boldsymbol{\mu}}LL, fixed variance8.0613.22
Mean μ~\tilde{\boldsymbol{\mu}}Unweighted squared errorTraining unstable—
Noise ϵ\boldsymbol{\epsilon}LL, variance also learnedTraining unstable—
Noise ϵ\boldsymbol{\epsilon}LL, fixed variance7.6713.51
Noise ϵ\boldsymbol{\epsilon}LsimpleL_{\mathrm{simple}}9.463.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)

ModelBedroomChurchCat
ProgressiveGAN8.346.4237.52
StyleGAN2—3.866.93
DDPM6.367.8919.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).

ItemValue
OptimizerAdam (learning rate 2×10−42 \times 10^{-4}; 2×10−52 \times 10^{-5} for 256 × 256 images)
Batch size128 for CIFAR-10, 64 for larger images
Training length800K updates for CIFAR-10 (10.6 hours on a TPU v3-8)
Parameter averagingExponential moving average (EMA) with decay 0.9999
Dropout0.1 for CIFAR-10, 0 otherwise
Data augmentationRandom horizontal flips (except LSUN Bedroom)

Practical notes

Keep the following points in mind when using DDPM.

  • Scale pixels to [−1,1][-1, 1]: the paper linearly scales pixels from 0-255 to [−1,1][-1, 1]. The magnitude of βt\beta_t is chosen assuming this range.
  • The βt\beta_t schedule determines whether xT\boldsymbol{x}_T becomes pure noise: with the paper's settings (linear from 10−410^{-4} to 0.020.02, T=1000T = 1000), the difference between xT\boldsymbol{x}_T and a standard Gaussian is about 10−510^{-5} bits per dimension. If TT is made smaller, βt\beta_t needs to be revised so that xT\boldsymbol{x}_T 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=1000T = 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.

MethodHow it generatesTraining objectiveGeneration speedLikelihood
VAEPasses a latent variable through the decoder onceMaximize a lower bound on the log-likelihoodFastLower bound can be computed
GANPasses noise through the generator onceFool the discriminatorFastCannot be computed
DDPMRemoves noise from pure noise over 1000 stepsSquared error of the added noise (variational bound with weights removed)SlowUpper bound can be computed
DDIMUses the same network as DDPM and goes back deterministically, skipping stepsSame as DDPMCan be 10-50 times faster in wall-clock time—
Latent DiffusionDiffuses in the latent space of an autoencoder and maps back to an image with the decoder at the endSame loss as DDPM, in latent spaceLighter 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\boldsymbol{x}_t and the step tt, and predicts the noise ϵ\boldsymbol{\epsilon} mixed into it. From the predicted noise, the mean of the previous step xt−1\boldsymbol{x}_{t-1} is computed as 1αt(xt−βt1−αˉtϵθ)\frac{1}{\sqrt{\alpha_t}}\big(\boldsymbol{x}_t - \frac{\beta_t}{\sqrt{1 - \bar{\alpha}_t}}\boldsymbol{\epsilon}_\theta\big). 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=αˉt x0+1−αˉt ϵ\boldsymbol{x}_t = \sqrt{\bar{\alpha}_t}\,\boldsymbol{x}_0 + \sqrt{1 - \bar{\alpha}_t}\,\boldsymbol{\epsilon}, the xt\boldsymbol{x}_t of any step can be produced from x0\boldsymbol{x}_0 in one shot. In training, one step tt 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.

References

  1. Ho, J., Jain, A., & Abbeel, P. (2020). Denoising Diffusion Probabilistic Models. NeurIPS 2020. arXiv:2006.11239.
  2. Sohl-Dickstein, J., Weiss, E., Maheswaranathan, N., & Ganguli, S. (2015). Deep Unsupervised Learning using Nonequilibrium Thermodynamics. ICML 2015. arXiv:1503.03585.