Diffusion Models from Scratch: Fifty Steps, If You Keep the Noise

Build a diffusion model from scratch in NumPy with hand-derived gradients. Measured over three seeds: DDIM's deterministic sampler is not worse on average, it is unreliable.

Cover Image for Diffusion Models from Scratch: Fifty Steps, If You Keep the Noise

When a diffusion model generates an image, it starts with noise and refines it over many steps. Each step calls the network again, so the wait for a sample depends partly on how many refinements the sampler uses. Reducing that count is appealing, but the samples still need to resemble the data the model learned. To understand the trade-off, it helps to work with a distribution you can draw and inspect at every stage.

Keeping noise in the sampler lets us reduce 400 network calls to 50 without a measurable quality loss here. Removing that noise makes results less reliable across training runs, even at the full step count. We build the diffusion model in NumPy on two-dimensional crescent data, derive the gradients by hand and train it to predict added noise with a mean squared error loss. Following the forward and reverse processes connects that objective to sampling; comparisons then measure network calls and sample quality together.

Let's Build It

Open this in Google Colab and run it top to bottom. It builds the noise schedule, an MLP denoiser with its backward pass written out, the training loop, both samplers, and the measurement that compares them. About two minutes on a CPU.

Open In Colab

import numpy as np


def two_moons(n, noise=0.08, seed=0):
    """Two interleaving crescents, standardised.

    Every failure mode of a generative model is visible on this data: a missing
    moon, a bridge across the gap that the data does not have, or a cloud that has
    forgotten there was a gap at all."""
    rng = np.random.default_rng(seed)
    m = n // 2
    a = np.linspace(0, np.pi, m)
    outer = np.stack([np.cos(a), np.sin(a)], 1)
    inner = np.stack([1 - np.cos(a), 0.5 - np.sin(a)], 1)
    X = np.concatenate([outer, inner]) + rng.normal(0, noise, (2 * m, 2))
    return (X - X.mean(0)) / X.std(0)


X = two_moons(3000)
print("data:", X.shape)

T = 400
beta = np.linspace(1e-4 * 1000 / T, 0.02 * 1000 / T, T)   # noise added at step t
alpha = 1 - beta
abar = np.cumprod(alpha)                                  # signal left at step t
abar_prev = np.concatenate([[1.0], abar[:-1]])
print(f"signal left at t = T: {abar[-1]:.1e}")            # must reach ~0


def q_sample(x0, t, eps):
    """The closed form. Any noise level in one line, no chain to walk."""
    return np.sqrt(abar[t])[:, None] * x0 + np.sqrt(1 - abar[t])[:, None] * eps


def time_features(t, dim=32):
    """Sinusoids of the timestep. A raw t is a poor input to an MLP: nearby steps
    should look similar and distant ones separable, which is what this gives."""
    half = dim // 2
    freqs = np.exp(-np.log(10000.0) * np.arange(half) / half)
    ang = np.asarray(t, float)[:, None] * freqs[None, :]
    return np.concatenate([np.cos(ang), np.sin(ang)], 1)


class Dense:
    def __init__(self, n_in, n_out, rng):
        self.W = rng.normal(0, np.sqrt(2 / n_in), (n_in, n_out))
        self.b = np.zeros(n_out)

    def forward(self, x):
        self.x = x
        return x @ self.W + self.b

    def backward(self, g):
        self.gW, self.gb = self.x.T @ g, g.sum(0)
        return g @ self.W.T


