AI Logic

Architectures

DDIM

Updated:

How DDIM generates. The left side shows the path from x_T back to x_0 that jumps through only S of the 1000 steps. The right side shows one update step (predict the noise, estimate x_0, then add three terms: the predicted x_0, the direction pointing to x_t, and random noise) and how the noise scale Ξ· switches between DDIM and DDPM

Background and overview

DDIM (Denoising Diffusion Implicit Models) is a method that reuses a trained DDPM as is and generates images quickly by skipping generation steps. Training is exactly the same as DDPM; only the way of generating changes. Following just 20-100 of the 1000 steps still produces images of quality close to a 1000-step DDPM.

It was introduced in 2020 by Song, Meng, and Ermon in the paper "Denoising Diffusion Implicit Models" and accepted at ICLR 2021. The motivation was the slow generation of DDPM. According to the paper, on a single NVIDIA 2080 Ti GPU, DDPM takes about 20 hours to generate 50,000 images of 32 Γ— 32, while a GAN takes less than a minute. For 50,000 images of 256 Γ— 256, it can take nearly 1000 hours.

DDIM rests on two ideas.

  • The DDPM loss depends only on "the distribution that produces xt\boldsymbol{x}_t from x0\boldsymbol{x}_0": changing how xtβˆ’1\boldsymbol{x}_{t-1} is connected to xt\boldsymbol{x}_t step by step gives the same loss. So instead of a Markov chain that advances one step at a time, the authors considered a non-Markovian forward process and built a new generation procedure that matches it.
  • Deterministic generation without added noise is possible: the new generation procedure lets the noise scale be chosen freely. Setting the noise to 0 means that once the initial noise xT\boldsymbol{x}_T is fixed, the image x0\boldsymbol{x}_0 is uniquely determined. This is DDIM.

Being deterministic made the following possible.

  • Fast generation by skipping steps: images of nearly the same quality, 10-50 times faster.
  • Interpolation in latent space: smoothly connecting two xT\boldsymbol{x}_T makes the images change smoothly in a meaningful way as well.
  • Encoding and reconstructing images: xT\boldsymbol{x}_T can be computed back from an image x0\boldsymbol{x}_0, and the image can be recovered almost exactly from it.

Theory

This article uses the same notation as the DDPM article and writes Ξ±Λ‰t=∏s=1t(1βˆ’Ξ²s)\bar{\alpha}_t = \prod_{s=1}^{t}(1 - \beta_s). The paper writes this quantity as Ξ±t\alpha_t, so translate accordingly when reading the paper.

Starting point: the DDPM loss depends only on the marginals

The DDPM forward process can produce xt\boldsymbol{x}_t from x0\boldsymbol{x}_0 at any step in the following form (Eq. 4 of the paper).

xt=Ξ±Λ‰t x0+1βˆ’Ξ±Λ‰t ϡ,ϡ∼N(0,I)\boldsymbol{x}_t = \sqrt{\bar{\alpha}_t}\,\boldsymbol{x}_0 + \sqrt{1 - \bar{\alpha}_t}\,\boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I})

The DDPM training loss (squared error of the noise) uses only this q(xt∣x0)q(\boldsymbol{x}_t \mid \boldsymbol{x}_0). It does not depend on how x1,…,xT\boldsymbol{x}_1, \dots, \boldsymbol{x}_T are connected to each other.

A non-Markovian forward process

Using Οƒtβ‰₯0\sigma_t \geq 0 for the noise scale, the paper considers the following family of forward processes (Eqs. 6 and 7). Since xtβˆ’1\boldsymbol{x}_{t-1} depends not only on xt\boldsymbol{x}_t but also on x0\boldsymbol{x}_0, it is not a Markov chain.

qΟƒ(xtβˆ’1∣xt,x0)=N(Ξ±Λ‰tβˆ’1 x0+1βˆ’Ξ±Λ‰tβˆ’1βˆ’Οƒt2β‹…xtβˆ’Ξ±Λ‰t x01βˆ’Ξ±Λ‰t,Β Οƒt2I)q_\sigma(\boldsymbol{x}_{t-1} \mid \boldsymbol{x}_t, \boldsymbol{x}_0) = \mathcal{N}\left(\sqrt{\bar{\alpha}_{t-1}}\,\boldsymbol{x}_0 + \sqrt{1 - \bar{\alpha}_{t-1} - \sigma_t^2}\cdot\frac{\boldsymbol{x}_t - \sqrt{\bar{\alpha}_t}\,\boldsymbol{x}_0}{\sqrt{1 - \bar{\alpha}_t}},\ \sigma_t^2\boldsymbol{I}\right)

