vikram

diffusion, from noise up

5 min#diffusion#math#generative

here’s the whole idea in one sentence: destroying data is easy, so learn to undo the destruction one small step at a time.

that’s it. no adversary, no clever latent bottleneck. you take a picture, add a little gaussian noise, add a little more, keep going until it’s pure static. then you train a network to walk backwards. once it can, you hand it fresh static and it walks you to a picture that never existed.

i spend most of my time making these models fast enough to serve, so this post goes the whole way: the math, a training loop that fits on a screen, and where the compute actually goes.

the forward process: ruining things on purpose

pick a schedule of small numbers β1,…,βT\beta_1, \dots, \beta_T (ddpm uses T=1000T = 1000, with β\beta rising linearly from 10−410^{-4} to 0.020.02). each step shrinks the data a bit and adds noise:

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

the 1−βt\sqrt{1-\beta_t} isn’t decoration. if xt−1x_{t-1} has unit variance, then xtx_t has variance (1−βt)+βt=1(1-\beta_t) + \beta_t = 1. the signal fades while the total energy stays put, so we land on a standard gaussian instead of something that blows up.

here’s what that does to 140 points sitting on a ring of radius 2, using the exact ddpm schedule:

t = 0t = 50t = 150t = 300t = 1000
the forward process on a toy dataset. by t = 300 the ring is barely there; by t = 1000 it's indistinguishable from noise.

the shortcut: jump to any tt in one shot

you never actually run that chain step by step. write αt=1−βt\alpha_t = 1 - \beta_t and αˉt=∏s=1tαs\bar\alpha_t = \prod_{s=1}^{t} \alpha_s. since each step is “scale, then add independent gaussian noise”, the noises stack into a single gaussian:

q(xt∣x0)=N ⁣(αˉt x0,  (1−αˉt)I)⟺xt=αˉt x0+1−αˉt ϵ,    ϵ∼N(0,I)q(x_t \mid x_0) = \mathcal{N}\!\left(\sqrt{\bar\alpha_t}\, x_0,\; (1 - \bar\alpha_t)\mathbf{I}\right) \quad\Longleftrightarrow\quad x_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\, \epsilon, \;\; \epsilon \sim \mathcal{N}(0, \mathbf{I})

this one line is why diffusion training is cheap. to make a training example you sample a random tt, sample ϵ\epsilon, and mix. no simulation.

αˉt\bar\alpha_t is the dial. the ratio SNR(t)=αˉt/(1−αˉt)\mathrm{SNR}(t) = \bar\alpha_t / (1 - \bar\alpha_t) tells you how much signal survives:

tt αˉt\bar\alpha_t snr what it looks like
50 0.971 33.5 basically the data
150 0.788 3.72 blurry, but obvious
300 0.396 0.66 more noise than signal
500 0.079 0.085 a ghost
1000 0.00004 ≈ 0 static

notice how fast the linear schedule burns through the signal: half the steps are spent in the “a ghost or less” regime. that’s the observation behind the cosine schedule,1 which sets αˉt\bar\alpha_t directly so snr falls more evenly and fewer steps are wasted on pure noise.

the reverse process: what we actually want

generation means sampling from q(xt−1∣xt)q(x_{t-1} \mid x_t). that’s intractable, because it depends on the whole data distribution: given a noisy image, which clean image did it come from?

but if you also know x0x_0, it’s just algebra with gaussians:

q(xt−1∣xt,x0)=N ⁣(μ~t,  β~tI),μ~t=αˉt−1 βt1−αˉt x0+αt (1−αˉt−1)1−αˉt xt,β~t=1−αˉt−11−αˉt βtq(x_{t-1} \mid x_t, x_0) = \mathcal{N}\!\left(\tilde\mu_t,\; \tilde\beta_t \mathbf{I}\right), \qquad \tilde\mu_t = \frac{\sqrt{\bar\alpha_{t-1}}\,\beta_t}{1 - \bar\alpha_t}\, x_0 + \frac{\sqrt{\alpha_t}\,(1 - \bar\alpha_{t-1})}{1 - \bar\alpha_t}\, x_t, \qquad \tilde\beta_t = \frac{1 - \bar\alpha_{t-1}}{1 - \bar\alpha_t}\, \beta_t

