Sign in

Diffusion

Denoising diffusion probabilistic model

A denoising diffusion model: it learns to remove a little noise at a time, then generates data by denoising pure noise.

Overview

Turning data into noise is easy: keep adding small amounts of random noise until nothing of the original is left. A diffusion model learns to run that process backwards. During training it takes a real sample, adds a known amount of noise, and asks a network to say what noise was added. Because the noise was chosen by the trainer, the right answer is always available. To generate, the model starts from pure noise and repeatedly subtracts the noise the network predicts, one small step at a time, until a clean sample remains. Many small easy steps replace one hard jump from noise to data.

A short history

Jascha Sohl-Dickstein and colleagues proposed diffusion models in 2015, borrowing the idea of gradually destroying and restoring structure from non-equilibrium thermodynamics. Jonathan Ho, Ajay Jain and Pieter Abbeel showed in 2020 that a simple noise prediction loss gives image quality rivalling GANs with far more stable training. From 2022, diffusion became the basis of widely used text-to-image systems such as Stable Diffusion and DALL-E 2.

How it works

  1. Fix a schedule of noise variances β1,…,βT\beta_1, \dots, \beta_T that rises linearly from beta_start to beta_end.
  2. Training step: pick a real row x0\mathbf{x}_0, a random step tt and Gaussian noise ε\boldsymbol{\varepsilon}.
  3. Form the noised row in one shot: xt=αˉt x0+1−αˉt ε\mathbf{x}_t = \sqrt{\bar{\alpha}_t}\,\mathbf{x}_0 + \sqrt{1 - \bar{\alpha}_t}\,\boldsymbol{\varepsilon}.
  4. Ask the network to predict ε\boldsymbol{\varepsilon} from xt\mathbf{x}_t and an embedding of tt, and take a gradient step on the squared error.
  5. Sampling: start from xT\mathbf{x}_T drawn from a standard normal distribution.
  6. For t=Tt = T down to 1, predict the noise, compute the mean of the previous step from it, and add fresh noise of variance σt2\sigma_t^2 (none at the last step).
  7. Convert the result back to the units of the training data.

Watch out for

  • If beta_end or n_steps is too small, xT\mathbf{x}_T still carries traces of the data, so starting the sampler from pure noise does not match what the network saw in training.
  • Sampling needs one network call per step, so generation is far slower than a single forward pass. This template has no fast sampler.
  • The network must tell the steps apart. Without the step embedding it would have to guess the noise level, and samples come out blurred between modes.
  • This is a small DDPM for rows of a few numbers, with an MLP in place of a U-Net and no conditioning or guidance. It is not an image model.

Use cases

When to use it

To learn how diffusion models work, to generate synthetic rows that follow a low-dimensional distribution with several modes, or as a reference to test a framework implementation against.

In industry

Creative tools
Text-to-image generation, as in Stable Diffusion, where a prompt guides the denoising of random noise into a picture.
Photo editing
Inpainting and outpainting: regenerating a masked part of an image so that it matches its surroundings.
Drug discovery
Generating candidate molecular or protein structures; RFdiffusion is a published example for protein design.

Choosing it: what must hold

  • A large set of examples of the data you want to generate.
  • Tolerance for slow sampling: generation takes many network evaluations, not one.
  • Substantial computing power for training on anything beyond toy data.

When to choose something else

IfUse instead
You need samples in a single fast forward passA GAN
You want a compact latent code for each input as well as generationA variational autoencoder (VAE)
The data is textAn autoregressive Transformer language model