This mean is chosen so that qΟƒ(xt∣x0)q_\sigma(\boldsymbol{x}_t \mid \boldsymbol{x}_0) is the same as in DDPM for any choice of Οƒt\sigma_t. The paper then shows that the variational objective for this forward process equals the DDPM loss up to a constant and weighting (Theorem 1). In other words, a network trained with DDPM can be used as is for generation with any Οƒt\sigma_t.

One generation step

During generation x0\boldsymbol{x}_0 is unknown, so it is estimated from the noise predicted by the network ϡθ\boldsymbol{\epsilon}_\theta and plugged into the formula above. One update step is the following (Eq. 12).

xtβˆ’1=Ξ±Λ‰tβˆ’1(xtβˆ’1βˆ’Ξ±Λ‰t ϡθ(xt,t)Ξ±Λ‰t)⏟predictedΒ x0+1βˆ’Ξ±Λ‰tβˆ’1βˆ’Οƒt2⋅ϡθ(xt,t)⏟directionΒ pointingΒ toΒ xt+Οƒt ϡt⏟randomΒ noise\boldsymbol{x}_{t-1} = \sqrt{\bar{\alpha}_{t-1}}\underbrace{\left(\frac{\boldsymbol{x}_t - \sqrt{1 - \bar{\alpha}_t}\,\boldsymbol{\epsilon}_\theta(\boldsymbol{x}_t, t)}{\sqrt{\bar{\alpha}_t}}\right)}_{\text{predicted } \boldsymbol{x}_0} + \underbrace{\sqrt{1 - \bar{\alpha}_{t-1} - \sigma_t^2}\cdot\boldsymbol{\epsilon}_\theta(\boldsymbol{x}_t, t)}_{\text{direction pointing to } \boldsymbol{x}_t} + \underbrace{\sigma_t\,\boldsymbol{\epsilon}_t}_{\text{random noise}}

Set Ξ±Λ‰0=1\bar{\alpha}_0 = 1. The noise scale is expressed with Ξ·β‰₯0\eta \geq 0 as follows (Eq. 16).

Οƒt(Ξ·)=Ξ·1βˆ’Ξ±Λ‰tβˆ’11βˆ’Ξ±Λ‰t1βˆ’Ξ±Λ‰tΞ±Λ‰tβˆ’1\sigma_t(\eta) = \eta\sqrt{\frac{1 - \bar{\alpha}_{t-1}}{1 - \bar{\alpha}_t}}\sqrt{1 - \frac{\bar{\alpha}_t}{\bar{\alpha}_{t-1}}}
  • Ξ·=1\eta = 1: the forward process becomes a Markov chain again, and generation is the same as DDPM.
  • Ξ·=0\eta = 0: the noise term vanishes and generation becomes deterministic. This is DDIM. The "implicit" in the name indicates that, like a GAN, it is a model that produces data from latent variables by a fixed procedure (an implicit probabilistic model).

Skipping steps

Since the loss depends only on q(xt∣x0)q(\boldsymbol{x}_t \mid \boldsymbol{x}_0), the same network can be used even if the forward process is defined not on all steps 1,…,T1, \dots, T but only on a subset of steps Ο„1<Ο„2<β‹―<Ο„S\tau_1 < \tau_2 < \dots < \tau_S (Section 4.2). Generation follows Ο„S,Ο„Sβˆ’1,…,Ο„1\tau_S, \tau_{S-1}, \dots, \tau_1 in that order, replacing tt and tβˆ’1t-1 in the formula above with Ο„i\tau_i and Ο„iβˆ’1\tau_{i-1}.

Two ways of choosing the subsequence Ο„\tau are used (Appendix D.2).

ChoiceFormulaDatasets used
LinearΟ„i=⌊c iβŒ‹\tau_i = \lfloor c\,i \rfloorCelebA, LSUN
QuadraticΟ„i=⌊c i2βŒ‹\tau_i = \lfloor c\,i^2 \rfloorCIFAR-10