class Denoiser:
    """eps_hat = f(x_t, t). A plain MLP over [x_t, time_features(t)], SiLU inside.

    Nothing here is diffusion-specific. The method's content is in what the
    network is asked to predict, not in its shape."""

    def __init__(self, dim, hidden=128, depth=3, t_dim=32, seed=0):
        rng = np.random.default_rng(seed)
        self.t_dim = t_dim
        widths = [dim + t_dim] + [hidden] * depth + [dim]
        self.L = [Dense(a, b, rng) for a, b in zip(widths[:-1], widths[1:])]
        self.L[-1].W *= 0.1        # start near zero, a good guess for unit noise

    def forward(self, x, t):
        h = np.concatenate([x, time_features(t, self.t_dim)], 1)
        self.a = []
        for i, layer in enumerate(self.L):
            h = layer.forward(h)
            if i < len(self.L) - 1:
                s = 1 / (1 + np.exp(-np.clip(h, -60, 60)))
                self.a.append((h, s))
                h = h * s
        return h

    def backward(self, g):
        for i in reversed(range(len(self.L))):
            if i < len(self.L) - 1:
                pre, s = self.a[i]
                g = g * (s * (1 + pre * (1 - s)))          # d/dz [z * sigmoid(z)]
            g = self.L[i].backward(g)

    def params_and_grads(self):
        return [(l.W, l.gW) for l in self.L] + [(l.b, l.gb) for l in self.L]


def train(model, X, steps=4000, lr=2e-3, batch=256, seed=0):
    rng = np.random.default_rng(seed)
    n, d = X.shape
    # Adam state has to be built from the parameters alone: the gradients do not
    # exist until the first backward pass.
    params = [l.W for l in model.L] + [l.b for l in model.L]
    state = [(np.zeros_like(p), np.zeros_like(p)) for p in params]
    for step in range(1, steps + 1):
        x0 = X[rng.integers(0, n, batch)]
        # --- the whole method, three lines ---
        t = rng.integers(0, T, batch)                 # a random noise level
        eps = rng.standard_normal(x0.shape)           # the noise that was added
        xt = q_sample(x0, t, eps)                     # jump straight there
        # -------------------------------------
        diff = model.forward(xt, t) - eps             # ask the net which noise
        model.backward(2 * diff / (batch * d))        # d(MSE)/d(output)

        for (p, g), (m, v) in zip(model.params_and_grads(), state):
            m *= 0.9
            m += 0.1 * g
            v *= 0.999
            v += 0.001 * g**2
            p -= lr * (m / (1 - 0.9**step)) / (np.sqrt(v / (1 - 0.999**step)) + 1e-8)
    return model


def ddpm_sample(model, n, dim, seed=0):
    """Ancestral sampling: walk back down the chain the model was trained on,
    injecting fresh noise at every step. All T network calls."""
    rng = np.random.default_rng(seed)
    x = rng.standard_normal((n, dim))
    for t in reversed(range(T)):
        eps = model.forward(x, np.full(n, t))
        x = (x - beta[t] / np.sqrt(1 - abar[t]) * eps) / np.sqrt(alpha[t])
        if t > 0:
            var = beta[t] * (1 - abar_prev[t]) / (1 - abar[t])
            x += np.sqrt(var) * rng.standard_normal(x.shape)
    return x


def ddim_sample(model, n, dim, n_steps=50, eta=0.0, seed=0):
    """DDIM: the same trained network, a shorter path.

    The step is rewritten in terms of the predicted clean sample, which stays
    valid on any subsequence of timesteps. eta scales the injected noise: eta = 0
    is deterministic, eta = 1 recovers ancestral sampling on that subsequence."""
    rng = np.random.default_rng(seed)
    x = rng.standard_normal((n, dim))
    taus = np.linspace(0, T - 1, n_steps).round().astype(int)[::-1]
    for i, t in enumerate(taus):
        prev = taus[i + 1] if i + 1 < len(taus) else -1
        ab_t = abar[t]
        ab_prev = abar[prev] if prev >= 0 else 1.0
        eps = model.forward(x, np.full(n, t))
        x0 = (x - np.sqrt(1 - ab_t) * eps) / np.sqrt(ab_t)
        sigma = (eta * np.sqrt((1 - ab_prev) / (1 - ab_t) * (1 - ab_t / ab_prev))
                 if prev >= 0 else 0.0)
        x = np.sqrt(ab_prev) * x0 + np.sqrt(max(1 - ab_prev - sigma**2, 0)) * eps
        if sigma > 0:
            x += sigma * rng.standard_normal(x.shape)
    return x