so the reverse step is a gaussian whose mean needs one thing we don’t have at sampling time: x0x_0. the model’s job is to fill that gap.

the trick: predict the noise

substitute x0=(xt−1−αˉt ϵ)/αˉtx_0 = \big(x_t - \sqrt{1-\bar\alpha_t}\,\epsilon\big) / \sqrt{\bar\alpha_t} into μ~t\tilde\mu_t and it collapses to

μ~t=1αt(xt−βt1−αˉt ϵ)\tilde\mu_t = \frac{1}{\sqrt{\alpha_t}} \left( x_t - \frac{\beta_t}{\sqrt{1 - \bar\alpha_t}}\, \epsilon \right)

everything in there is known except ϵ\epsilon, the noise that was mixed in. so instead of asking a network for an image, ho et al.2 ask it for the noise: ϵθ(xt,t)≈ϵ\epsilon_\theta(x_t, t) \approx \epsilon. the variational bound on the likelihood turns into a weighted sum of squared errors on ϵ\epsilon, and dropping the weights works better in practice:

Lsimple=Et, x0, ϵ[∥ϵ−ϵθ(αˉt x0+1−αˉt ϵ,  t)∥2]\mathcal{L}_{\text{simple}} = \mathbb{E}_{t,\, x_0,\, \epsilon} \Big[ \big\| \epsilon - \epsilon_\theta\big(\sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\, \epsilon,\; t\big) \big\|^2 \Big]

a generative model whose loss is mean squared error. that’s a big part of why diffusion trains so stably compared to gans.

why this is secretly a score model

differentiate the log of q(xt∣x0)q(x_t \mid x_0):

∇xtlog⁡q(xt∣x0)=−xt−αˉt x01−αˉt=−ϵ1−αˉt\nabla_{x_t} \log q(x_t \mid x_0) = -\frac{x_t - \sqrt{\bar\alpha_t}\, x_0}{1 - \bar\alpha_t} = -\frac{\epsilon}{\sqrt{1 - \bar\alpha_t}}

so predicting noise is predicting the score, the direction that makes a sample more likely, up to a scale: ϵθ≈−1−αˉt ∇xtlog⁡p(xt)\epsilon_\theta \approx -\sqrt{1-\bar\alpha_t}\, \nabla_{x_t} \log p(x_t). sampling is gradient ascent on log-density with carefully added noise. this is the bridge to the score-based / sde view of diffusion, and it’s why “denoiser”, “score model” and “noise predictor” all name the same network.

the code

the whole thing on a 2d toy. the network sees a noisy point and a sinusoidal embedding of tt, and outputs a guess for the noise:

import math, torch, torch.nn as nn

T = 1000
betas = torch.linspace(1e-4, 0.02, T)
alphas = 1 - betas
abar = torch.cumprod(alphas, dim=0)

def q_sample(x0, t, eps):
    a = abar[t].view(-1, *[1] * (x0.dim() - 1))
    return a.sqrt() * x0 + (1 - a).sqrt() * eps

class EpsNet(nn.Module):
    def __init__(self, dim=2, hidden=128):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(dim + 16, hidden), nn.SiLU(),
            nn.Linear(hidden, hidden), nn.SiLU(),
            nn.Linear(hidden, hidden), nn.SiLU(),
            nn.Linear(hidden, dim),
        )

    def forward(self, x, t):
        freqs = torch.exp(torch.arange(8) * -math.log(1000) / 8)
        ang = t[:, None].float() * freqs[None]
        return self.net(torch.cat([x, ang.sin(), ang.cos()], dim=-1))

def train_step(model, opt, x0):
    t = torch.randint(0, T, (x0.shape[0],))
    eps = torch.randn_like(x0)
    loss = (model(q_sample(x0, t, eps), t) - eps).pow(2).mean()
    opt.zero_grad(); loss.backward(); opt.step()
    return loss.item()

and the sampler, which is just the reverse-step mean from above plus fresh noise (σt2=βt\sigma_t^2 = \beta_t):