Math foundations

  1. One forward step

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

    Each step shrinks the sample slightly and adds Gaussian noise of variance βt\beta_t. The shrinking keeps the overall variance from growing.

  2. Jumping straight to step t

    xt=αˉt x0+1−αˉt ε,αˉt=∏s=1t(1−βs),ε∼N(0,I)\mathbf{x}_t = \sqrt{\bar{\alpha}_t}\,\mathbf{x}_0 + \sqrt{1 - \bar{\alpha}_t}\,\boldsymbol{\varepsilon}, \qquad \bar{\alpha}_t = \prod_{s=1}^{t} (1 - \beta_s), \quad \boldsymbol{\varepsilon} \sim \mathcal{N}(\mathbf{0}, I)

    Composing tt Gaussian steps gives one Gaussian, so a noised sample for any step can be drawn directly. αˉt\bar{\alpha}_t is the share of signal variance left, and it falls towards 0.

  3. Training loss

    L=Ex0, t, ε[∥ε−εθ(xt,t)∥2]\mathcal{L} = \mathbb{E}_{\mathbf{x}_0,\, t,\, \boldsymbol{\varepsilon}} \Big[ \big\| \boldsymbol{\varepsilon} - \boldsymbol{\varepsilon}_\theta(\mathbf{x}_t, t) \big\|^2 \Big]

    The network is scored on how well it recovers the noise that was mixed in. This is the simplified DDPM objective, an ordinary regression loss.

  4. Mean of the reverse step

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

    The best guess for xt−1\mathbf{x}_{t-1}: remove this step's share of the predicted noise, then undo the shrinking.

  5. Ancestral sampling

    xt−1=μθ(xt,t)+σt z,z∼N(0,I)\mathbf{x}_{t-1} = \boldsymbol{\mu}_\theta(\mathbf{x}_t, t) + \sigma_t\, \mathbf{z}, \qquad \mathbf{z} \sim \mathcal{N}(\mathbf{0}, I)

    The reverse step is itself random: fresh noise is added after each denoising move, except at the final step. This keeps the samples as varied as the data.

  6. The sampling variance

    σt2=β~t=βt 1−αˉt−11−αˉtorσt2=βt\sigma_t^2 = \tilde{\beta}_t = \beta_t\, \frac{1 - \bar{\alpha}_{t-1}}{1 - \bar{\alpha}_t} \qquad \text{or} \qquad \sigma_t^2 = \beta_t

    The two standard choices, selected by variance. The first is the variance of the true reverse step when x0\mathbf{x}_0 is known, and it is the smaller of the two.

Symbols

x0\mathbf{x}_0
a clean data row (standardised)
xt\mathbf{x}_t
the row after t noising steps
TT
n_steps, the number of noising steps
βt\beta_t
noise variance added at step t
αˉt\bar{\alpha}_t
product of (1 - beta) up to step t: the share of signal variance left
ε\boldsymbol{\varepsilon}
the Gaussian noise mixed into the sample
εθ\boldsymbol{\varepsilon}_\theta
the network's prediction of that noise
μθ\boldsymbol{\mu}_\theta
mean of the learned reverse step
σt2\sigma_t^2
variance of the noise added back during sampling
β~t\tilde{\beta}_t
the posterior variance of the reverse step
z\mathbf{z}
fresh standard normal noise used in sampling

Worked by hand

A one-dimensional example with two steps, β1=0.1\beta_1 = 0.1 and β2=0.2\beta_2 = 0.2. Noise the value x0=2x_0 = 2 to step 2 with ε=0.5\varepsilon = 0.5, then find the posterior variance at step 2.

αˉ1=0.9,αˉ2=0.9×0.8=0.72\bar{\alpha}_1 = 0.9, \qquad \bar{\alpha}_2 = 0.9 \times 0.8 = 0.72
x2=0.72⋅2+0.28⋅0.5=1.697+0.265=1.962x_2 = \sqrt{0.72} \cdot 2 + \sqrt{0.28} \cdot 0.5 = 1.697 + 0.265 = 1.962
β~2=0.2⋅1−0.91−0.72=0.020.28=0.0714\tilde{\beta}_2 = 0.2 \cdot \frac{1 - 0.9}{1 - 0.72} = \frac{0.02}{0.28} = 0.0714

After two steps 72 percent of the signal variance is left. The posterior variance of 0.071 is well below β2=0.2\beta_2 = 0.2, which shows how much smaller the first variance choice can be at early steps.

Visual example

Loading the example.

Try this

  • Press Start over, then Step a few times to watch the data dissolve one small step at a time.
  • Lower beta_end to 0.04 and choose the box for the noise at step T: about a third of the signal is still there, so the left side never becomes pure noise.
  • Switch the sampling variance to beta and compare how much the reverse paths jitter on their way to the bumps.

Code sample

import numpy as np
from impl import Diffusion
from config import DiffusionConfig

rng = np.random.default_rng(0)
centres = np.array([[-2.0, 0.0], [2.0, 1.0]])
X = centres[rng.integers(0, 2, size=1000)] + rng.normal(0, 0.3, size=(1000, 2))   # two clusters
model = Diffusion(DiffusionConfig(train_steps=1500)).fit(X)
samples = model.sample(500, seed=1)                                               # (500, 2) new points
print(round(float(np.mean(model.loss_history[:50])), 2), "->", round(float(np.mean(model.loss_history[-200:])), 2))
print(samples[:3].round(2))
Read the implementation (158 lines)
"""Diffusion: a denoising diffusion probabilistic model (DDPM) for small vector data.

NumPy only, manual backpropagation. The forward process adds Gaussian noise to the data over `n_steps` steps
until nothing but noise is left; a network is trained to predict the noise that was added; sampling starts
from pure noise and removes the predicted noise step by step.

    forward:   x_t = sqrt(abar_t) x_0 + sqrt(1 - abar_t) eps,   eps ~ N(0, I),  abar_t = prod_{s<=t} (1 - beta_s)
    training:  minimise || eps - eps_theta(x_t, t) ||^2 at a random step t
    sampling:  x_{t-1} = (x_t - beta_t / sqrt(1 - abar_t) * eps_theta(x_t, t)) / sqrt(1 - beta_t) + sigma_t z
"""
from __future__ import annotations