def energy_distance(a, b, cap=1500, seed=0):
    """A distance between two samples, not between two points. Zero only when the
    distributions match. Unlike eyeing a scatter plot it notices a missing mode or
    a cloud that is too fat, and it needs no density and no fitted judge."""
    rng = np.random.default_rng(seed)
    a = a[rng.choice(len(a), cap, replace=False)] if len(a) > cap else a
    b = b[rng.choice(len(b), cap, replace=False)] if len(b) > cap else b
    d = lambda p, q: np.sqrt(((p[:, None, :] - q[None, :, :]) ** 2).sum(-1))
    return 2 * d(a, b).mean() - d(a, a).mean() - d(b, b).mean()


model = train(Denoiser(2), X)
holdout = two_moons(3000, seed=99)
print(f"{'sampler':<24}{'net calls':>10}{'energy':>10}")
print(f"{'real data (the floor)':<24}{'-':>10}{energy_distance(X, holdout):>10.4f}")
runs = [("ancestral", T, ddpm_sample(model, 3000, 2, seed=7))]
for k in (10, 50):
    runs.append((f"DDIM, eta = 0", k, ddim_sample(model, 3000, 2, n_steps=k, seed=7)))
    runs.append((f"DDIM, eta = 1", k, ddim_sample(model, 3000, 2, n_steps=k, eta=1.0, seed=7)))
for label, k, s in runs:
    print(f"{label:<24}{k:>10}{energy_distance(s, holdout):>10.4f}")

The table it prints is the whole point of the post:

sampler                  net calls    energy
real data (the floor)            -    0.0001
ancestral                      400    0.0049
DDIM, eta = 0                   10    0.1649
DDIM, eta = 1                   10    0.0590
DDIM, eta = 0                   50    0.0963
DDIM, eta = 1                   50    0.0081

Read down the eta = 0 rows and the story is the familiar one: fewer steps, worse samples. Read across at 50 calls and a different story appears. The two samplers there did the same amount of work and one of them is 12 times closer to the data.

That is one training run, on one seed. Hold on to the size of that gap rather than the number itself, because it is not stable across runs, and what makes it unstable turns out to be the most useful thing in this post.

What Just Happened?

The forward process, and the line that makes it cheap

The forward process adds a little Gaussian noise at each of TT steps:

q(xt∣xt−1)=N ⁣(xt; 1−βt xt−1, βtI)q(x_t \mid x_{t-1}) = \mathcal{N}\!\left(x_t;\ \sqrt{1 - \beta_t}\, x_{t-1},\ \beta_t I\right)

Written that way it is a chain, and reaching step 300 means taking 300 steps. That would make training hopeless. But a Gaussian perturbed by a Gaussian is a Gaussian, and the composition telescopes. Writing αt=1−βt\alpha_t = 1 - \beta_t and αˉt=∏s≤tαs\bar\alpha_t = \prod_{s \le t} \alpha_s:

q(xt∣x0)=N ⁣(xt; αˉt x0, (1−αˉt)I)⟹xt=αˉt x0+1−αˉt ϵq(x_t \mid x_0) = \mathcal{N}\!\left(x_t;\ \sqrt{\bar\alpha_t}\, x_0,\ (1 - \bar\alpha_t) I\right) \qquad\Longrightarrow\qquad x_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\, \epsilon

That is the single most important line in the method. Any noise level is one multiplication away from the clean sample, so training can pick a timestep at random and jump straight to it rather than simulating the chain. αˉt\bar\alpha_t is the fraction of the original signal still present at step t, running from nearly 1 at the start to nearly 0 at the end, and a schedule is nothing more than the choice of how it gets there.

The forward process under two schedules

The requirement on that choice is easy to state and easy to get wrong: αˉT\bar\alpha_T has to reach approximately zero. If it does not, xTx_T is not noise, sampling starts from a distribution the network never saw, and the samples are wrong in a way no amount of training corrects. Printing abar[-1] is the single most useful diagnostic in the whole method.