cc is chosen so that the last Ο„S\tau_S is close to TT.

Generation procedure

  1. Choose the number of steps SS, the subsequence Ο„\tau, and the noise scale Ξ·\eta (DDIM uses Ξ·=0\eta = 0).
  2. Draw xΟ„S∼N(0,I)\boldsymbol{x}_{\tau_S} \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I}).
  3. For i=S,…,1i = S, \dots, 1, predict the noise ϡθ(xΟ„i,Ο„i)\boldsymbol{\epsilon}_\theta(\boldsymbol{x}_{\tau_i}, \tau_i) with the network and estimate x0\boldsymbol{x}_0 from it.
  4. Compute xΟ„iβˆ’1\boldsymbol{x}_{\tau_{i-1}} with Eq. 12 (Ο„0=0\tau_0 = 0, Ξ±Λ‰0=1\bar{\alpha}_0 = 1).
  5. Output the final x0\boldsymbol{x}_0.

DDIM changes only the computation at generation time. The network architecture and training are the same as DDPM. The paper's experiments also use DDPM's trained models (CIFAR-10 and LSUN) as is.

Why steps can be skipped

The reasons DDIM produces good images with few steps can be summarized in three points.

  • It re-estimates the "destination x0\boldsymbol{x}_0" at every step: one step of Eq. 12 first estimates the finished image x0\boldsymbol{x}_0 from the current xt\boldsymbol{x}_t, then re-mixes it to match the noise level of Ο„iβˆ’1\tau_{i-1}. Even with large jumps, it reviews the finished picture each time before moving on, so it is less likely to stray. It is like walking a mountain trail with long strides while checking the direction of the summit each time.
  • No added noise, so noise does not pile up: DDPM adds random noise at every step. With few steps, the noise added per step becomes large and graininess remains in the image. DDIM adds no noise, so images come out clean even with few steps.
  • It is equivalent to solving an ordinary differential equation: one DDIM step has the same form as one Euler step for numerically solving an ordinary differential equation (ODE) (Eqs. 13 and 14). Reducing the number of steps corresponds to solving the ODE with a coarse step size, and finer steps approach the ODE solution. This ODE is the same as a special case of the "probability flow ODE" of Score SDE (Proposition 1).

Because generation is deterministic, the high-level features of the image are determined by xT\boldsymbol{x}_T alone. Generating from the same xT\boldsymbol{x}_T with different numbers of steps gave images with consistent high-level features at both 20 and 1000 steps (Figure 5). More steps only raise the quality of the details.

In DDPM, even starting from the same xT\boldsymbol{x}_T, the noise added along the way leads to very different images. In DDIM, xT\boldsymbol{x}_T and the image correspond nearly one-to-one, so xT\boldsymbol{x}_T can be treated like the latent variable of a GAN.

Experimental results

The paper used the same trained models (T=1000T = 1000) on CIFAR-10 (32 Γ— 32), CelebA (64 Γ— 64), and LSUN Bedroom and Church (256 Γ— 256), and compared them by changing only the number of generation steps SS and Ξ·\eta.

Number of steps and image quality (Table 1; FID, lower is better; Ξ·=1\eta = 1 is DDPM, Ξ·=0\eta = 0 is DDIM; Οƒ^\hat{\sigma} is the DDPM with larger noise used in the DDPM paper on CIFAR-10)

DatasetMethodS=10S = 1020501001000
CIFAR-10DDIM (Ξ·=0\eta = 0)13.366.844.674.164.04
CIFAR-10DDPM (Ξ·=1\eta = 1)41.0718.368.015.784.73
CIFAR-10DDPM (Οƒ^\hat{\sigma})367.43133.3732.729.993.17
CelebADDIM (Ξ·=0\eta = 0)17.3313.739.176.533.51
CelebADDPM (Ξ·=1\eta = 1)33.1226.0318.4813.935.98
CelebADDPM (Οƒ^\hat{\sigma})299.71183.8371.7145.203.26

The fewer the steps, the larger the gap between DDIM and DDPM. At 1000 steps, the DDPM with larger noise came out slightly ahead. The paper states that DDIM reaches quality close to the 1000-step model with 20-100 steps, which is 10-50 times faster in wall-clock time than the original DDPM. On CelebA, the FID of 100-step DDPM and 20-step DDIM were about the same. Generation time is roughly proportional to the number of steps (Figure 4).