import numpy as np

try:
    from .config import DiffusionConfig
except ImportError:  # run from the template's own folder
    from config import DiffusionConfig


class _MLP:
    """A dense network with (leaky) ReLU hidden layers and a linear output, with its own Adam state."""

    def __init__(self, sizes: list, rng: np.random.Generator, slope: float = 0.0) -> None:
        self.slope = slope  # negative-side slope of the hidden activation; 0 is plain ReLU
        self.W = [rng.normal(0.0, np.sqrt(2.0 / a), size=(a, b)) for a, b in zip(sizes[:-1], sizes[1:])]
        self.b = [np.zeros(b) for b in sizes[1:]]
        self._m = [np.zeros_like(p) for p in self.params()]
        self._v = [np.zeros_like(p) for p in self.params()]
        self._step = 0

    def params(self) -> list:
        return self.W + self.b

    def forward(self, x: np.ndarray) -> np.ndarray:
        """x: (n, sizes[0]) -> (n, sizes[-1]). Keeps the activations for `backward`."""
        self._acts = [x]
        for i, (W, b) in enumerate(zip(self.W, self.b)):
            z = self._acts[-1] @ W + b
            self._acts.append(z if i == len(self.W) - 1 else np.where(z > 0, z, self.slope * z))
        return self._acts[-1]

    def backward(self, d: np.ndarray) -> tuple[np.ndarray, list]:
        """d: gradient at the output of the last `forward`. Returns (gradient at the input, parameter gradients)."""
        gW, gb = [None] * len(self.W), [None] * len(self.W)
        for i in range(len(self.W) - 1, -1, -1):
            if i < len(self.W) - 1:
                d = d * np.where(self._acts[i + 1] > 0, 1.0, self.slope)
            gW[i] = self._acts[i].T @ d
            gb[i] = d.sum(axis=0)
            d = d @ self.W[i].T
        return d, gW + gb

    def adam_step(self, grads: list, lr: float, beta1: float = 0.9) -> None:
        self._step += 1
        for p, g, m, v in zip(self.params(), grads, self._m, self._v):
            m *= beta1
            m += (1 - beta1) * g
            v *= 0.999
            v += 0.001 * g * g
            p -= lr * (m / (1 - beta1**self._step)) / (np.sqrt(v / (1 - 0.999**self._step)) + 1e-8)