The noise as the target

The reverse step needs the posterior q(xt−1∣xt,x0)q(x_{t-1} \mid x_t, x_0), which is Gaussian and has a closed form. The problem is that it depends on x0x_0, which is exactly what is unknown at sampling time. So the network estimates it.

It could estimate x0x_0 directly. Instead it estimates the noise, and the closed form says these are the same quantity in different clothes:

x^0=xt−1−αˉt ϵ^αˉt\hat{x}_0 = \frac{x_t - \sqrt{1 - \bar\alpha_t}\, \hat\epsilon}{\sqrt{\bar\alpha_t}}

Given xtx_t and t, either determines the other exactly. What differs is the loss. The noise target has unit variance at every timestep by construction, so a mean squared error weights all timesteps equally. The x0x_0 target does not: at high noise levels recovering the clean sample is close to impossible and the squared error there is enormous, so those timesteps dominate the gradient and the easy ones are ignored. Trained both ways, the noise parameterisation scores 0.0037 against 0.0841.

The gradients, by hand

There is little to derive, which is the point. The loss is

L=Et, x0, ϵ[∥ϵ−ϵθ(xt,t)∥2]L = \mathbb{E}_{t,\, x_0,\, \epsilon}\left[\left\| \epsilon - \epsilon_\theta(x_t, t) \right\|^2\right]

a plain mean squared error, so ∂L/∂ϵ^=2(ϵ^−ϵ)/n\partial L / \partial \hat\epsilon = 2(\hat\epsilon - \epsilon)/n and everything after that is ordinary backpropagation through an MLP. There is no variational bound to differentiate, no reparameterisation trick to be careful with, and no second network. Compare that with the variational autoencoder in the previous post, where the KL term, the sampling step and the likelihood each contributed a term that had to be worked out separately.

The one piece of machinery that is not obvious is how t enters the network. A raw integer is a poor input: the network would have to carve hundreds of distinct behaviours out of a single nearly-constant number. Feeding a bank of sinusoids at different frequencies instead makes nearby timesteps look similar and distant ones separable, which is the same construction as the positional encoding in a transformer.

The Fast Sampler, Measured

Sampling is where a diffusion model spends its money. Training touched one random timestep per example; generating touches every step in the chain, in order, and each step is a full forward pass.

The reverse process pulling noise back into two crescents

That is 400 network calls for one batch, and the reason a great deal of engineering effort has gone into needing fewer. DDIM is the standard answer. It rewrites the reverse step so that it depends only on the current state and the network's estimate of the clean sample, which makes the step valid on any subsequence of timesteps rather than only on adjacent ones. You can therefore walk 400 down to 0 in fifty jumps instead of 400. It also introduces a parameter, η\eta, that scales the noise injected at each step: at η=1\eta = 1 the sampler is ancestral sampling on the subsequence it walks, and at η=0\eta = 0 it injects nothing and is fully deterministic.

Almost every published step-count comparison uses η=0\eta = 0, because determinism is useful in its own right. It gives a reproducible map from a seed to an image and makes interpolation between two seeds meaningful. On this data it is also the expensive half of the trade.

Sample quality against sampling cost

samplernetwork callsenergy distance
real data, held out-0.0001
ancestral4000.0037
DDIM, η=0\eta = 0100.0653
DDIM, η=0\eta = 0500.0352
DDIM, η=0\eta = 04000.0327
DDIM, η=1\eta = 1100.0392
DDIM, η=1\eta = 1500.0051
DDIM, η=1\eta = 14000.0037

The pattern is not a simple speed-quality trade. At every budget from twenty calls upward the deterministic sampler is beaten by the stochastic one running on fewer calls. Adding steps to it stops helping almost immediately: 0.0352 at fifty calls and 0.0327 at four hundred, an eight-fold increase in compute for nothing. Whatever it is losing, it is not losing it to the step count.