256 Γ— 256 images (Table 3, FID; 1000-step DDPM gives 6.36 on Bedroom and 7.89 on Church)

DatasetMethodS=10S = 102050100
BedroomDDIM16.958.896.756.62
BedroomDDPM42.7822.7710.816.81
ChurchDDIM19.4512.4710.8410.58
ChurchDDPM51.5623.3711.168.27

Encoding and reconstruction (Table 2, CIFAR-10 test data; per-dimension squared error for x0→xT→x0\boldsymbol{x}_0 \to \boldsymbol{x}_T \to \boldsymbol{x}_0, solving the ODE backward and then forward; pixels in 0-1)

SS1020501002005001000
Error0.0140.00650.00230.00090.00040.00010.0001

The more steps, the more exactly the original image is recovered. DDPM adds random noise, so this kind of encoding is not possible.

The paper also showed that connecting two xT\boldsymbol{x}_T by spherical linear interpolation makes the generated images change smoothly in a meaningful way (Figure 6).

Practical notes

Keep the following points in mind when using DDIM.

  • The paper's Ξ±t\alpha_t is DDPM's Ξ±Λ‰t\bar{\alpha}_t: the DDIM paper writes the accumulated noise schedule as Ξ±t\alpha_t. It is not the same as Ξ±t=1βˆ’Ξ²t\alpha_t = 1 - \beta_t in the DDPM paper, so do not mix them up when implementing.
  • The choice of subsequence Ο„\tau changes the FID: the paper uses quadratic spacing on CIFAR-10 and linear spacing on the other datasets, getting slightly better FID with each.
  • Number of steps and image quality are a trade-off: fewer steps are faster but lower the quality. In the paper's tables, 10 steps give a much worse FID than 1000 steps, and 50-100 steps come close to 1000 steps.
  • The DDPM with larger noise breaks down with fewer steps: generation with Οƒ^\hat{\sigma} is the best at 1000 steps, but its FID worsens sharply as steps are reduced. When reducing steps, use Ξ·=0\eta = 0.

DDIM is a method for speeding up generation and does not reduce training time. Also, the fewer the steps, the wider the gap from 1000-step quality, so if you need high quality with few steps, check with FID or similar metrics while varying the number of steps before using it.

Comparison with other methods

The following compares DDIM with methods whose generation procedures are similar, from the same viewpoints.

MethodTrainingNumber of generation stepsRandom noiseCorrespondence between xT\boldsymbol{x}_T and image
DDPMSquared error of the noiseAll TT (1000) stepsAdded at every stepImages vary even for the same xT\boldsymbol{x}_T
DDIMSame as DDPMSS steps of a subsequence (e.g., 10-100)Not added (Ξ·=0\eta = 0)Nearly one-to-one; supports interpolation and encoding
Score SDE (probability flow ODE)Score learning (includes a form equivalent to DDPM)Set by the ODE solverNot addedOne-to-one; likelihood can also be computed
GANAdversarial training1β€”One-to-one

Rough guidelines for choosing:

  • To use a trained DDPM faster without retraining: DDIM is a good fit. Start with 50-100 steps and check the balance between speed and quality.
  • To get the best quality even if it takes 1000 steps: DDPM's own generation is fine.
  • To interpolate between generated images or encode images into latent variables: the deterministic DDIM is a good fit.
  • To generate high-resolution images with even less computation: combine it with a method that diffuses in latent space, such as Latent Diffusion. The Latent Diffusion paper also uses DDIM for generation in many experiments.

PyTorch example

Show code
python
import math
import torch

"""
DDIM generation from Song et al. (2021) (Eqs. 12 and 16, Appendices D.2 and D.3).
Training is the same as DDPM. eps_model is the noise-predicting network eps_model(x_t, t) trained with DDPM.
Notation follows DDPM and uses alpha_bar_t (alpha_t in the paper)
"""

T = 1000
betas = torch.linspace(1e-4, 0.02, T)                  # same beta schedule as DDPM
alpha_bars = torch.cumprod(1.0 - betas, dim=0)         # alpha_bar_1, ..., alpha_bar_T


