Equations · Ho, Jain and Abbeel, “Denoising Diffusion Probabilistic Models” (2020)

The DDPM training loss (predict the noise), explained

How a diffusion model is trained: take a clean example, add a known amount of noise in one jump, and ask the network to say what noise was added. The loss is the squared error. The paper derives it from a variational bound and finds that dropping the bound's weights trains better.

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

Open in the decoder →

Term by term

  1. Et,x0,ϵ\mathbb{E}_{t, \mathbf{x}_0, \boldsymbol{\epsilon}}

    Average over a random step tt (uniform on 1,…,T1, \ldots, T), a training example x0\mathbf{x}_0 and a noise draw ϵ∼N(0,I)\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}). Each training step samples one of each per example.

  2. αˉt x0+1−αˉt ϵ\sqrt{\bar{\alpha}_t}\,\mathbf{x}_0 + \sqrt{1 - \bar{\alpha}_t}\,\boldsymbol{\epsilon}

    The noised input xt\mathbf{x}_t, made in one step with the forward process's closed form.

  3. ϵθ(xt,t)\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t)

    The network (usually a U-Net or Transformer) with parameters θ\theta: given the noisy input and the step number, it predicts the noise. Here ϵ\boldsymbol{\epsilon} is a noise vector, not a small constant.

  4. ∥…∥2\left\| \ldots \right\|^2

    The squared Euclidean norm: the sum of squared errors over all pixels. Code usually takes the mean instead, which only changes the scale.

  5. LsimpleL_{\mathrm{simple}}

    The subscript is a label: the "simple" version, without the weighting terms of the full bound.

A small worked example

Two-pixel image, drawn noise ϵ=(0.5,−1)\boldsymbol{\epsilon} = (0.5, -1), network prediction (0.3,−0.8)(0.3, -0.8). Loss: 0.22+0.22=0.080.2^2 + 0.2^2 = 0.08. Sampling then runs the network backward from pure noise, removing a little predicted noise at each of the TT steps.

In code

import torch
import torch.nn.functional as F

def ddpm_loss(model, x0, alpha_bar):
    # x0: (B, C, H, W); alpha_bar: (T,)
    t = torch.randint(0, len(alpha_bar), (x0.shape[0],))
    eps = torch.randn_like(x0)
    ab = alpha_bar[t].view(-1, 1, 1, 1)
    x_t = ab.sqrt() * x0 + (1 - ab).sqrt() * eps
    return F.mse_loss(model(x_t, t), eps)

Every symbol in it

Ex∼p[f(x)]\mathbb{E}_{x \sim p}[f(x)]Expectationxi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)dk\sqrt{d_k}Square rootxˉ\bar{x}Bar (mean)α\alphaAlphaϵ\epsilonEpsilonpθ(x)p_\theta(x)Thetax∈Rd\mathbf{x} \in \mathbb{R}^{d}Bold lowercase (vector)∥x∥2\|\mathbf{x}\|_2Normx2,  βt,  WQx^2,\; \beta^t,\; W^QSuperscript (power or label)L(θ)\mathcal{L}(\theta)Loss (ℒ)

Other equations