The averages in that table hide the more useful finding, and the giveaway is in the error bars: the deterministic sampler's spread is wider than its own mean. Per seed, at the full step count:

seedancestral, 400 callsDDIM, η=0\eta = 0, 400 calls
00.00490.0883
10.00190.0058
20.00440.0041

Two of the three runs are fine. One is 18 times worse than ancestral sampling, and it drags the mean from a median of 0.0058 up to 0.0327. Nothing distinguishes these three runs except the initialisation: same architecture, same data, same schedule, same number of gradient steps.

So the honest claim is not that the deterministic sampler is reliably worse. It is that the deterministic sampler is unreliable. Its typical run is close to ancestral sampling, and it has a failure mode that ancestral sampling does not have. That also reconciles the two diagnostics, which had looked inconsistent with an eight-fold gap in the mean: the off-manifold rate and the density error both describe the typical case, and the typical case is unremarkable.

sampleroff-manifolddensity error
real data, held out1.2%0.090
ancestral, 400 calls4.1%0.177
DDIM, η=0\eta = 0, 400 calls5.3%0.236
DDIM, η=1\eta = 1, 50 calls3.9%0.193

What the failing run looks like is worth seeing, because it is not what the theory would predict. The tempting story is that a deterministic sampler cannot separate the two crescents: it is a continuous map from a connected Gaussian, so it ought to leave a bridge across the gap. The scatter plot says otherwise. The crescents are cleanly separated and there is no bridge. What the samples are is lumpy, piled into clumps along the arcs with thin patches between them, which is a distribution with the right support and the wrong density.

That points at accumulation rather than topology. The network's estimate of the noise is not exact, and at η=0\eta = 0 each trajectory is a deterministic path: an error at one step moves the state, the next step is evaluated at the moved state, and the error compounds all the way down. Nearby starting points get funnelled into the same places, which is the clumping. Whether a given training run lands in a regime where that compounding matters appears to be a lottery, which is what the seed table shows. Injecting noise removes the lottery. Each step becomes a draw rather than a point map, so errors are resampled away instead of accumulated, and η=1\eta = 1 at fifty calls stays close to ancestral sampling on every seed: 0.0081, 0.0017 and 0.0056 against 0.0049, 0.0019 and 0.0044.

The η\eta dial in the right-hand panel is the same statement without the argument. Quality improves monotonically as the injected noise is turned back up, from 0.0352 at η=0\eta = 0 to 0.0051 at η=1\eta = 1, holding the budget at fifty calls throughout.

None of this is a general indictment of DDIM, and three seeds on a two-dimensional problem is far too small an experiment to put a frequency on the failure. What is worth carrying away is the shape of the risk rather than its rate. A deterministic sampler has no mechanism for correcting its own errors, so when the learned noise estimate is wrong in a way that compounds, nothing in the procedure pushes back. In the several thousand dimensions of an image the same accumulation happens and is far harder to see, which is an argument for running the check where the failure is legible rather than an argument that it does not occur.

One check before drawing conclusions from any of this. Everything above trains for 12,000 steps. At a third of that budget ancestral sampling scores 0.0110 and the deterministic sampler at full step count scores 0.0209. Tripling the training improves ancestral sampling 2.9 times over and does not improve the deterministic sampler at all. Whatever the deterministic sampler is losing, it is not something more training recovers, which is worth establishing before reading anything else into the gap.

Going Deeper

The schedule is a design decision

The schedule is the sequence of βt\beta_t values, and it is a real design decision rather than a hyperparameter to leave alone. The linear schedule used above is the one from Ho, Jain and Abbeel (2020). The usual recommendation is to replace it with the cosine schedule of Nichol and Dhariwal (2021), which defines αˉt\bar\alpha_t directly as a shifted cosine and reads the βt\beta_t off it.

Their argument for it is specific and worth reading before adopting it. On 32x32 images the linear schedule destroys the signal too early: by roughly three quarters of the way through the chain the image is already indistinguishable from noise, so the remaining timesteps contribute nothing and the model spends capacity on them. The cosine schedule spreads the destruction more evenly.