def make_tau(S, kind="linear"):
  """Choose S steps from 1..T. Linear: tau_i = floor(c i), quadratic: tau_i = floor(c i^2)"""
  i = torch.arange(1, S + 1, dtype=torch.float64)
  if kind == "linear":
    tau = torch.floor(i * (T / S))
  else:
    tau = torch.floor(i ** 2 * (T / S ** 2))
  return tau.clamp(1, T).long().unique()                # choose c so that the last step is close to T


@torch.no_grad()
def ddim_sample(eps_model, shape, S=50, eta=0.0, kind="linear", device="cpu"):
  """eta = 0 gives DDIM (deterministic), eta = 1 gives the same generation as DDPM"""
  tau = make_tau(S, kind).tolist()
  ab = alpha_bars.to(device)
  x = torch.randn(shape, device=device)                 # x_{tau_S} ~ N(0, I)
  for i in reversed(range(len(tau))):
    t = tau[i]
    a_t = ab[t - 1]
    a_prev = ab[tau[i - 1] - 1] if i > 0 else torch.tensor(1.0, device=device)   # alpha_bar_0 = 1
    eps = eps_model(x, torch.full((shape[0],), t, device=device, dtype=torch.long))
    x0_pred = (x - (1 - a_t).sqrt() * eps) / a_t.sqrt()                         # predicted x_0 (Eq. 9)
    sigma = eta * ((1 - a_prev) / (1 - a_t)).sqrt() * (1 - a_t / a_prev).sqrt()  # Eq. 16
    direction = (1 - a_prev - sigma ** 2).clamp(min=0).sqrt() * eps            # direction pointing to x_t
    noise = sigma * torch.randn_like(x) if eta > 0 else 0.0                    # random noise (0 for DDIM)
    x = a_prev.sqrt() * x0_pred + direction + noise                            # Eq. 12
  return x.clamp(-1, 1)


@torch.no_grad()
def ddim_encode(eps_model, x0, S=50, device="cpu"):
  """Run the eta = 0 update in reverse to encode an image x_0 into x_T (solve the ODE backward)"""
  tau = [0] + make_tau(S).tolist()
  ab = torch.cat([torch.ones(1), alpha_bars]).to(device)  # ab[0] = alpha_bar_0 = 1
  x = x0
  for i in range(len(tau) - 1):
    t, t_next = tau[i], tau[i + 1]
    eps = eps_model(x, torch.full((x.shape[0],), max(t, 1), device=device, dtype=torch.long))
    x0_pred = (x - (1 - ab[t]).sqrt() * eps) / ab[t].sqrt()
    x = ab[t_next].sqrt() * x0_pred + (1 - ab[t_next]).sqrt() * eps
  return x


# Usage (pass a model trained with DDPM, put in eval() mode, as eps_model)
# eps_model.eval()
# images = ddim_sample(eps_model, (16, 3, 32, 32), S=50, eta=0.0, kind="quadratic")   # quadratic spacing for CIFAR-10

FAQ

Q. Does using DDIM require retraining the model?
A.

No. The training objective of DDIM is exactly the same as DDPM, so a noise-prediction network trained with DDPM can be used as is. Only the update formula at generation time and the number of steps followed change. The paper's experiments also use trained DDPM models.

Q. What does Ξ· in DDIM control?
A.

It sets the scale Οƒt\sigma_t of the random noise added at each generation step, as a multiple Ξ·\eta. With Ξ·=0\eta = 0, generation is deterministic with no added noise (DDIM); with Ξ·=1\eta = 1, it is the same as DDPM. In the paper's tables, the fewer the steps, the better the FID of Ξ·=0\eta = 0 was.

Q. How many steps should be used for generation?
A.

In the paper, 20-100 steps give quality close to the 1000-step model. For example, the CIFAR-10 FID was 4.04 for 1000-step DDIM, 4.16 for 100 steps, 4.67 for 50 steps, and 13.36 for 10 steps. If speed matters, try 20-50 steps; if quality matters, start around 100 steps, and check with FID or similar metrics.

References

  1. Song, J., Meng, C., & Ermon, S. (2021). Denoising Diffusion Implicit Models. ICLR 2021. arXiv:2010.02502.
  2. Ho, J., Jain, A., & Abbeel, P. (2020). Denoising Diffusion Probabilistic Models. NeurIPS 2020. arXiv:2006.11239.