Skip to content
Generative models and multimodal Advanced 40 min read

Diffusion models

A diffusion model learns to generate data by learning to remove noise. Training is almost embarrassingly simple: take a clean example, add a random amount of Gaussian noise, and train a network to predict the noise you added. Sampling runs that denoiser hundreds or a few dozen times, starting from pure noise. The idea to walk away with: destroying structure gradually turns one impossible problem (sample from the data distribution) into a thousand easy ones (remove a little noise), each of which is plain regression.

10,000 ft

Diffusion models are the engine of modern image, video and audio generation: DALL·E 2, Imagen, Stable Diffusion, Sora-class video models and many speech systems are diffusion models or their close cousins (latent diffusion, flow matching). They displaced GANs around 2021 because they train with a stable regression loss, cover all the modes of the data and scale predictably. Conceptually they sit at a crossroads. They are deep latent-variable models trained on an ELBO, with a fixed encoder that adds noise; they are score-based models that learn the gradient of the log-density and sample with Langevin-like dynamics (score matching); and they are continuous normalising flows once you write sampling as an ordinary differential equation. Their reach now extends to protein structure (AlphaFold 3's structure module is a diffusion model), robot control (Diffusion Policy) and even text, where masked diffusion language models compete with autoregressive LLMs at the 8-billion-parameter scale.

2,000 ft

A fixed forward process destroys data in \(T\) small Gaussian steps; a learned reverse process undoes it one step at a time.

Forward noising (fixed) and reverse denoising (learned)
Forward noising (fixed) and reverse denoising (learned). x₀ data, x₁ slightly noisy, x_t half signal, x_T ≈ N(0, I), denoiser ε_θ(x_t, t) U-Net or transformer, q: add noise, q, start here to sample, p_θ: remove a little noiseForward noising (fixed) and reverse denoising (learned). x₀ data, x₁ slightly noisy, x_t half signal, x_T ≈ N(0, I), denoiser ε_θ(x_t, t) U-Net or transformer, q: add noise, q, start here to sample, p_θ: remove a little noise

  1. Forward: \(\mathbf x_t = \sqrt{\bar\alpha_t}\,\mathbf x_0 + \sqrt{1-\bar\alpha_t}\,\boldsymbol\epsilon\), with a schedule \(\bar\alpha_t\) falling from 1 to almost 0. You can jump to any \(t\) in one line, no simulation.
  2. Train: pick a data point, a random \(t\) and fresh noise \(\boldsymbol\epsilon\); regress \(\epsilon_\theta(\mathbf x_t, t)\) onto \(\boldsymbol\epsilon\) with mean squared error. That is the whole loss.
  3. Why it works: the best possible noise prediction is \(\mathbb E[\boldsymbol\epsilon\mid\mathbf x_t]\), which is (up to scale) the score \(\nabla\log p_t(\mathbf x_t)\), the direction towards more probable data.
  4. Sample: start from \(\mathbf x_T\sim\mathcal N(\mathbf 0, I)\), repeatedly estimate the noise and step to a slightly cleaner \(\mathbf x_{t-1}\).
  5. Faster: deterministic samplers (DDIM, ODE solvers) take 20–50 steps instead of 1,000; distillation gets to 1–4.
  6. Theory: the loss is a re-weighted ELBO, so a diffusion model is a hierarchical VAE with \(T\) latent layers and a fixed encoder.

Ground level

Creating noise from data is easy

Take an image and add a little Gaussian noise. Do it again, and again. After enough steps you have pure static, and every image in the world ends up as the same thing: a sample from \(\mathcal N(\mathbf 0, I)\). That direction requires no learning. The bet of diffusion models, first made by Sohl-Dickstein et al. (2015) and inspired by non-equilibrium thermodynamics, is that the reverse direction is learnable if each step is small. A single small step of noise is almost invertible: given a slightly noisy image, you can make a very good guess at the slightly less noisy one. Chain a thousand such guesses and you have walked from static to an image.

Compare the alternatives. A GAN must map noise to data in one shot, learned through a game. A VAE does it in one shot with a learned encoder, and the encoder–decoder pair must agree. A diffusion model breaks generation into many easy denoising problems, and its "encoder" is fixed noise, so there is nothing to agree on and nothing to collapse.

The forward process

Choose a variance schedule \(\beta_1,\dots,\beta_T\) of small numbers. Each forward step shrinks the signal slightly and adds noise:

\[ q(\mathbf x_t\mid\mathbf x_{t-1}) = \mathcal N\big(\sqrt{1-\beta_t}\,\mathbf x_{t-1},\ \beta_t I\big). \]

The shrink factor \(\sqrt{1-\beta_t}\) is there so that the total variance stays at 1 if the data has unit variance: the process is variance-preserving. Because a sum of Gaussians is Gaussian, steps compose. Write \(\alpha_t = 1-\beta_t\) and \(\bar\alpha_t = \prod_{s\le t}\alpha_s\); then

\[ q(\mathbf x_t\mid\mathbf x_0) = \mathcal N\big(\sqrt{\bar\alpha_t}\,\mathbf x_0,\ (1-\bar\alpha_t) I\big), \qquad\text{i.e.}\qquad \mathbf x_t = \sqrt{\bar\alpha_t}\,\mathbf x_0 + \sqrt{1-\bar\alpha_t}\,\boldsymbol\epsilon,\ \ \boldsymbol\epsilon\sim\mathcal N(\mathbf 0, I). \]

This closed form is what makes training cheap: to produce a training example at step 700 you do not simulate 700 steps, you mix signal and noise in one line. The single number that describes how much information survives is the signal-to-noise ratio, \(\mathrm{SNR}(t) = \bar\alpha_t/(1-\bar\alpha_t)\).

Worked example. Ho, Jain and Abbeel (2020) used \(T = 1000\) and \(\beta_t\) rising linearly from \(10^{-4}\) to \(0.02\). Nichol and Dhariwal (2021) proposed a cosine schedule. Computed in Build it:

\(t\) linear \(\bar\alpha_t\) \(\sqrt{\bar\alpha_t}\) SNR (dB) cosine \(\bar\alpha_t\) \(\sqrt{\bar\alpha_t}\) SNR (dB)
1 0.99990 0.9999 40.0 0.99996 1.0000 43.8
50 0.97102 0.9854 15.3 0.99201 0.9960 20.9
250 0.52409 0.7239 0.4 0.84701 0.9203 7.4
500 0.07859 0.2803 −10.7 0.49384 0.7027 −0.1
750 0.00335 0.0579 −24.7 0.14427 0.3798 −7.7
1000 0.00004 0.0064 −43.9 ≈ 0 ≈ 0 −86.1

Under the linear schedule, \(\mathbf x_{500} = 0.28\,\mathbf x_0 + 0.96\,\boldsymbol\epsilon\): by the halfway point, noise already dominates, and 327 of the 1,000 steps have \(\bar\alpha_t < 0.01\), which wastes them on near-pure noise. The cosine schedule keeps \(\bar\alpha_t\) near 0.5 at the midpoint and spends only 65 steps in that regime. Note also that the linear schedule never quite reaches pure noise: 0.64% of the signal amplitude survives at \(t = T\). Lin et al. (2023) showed that this mismatch between training (where a trace of the image remains) and sampling (which starts from pure noise) is why some Stable Diffusion versions could not generate very dark or very bright images, and fixed it by rescaling the schedule to zero terminal SNR.

t = 0t = 100t = 250t = 500t = 1000 ᾱ = 1ᾱ = 0.90ᾱ = 0.52ᾱ = 0.08ᾱ ≈ 0 −303
The exact noisy marginal q(x_t) of a three-mode mixture (weights 0.2, 0.5, 0.3; modes at −3, 0, 3) under the linear schedule. Reading downwards is the forward process; reading upwards is generation. The modes blur together by t ≈ 250 and the distribution is Gaussian by t = 1000. The denoiser's job at each level is to sharpen one row into the row above it.

The reverse process, and why small steps make it Gaussian

Generation needs \(q(\mathbf x_{t-1}\mid\mathbf x_t)\): given a noisy point, where did it come from one step earlier? By Bayes' rule this is proportional to \(q(\mathbf x_t\mid\mathbf x_{t-1})\,q(\mathbf x_{t-1})\), and the second factor is the intractable noisy data distribution. Two facts rescue us.

  1. For small \(\beta_t\) the reverse step is nearly Gaussian. The forward kernel is a very narrow Gaussian, so over its width \(q(\mathbf x_{t-1})\) is approximately log-linear, and a Gaussian times a log-linear function is a shifted Gaussian (a classical result for diffusion processes that Sohl-Dickstein et al. invoke). So we model \(p_\theta(\mathbf x_{t-1}\mid\mathbf x_t) = \mathcal N(\boldsymbol\mu_\theta(\mathbf x_t, t), \sigma_t^2 I)\) and only have to learn its mean. This is why diffusion needs many steps: with big steps the true reverse kernel is multimodal and a Gaussian cannot represent it.
  2. Conditioned on \(\mathbf x_0\), the reverse step is exactly Gaussian and known. \(q(\mathbf x_{t-1}\mid\mathbf x_t, \mathbf x_0) = \mathcal N(\tilde{\boldsymbol\mu}_t, \tilde\beta_t I)\) with a closed-form mean that blends \(\mathbf x_0\) and \(\mathbf x_t\) (derived in The maths). We do not know \(\mathbf x_0\) at sampling time, but during training we do, and that gives a regression target.

The model's mean therefore needs a guess of \(\mathbf x_0\), or equivalently of the noise \(\boldsymbol\epsilon\) that was added, since \(\mathbf x_0 = (\mathbf x_t - \sqrt{1-\bar\alpha_t}\,\boldsymbol\epsilon)/\sqrt{\bar\alpha_t}\). Ho et al. chose to predict \(\boldsymbol\epsilon\) and found it worked markedly better than predicting the mean directly. Substituting gives the update

\[ \boldsymbol\mu_\theta(\mathbf x_t, t) = \frac{1}{\sqrt{\alpha_t}}\Big(\mathbf x_t - \frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\epsilon_\theta(\mathbf x_t, t)\Big). \]

Training is regression onto the noise

The full objective is an ELBO with one KL term per step, and each KL is a weighted squared error between true and predicted noise. Ho et al. dropped the weights and got better samples:

\[ \mathcal L_\text{simple}(\theta) = \mathbb E_{\mathbf x_0,\ t\sim U\{1..T\},\ \boldsymbol\epsilon\sim\mathcal N(\mathbf 0, I)}\Big[\big\lVert\boldsymbol\epsilon - \epsilon_\theta\big(\sqrt{\bar\alpha_t}\,\mathbf x_0 + \sqrt{1-\bar\alpha_t}\,\boldsymbol\epsilon,\ t\big)\big\rVert^2\Big]. \]
One training step (Ho et al., Algorithm 1)
One training step (Ho et al., Algorithm 1). x₀ from the dataset, t ~ Uniform, ε ~ N(0, I), x_t = √ᾱ_t x₀ + √(1−ᾱ_t) ε, ε_θ(x_t, t), ‖ε − ε_θ‖² backprop, step, targetOne training step (Ho et al., Algorithm 1). x₀ from the dataset, t ~ Uniform, ε ~ N(0, I), x_t = √ᾱ_t x₀ + √(1−ᾱ_t) ε, ε_θ(x_t, t), ‖ε − ε_θ‖² backprop, step, target

Three things make this the easiest generative objective to train. There is no adversary, so no game dynamics. There is no encoder to learn, so no posterior collapse or holes in latent space. And the loss never needs a sample from the model, so training costs one forward and one backward pass per example, exactly like a classifier.

What the network is really learning

The best possible noise prediction is the conditional mean \(\mathbb E[\boldsymbol\epsilon\mid\mathbf x_t]\). Given a noisy image, the network averages over every clean image that could have produced it. At high noise that average is a blurry prototype ("something face-shaped"); at low noise it is a sharp image. Because \(\mathbf x_t\) is Gaussian-corrupted, this average is also the score: \(\mathbb E[\boldsymbol\epsilon\mid\mathbf x_t] = -\sqrt{1-\bar\alpha_t}\,\nabla_{\mathbf x_t}\log p_t(\mathbf x_t)\) (Tweedie's formula). The denoiser is a field of arrows pointing towards higher data density, one field per noise level. Score matching starts from that view.

The loss does not go to zero, and it should not. For the three-mode mixture in Build it, the perfect denoiser, computed in closed form, still has an expected loss of 0.3029: at high noise levels the noise is genuinely unpredictable. A small MLP trained from scratch in NumPy reaches 0.3034 on the same held-out set and generates the mixture with mode weights 0.207, 0.497 and 0.296 against the true 0.2, 0.5 and 0.3.

Sampling: ancestral steps, and DDIM

Ancestral sampling (Ho et al., Algorithm 2) runs the learned chain:

\[ \mathbf x_{t-1} = \frac{1}{\sqrt{\alpha_t}}\Big(\mathbf x_t - \frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\epsilon_\theta(\mathbf x_t, t)\Big) + \sigma_t\mathbf z,\qquad \mathbf z\sim\mathcal N(\mathbf 0, I), \]

with \(\sigma_t^2 = \beta_t\) or \(\tilde\beta_t\) (both work). That is 1,000 network evaluations per sample. Reading the update: subtract a scaled estimate of the noise, rescale, then add a little fresh noise back. The fresh noise is not a bug; it keeps the sample on the right distribution while earlier mistakes are corrected.

DDIM (Song, Meng and Ermon, 2020) observed that the training loss only depends on the marginals \(q(\mathbf x_t\mid\mathbf x_0)\), not on the forward process being Markov. Many processes share those marginals, including a deterministic one. Its update first estimates the clean sample, then re-noises it to the next level using the predicted noise instead of fresh noise:

\[ \hat{\mathbf x}_0 = \frac{\mathbf x_t - \sqrt{1-\bar\alpha_t}\,\epsilon_\theta(\mathbf x_t, t)}{\sqrt{\bar\alpha_t}},\qquad \mathbf x_{t'} = \sqrt{\bar\alpha_{t'}}\,\hat{\mathbf x}_0 + \sqrt{1-\bar\alpha_{t'}-\sigma^2}\,\epsilon_\theta(\mathbf x_t, t) + \sigma\mathbf z . \]

With \(\sigma = 0\) this maps each starting noise to one image (so you can interpolate between noise vectors and get meaningful image interpolations), it allows jumping from \(t\) to any earlier \(t'\), and it is a discretisation of an ordinary differential equation, the probability-flow ODE (score and flow matching). The DDIM paper reports 10× to 50× faster sampling than DDPM for comparable quality. A parameter \(\eta\in[0,1]\) interpolates: \(\eta = 1\) recovers DDPM-like stochastic sampling.

Worked example: steps versus quality. To separate the sampler from the network, Build it uses the exact optimal denoiser for the three-mode mixture, so every error below comes from taking too few steps:

Steps Sampler Mode weights (target 0.200 / 0.500 / 0.300) Std of right mode (target 0.300) \(W_1\) to data
1000 stochastic (\(\eta = 1\)) 0.201 / 0.502 / 0.297 0.295 0.016
1000 DDIM (\(\eta = 0\)) 0.203 / 0.500 / 0.296 0.298 0.021
100 stochastic 0.188 / 0.520 / 0.291 0.280 0.067
100 DDIM 0.195 / 0.508 / 0.297 0.295 0.034
20 stochastic 0.174 / 0.548 / 0.278 0.251 0.179
20 DDIM 0.188 / 0.526 / 0.286 0.282 0.112
5 stochastic 0.086 / 0.724 / 0.190 0.478 0.684
5 DDIM 0.122 / 0.655 / 0.224 0.481 0.497

With few steps the deterministic sampler wins clearly. The failure at five steps has a characteristic shape: mass collapses towards the middle mode, because one big step from noise lands near the average of the plausible clean points, \(\mathbb E[\mathbf x_0\mid\mathbf x_t]\), which sits between modes. That is the same blur you see in VAE samples, and it is exactly what fast samplers and distillation must overcome.

What to predict: ε, x₀, v or the score

Given \(\mathbf x_t\) and \(t\), predicting \(\boldsymbol\epsilon\), predicting \(\mathbf x_0\) and predicting the score are linear reparameterisations of one another. They differ in how errors are weighted:

  • ε-prediction (DDPM) works well at low and medium noise, but at very high noise \(\mathbf x_t \approx \boldsymbol\epsilon\), so the network can nearly copy its input while its implied \(\hat{\mathbf x}_0 = (\mathbf x_t - \sqrt{1-\bar\alpha_t}\hat{\boldsymbol\epsilon})/\sqrt{\bar\alpha_t}\) amplifies tiny errors by \(1/\sqrt{\bar\alpha_t}\), which is 156 at the end of the linear schedule.
  • x₀-prediction is well behaved at high noise but poorly conditioned at low noise.
  • v-prediction (Salimans and Ho, 2022), \(\mathbf v = \sqrt{\bar\alpha_t}\,\boldsymbol\epsilon - \sqrt{1-\bar\alpha_t}\,\mathbf x_0\), blends the two so the target has unit variance at every noise level. It made few-step distillation stable and is used in many production models.
  • Velocity for flow matching, \(\boldsymbol\epsilon - \mathbf x_0\) on a straight-line path, is the same idea with a different schedule; see flow matching.

Karras et al. (2022, "EDM") went further and derived input and output scalings ("preconditioning") that keep the network's inputs and targets at unit variance for every noise level, a second-order Heun sampler, and a noise-level distribution for training. Together these reached FID 1.79 on class-conditional CIFAR-10 with 35 network evaluations per image.

Noise schedules and loss weighting, seen through the SNR

Kingma et al. (2021, Variational Diffusion Models) showed that the noise schedule and the loss weighting can be described with one function, the log-SNR \(\lambda(t) = \log\mathrm{SNR}(t)\). In continuous time the ELBO depends on the schedule only through its endpoints: the shape in between does not change the likelihood objective, only the variance of its Monte Carlo estimate. Everything practitioners tune, \(\epsilon\)- versus \(\mathbf v\)-prediction, uniform versus logit-normal sampling of \(t\), cosine versus linear schedules, is equivalent to choosing a weighting over noise levels. Kingma and Gao (2023) showed that every common diffusion objective is a weighted integral of ELBOs over noise levels, and that when the weighting is monotonic the objective is the ELBO of the data augmented with Gaussian noise.

Which noise levels matter? Natural images have power spectra that fall off steeply with frequency, so Gaussian noise drowns fine detail first and coarse structure last. Denoising from high noise to low noise therefore generates coarse to fine: layout first, then shapes, then texture. Dieleman calls this "spectral autoregression". It also explains why higher resolutions need schedules shifted towards more noise: at 1024×1024 the same noise level leaves more of the coarse structure intact than at 256×256, so the model needs to train more at high noise (Hoogeboom et al., 2023; SD3's timestep shift, covered in latent diffusion).

Architectures

The denoiser maps a tensor to a tensor of the same shape, conditioned on \(t\):

  • U-Net (DDPM through Stable Diffusion 2 and SDXL): a convolutional encoder–decoder with skip connections between matching resolutions, residual blocks, group normalisation, self-attention at low resolutions (16×16 in DDPM), and the timestep injected via a sinusoidal embedding into every residual block. Dhariwal and Nichol's improved U-Net (more attention heads, adaptive group normalisation) produced Diffusion Models Beat GANs on Image Synthesis (2021): FID 4.59 on ImageNet 256×256 with classifier guidance, 3.94 with an upsampling stage.
  • Diffusion transformer, DiT (Peebles and Xie, 2022): patchify the (latent) image into tokens and run a plain transformer, conditioning on \(t\) and the class through adaptive layer norm. FID fell steadily with model compute, reaching 2.27 on ImageNet 256×256, and transformers became the backbone of SD3, FLUX-class image models and video models.

Conditioning on text, classes or images and the guidance that makes it work are the subject of latent diffusion and guidance.

Making sampling fast

A thousand network calls per sample is the main cost of diffusion. Three families of fixes:

  1. Better ODE/SDE solvers: DDIM, Heun (EDM), and DPM-Solver (Lu et al., 2022), which exploits the semi-linear structure of the diffusion ODE to sample well in around 10 steps. No retraining.
  2. Distillation into fewer steps: progressive distillation (Salimans and Ho, 2022) repeatedly trains a student to match two teacher steps with one, halving the step count each round, down to 4 steps with FID 3.0 on CIFAR-10. Consistency models (Song et al., 2023) learn to map any point on an ODE trajectory directly to its endpoint, reaching FID 3.55 on CIFAR-10 in one step; continuous-time consistency models (Lu and Song, 2024) reached FID 1.88 on ImageNet 512×512 in two steps.
  3. Adversarial and distribution-matching distillation: add a GAN loss or match the student's output distribution to the teacher's (Adversarial Diffusion Distillation behind SDXL Turbo; Distribution Matching Distillation) to get usable one- to four-step generators.

Beyond images

The recipe needs only a way to add Gaussian noise and a network to remove it, so it travels: audio (waveform and spectrogram diffusion, speech and audio); video (diffusion over space-time latents, video and world models); 3-D molecules and proteins (AlphaFold 3 generates atom coordinates with a diffusion module); robot actions (Diffusion Policy, Chi et al., 2023, denoises action sequences conditioned on observations, embodied AI). For discrete data such as text, Gaussian noise is replaced by a corruption process on tokens, most successfully masking: D3PM (Austin et al., 2021) set up the framework, SEDD (Lou, Meng and Ermon, 2023) and MDLM (Sahoo et al., 2024) brought its perplexity close to autoregressive models, and LLaDA (Nie et al., 2025) trained an 8-billion-parameter masked diffusion language model that its authors report competitive with LLaMA 3 8B on in-context learning. Diffusion LLMs generate many tokens in parallel per step, which is their attraction for latency (Inception Labs' Mercury, 2025).

History

Who found it

2015: Jascha Sohl-Dickstein, Eric Weiss, Niru Maheswaranathan and Surya Ganguli, Deep Unsupervised Learning using Nonequilibrium Thermodynamics, define the forward and reverse processes and the ELBO; samples are modest and the paper is little noticed for five years. 2019: Yang Song and Stefano Ermon, Generative Modeling by Estimating Gradients of the Data Distribution, learn scores at many noise levels and sample with annealed Langevin dynamics (score matching). 2020: Jonathan Ho, Ajay Jain and Pieter Abbeel, Denoising Diffusion Probabilistic Models, connect the two lines, introduce the ε-prediction loss and reach FID 3.17 on CIFAR-10, the field's starting gun. Song et al.'s SDE paper (late 2020, ICLR 2021) unifies everything in continuous time. 2021: improved DDPM and the cosine schedule; Diffusion Models Beat GANs; classifier guidance; latent diffusion. 2022: classifier-free guidance, DALL·E 2, Imagen, Stable Diffusion's open release, EDM, DiT, flow matching and rectified flow. 2023–2025: consistency models and few-step distillation; SD3 and FLUX move to rectified-flow transformers; video diffusion at scale; diffusion language models. The ideas that won were simple: a regression loss, a fixed noising process, and patience at sampling time.

First principles

Why must it look like this? Start from what we want and what we refuse to do.

1. We want maximum likelihood (or a bound on it). Like a VAE, a diffusion model is a latent-variable model, \(p_\theta(\mathbf x_0) = \int p_\theta(\mathbf x_{0:T})\,d\mathbf x_{1:T}\), trained on an ELBO. Likelihood-based training minimises the forward KL from data to model, which is mass-covering: diffusion models do not drop modes, the property GANs lacked.

2. We refuse to learn an encoder. A VAE's weak point is the learned posterior and the balancing act between encoder and decoder. Fix the "encoder" to Gaussian noising and the posterior \(q(\mathbf x_{1:T}\mid\mathbf x_0)\) is known exactly; only the decoder (the reverse process) is learned. The cost is that the latents are as large as the data and carry no compressed meaning, which is why practical systems run diffusion inside an autoencoder's latent space (latent diffusion).

3. Why Gaussian noise? Three reasons, each necessary. Gaussians compose in closed form, so any \(\mathbf x_t\) can be sampled in one step and training needs no simulation. The posterior \(q(\mathbf x_{t-1}\mid\mathbf x_t,\mathbf x_0)\) is Gaussian, so every KL in the ELBO is a squared error. And the end of the process, \(\mathcal N(\mathbf 0, I)\), is easy to sample and does not depend on the data.

4. Why many small steps? The reverse of a small Gaussian step is approximately Gaussian; the reverse of a large one is not (it inherits the multimodality of the data). Generation is split into steps small enough that a unimodal Gaussian is a good model of each. The worked example above shows what happens if you ignore this: five steps produce samples that fall between modes.

5. Why does denoising teach density? Because for Gaussian corruption the optimal denoiser is the score: \(\mathbb E[\mathbf x_0\mid\mathbf x_t] = \big(\mathbf x_t + (1-\bar\alpha_t)\nabla\log p_t(\mathbf x_t)\big)/\sqrt{\bar\alpha_t}\) (Tweedie). Learning to denoise at every noise level is learning the gradient of the log-density at every smoothing scale. The noise levels solve a problem the plain score has: real data lies near a low-dimensional manifold, where the density is not even defined off the manifold; adding noise fills the space and makes the score well defined everywhere, with large noise guiding samples from far away and small noise refining them.

What breaks if you change things? Remove the shrink factor \(\sqrt{1-\beta_t}\) and the variance explodes (that is the "variance-exploding" family, which works if you plan for it). Train only on low noise levels and sampling from pure noise fails. Use too few steps with an ancestral sampler and you get blurry, mode-averaged samples. Make the forward process non-Gaussian and you lose the closed forms (unless you move to discrete corruption, which brings its own closed forms).

The maths

Setup and shapes. Data \(\mathbf x_0\in\mathbb R^D\) (an image of shape \((C, H, W)\) flattened, or kept as a tensor; the network maps shape \((B, C, H, W)\) plus timesteps \((B,)\) to \((B, C, H, W)\)). Schedule \(\beta_t\in(0,1)\), \(\alpha_t = 1-\beta_t\), \(\bar\alpha_t = \prod_{s=1}^t\alpha_s\), \(\bar\alpha_0 = 1\).

Forward marginal. By induction: if \(\mathbf x_{t-1} = \sqrt{\bar\alpha_{t-1}}\mathbf x_0 + \sqrt{1-\bar\alpha_{t-1}}\boldsymbol\epsilon'\), then \(\mathbf x_t = \sqrt{\alpha_t}\mathbf x_{t-1} + \sqrt{\beta_t}\boldsymbol\epsilon''\) has mean \(\sqrt{\bar\alpha_t}\mathbf x_0\) and noise variance \(\alpha_t(1-\bar\alpha_{t-1}) + \beta_t = 1-\bar\alpha_t\).

Derivation: the posterior q(x_{t-1} | x_t, x_0)

By Bayes, \(q(\mathbf x_{t-1}\mid\mathbf x_t,\mathbf x_0)\propto q(\mathbf x_t\mid\mathbf x_{t-1})\,q(\mathbf x_{t-1}\mid\mathbf x_0)\), a product of two Gaussians in \(\mathbf x_{t-1}\):

\[ \exp\Big(-\frac{\lVert\mathbf x_t - \sqrt{\alpha_t}\mathbf x_{t-1}\rVert^2}{2\beta_t} - \frac{\lVert\mathbf x_{t-1} - \sqrt{\bar\alpha_{t-1}}\mathbf x_0\rVert^2}{2(1-\bar\alpha_{t-1})}\Big). \]

Collect the quadratic and linear terms in \(\mathbf x_{t-1}\). The precision is \(\frac{\alpha_t}{\beta_t} + \frac{1}{1-\bar\alpha_{t-1}} = \frac{1-\bar\alpha_t}{\beta_t(1-\bar\alpha_{t-1})}\), so

\[ \tilde\beta_t = \frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\,\beta_t,\qquad \tilde{\boldsymbol\mu}_t(\mathbf x_t,\mathbf x_0) = \frac{\sqrt{\bar\alpha_{t-1}}\,\beta_t}{1-\bar\alpha_t}\,\mathbf x_0 + \frac{\sqrt{\alpha_t}\,(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}\,\mathbf x_t . \]

Substituting \(\mathbf x_0 = (\mathbf x_t - \sqrt{1-\bar\alpha_t}\,\boldsymbol\epsilon)/\sqrt{\bar\alpha_t}\) and simplifying (use \(\bar\alpha_t = \alpha_t\bar\alpha_{t-1}\)):

\[ \tilde{\boldsymbol\mu}_t = \frac{1}{\sqrt{\alpha_t}}\Big(\mathbf x_t - \frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\boldsymbol\epsilon\Big). \]
Derivation: the ELBO and the ε-prediction loss

Exactly as for a VAE, with \(q(\mathbf x_{1:T}\mid\mathbf x_0)\) as the variational posterior, \(\log p_\theta(\mathbf x_0)\ge\mathbb E_q\big[\log p_\theta(\mathbf x_{0:T}) - \log q(\mathbf x_{1:T}\mid\mathbf x_0)\big]\). Write \(q(\mathbf x_{1:T}\mid\mathbf x_0) = q(\mathbf x_T\mid\mathbf x_0)\prod_{t=2}^T q(\mathbf x_{t-1}\mid\mathbf x_t,\mathbf x_0)\) (Bayes on each forward factor, conditioning on \(\mathbf x_0\), then telescoping). The negative ELBO splits into

\[ \underbrace{\mathrm{KL}\big(q(\mathbf x_T\mid\mathbf x_0)\,\|\,p(\mathbf x_T)\big)}_{L_T\ \text{(no parameters)}} + \sum_{t=2}^{T}\underbrace{\mathbb E_q\,\mathrm{KL}\big(q(\mathbf x_{t-1}\mid\mathbf x_t,\mathbf x_0)\,\|\,p_\theta(\mathbf x_{t-1}\mid\mathbf x_t)\big)}_{L_{t-1}} \;\underbrace{-\ \mathbb E_q\log p_\theta(\mathbf x_0\mid\mathbf x_1)}_{L_0}. \]

Both distributions in \(L_{t-1}\) are Gaussians with the same fixed covariance \(\sigma_t^2 I\) on the model side, so the KL is a scaled squared distance between means plus a constant: \(L_{t-1} = \mathbb E\big[\lVert\tilde{\boldsymbol\mu}_t - \boldsymbol\mu_\theta\rVert^2\big]/(2\sigma_t^2) + C\). Parameterise \(\boldsymbol\mu_\theta\) with the same formula as \(\tilde{\boldsymbol\mu}_t\), using \(\epsilon_\theta\) in place of \(\boldsymbol\epsilon\):

\[ L_{t-1} = \frac{\beta_t^2}{2\sigma_t^2\,\alpha_t\,(1-\bar\alpha_t)}\;\mathbb E_{\mathbf x_0,\boldsymbol\epsilon}\Big[\big\lVert\boldsymbol\epsilon - \epsilon_\theta(\sqrt{\bar\alpha_t}\mathbf x_0 + \sqrt{1-\bar\alpha_t}\boldsymbol\epsilon,\ t)\big\rVert^2\Big] + C . \]

\(\mathcal L_\text{simple}\) sets the weight to 1 and samples \(t\) uniformly. Relative to the ELBO this down-weights the low-noise terms, which carry the most likelihood but matter least perceptually; that is why it gives better samples and worse likelihoods.

The SNR form. With \(\sigma_t^2 = \tilde\beta_t\) and an \(\mathbf x_0\)-prediction \(\hat{\mathbf x}_\theta\), each term simplifies to

\[ L_{t-1} = \tfrac12\big(\mathrm{SNR}(t-1) - \mathrm{SNR}(t)\big)\,\mathbb E\big\lVert\mathbf x_0 - \hat{\mathbf x}_\theta(\mathbf x_t, t)\big\rVert^2 , \]

since \(\tilde{\boldsymbol\mu}_t - \boldsymbol\mu_\theta = \frac{\sqrt{\bar\alpha_{t-1}}\beta_t}{1-\bar\alpha_t}(\mathbf x_0 - \hat{\mathbf x}_\theta)\) and \(\frac{\bar\alpha_{t-1}\beta_t}{(1-\bar\alpha_t)(1-\bar\alpha_{t-1})} = \mathrm{SNR}(t-1)-\mathrm{SNR}(t)\) (check: \(\bar\alpha_{t-1}-\bar\alpha_t = \bar\alpha_{t-1}\beta_t\)). Summed over \(t\) and taken to continuous time, this is \(-\tfrac12\int\frac{d\,\mathrm{SNR}}{dt}\,\mathbb E\lVert\mathbf x_0-\hat{\mathbf x}_\theta\rVert^2\,dt\), a change of variables away from an integral over SNR alone, which is why the schedule's interior shape drops out (Kingma et al., 2021).

Parameterisations. With \(\mathbf x_t = a_t\mathbf x_0 + b_t\boldsymbol\epsilon\), \(a_t = \sqrt{\bar\alpha_t}\), \(b_t = \sqrt{1-\bar\alpha_t}\):

\[ \hat{\mathbf x}_0 = \frac{\mathbf x_t - b_t\hat{\boldsymbol\epsilon}}{a_t},\qquad \nabla_{\mathbf x_t}\log p_t(\mathbf x_t) \approx -\frac{\hat{\boldsymbol\epsilon}}{b_t},\qquad \mathbf v = a_t\boldsymbol\epsilon - b_t\mathbf x_0,\quad \hat{\mathbf x}_0 = a_t\mathbf x_t - b_t\hat{\mathbf v}. \]

The last identity uses \(a_t^2 + b_t^2 = 1\).

Derivation: DDIM's non-Markovian process

Song, Meng and Ermon define, for any choice of \(\sigma_t\ge0\),

\[ q_\sigma(\mathbf x_{t-1}\mid\mathbf x_t,\mathbf x_0) = \mathcal N\Big(\sqrt{\bar\alpha_{t-1}}\,\mathbf x_0 + \sqrt{1-\bar\alpha_{t-1}-\sigma_t^2}\;\frac{\mathbf x_t - \sqrt{\bar\alpha_t}\,\mathbf x_0}{\sqrt{1-\bar\alpha_t}},\ \sigma_t^2 I\Big). \]

If \(\mathbf x_t\sim\mathcal N(\sqrt{\bar\alpha_t}\mathbf x_0, (1-\bar\alpha_t)I)\), the fraction is a standard normal \(\boldsymbol\epsilon\), so \(\mathbf x_{t-1}\) has mean \(\sqrt{\bar\alpha_{t-1}}\mathbf x_0\) and variance \((1-\bar\alpha_{t-1}-\sigma_t^2) + \sigma_t^2 = 1-\bar\alpha_{t-1}\): the marginals match the DDPM forward process for every \(\sigma_t\). The ELBO for each such process is the ε-regression loss with different per-\(t\) weights, so one trained network serves all of them. Sampling replaces \(\mathbf x_0\) by \(\hat{\mathbf x}_0\) and the fraction by \(\hat{\boldsymbol\epsilon}\). Choosing \(\sigma_t = \eta\sqrt{\tilde\beta_t}\), i.e. \(\sigma_t = \eta\sqrt{\frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\big(1-\frac{\bar\alpha_t}{\bar\alpha_{t-1}}\big)}\), gives the DDPM posterior variance at \(\eta=1\) and a deterministic map at \(\eta = 0\). Nothing requires \(t-1\) to be the previous integer, so the same formula skips steps.

Build it

1. Noise schedules in numbers (NumPy):

import numpy as np

T = 1000
t = np.arange(0, T + 1)
# Linear schedule (Ho et al., 2020): beta_t from 1e-4 to 0.02
beta_lin = np.linspace(1e-4, 0.02, T)
# Cosine schedule (Nichol & Dhariwal, 2021): abar(t) = f(t)/f(0), f(t) = cos^2(((t/T)+s)/(1+s) * pi/2),
# turned into betas and clipped at 0.999 as in the paper
s = 0.008
f = np.cos((t / T + s) / (1 + s) * np.pi / 2) ** 2
beta_cos = np.minimum(1 - f[1:] / f[:-1], 0.999)
schedules = {"linear": np.cumprod(1 - beta_lin), "cosine": np.cumprod(1 - beta_cos)}

snr_db = lambda a: 10 * np.log10(a / (1 - a))
print("   t |  linear: abar  sqrt(abar)  SNR dB |  cosine: abar  sqrt(abar)  SNR dB")
for k in [1, 50, 250, 500, 750, 900, 1000]:
    row = [f"{k:4d}"]
    for a in schedules.values():
        ab = a[k - 1]
        row.append(f"{ab:13.5f}  {np.sqrt(ab):9.4f}  {snr_db(ab):6.1f}")
    print(" | ".join(row))
for name, a in schedules.items():
    print(f"{name}: steps with abar > 0.9: {np.sum(a > 0.9):3d};  steps with abar < 0.01: {np.sum(a < 0.01):3d}")
   t |  linear: abar  sqrt(abar)  SNR dB |  cosine: abar  sqrt(abar)  SNR dB
   1 |       0.99990     0.9999    40.0 |       0.99996     1.0000    43.8
  50 |       0.97102     0.9854    15.3 |       0.99201     0.9960    20.9
 250 |       0.52409     0.7239     0.4 |       0.84701     0.9203     7.4
 500 |       0.07859     0.2803   -10.7 |       0.49384     0.7027    -0.1
 750 |       0.00335     0.0579   -24.7 |       0.14427     0.3798    -7.7
 900 |       0.00028     0.0166   -35.6 |       0.02409     0.1552   -16.1
1000 |       0.00004     0.0064   -43.9 |       0.00000     0.0000   -86.1
linear: steps with abar > 0.9:  98;  steps with abar < 0.01: 327
cosine: steps with abar > 0.9: 198;  steps with abar < 0.01:  65

2. Samplers with a perfect denoiser (NumPy). For a Gaussian mixture the optimal noise predictor is known in closed form, so this isolates the sampler. One function implements both DDPM-style (\(\eta = 1\)) and DDIM (\(\eta = 0\)) sampling on any sub-sequence of timesteps:

import numpy as np
rng = np.random.default_rng(0)

# Data: a 1-D mixture of three Gaussians. Its noisy marginals are mixtures too, so the
# ideal noise predictor eps*(x_t, t) = E[eps | x_t] has a closed form: no training needed.
pi, m, s = np.array([0.2, 0.5, 0.3]), np.array([-3.0, 0.0, 3.0]), np.array([0.3, 0.3, 0.3])
T = 1000
abar = np.cumprod(1 - np.linspace(1e-4, 0.02, T))       # linear schedule, abar[t-1] for t = 1..T

def eps_star(x, ab):
    ab = np.broadcast_to(ab, x.shape)[:, None]           # works for one t or one t per sample
    var = ab * s**2 + 1 - ab                             # x_t | component k ~ N(sqrt(ab) m_k, var_k)
    logw = np.log(pi) - 0.5 * np.log(var) - 0.5 * (x[:, None] - np.sqrt(ab) * m) ** 2 / var
    r = np.exp(logw - logw.max(1, keepdims=True)); r /= r.sum(1, keepdims=True)
    x0_k = m + np.sqrt(ab) * s**2 / var * (x[:, None] - np.sqrt(ab) * m)   # E[x0 | x_t, k]
    x0 = (r * x0_k).sum(1)                               # Tweedie: E[x0 | x_t]
    return (x - np.sqrt(ab[:, 0]) * x0) / np.sqrt(1 - ab[:, 0])

def sample(n_steps, eta, n=20_000):
    ts = np.linspace(T, 1, n_steps).round().astype(int)  # e.g. 1000, 950, ..., 1
    x = rng.standard_normal(n)
    for i, t in enumerate(ts):
        ab = abar[t - 1]; ab_prev = abar[ts[i + 1] - 1] if i + 1 < len(ts) else 1.0
        e = eps_star(x, ab)
        x0 = (x - np.sqrt(1 - ab) * e) / np.sqrt(ab)      # predicted clean sample
        sig = eta * np.sqrt((1 - ab_prev) / (1 - ab) * (1 - ab / ab_prev))
        x = np.sqrt(ab_prev) * x0 + np.sqrt(1 - ab_prev - sig**2) * e + sig * rng.standard_normal(n)
    return x

def report(x):
    true = np.concatenate([rng.normal(mk, sk, int(20_000 * pk)) for pk, mk, sk in zip(pi, m, s)])
    w1 = np.mean(np.abs(np.sort(x) - np.sort(true)))      # 1-D Wasserstein-1 distance
    frac = [np.mean(np.abs(x - mk) < 1.5) for mk in m]
    spread = np.std(x[np.abs(x - 3) < 1.5])
    return f"mode fractions {frac[0]:.3f} {frac[1]:.3f} {frac[2]:.3f}  std(right mode) {spread:.3f}  W1 {w1:.3f}"

print("target                          mode fractions 0.200 0.500 0.300  std(right mode) 0.300")
for steps in [1000, 100, 20, 5]:
    for eta, name in [(1.0, "DDPM-style (eta=1)"), (0.0, "DDIM (eta=0)      ")]:
        print(f"{steps:4d} steps  {name}  " + report(sample(steps, eta)))

# The loss floor: even the perfect denoiser cannot predict eps exactly
ev = np.random.default_rng(1)
t = ev.integers(1, T + 1, 100_000); e = ev.standard_normal(100_000)
x0 = m[ev.choice(3, 100_000, p=pi)] + 0.3 * ev.standard_normal(100_000)
xt = np.sqrt(abar[t - 1]) * x0 + np.sqrt(1 - abar[t - 1]) * e
print(f"irreducible loss E|eps* - eps|^2 = {np.mean((eps_star(xt, abar[t - 1]) - e) ** 2):.4f}")
target                          mode fractions 0.200 0.500 0.300  std(right mode) 0.300
1000 steps  DDPM-style (eta=1)  mode fractions 0.201 0.502 0.297  std(right mode) 0.295  W1 0.016
1000 steps  DDIM (eta=0)        mode fractions 0.203 0.500 0.296  std(right mode) 0.298  W1 0.021
 100 steps  DDPM-style (eta=1)  mode fractions 0.188 0.520 0.291  std(right mode) 0.280  W1 0.067
 100 steps  DDIM (eta=0)        mode fractions 0.195 0.508 0.297  std(right mode) 0.295  W1 0.034
  20 steps  DDPM-style (eta=1)  mode fractions 0.174 0.548 0.278  std(right mode) 0.251  W1 0.179
  20 steps  DDIM (eta=0)        mode fractions 0.188 0.526 0.286  std(right mode) 0.282  W1 0.112
   5 steps  DDPM-style (eta=1)  mode fractions 0.086 0.724 0.190  std(right mode) 0.478  W1 0.684
   5 steps  DDIM (eta=0)        mode fractions 0.122 0.655 0.224  std(right mode) 0.481  W1 0.497
irreducible loss E|eps* - eps|^2 = 0.3029

3. A diffusion model trained from scratch (NumPy). A two-hidden-layer MLP with a sinusoidal time embedding, trained with \(\mathcal L_\text{simple}\) and hand-written backpropagation, then sampled with 1,000 ancestral steps. It takes about 30 seconds on a laptop:

import numpy as np
rng = np.random.default_rng(0)

# Train a real (tiny) diffusion model in NumPy: an MLP eps_theta(x_t, t), manual backprop.
pi, m = np.array([0.2, 0.5, 0.3]), np.array([-3.0, 0.0, 3.0])        # same mixture, std 0.3
data = lambda n: m[rng.choice(3, n, p=pi)] + 0.3 * rng.standard_normal(n)
T = 1000
abar = np.cumprod(1 - np.linspace(1e-4, 0.02, T))
freqs = np.exp(np.linspace(0, np.log(100), 8))
def features(x, t):                                    # x: (B,), t: (B,) ints in 1..T
    a = t[:, None] / T * freqs                         # sinusoidal time embedding, 16 dims
    return np.concatenate([x[:, None], np.sin(a), np.cos(a)], 1)   # (B, 17)

H = 128
params = [rng.standard_normal((17, H)) / np.sqrt(17), np.zeros(H),
          rng.standard_normal((H, H)) / np.sqrt(H), np.zeros(H),
          rng.standard_normal((H, 1)) / np.sqrt(H), np.zeros(1)]
mom = [np.zeros_like(p) for p in params]; vel = [np.zeros_like(p) for p in params]

def forward(f):
    W1, b1, W2, b2, W3, b3 = params
    h1 = np.maximum(f @ W1 + b1, 0); h2 = np.maximum(h1 @ W2 + b2, 0)
    return (h2 @ W3 + b3)[:, 0], (f, h1, h2)

ev_rng = np.random.default_rng(1)                        # fixed held-out set of (x0, t, eps)
ev_t = ev_rng.integers(1, T + 1, 100_000); ev_e = ev_rng.standard_normal(100_000)
ev_x0 = m[ev_rng.choice(3, 100_000, p=pi)] + 0.3 * ev_rng.standard_normal(100_000)
ev_xt = np.sqrt(abar[ev_t - 1]) * ev_x0 + np.sqrt(1 - abar[ev_t - 1]) * ev_e

for step in range(1, 30_001):
    B = 512
    x0, t, eps = data(B), rng.integers(1, T + 1, B), rng.standard_normal(B)
    ab = abar[t - 1]
    xt = np.sqrt(ab) * x0 + np.sqrt(1 - ab) * eps        # one-shot forward noising
    pred, (f, h1, h2) = forward(features(xt, t))      # predict the noise
    g = 2 * (pred - eps)[:, None] / B                    # backprop by hand
    gW3, gb3 = h2.T @ g, g.sum(0); g = (g @ params[4].T) * (h2 > 0)
    gW2, gb2 = h1.T @ g, g.sum(0); g = (g @ params[2].T) * (h1 > 0)
    gW1, gb1 = f.T @ g, g.sum(0)
    lr = 1e-3 * min(1.0, (30_001 - step) / 10_000)       # linear decay over the last third
    for i, gr in enumerate([gW1, gb1, gW2, gb2, gW3, gb3]):        # Adam
        mom[i] = 0.9 * mom[i] + 0.1 * gr; vel[i] = 0.999 * vel[i] + 0.001 * gr**2
        params[i] -= lr * (mom[i] / (1 - 0.9**step)) / (np.sqrt(vel[i] / (1 - 0.999**step)) + 1e-8)
    if step % 10_000 == 0:                               # the "simple" DDPM loss, held out
        print(f"step {step:6d}  held-out loss {np.mean((forward(features(ev_xt, ev_t))[0] - ev_e)**2):.4f}")

x = rng.standard_normal(20_000)                          # ancestral DDPM sampling, 1000 steps
for t in range(T, 0, -1):
    beta, ab = 1 - abar[t - 1] / (abar[t - 2] if t > 1 else 1.0), abar[t - 1]
    e, _ = forward(features(x, np.full(x.shape, t)))
    x = (x - beta / np.sqrt(1 - ab) * e) / np.sqrt(1 - beta)
    if t > 1: x += np.sqrt(beta) * rng.standard_normal(x.shape)
print("mode fractions:", [round(float(np.mean(np.abs(x - mk) < 1.5)), 3) for mk in m], " target [0.2, 0.5, 0.3]")
print("std within each mode:", [round(float(np.std(x[np.abs(x - mk) < 1.5])), 3) for mk in m], " target 0.3")
step  10000  held-out loss 0.3073
step  20000  held-out loss 0.3065
step  30000  held-out loss 0.3034
mode fractions: [0.207, 0.497, 0.296]  target [0.2, 0.5, 0.3]
std within each mode: [0.297, 0.295, 0.307]  target 0.3

The held-out loss (0.3034) sits just above the floor that snippet 2 computes for the perfect denoiser on the identical held-out set (0.3029). The loss alone looks unimpressive; the samples show the model has learned the distribution.

4. The same thing on images (PyTorch; standard code, not run here). Swap the MLP for a small U-Net from diffusers and nothing else changes:

import torch, torch.nn.functional as F
from diffusers import UNet2DModel, DDPMScheduler

model = UNet2DModel(sample_size=32, in_channels=3, out_channels=3,
                    block_out_channels=(64, 128, 256), layers_per_block=2)
sched = DDPMScheduler(num_train_timesteps=1000, beta_schedule="linear")
opt = torch.optim.AdamW(model.parameters(), lr=2e-4)

def train_step(x0):                                  # x0: (B, 3, 32, 32) scaled to [-1, 1]
    t = torch.randint(0, 1000, (x0.size(0),))
    eps = torch.randn_like(x0)
    xt = sched.add_noise(x0, eps, t)                 # sqrt(abar) x0 + sqrt(1 - abar) eps
    loss = F.mse_loss(model(xt, t).sample, eps)
    opt.zero_grad(); loss.backward(); opt.step()
    return loss.item()

@torch.no_grad()
def sample(n=16, steps=1000):
    sched.set_timesteps(steps)
    x = torch.randn(n, 3, 32, 32)
    for t in sched.timesteps:
        x = sched.step(model(x, t).sample, t, x).prev_sample
    return x

Things to try

  • In snippet 2, change the right mode's weight to 0.05. How many steps does each sampler need before the small mode gets its fair share? Rare modes are where few-step samplers fail first.
  • In snippet 2, switch to the cosine schedule from snippet 1 and redo the 20-step rows.
  • In snippet 3, train with \(t\) restricted to \(t\le 500\) and then sample from pure noise. The model has never seen high-noise inputs; watch the samples fail.
  • In snippet 3, predict \(\mathbf v\) instead of \(\boldsymbol\epsilon\) (change the target and convert back in the sampler) and compare held-out \(\hat{\mathbf x}_0\) errors at large \(t\).
  • Replace the sampler in snippet 3 with the DDIM loop from snippet 2 at 50 steps.
  • Work through the Annotated Diffusion Model and train snippet 4 on Fashion-MNIST.

In practice

  • Defaults: \(T = 1000\) for training; cosine or a shifted schedule; ε- or v-prediction (or flow matching's velocity); AdamW, learning rate around \(10^{-4}\), an exponential moving average of the weights with decay 0.9999 for sampling; mixed precision.
  • Sampling budget: 20–50 steps with DDIM, DPM-Solver++ or Euler/Heun for most uses; distilled models for real-time.
  • Watch the loss per noise level, not just the average: a model that is good on average can be bad at high noise, which ruins global structure. Track FID or a task metric on samples periodically.
  • Resolution and latents: pixel-space diffusion beyond 256×256 is expensive. Use latent diffusion, cascades, or schedule shifts.
  • Check the terminal SNR: if your schedule leaves signal at \(t = T\), either rescale to zero terminal SNR or start sampling from a matching noisy distribution.

Common misconceptions

\"The network removes all the noise at each step.\"

It predicts all of the noise (equivalently, a full guess of \(\mathbf x_0\)) at every step, but the sampler only moves a small way towards that guess and, in stochastic samplers, adds fresh noise back. Generation is a slow walk, not a jump.

\"Diffusion models memorise and paste training images.\"

A model with the exact optimal denoiser for the empirical training distribution would only reproduce training images, and large models do memorise some heavily duplicated ones. But trained networks generalise because they cannot represent that empirical denoiser exactly; they learn a smoother function. Memorisation is a real risk to measure, not the mechanism.

\"DDIM is a different model from DDPM.\"

It is a different sampler for the same trained network. Any ε-prediction model trained with the DDPM loss can be sampled with DDIM, DPM-Solver or an SDE solver.

Check yourself

Why can you train at step t = 700 without simulating 700 noising steps?

Gaussian steps compose: \(q(\mathbf x_t\mid\mathbf x_0) = \mathcal N(\sqrt{\bar\alpha_t}\mathbf x_0, (1-\bar\alpha_t)I)\), so \(\mathbf x_{700}\) is one line of arithmetic from \(\mathbf x_0\) and a fresh noise sample.

With the linear schedule, x_250 = 0.724 x₀ + c·ε. What is c, and what is the SNR in dB?

\(c = \sqrt{1-\bar\alpha_{250}} = \sqrt{1-0.524} = 0.690\). SNR \(= 0.524/0.476 = 1.10\), i.e. \(+0.4\) dB: signal and noise have almost equal power.

The optimal ε-predictor has non-zero loss. Why, and what does that imply for monitoring training?

At high noise many clean points are consistent with the same \(\mathbf x_t\), so the noise is not determined by \(\mathbf x_t\); the best predictor is a conditional mean with irreducible variance. The loss floor depends on the data and the schedule, so the raw loss value says little about sample quality; compare against held-out loss, per-noise-level loss, and samples.

Why does the deterministic DDIM sampler outperform stochastic sampling at 20 steps in the worked example?

The fresh noise in stochastic sampling must be removed by later steps; with few steps there are not enough of them to correct it, so error accumulates. DDIM follows the probability-flow ODE, whose trajectories are smoother and better approximated by large steps. With many steps, the noise in stochastic samplers helps correct earlier errors, and the gap closes.

Show that predicting v = √ᾱ ε − √(1−ᾱ) x₀ lets you recover x₀ as √ᾱ x_t − √(1−ᾱ) v.

\(\sqrt{\bar\alpha}\,\mathbf x_t = \bar\alpha\,\mathbf x_0 + \sqrt{\bar\alpha(1-\bar\alpha)}\,\boldsymbol\epsilon\) and \(\sqrt{1-\bar\alpha}\,\mathbf v = \sqrt{\bar\alpha(1-\bar\alpha)}\,\boldsymbol\epsilon - (1-\bar\alpha)\mathbf x_0\). Subtracting gives \((\bar\alpha + 1 - \bar\alpha)\mathbf x_0 = \mathbf x_0\).

In what sense is a diffusion model a VAE? What is unusual about its encoder and latents?

It is a hierarchical latent-variable model \(p_\theta(\mathbf x_{0:T})\) trained by maximising an ELBO with the forward process as the approximate posterior. Unusually, the "encoder" has no parameters (fixed noising), the latents \(\mathbf x_{1:T}\) have the same dimension as the data, and the top latent \(\mathbf x_T\) is (nearly) independent of \(\mathbf x_0\).

Hard: why do high-resolution models need the noise schedule shifted towards more noise?

Neighbouring pixels at high resolution are highly correlated; independent per-pixel noise of a given variance averages out over a patch, so coarse structure survives longer. At the same \(t\), a 1024×1024 image is effectively less noisy than a 256×256 one, and the model spends too little training on the high-noise regime that decides global layout. Shifting the schedule (or the distribution of \(t\)) restores the balance.

Hard: the ELBO-weighted loss gives better likelihoods but worse samples than L_simple. Explain using the SNR form.

The ELBO weight on step \(t\) is proportional to \(\mathrm{SNR}(t-1)-\mathrm{SNR}(t)\), which is huge at low noise (SNR changes fast near \(t = 0\)) and tiny at high noise. Likelihood is dominated by imperceptible fine detail, so the ELBO spends capacity there. \(\mathcal L_\text{simple}\) weights noise levels more evenly, giving more capacity to the high- and mid-noise levels that determine structure, which is what perceptual quality measures.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

Where this leads