The forward-process figure earlier in the post shows the effect they describe. At t = 50 the linear schedule has already reduced the two crescents to a single blob, while the cosine schedule still has both arcs clearly separated. Whatever else is true, the cosine schedule does keep structure alive for longer.

That argument is about images. On two-dimensional data the extra structure does not turn into better samples, and the measurement says so.

Linear against cosine schedules

Ancestral sampling does not care which schedule it is given. It scores 0.0037 +- 0.0013 on the linear schedule and 0.0026 +- 0.0014 on the cosine one, a difference the seed spread does not resolve. DDIM does not survive the swap. At fifty calls it scores 2.5 on the cosine schedule against 0.0352 on the linear one, roughly 70 times further from the data, and the cause is arithmetic rather than modelling. The cosine schedule drives αˉT\bar\alpha_T to 1.5 x 10^-8 against the linear schedule's 3.6 x 10^-5, and DDIM's estimate of the clean sample divides by αˉt\sqrt{\bar\alpha_t}. At the first reverse step that turns any error in the predicted noise into an error about 8,116 times larger, against 166 on the linear schedule. Ancestral sampling never forms that quotient. It divides by αt\sqrt{\alpha_t}, a per-step quantity that stays close to one, which is why it is untouched.

The lesson generalises past this particular schedule. A default carried over from a different data regime is a hypothesis, not a setting, and this one is cheap to test.

Prediction error against noise level

A natural assumption about the denoiser is that its job gets harder as the noise rises. The opposite is true, and seeing why makes the method clearer.

Prediction error against timestep

At a late timestep, xtx_t is almost pure noise. Predicting the noise is then close to trivial: output roughly what you were given. What is impossible at that timestep is saying what the clean sample was, because almost nothing of it survives. At an early timestep the situation inverts. xtx_t is almost the clean sample, so recovering it is easy, while the small amount of noise mixed in is nearly unrecoverable.

Both curves in the left panel are the same network measured two ways, related exactly by the closed form above. Neither is a statement about model capacity. They describe what information is present in the input at each noise level, and no network can do better.

The right-hand end of that orange curve is also where the cosine schedule came apart. Recovering x0x_0 means dividing by αˉt\sqrt{\bar\alpha_t}, which is why the implied clean sample is hopeless at high t on any schedule. DDIM forms that quotient at every step; ancestral sampling never does. Push αˉT\bar\alpha_T three orders of magnitude lower, as the cosine schedule does, and a quantity that was merely inaccurate becomes numerically useless.

This is the concrete reason the noise parameterisation is preferred. The quantity being predicted has unit variance at every timestep, so no part of the chain dominates the mean squared error.

The same code, on digits

Nothing above is specific to two dimensions. Swapping the data for scikit-learn's 8x8 handwritten digits, scaled to [-1, 1], and widening the hidden layer is the whole change: the schedule, the training loop and both samplers are untouched.

The energy distance is less useful here. In 64 dimensions pairwise distances concentrate and the number stops being interpretable. So this section uses the instrument from the variational autoencoder post instead: decode a large batch of samples, label each one with a logistic regression fitted to the real digits, and look at the histogram of classes that come back. That classifier is 98.5% accurate on the real digits, which is the sense in which it is entitled to an opinion about the generated ones.

Digits generated by the same code

DDIM at twenty calls reaches all ten digit classes on every seed, with a coverage entropy of 2.22 against the data's own 2.30. That is worth comparing with the previous post, where a variational autoencoder with its KL term switched off reached 3.3 classes out of ten. The forward process here is fixed rather than learned, so there is no term to switch off and no way to make that particular mistake.

Coverage is a measure of diversity, though, and it is worth being clear about what it does not say. It counts how many classes the samples spread across, not how good any individual sample looks, and the two middle panels show why that distinction matters. Ancestral sampling at 400 calls produces clean strokes. DDIM at 20 calls reaches the same ten classes and the same coverage entropy while producing visibly speckled digits. The 2-D measurement said the fast deterministic sampler distributes mass badly; here that shows up as pixel noise, and no coverage number would have reported it. Instruments measure what they measure.