@torch.no_grad()
def ddpm_sample(model, shape):
    x = torch.randn(shape)
    for t in reversed(range(T)):
        eps = model(x, torch.full((shape[0],), t))
        x = (x - betas[t] / (1 - abar[t]).sqrt() * eps) / alphas[t].sqrt()
        if t > 0:
            x = x + betas[t].sqrt() * torch.randn_like(x)
    return x

i trained this on the ring from the figure for 6,000 steps (batch 512, adam, lr 10−310^{-3}, on cpu). pure gaussian noise sits at an average radius of about 1.26. after 1,000 reverse steps, 2,000 samples land at radius 2.01 ± 0.06, right on the ring.

the catch: 1,000 forward passes per sample

that loop calls the network a thousand times. for a 2d toy, fine. for a video model, that’s the bill. this is the part i think about most at work, and nearly every speedup is one of a few moves.

take bigger steps (ddim). song et al.3 noticed the training objective only pins down the marginals q(xt∣x0)q(x_t \mid x_0), not the step-by-step chain, so you can sample with a different, deterministic chain using the same trained model. predict the clean point, then jump straight to an earlier tt:

x^0=xt−1−αˉt ϵθ(xt,t)αˉt,xt′=αˉt′ x^0+1−αˉt′ ϵθ(xt,t)\hat x_0 = \frac{x_t - \sqrt{1 - \bar\alpha_t}\, \epsilon_\theta(x_t, t)}{\sqrt{\bar\alpha_t}}, \qquad x_{t'} = \sqrt{\bar\alpha_{t'}}\, \hat x_0 + \sqrt{1 - \bar\alpha_{t'}}\, \epsilon_\theta(x_t, t)
@torch.no_grad()
def ddim_sample(model, shape, steps=50):
    ts = torch.linspace(T - 1, 0, steps).long()
    x = torch.randn(shape)
    for i, t in enumerate(ts):
        eps = model(x, torch.full((shape[0],), int(t)))
        x0 = (x - (1 - abar[t]).sqrt() * eps) / abar[t].sqrt()
        a_next = abar[ts[i + 1]] if i + 1 < steps else torch.tensor(1.0)
        x = a_next.sqrt() * x0 + (1 - a_next).sqrt() * eps
    return x

on the same toy model, 50 ddim steps give radius 2.01 ± 0.10: a 20× cut in network calls for a slightly fuzzier ring and no retraining. higher-order ode solvers push this further, and distillation can get you down to a handful of steps.

make each step cheaper (latents). run diffusion in an autoencoder’s latent space instead of on pixels.4 with 8× downsampling, a 512×512×3512 \times 512 \times 3 image (786,432 numbers) becomes a 64×64×464 \times 64 \times 4 latent (16,384 numbers), 48× fewer values per denoising step. video models lean on this even harder, because a time axis multiplies everything.

know what guidance costs. classifier-free guidance5 steers toward the prompt by extrapolating between a conditional and an unconditional prediction:

ϵ^=ϵθ(xt,∅)+w(ϵθ(xt,c)−ϵθ(xt,∅))\hat\epsilon = \epsilon_\theta(x_t, \varnothing) + w \big( \epsilon_\theta(x_t, c) - \epsilon_\theta(x_t, \varnothing) \big)

it works great, and it means two network evaluations per step. that’s a 2× tax hiding inside every “number of steps” you see quoted, and a reason to batch the two passes together.

what to take away

next up, i want to write about flow matching, which straightens these noisy paths so you need even fewer steps. if you spot a mistake in the math, tell me. that’s half the reason i write these.

Footnotes

  1. nichol & dhariwal, “improved denoising diffusion probabilistic models”, 2021. ↩

  2. ho, jain & abbeel, “denoising diffusion probabilistic models”, 2020. ↩

  3. song, meng & ermon, “denoising diffusion implicit models”, 2021. ↩

  4. rombach et al., “high-resolution image synthesis with latent diffusion models”, 2022. ↩

  5. ho & salimans, “classifier-free diffusion guidance”, 2022. ↩