class Diffusion:
    """DDPM over rows of a table: `fit(X)` learns the distribution of the rows, `sample(n)` draws new ones.

    Steps are numbered 0 .. n_steps - 1 in the arrays below (step index t holds the paper's step t + 1).
    The data is standardised per column inside the model, so the noise schedule suits any scale.
    """

    def __init__(self, config: DiffusionConfig | None = None) -> None:
        self.config = cfg = config or DiffusionConfig()
        self.betas = np.linspace(cfg.beta_start, cfg.beta_end, cfg.n_steps)
        self.alphas = 1.0 - self.betas
        self.alpha_bars = np.cumprod(self.alphas)
        self.mean_: np.ndarray | float = 0.0   # column means and stds of the training data
        self.std_: np.ndarray | float = 1.0
        self.net: _MLP | None = None
        self.loss_history: list[float] = []

    # ---- forward (noising) process ---------------------------------------------------------------------
    def q_sample(self, x0: np.ndarray, t: np.ndarray, noise: np.ndarray) -> np.ndarray:
        """Noised data at step t in closed form. x0, noise: (n, d). t: (n,) step indices. Returns (n, d)."""
        ab = self.alpha_bars[t][:, None]
        return np.sqrt(ab) * x0 + np.sqrt(1.0 - ab) * noise

    def time_embedding(self, t: np.ndarray) -> np.ndarray:
        """Sinusoidal embedding of the step index. t: (n,) -> (n, time_embedding_size)."""
        half = self.config.time_embedding_size // 2
        freqs = np.exp(-np.log(1000.0) * np.arange(half) / max(half - 1, 1))
        angles = (np.asarray(t, dtype=float)[:, None] + 1.0) * freqs[None, :] * (1000.0 / self.config.n_steps)
        return np.hstack([np.sin(angles), np.cos(angles)])

    # ---- the noise-prediction network ------------------------------------------------------------------
    def _init_net(self, n_features: int) -> None:
        cfg = self.config
        rng = np.random.default_rng(cfg.seed)
        self.net = _MLP([n_features + 2 * (cfg.time_embedding_size // 2), cfg.hidden_size, cfg.hidden_size, n_features], rng)

    def predict(self, x_t: np.ndarray, t: np.ndarray) -> np.ndarray:
        """The network's estimate of the noise inside x_t (standardised units). x_t: (n, d). t: (n,). -> (n, d)."""
        return self.net.forward(np.hstack([np.asarray(x_t, dtype=float), self.time_embedding(t)]))

    def loss_and_grads(self, x0: np.ndarray, t: np.ndarray, noise: np.ndarray) -> tuple[float, list]:
        """Mean squared error between the true and the predicted noise, and the network gradients.

        x0: (n, d) standardised data. t: (n,) step indices. noise: (n, d) the noise to add.
        """
        diff = self.predict(self.q_sample(x0, t, noise), t) - noise
        loss = float(np.mean(diff**2))
        _, grads = self.net.backward(2.0 * diff / diff.size)
        return loss, grads

    def fit(self, X: np.ndarray) -> "Diffusion":
        """Train the noise predictor on the rows of X. X: (n, d)."""
        cfg = self.config
        X = np.asarray(X, dtype=float)
        if X.ndim != 2:
            raise ValueError(f"X must be 2-d (rows, features), got shape {X.shape}")
        self.mean_ = X.mean(axis=0)
        self.std_ = np.where(X.std(axis=0) > 0, X.std(axis=0), 1.0)
        Z = (X - self.mean_) / self.std_
        self._init_net(X.shape[1])
        rng = np.random.default_rng(cfg.seed + 1)
        self.loss_history = []
        for _ in range(cfg.train_steps):
            rows = rng.integers(0, len(Z), size=cfg.batch_size)
            t = rng.integers(0, cfg.n_steps, size=cfg.batch_size)
            loss, grads = self.loss_and_grads(Z[rows], t, rng.normal(size=(cfg.batch_size, Z.shape[1])))
            self.net.adam_step(grads, cfg.learning_rate)
            self.loss_history.append(loss)
        return self

    # ---- reverse (sampling) process --------------------------------------------------------------------
    def sample(self, n: int, seed: int = 0, noise_fn=None, n_features: int | None = None) -> np.ndarray:
        """Draw n new rows by ancestral sampling, in the units of the training data. Returns (n, d).

        noise_fn: optional replacement for the trained network, called as noise_fn(x_t, t) -> predicted noise.
                  With it the sampler can be run (and checked) without training; pass `n_features` as well.
        """
        cfg = self.config
        predict = noise_fn or self.predict
        if noise_fn is None and self.net is None:
            raise ValueError("call fit before sample, or pass noise_fn")
        d = n_features if n_features is not None else len(self.net.b[-1])
        rng = np.random.default_rng(seed)
        x = rng.normal(size=(n, d))
        for step in range(cfg.n_steps - 1, -1, -1):
            beta, ab = self.betas[step], self.alpha_bars[step]
            eps = predict(x, np.full(n, step))
            x = (x - beta / np.sqrt(1.0 - ab) * eps) / np.sqrt(1.0 - beta)
            if step > 0:
                if cfg.variance == "posterior":
                    sigma2 = beta * (1.0 - self.alpha_bars[step - 1]) / (1.0 - ab)
                else:
                    sigma2 = beta
                x = x + np.sqrt(sigma2) * rng.normal(size=(n, d))
        return x * self.std_ + self.mean_
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Create a Diffusion model and call q_sample on one point for steps 0, 10, 25 and 49 with the same noise, and watch the signal fade as alpha_bars falls. Then fit on the two-cluster data from the README, draw 500 points with sample, and check that both clusters appear in about the right shares.

Check on learning

  1. Why train the network to predict the noise and not to produce a clean sample from pure noise in one step?
    A way to think about it

    Compare how well defined each target is. For a slightly noised point the answer is nearly unique. For pure noise, ask which of the many data points is the right answer.

  2. The closed form lets training jump to any step directly. What would training cost without it, and what property of Gaussian noise makes it possible?
    A way to think about it

    Think about what you would have to simulate for step 40. Then recall what the sum of independent Gaussian variables is.

  3. What would the samples look like if beta_end were so small that αˉT\bar{\alpha}_T stayed at 0.5?
    A way to think about it

    Compare the distribution of noised training points at the last step with the standard normal the sampler starts from. The network has never seen inputs like the latter.

  4. The sampler adds fresh noise after every step except the last. What would happen to the variety of the samples if it never added noise?
    A way to think about it

    Without added noise every step is a fixed function of the start. Consider whether following the predicted mean alone pulls points toward typical values.

  5. A GAN generates in one network call and this model needs 50. What does the diffusion model get in return for that cost?
    A way to think about it

    Compare the two training setups: a regression loss with a fixed target against a game between two networks. Think about stability and about covering several modes.