A diffusion model is a stack of variational autoencoders

The connection to the previous post is exact rather than a loose analogy, and it explains most of what is different about training this model.

A VAE has one encoder and one decoder. The encoder is learned, and almost all of the difficulty in training one comes from that: the encoder can place its codes anywhere, including far outside the region the prior reaches, and the KL term exists to stop it. Set that term to zero and the model still reconstructs well while generating almost nothing, which is the measurement the previous post is built around.

A diffusion model has 400 encoders and 400 decoders. Every encoder is the same fixed Gaussian step, chosen in advance, with no parameters. Only the decoders are learned. Two consequences follow directly. There is no KL term to balance, because the forward process is guaranteed by construction to end at the prior; and there is no posterior collapse, because there is no encoder to collapse. The price is that generation now needs one decoder pass per step instead of one in total, which is the entire subject of the sampler measurement above.

The variational bound is still there underneath. Ho, Jain and Abbeel (2020) derive it, then show that a particular parameterisation and weighting reduce it to the mean squared error used here. The bound is what explains why the squared error is the right thing to minimise.

The conditioning that is missing

Everything above generates unconditionally: draw noise, get a sample, take what you are given. Real systems condition on something, usually text, and the mechanism is simpler than its reputation.

Append the condition to the network's input and train as before, dropping the condition at random on some fraction of examples so that one network learns both the conditional and the unconditional task. At sampling time, evaluate both and step in the direction that leads away from the unconditional prediction:

ϵ^=ϵ^uncond+w(ϵ^cond−ϵ^uncond)\hat\epsilon = \hat\epsilon_{\text{uncond}} + w \left( \hat\epsilon_{\text{cond}} - \hat\epsilon_{\text{uncond}} \right)

with w>1w > 1 exaggerating the difference. That is classifier-free guidance (Ho and Salimans, 2022), and the name is historical: the previous method needed a separately trained classifier of noisy images to supply a gradient, and this one does not. On the two-crescent data the condition would be which crescent a point came from, and it is the fourth exercise in the notebook.

Where This Comes From

The formulation is Sohl-Dickstein et al. (2015), which framed generation as reversing a diffusion process borrowed from non-equilibrium thermodynamics. It was, by the authors' own framing, a statistical-physics argument first and a generative model second, and for five years it stayed a curiosity.

Ho, Jain and Abbeel (2020) made it work, and the paper is worth reading for what it removes rather than what it adds. The variational bound of the 2015 paper is still there in section 3, but the paper shows that under a particular parameterisation, predicting the noise rather than the mean, and a particular weighting of the per-timestep terms, the whole bound collapses to an unweighted mean squared error. The simplification is the contribution. It is also why the training loop above is three lines rather than thirty.

Song, Meng and Ermon (2021) gave the sampler used here. Their observation is that the training objective never depends on the forward process being Markov, only on its marginals, so a whole family of processes share the same trained network and some of them are far cheaper to reverse. eta indexes that family.

Nichol and Dhariwal (2021) introduced the cosine schedule measured above, and their reasoning is specific: on 32x32 images the linear schedule destroys information too early, leaving the last quarter of the forward process doing nothing useful. That argument is about the dimensionality and structure of image data and does not transfer to two dimensions, which is what the measurement here shows.

Ho and Salimans (2022) is the conditioning method everything downstream uses. It trains one network on both the conditional and unconditional task by dropping the label at random, then extrapolates away from the unconditional prediction at sampling time. There is no separate classifier, which is the point of the name.

Interactive Tools

  • Distribution Explorer - the Gaussian whose closure under addition is what makes the closed form above possible, alongside the distributions that lack it.
  • Gradient Descent Visualizer - the optimiser doing the work in the training loop, on surfaces where you can watch it.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions