Denoising Diffusion Probabilistic Models
DDPMs generate data by learning to reverse a gradual Gaussian noising process: a fixed forward process destroys structure over T steps, and a trained network predicts the added noise so the chain can be run backwards from pure noise. The variational bound reduces to a denoising squared-error loss, noise schedules and parameterizations control quality, and DDIM/latent diffusion make sampling practical.
1. Concept overview
A denoising diffusion probabilistic model is a latent-variable generative model with a fixed -step forward (diffusion) process that gradually corrupts data with Gaussian noise, and a learned reverse process that denoises step by step:
With and , a crucial closed form holds:
Ho et al. (2020) parameterize through a noise predictor and train with the strikingly simple objective
Sampling starts from and iterates learned denoising steps. DDPMs combine the sharpness of GAN-like adversarial training with a stable, supervised-style regression loss, at the cost of slow, sequential sampling.
2. Why this concept exists
Generative models face a trilemma: sample quality, training stability, and likelihood/compositional flexibility. GANs produce sharp samples but train via a minimax game prone to mode collapse and instability; autoregressive models give exact likelihoods but generate pixel-by-pixel (slow, no global coherence); VAEs are fast and likelihood-based but produce blurry samples due to the KL regularization and simple decoders.
Diffusion models avoid adversarial training entirely: the forward process is fixed and the learning problem is "predict the noise you added" — a denoising regression with a well-defined target at every step. This yields:
- stable training with a simple MSE loss and no discriminator;
- high-quality, diverse samples (state of the art on ImageNet at high resolution);
- conditional generation via cross-attention or guidance without retraining the generator;
- tractable likelihoods via the variational lower bound.
Earlier ideas: Sohl-Dickstein et al. (2015) framed diffusion as a variational Markov chain; Song & Ermon (2019/2020) developed score matching with Langevin dynamics; Ho et al. (2020) connected and simplified these into DDPM, making high-quality image generation practical.
3. Historical background
Sohl-Dickstein, Weiss, Maheswaranathan & Ganguli (2015) introduced the framework of using a sequence of small Gaussian perturbations and learning the reverse Markov chain by variational inference.
Song & Ermon (2019, 2020) developed noise-conditional score networks and Langevin sampling, showing that estimating (the score) gives a generative process; their 2020 SDE paper unified score-based and diffusion models.
Ho, Jain & Abbeel (2020) introduced DDPM: reparameterized the reverse mean in terms of , derived the simplified loss, used a cosine-friendly linear noise schedule, and achieved strong unconditional image samples with a U-Net.
Nichol & Dhariwal (2021) improved DDPM with learned reverse variances, a cosine schedule, and better conditioning, achieving likelihoods competitive with autoregressive models. Dhariwal & Nichol (2021) showed diffusion classifiers/guidance beating BigGAN. Song et al. (2020) introduced DDIM for fast deterministic sampling. Rombach et al. (2022) moved diffusion into a compressed VAE latent space (Latent Diffusion Models), enabling high-resolution text-to-image generation at feasible cost (Stable Diffusion). Ho & Salimans (2022) formalized classifier-free guidance; Karras et al. (2022) distilled sampling to few steps via EDM.
4. Fundamental problem
Learn a distribution close to the data distribution such that:
- we can compute a tractable training objective (no adversarial game, no exhaustive normalization constants);
- sampling is possible by a finite procedure from ;
- the model can be conditioned on text, class labels, or images;
- the same machinery scales to high-dimensional data ( images or billions of language-model parameters).
The key observation is that while itself is intractable, each reverse conditional is a small Gaussian whose mean can be learned by a denoiser. The variational upper bound on decomposes into per-step KL terms, each of which is a denoising regression.
5. First-principles explanation
Fact 1 — repeated small Gaussian perturbations converge to standard normal. With , the closed form implies independent of . Thus noise provides a simple, known prior.
Fact 2 — the posterior is Gaussian and computable given . Bayes' rule gives
with and . This is the target for the reverse step.
Fact 3 — the network only needs to predict noise. If estimates , we can recover via and plug it into . Algebraically this gives
which is why the loss becomes noise-prediction MSE.
Fact 4 — variational bound. Since each forward and reverse step is Gaussian, all KL divergences are analytic; maximizing the VLB is equivalent to minimizing a weighted sum of denoising errors, which Ho et al. simplified to uniform weights over .
6. Prerequisite concepts
You need: (a) multivariate Gaussian distributions, covariance matrices, and the reparameterization trick (sampling ); (b) KL divergence and the variational lower bound as used in VAEs; (c) Markov chains, Bayes' rule, and completing the square to get a Gaussian posterior; (d) denoising score matching and the connection ; (e) U-Net architectures with residual blocks, group normalization, and attention; (f) PyTorch tensor broadcasting, torch.cumprod, and autograd. Familiarity with FID and sample-quality evaluation helps when interpreting benchmark claims.
7. Complete mathematical formulation
Forward process. , , with a fixed variance schedule (linear: , ; cosine schedule as an alternative).
Closed form. .
Reverse process. , .
Variational lower bound.
With , the -th KL becomes , and substituting the -parameterization gives a weight .
Simplified loss (DDPM).
Sampler (DDPM). , , (DDPM often uses for the last steps).
DDIM (deterministic, ). , allowing a subsequence of –50 steps.
Classifier-free guidance. , with the guidance scale.
8. Notation dictionary
| Symbol | Meaning | Type / shape | |---|---|---| | | clean data sample | e.g. image in | | | noised sample at step | same shape as | | | Gaussian noise added by forward process | , same shape | | | forward variance at step | scalar schedule | | | retained-signal factor | scalar | | | cumulative product | scalar | | | number of diffusion steps | integer, e.g. 1000 | | | forward / learned reverse process | Markov chains | | | neural noise predictor | same shape as | | | true posterior mean / variance | scalar–vector | | | reverse mean / std | vector / scalar | | | predicted clean sample | same shape as | | | classifier-free guidance scale | scalar | | | variational / simplified loss | scalar | | | DDIM sampling subsequence | list of timesteps |
9. Step-by-step derivation
Step 1 — forward marginal. Because Gaussians add and , unrolling gives (variances add as weighted sums; verify by induction: ).
Step 2 — posterior via Bayes. ; completing the square in gives and as in section 8.
Step 3 — variational bound. Use and the Markov factorization; most terms cancel, leaving KLs between Gaussians.
Step 4 — parameterize the mean. Substitute into and simplify coefficients:
The identity uses and .
Step 5 — simplify the loss. . Ho et al. observed that dropping the time-dependent coefficient (i.e. using uniform weights) improves perceptual sample quality, giving ; learned/rebalanced weights recover better likelihoods (Nichol & Dhariwal 2021).
Step 6 — sampling. Iterating from implements the reverse chain. DDIM observes that the same trained defines a family of reverse processes indexed by ; is deterministic and consistent for a subsequence of steps, enabling fast sampling.
10. Proofs and proof intuition
Lemma 1 (forward marginal). . Proof by induction. For true. If true at , then . The noise has variance (using ), and independent Gaussians add.
Lemma 2 (posterior Gaussian). with the formulas in section 8. Proof. up to constants (using the marginal for given ); complete the square in .
Lemma 3 (mean error equals noise error up to a factor). With , . Proof. Substitute into and collect coefficients; the coefficient is common and cancels.
Lemma 4 (DDIM consistency). For , deterministic steps leave the training objective's marginals unchanged for any increasing subsequence. Proof sketch. Under the model's constant along the chain, substituting gives the same form at ; hence skipping steps is consistent (Song et al. 2020).
Proof intuition. Every reverse step is a least-squares denoising problem: knowing would make the posterior mean exact; the network estimates the missing information through the noise. The VLB is just the sum of Gaussian KLs, which reduce to squared errors.
11. Geometric interpretation
The forward process traces a straight line in signal–noise space: at time , is a convex combination (in quadrature) of the data point and Gaussian noise, with signal-to-noise ratio decreasing monotonically from large to ~0. Geometrically, noising shrinks the data manifold toward the origin while inflating it with isotropic noise until it is indistinguishable from the prior Gaussian ball.
The reverse process learns a vector field on noisy images: at each , points roughly from toward the nearest high-density region of the data manifold. Iterating small steps follows this field back to the manifold — analogous to gradient descent on an energy landscape where the score .
In distribution space, diffusion transports a simple Gaussian to a complex multimodal data distribution through a smooth chain of intermediate densities; unlike GANs, the chain is not a single mapping but a sequence of small, learnable Gaussian transitions, which is why training is stable. Classifier-free guidance effectively extrapolates the score away from the unconditional density, sharpening modes at the cost of diversity.
12. Visual explanation
Draw a horizontal chain of boxes : the forward arrows are fixed Gaussians (blue, labelled ), the reverse arrows are learned (orange, labelled ). Show a sample image progressively turning into static, then the chain running backwards from static to a new image.
A second visual plots and versus for the linear and cosine schedules: linear keeps SNR high early and collapses near ; cosine decays more gradually, improving sample quality. Show the 1-D toy trajectory from section 13: drifting toward 0 with variance .
Third visual: the U-Net architecture — a "U" with downsampling (32→64→128 channels), a bottleneck with attention at 16×16, and upsampling with skip connections; a time-embedding vector enters each residual block via an MLP and feature-wise affine transformation (AdaGN).
The Interactive Diffusion Playground in Practical Labs lets you drag , see and the network's , and toggle classifier-free guidance to watch samples sharpen.
13. Numerical worked example
Use a tiny 1-D "dataset" with , , , hence and . Draw a single noise realization .
Forward samples :
- : .
- : .
- : .
- : , and for large .
True posterior at given and :
If the network predicts the true , then
confirming the parameterization identity. A reverse sample is ; one draw with lands exactly at the posterior mean.
SNR at is ; at with the linear schedule it is — the signal is essentially gone.
14. Real-world analogy
Imagine restoring a photograph that has been degraded by adding a little grain 1000 times. The forward process is easy: add a fresh dusting of grain each time. The restoration network is trained by being shown a photo at a random stage of degradation and asked "how much grain did I add?" — a concrete supervised question. Since it learns to recognize grain at every noise level, you can start with pure static and repeatedly ask it to remove a little grain, nudging the image back toward a plausible photograph each step. Classifier-free guidance is like telling the restorer "make it more like a sunset" and amplifying the difference between that instruction and an unconditioned restoration.
15. Algorithm pseudocode
algorithm DDPM_Train(denoiser eps_theta, data q_data, T, schedule beta_t):
precompute alpha_t = 1-beta_t ; alpha_bar_t = prod_{s<=t} alpha_s
repeat:
x0 ~ q_data
t ~ Uniform{1,...,T}
eps ~ N(0,I)
x_t <- sqrt(alpha_bar_t)*x0 + sqrt(1-alpha_bar_t)*eps # forward
loss <- ||eps_theta(x_t, t) - eps||^2 # denoising MSE
gradient step on loss
algorithm DDPM_Sample(eps_theta, T, beta_t):
x_T ~ N(0,I)
for t = T down to 1:
eps_hat <- eps_theta(x_t, t)
mu <- (1/sqrt(alpha_t)) * (x_t - beta_t/sqrt(1-alpha_bar_t)*eps_hat)
z ~ N(0,I) if t > 1 else 0
x_{t-1} <- mu + sqrt(beta_t)*z # or sqrt(beta_tilde_t)
return x_0
algorithm DDIM_Sample(eps_theta, subsequence tau of length S):
x_T ~ N(0,I)
for i = S down to 1:
t <- tau[i] ; t_prev <- tau[i-1]
eps_hat <- eps_theta(x_t, t)
x0_hat <- (x_t - sqrt(1-alpha_bar_t)*eps_hat)/sqrt(alpha_bar_t)
x_{t_prev} <- sqrt(alpha_bar_{t_prev})*x0_hat
+ sqrt(1-alpha_bar_{t_prev})*eps_hat # eta=0, deterministic
return x_0
16. Implementation from scratch
import numpy as np
betas = np.array([0.1, 0.2, 0.3, 0.4])
alphas = 1 - betas
abar = np.cumprod(alphas)
T = len(betas)
def q_sample(x0, t, eps):
"""Closed-form forward sample at 1-based timestep t."""
a = abar[t-1]
return np.sqrt(a)*x0 + np.sqrt(1-a)*eps
x0, eps = 2.0, 1.0
xt = np.array([q_sample(x0, t, eps) for t in range(1, T+1)])
print("abar:", np.round(abar, 4))
print("x_t:", np.round(xt, 4)) # [2.2136, 2.2262, 2.1241, 1.9350]
def posterior(t, x_t, x0):
"""True q(x_{t-1}|x_t,x0) mean and variance, 1-based t."""
a_t, ab_t = alphas[t-1], abar[t-1]
ab_prev = abar[t-2] if t > 1 else 1.0
b_t = betas[t-1]
mean = (np.sqrt(a_t)*(1-ab_prev)/(1-ab_t))*x_t \
+ (np.sqrt(ab_prev)*b_t/(1-ab_t))*x0
var = (1-ab_prev)/(1-ab_t)*b_t
return mean, var
mu_true, var_true = posterior(2, xt[1], x0)
mu_pred = (xt[1] - betas[1]/np.sqrt(1-abar[1])*eps)/np.sqrt(alphas[1])
print(mu_true, var_true, mu_pred) # 2.066397 0.071428... 2.066397
assert abs(mu_true - mu_pred) < 1e-10
# One reverse step with a perfect denoiser and zero noise.
sample = mu_true
assert abs(sample - 2.0664) < 1e-3
17. Professional library implementation
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
def time_embedding(t, dim=64):
"""Sinusoidal timestep embedding; t: (b,) -> (b, dim), dim even."""
half = dim // 2
freq = torch.exp(torch.arange(half, device=t.device) * (-math.log(10000)/half))
ang = t[:, None].float() * freq[None, :]
return torch.cat([torch.sin(ang), torch.cos(ang)], dim=-1)
class ResBlock(nn.Module):
def __init__(self, c, tdim=64):
super().__init__()
self.n1, self.c1 = nn.GroupNorm(8, c), nn.Conv2d(c, c, 3, padding=1)
self.n2, self.c2 = nn.GroupNorm(8, c), nn.Conv2d(c, c, 3, padding=1)
self.tproj = nn.Linear(tdim, c)
def forward(self, x, temb):
h = self.c1(F.silu(self.n1(x)))
h = h + self.tproj(F.silu(temb))[:, :, None, None] # AdaGN-style conditioning
return x + self.c2(F.silu(self.n2(h)))
class TinyUNet(nn.Module):
"""Predicts noise: (b,1,28,28) + timestep -> (b,1,28,28)."""
def __init__(self, in_ch=1, base=32, tdim=64):
super().__init__()
self.tmlp = nn.Sequential(nn.Linear(tdim, tdim), nn.SiLU(), nn.Linear(tdim, tdim))
self.in_conv = nn.Conv2d(in_ch, base, 3, padding=1)
self.down = ResBlock(base, tdim)
self.pool = nn.AvgPool2d(2) # 28x28 -> 14x14
self.mid = ResBlock(base, tdim)
self.up = nn.Upsample(scale_factor=2, mode="nearest")
self.merge = nn.Conv2d(2*base, base, 3, padding=1)
self.out_block = ResBlock(base, tdim)
self.out_conv = nn.Conv2d(base, in_ch, 3, padding=1)
def forward(self, x, t):
temb = self.tmlp(time_embedding(t)) # (b,64)
h0 = self.in_conv(x) # (b,32,28,28)
h1 = self.down(h0, temb) # skip connection
h = self.pool(h1) # (b,32,14,14)
h = self.mid(h, temb)
h = self.merge(torch.cat([self.up(h), h1], dim=1))
return self.out_conv(self.out_block(h, temb))
T = 1000
beta = torch.linspace(1e-4, 0.02, T)
alpha = 1 - beta
abar = torch.cumprod(alpha, dim=0)
ab_prev = torch.cat([torch.ones(1), abar[:-1]])
model = TinyUNet()
opt = torch.optim.AdamW(model.parameters(), lr=2e-4)
def q_sample(x0, t, eps):
a = abar[t][:, None, None, None]
return torch.sqrt(a)*x0 + torch.sqrt(1-a)*eps
dataset = datasets.MNIST("./data", train=True, download=True,
transform=transforms.ToTensor())
loader = torch.utils.data.DataLoader(dataset, batch_size=128, shuffle=True)
for epoch in range(10):
for x0, _ in loader:
x0 = x0*2 - 1 # scale to [-1,1]
t = torch.randint(0, T, (x0.shape[0],))
eps = torch.randn_like(x0)
loss = F.mse_loss(model(q_sample(x0, t, eps), t), eps)
opt.zero_grad(set_to_none=True); loss.backward(); opt.step()
@torch.no_grad()
def sample(n=16):
x = torch.randn(n, 1, 28, 28)
for i in reversed(range(T)):
ti = torch.full((n,), i, dtype=torch.long)
eps_hat = model(x, ti)
a, ap, b = abar[i], ab_prev[i], beta[i]
x0_hat = (x - torch.sqrt(1-a)*eps_hat)/torch.sqrt(a)
mean = (torch.sqrt(alpha[i])*(1-ap)/(1-a))*x \
+ (torch.sqrt(ap)*b/(1-a))*x0_hat
x = mean + math.sqrt(b)*torch.randn_like(x) if i > 0 else mean
return x.clamp(-1, 1)
images = sample()
Classifier-free guidance: during training randomly replace the condition with a learned null token (~10% of the time); at sampling compute two noise predictions and use .
18. Code walkthrough
Forward sample. q_sample uses the closed form, so the training loop never simulates sequential noise additions; this is what makes training parallel over timesteps — sample a random per example and jump directly to . The broadcasting [:,None,None,None] turns the per-sample into a spatial multiplier.
Network. TinyUNet maps a noisy image and a timestep to a noise tensor of identical shape — the key design constraint for -prediction. time_embedding uses sinusoidal features of (as in transformers); tproj(...)[:,:,None,None] broadcasts a channelwise affine shift into every spatial position, telling the network which noise level it is denoising. Skip connections preserve fine spatial detail.
Training. F.mse_loss(pred, eps) is exactly : no VLB weights, no discriminator. The target is known because we added it. The schedule buffers alpha, abar, ab_prev are precomputed once; ab_prev[0]=1 handles where .
Sampling. The reverse loop uses the exact posterior mean with from the network, i.e. ; adding reproduces DDPM's stochastic chain. For DDIM, replace that line with the deterministic update using the ab_prev value of a skipped timestep. This loop is sequential by nature — network evaluations — which is the main practical bottleneck.
Numerical check. The scratch code verifies to on the 1-D example, a cheap unit test for any reparameterization change.
19. Tensor and memory analysis
Training memory for the tiny MNIST model, batch , images , base=32:
- input/noise/target tensors: floats ≈ 1.2 MB;
- U-Net activations: down path ≈ 12.8 MB, bottleneck ≈ 3.2 MB, up path with concatenation ≈ 12.8 MB; total activations ~30 MB; gradients of similar size; Adam states params (~0.8M parameters ≈ 3 MB ×3) — training fits easily in a few hundred MB.
Scaling to latent diffusion (Stable Diffusion): a 512×512 RGB image in pixel space would be ≈ 3 MB per sample; the VAE encoder maps it to ≈ 64 KB, an 8× spatial compression. A batch of 8 latents is 0.5 MB; the U-Net (≈860M parameters in SD 1.5, ~3.4 GB fp32) dominates memory, plus activations of order gigabytes at attention layers. Mixed precision (fp16) halves weights and activations.
During sampling, only the current , the noise prediction, and a few scratch tensors are needed — memory is small, but the sequential forward passes cost time. Caching schedules and using torch.no_grad() avoids autograd graph storage.
20. Time complexity
Training: each step samples a random and performs one U-Net forward/backward on a batch, costing — independent of (the schedule is just a lookup). This is a major practical advantage: training cost is the same as a supervised denoiser.
Sampling: sequential denoising evaluations, ; with and a large U-Net this can take minutes per image on a GPU. DDIM with a subsequence of –50 steps reduces this by (20–50×); distillation (consistency models, progressive distillation) can reach 1–4 steps.
Complexity of the U-Net itself is dominated by convolutions () and self-attention at resolution ( in memory and compute for tokens). In latent space, gives 4096 tokens instead of — a 64× attention saving.
21. Space complexity
Model storage: parameters (tiny MNIST net ~0.8M; Stable Diffusion U-Net ~860M ≈ 3.4 GB fp32, 1.7 GB fp16). Optimizer states add for Adam. Training activations scale as and can be cut by checkpointing at ~30% extra compute.
Sampling needs for the state plus one denoiser forward's activations (no backward graph under no_grad). Storing the whole reverse trajectory for visualization costs , e.g. floats ≈ 50 MB for MNIST — manageable, but for high-resolution latents it is avoided.
Variance schedules and buffers are — negligible. Classifier-free guidance doubles (or triples, with text conditioning) the denoiser evaluations per sampling step unless batched.
22. Experimental demonstration
- Verify the forward closed form numerically: generate by applying single-step noisings iteratively and compare with ; assert equality in distribution and (with fixed noise decomposition) exact sample equality.
- Verify when on the 1-D example at several ; this catches schedule indexing errors.
- Train the tiny MNIST DDPM for 5–10 epochs and sample 16 digits; inspect progression at to see structure emerge progressively.
- Compare samplers: DDPM vs. DDIM with and from the same trained model; record wall-clock time per image and qualitative quality; compute FID if feasible.
- Ablate the schedule: replace linear with cosine; compare sample sharpness and training loss curves at the same number of steps.
- Classifier-free guidance sweep on a class-conditional model: compute inception score / FID and record the diversity–fidelity tradeoff (higher : sharper, less diverse).
23. Benchmark results
Ho et al. (2020) reported DDPM FID scores on unconditional CIFAR-10 of 3.17 with the simplified loss (and 3.21 with the full VLB loss), outperforming contemporary GANs' ~5–10 range, and strong Inception scores on ImageNet 128×128 conditional generation.
Dhariwal & Nichol (2021) reached FID 2.14 on ImageNet 128×128 with improved architectures/guidance, and a diffusion classifier achieved 78.9% top-1 accuracy, beating BigGAN-deep on some metrics. Nichol & Dhariwal (2021) obtained likelihoods around 3.72 bits/dim on CIFAR-10 with learned variances and cosine schedules, rivaling autoregressive models.
Latent diffusion (Rombach et al. 2022) reported FID 3.60 on ImageNet 256×256 and competitive MS-COCO text-to-image results at a fraction of pixel-space compute; SD 1.5 (a later derivative) became the de-facto open baseline.
These numbers depend heavily on evaluation protocol (number of samples, FID implementation, guidance scale, sampler steps, classifier-free vs. classifier guidance). Always report sampler, steps, guidance scale, and sample count; compare within one protocol only.
24. Limitations
- Sampling is slow: hundreds to thousands of sequential network evaluations (DDIM/distillation mitigate but trade quality/Training complexity).
- Training may be stable but is expensive: large U-Nets and long schedules need substantial compute; high-resolution pixel-space diffusion is memory-hungry.
- The simplified loss ignores VLB weights, giving worse likelihoods even when samples are better; likelihood and perceptual quality disagree.
- Mode coverage can still be imperfect; classifier-free guidance with large reduces diversity and can saturate images.
- The forward process assumes a fixed Gaussian noise schedule; mismatched schedules/parameterizations cause instability or poor samples.
- Conditional generation requires extra machinery (cross-attention, guidance, classifiers).
- Evaluation is tricky: FID is sensitive to sample count and preprocessing; no single number captures fidelity and diversity.
25. Failure scenarios
- Samples are pure noise: the reverse mean is miscomputed (wrong indexing), or the model was trained at a different schedule than sampling; unit-test .
- Samples are oversaturated / burned with high guidance: reduce ; monitor per-channel clipping rate.
- Training loss plateaus: learning rate too small/large, or the network cannot see (missing time embedding); log loss per timestep bucket.
- Off-by-one in : using
abar[t]instead ofabar[t-1]for 1-based ; verify with the 1-D example and witht=1where . - NaN in sampling near : division by when ; clamp or skip the noise-adding step at .
- DDIM produces blurred samples after skipping steps: the subsequence is too coarse or the model was trained with a different schedule; use 20–50 steps and verify consistency.
- Memory explosion at high resolution: pixel-space attention at 512² is quadratic; use latent diffusion or local attention.
26. Common misconceptions
- "The forward process is learned." It is fixed; only the reverse denoiser is trained.
- "The network predicts the clean image." DDPM predicts the noise ; is derived (prediction of is an equivalent parameterization used by some variants).
- "The simplified loss is the VLB." It drops time-dependent weights; it optimizes sample quality better but gives worse likelihood.
- "More diffusion steps always mean better samples." Quality saturates; is often more than needed, especially with DDIM.
- "DDIM is a different trained model." It reuses the same with a different (deterministic) reverse process.
- "Classifier-free guidance needs a classifier." It needs only a conditional and an unconditional denoiser (null-condition dropout during training).
- "Diffusion models are autoregressive." They generate all pixels in parallel per step but sequentially across ; the factorization is over noise levels, not pixels.
27. Alternative approaches
- GANs (StyleGAN, BigGAN): single forward pass, sharp samples, but unstable training and mode collapse.
- VAEs: fast, likelihood-based, but often blurry samples; expressive priors partly close the gap.
- Autoregressive models (PixelCNN, GPT-style image models): exact likelihood, slow sequential pixel/token generation.
- Score-based SDEs / flow matching: continuous-time generalization; probability-flow ODEs enabling adaptive solvers and few-step sampling.
- Consistency models / progressive distillation: distill the -step chain to 1–4 steps.
- Normalizing flows: invertible, exact likelihood, architectural constraints.
- Latent diffusion: the same DDPM machinery in a compressed autoencoder space for efficiency.
29. Research applications
- Text-to-image / video: Stable Diffusion, Imagen, DALL·E 2/3, Sora-style video diffusion with spatiotemporal U-Nets or diffusion transformers.
- Image-to-image / editing: inpainting, super-resolution, style transfer via conditional diffusion and guidance.
- Scientific domains: molecular conformation generation, protein design (diffusion on 3D coordinates), weather forecasting, medical image synthesis.
- Audio / speech: waveform diffusion (WaveNet-style), vocoders, music generation.
- Reinforcement learning: diffusion policies for robotic action sequences; generative modeling of trajectories.
- Theory: score-based SDE frameworks, optimal transport connections, sampling acceleration, and understanding guidance biases.
30. Important research papers
- Sohl-Dickstein J., Weiss E. A., Maheswaranathan N., Ganguli S. (2015), Deep Unsupervised Learning using Nonequilibrium Thermodynamics, ICML — original diffusion framework.
- Song Y., Ermon S. (2019/2020), Generative Modeling by Estimating Gradients of the Data Distribution / Score-Based Generative Modeling through Stochastic Differential Equations, NeurIPS/ICLR.
- Ho J., Jain A., Abbeel P. (2020), Denoising Diffusion Probabilistic Models, NeurIPS — DDPM and the simplified loss.
- Song J., Meng C., Ermon S. (2020), Denoising Diffusion Implicit Models, ICLR — DDIM.
- Nichol A. Q., Dhariwal P. (2021), Improved Denoising Diffusion Probabilistic Models, ICML — cosine schedule, learned variance.
- Dhariwal P., Nichol A. (2021), Diffusion Models Beat GANs on Image Synthesis, NeurIPS.
- Ho J., Salimans T. (2022), Classifier-Free Diffusion Guidance, NeurIPS workshop.
- Rombach R. et al. (2022), High-Resolution Image Synthesis with Latent Diffusion Models, CVPR.
31. Further reading
- Ho et al. (2020) — the paper's derivations and pseudocode are compact enough to reproduce in a weekend.
- Song et al. (2020) DDIM for the deterministic-sampling family.
- Nichol & Dhariwal (2021) for schedules and learned variances.
- Rombach et al. (2022) for latent diffusion and cross-attention conditioning.
- Hugging Face "Diffusion Models" course and the
diffuserslibrary docs. - Karras et al. (2022), Elucidating the Design Space of Diffusion-Based Generative Models, for modern sampler design.
32. Practical exercises
- Implement the forward closed form and the posterior mean/variance in NumPy; verify the 1-D numbers in section 13 to 4 decimals.
- Prove when symbolically, then verify numerically for 5 timesteps.
- Implement the tiny MNIST DDPM from memory; train for 3 epochs and sample digits; show the denoising trajectory at 5 timesteps.
- Derive the VLB weights and implement both and ; compare likelihood proxy and sample quality.
- Implement DDIM sampling on the same trained model and compare times/quality for .
- Add classifier-free guidance: train with null-condition dropout, sample with , and quantify the diversity–fidelity tradeoff (FID vs. feature diversity).
33. Debugging challenges
- Sampled images look like static: check the schedule indexing (
abar[t-1]), that the model output shape matches , and that sampling uses the same /schedule as training. - NaN losses early in training: scale inputs to , check
tdtype (long), and clamp schedules at . - Loss decreases but samples are blurry: schedule too aggressive or network too small; try cosine and more capacity.
- Guidance saturates images: reduce and check that the null-condition branch is actually being used during training.
- DDIM with few steps gives artefacts: use more steps or a schedule-matched subsequence; verify is computed with the correct .
- Out of memory during training: enable mixed precision, reduce batch, or move to latent space.
t=1sampling divides by zero: use and setab_prev[0]=1explicitly.
34. Advanced exercises
- Derive the continuous-time limit of DDPM as an SDE (Song et al. 2020) and show the reverse-time SDE uses the score .
- Derive the DDIM family from the non-Markovian forward process and prove that different values give the same training marginals.
- Prove that optimizing corresponds to a reweighted score-matching objective; identify the weighting and its effect on low/high-noise regimes.
- Implement learned reverse variance (Nichol & Dhariwal) by predicting a mixture parameter over ; compare VLB scores.
- Implement a diffusion transformer (DiT) patchifying latents instead of using a U-Net; compare FLOPs at the same sample quality.
- Derive classifier-free guidance from a classifier-guided score and analyze how large distorts the implied distribution.
35. Interview questions
- State the forward process and derive in closed form.
- Derive and show that predicting suffices to parameterize the reverse mean.
- Why do Ho et al. drop the VLB weights? What is gained and lost?
- Compare DDPM sampling with DDIM sampling; why can DDIM skip steps?
- Explain classifier-free guidance and the effect of the scale .
- Why is training cost independent of but sampling cost proportional to ?
- What is the role of the noise schedule, and how do linear and cosine schedules differ?
- Why do latent diffusion models use a VAE encoder/decoder?
36. Research questions
- Can we design noise schedules and loss weightings that simultaneously optimize likelihood and perceptual quality?
- What is the minimal number of sampling steps achievable without distillation while preserving fidelity for a given model capacity?
- How does classifier-free guidance bias the generated distribution, and can we correct it while keeping sharpness?
- Can diffusion models be trained with single-step consistency objectives from scratch at scale?
- How do diffusion-generated data affect downstream model training (data quality, memorization, and distribution collapse)?
37. Mastery assessment
To pass: (1) derive the forward marginal and posterior mean without notes; (2) prove the -parameterization identity and derive from the VLB; (3) reproduce the 1-D numerical example; (4) implement DDPM training and sampling for MNIST plus DDIM sampling; (5) explain schedules, U-Net conditioning, and guidance; (6) diagnose static/blurry/saturated samples; (7) answer the interview questions. Complete the linked assessment; reading alone is not mastery.
38. Implementation submission
Push a repository containing ddpm_numpy.py (forward, posterior, parameterization check), ddpm_torch.py (TinyUNet, schedule, training loop, samplers DDPM/DDIM, CFG hook), experiments.ipynb (1-D verification, MNIST samples with denoising trajectory, sampler-step sweep, guidance sweep), a README.md with derivations and measured timings, and tests asserting and shape/dtype correctness. Submit the repository URL and exact reproduction command.
39. Completion criteria
All of: every section read; forward and reverse derivations reproduced on paper; NumPy and PyTorch implementations passing tests; at least three experiments with recorded numbers and plots; assessment score ; one failure case (noise-only samples, schedule off-by-one, or guidance saturation) reproduced and explained; one research question answered in a one-page note citing a paper. Only then mark the concept mastered.`