Diffusion Models: Training and Sampling
The previous lesson built the forward process: a schedule and the one-step formula . This lesson does the learning and the generating. A network is trained to predict the noise in a noisy input, and generation starts from pure noise and removes a little of it at each step. You will see that the training loss is a plain regression, why it can never reach zero, and two samplers: DDPM, which is stochastic and uses every step, and DDIM, which is deterministic and can skip steps. A NumPy sampler driven by the exact optimal noise predictor recovers an 8-mode distribution in the browser. A small trained PyTorch denoiser does the same for the two-moons data. The lesson ends with classifier-free guidance and latent diffusion, the two ideas behind text-to-image systems.
The training objective
Ho et al. (2020) showed that a weighted form of the ELBO for this model reduces to a regression on the noise. With weights dropped, it becomes the simple loss:
One training step draws a batch of images, a random and a fresh for each, builds in one step, and regresses the network's output on . There is no adversary and no sampling during training. That is a large part of why diffusion models train so reliably.
The time input. The same network serves all noise levels, so it must know . The usual encoding is the sinusoidal one from transformers (Positional Encodings): and for geometrically spaced frequencies . Large networks pass it through a small MLP and add it to every block of the denoiser.
What the optimum is. For squared error, the best possible predictor is the conditional mean . Tweedie's formula ties it to the score of the noisy data distribution :
So a noise predictor is a scaled score estimator, the same object a denoising autoencoder approximates. For a Gaussian mixture, is again a Gaussian mixture, with each mean scaled by and each variance . Its score has a closed form, and so does . The next example uses this on the 8-blob ring from the GAN lesson to compute the loss the best possible network would reach, and it checks the time embedding.
import numpy as np
K, s = 8, 0.05
angles = np.arange(K) * 2 * np.pi / K
mu = np.stack([2 * np.cos(angles), 2 * np.sin(angles)], axis=1)
T = 1000
ab = np.cumprod(1 - np.linspace(1e-4, 0.02, T))
def eps_star(x, t): # optimal predictor; t may differ per row
a = ab[np.broadcast_to(t, len(x)) - 1][:, None] # (n, 1)
m, v = np.sqrt(a)[:, :, None] * mu[None], a * s ** 2 + (1 - a) # (n, K, 2), (n, 1)
logw = -((x[:, None, :] - m) ** 2).sum(-1) / (2 * v)
w = np.exp(logw - logw.max(axis=1, keepdims=True)); w /= w.sum(axis=1, keepdims=True)
return -np.sqrt(1 - a) * (w[:, :, None] * (m - x[:, None, :])).sum(1) / v
rng = np.random.default_rng(0)
n = 4000
x0 = mu[rng.integers(0, K, n)] + s * rng.standard_normal((n, 2))
print(" t loss of eps = 0 loss of the best possible predictor")
total = []
for t in (1, 10, 50, 200, 500, 1000):
eps = rng.standard_normal((n, 2))
xt = np.sqrt(ab[t - 1]) * x0 + np.sqrt(1 - ab[t - 1]) * eps
best = np.mean((eps_star(xt, t) - eps) ** 2)
print(f"{t:5d} {np.mean(eps ** 2):15.3f} {best:20.3f}")
# the simple loss averages over t drawn uniformly: estimate it for the best predictor
t = rng.integers(1, T + 1, n)
eps = rng.standard_normal((n, 2))
xt = np.sqrt(ab[t - 1])[:, None] * x0 + np.sqrt(1 - ab[t - 1])[:, None] * eps
best = np.mean((eps_star(xt, t) - eps) ** 2)
print(f"simple loss of the best predictor, t uniform: {best:.3f} (a trained network cannot go below this)")
# sinusoidal time embedding: nearby steps get similar vectors, distant steps different ones
def time_embedding(t, dim=32):
freqs = np.exp(-np.log(1000.0) * np.arange(dim // 2) / (dim // 2))
ang = np.asarray(t, dtype=float)[:, None] * freqs[None]
return np.concatenate([np.sin(ang), np.cos(ang)], axis=1)
E = time_embedding([500, 501, 510, 600, 900])
cos = E @ E[0] / (np.linalg.norm(E, axis=1) * np.linalg.norm(E[0]))
print("cosine similarity of t = 500 with t = 501, 510, 600, 900:", np.round(cos[1:], 3).tolist()) t loss of eps = 0 loss of the best possible predictor
1 0.987 0.950
10 0.991 0.571
50 1.013 0.078
200 1.029 0.555
500 1.000 0.145
1000 0.983 0.000
simple loss of the best predictor, t uniform: 0.196 (a trained network cannot go below this)
cosine similarity of t = 500 with t = 501, 510, 600, 900: [0.949, 0.529, 0.26, -0.02]
Predicting zero costs about 1 at every , the variance of . The best predictor's loss depends strongly on . At it is 0.000, because is almost pure noise and the noise is the input. At it is 0.950: the added noise (standard deviation 0.01) is much smaller than the blobs' own spread of 0.05, so it cannot be told apart from the data. At it is 0.555, where neighbouring blobs overlap and a point could belong to either. Averaged over a uniform , the minimum is 0.196, not 0. A diffusion loss curve that levels off is not necessarily a failure, and comparing it with 0 means nothing. The embedding gives a cosine similarity of 0.949 to , only 0.529, and about 0. The network can tell nearby noise levels apart and still share what it learns between them.
Sampling: DDPM and DDIM
DDPM ancestral sampling runs the learned reverse chain. Start from and for compute
with no noise at the last step. The mean is the posterior mean of with replaced by its estimate. Ho et al. found works about as well. It costs network evaluations per sample.
DDIM (Song, Meng and Ermon, 2020) uses the same trained network with a deterministic update between any two steps . First estimate the clean sample, then re-noise it to level with the predicted noise instead of fresh noise:
Because the update does not need consecutive steps, 50 or 20 network calls can replace 1000. Being deterministic, it maps each starting noise to one sample, which makes interpolation between noises meaningful. It is a discretisation of an ordinary differential equation (the probability-flow ODE), so with very few steps the discretisation error grows.
Both samplers, in NumPy, driven by the exact for the 8-blob ring. A sample is "near a mode" within 0.15 (3 standard deviations) of a centre, a mode is covered if it gets a quarter of its fair share, and "spread" is the per-coordinate standard deviation of the near samples around their centre.
import numpy as np
# Data: 8 Gaussian blobs on a ring of radius 2, standard deviation 0.05 (the GAN lesson's test set)
K, s = 8, 0.05
angles = np.arange(K) * 2 * np.pi / K
mu = np.stack([2 * np.cos(angles), 2 * np.sin(angles)], axis=1)
T = 1000
beta = np.linspace(1e-4, 0.02, T)
alpha = 1 - beta
ab = np.cumprod(alpha)
def eps_star(x, t):
"""The optimal noise predictor E[eps | x_t] for this data, in closed form (t = 1..T)."""
a = ab[t - 1]
m, v = np.sqrt(a) * mu, a * s ** 2 + (1 - a) # x_t is a mixture of N(m_k, v I)
logw = -((x[:, None, :] - m[None]) ** 2).sum(-1) / (2 * v)
w = np.exp(logw - logw.max(axis=1, keepdims=True))
w /= w.sum(axis=1, keepdims=True) # responsibilities of the 8 blobs
score = (w[:, :, None] * (m[None] - x[:, None, :])).sum(1) / v # gradient of log p_t(x)
return -np.sqrt(1 - a) * score
def report(name, x):
d = np.sqrt(((x[:, None, :] - mu[None]) ** 2).sum(-1))
near = d.min(axis=1) < 3 * s
counts = np.bincount(d.argmin(axis=1)[near], minlength=K)
spread = np.sqrt((d.min(axis=1)[near] ** 2).mean() / 2) # per-coordinate std around the blob
print(f"{name:21s} near a mode {near.mean():.3f} covered {int((counts > 0.25 * len(x) / K).sum())}/8"
f" spread {spread:.4f} per mode {counts.tolist()}")
rng = np.random.default_rng(0)
n = 1000
report("data itself", mu[rng.integers(0, K, n)] + s * rng.standard_normal((n, 2)))
report("x_T ~ N(0, I)", rng.standard_normal((n, 2)))
# DDPM ancestral sampling: T steps, fresh noise at each step
x = rng.standard_normal((n, 2))
for t in range(T, 0, -1):
eps = eps_star(x, t)
mean = (x - beta[t - 1] / np.sqrt(1 - ab[t - 1]) * eps) / np.sqrt(alpha[t - 1])
var = beta[t - 1] * (1 - ab[t - 2]) / (1 - ab[t - 1]) if t > 1 else 0.0 # posterior variance
x = mean + np.sqrt(var) * rng.standard_normal((n, 2))
report("DDPM, 1000 steps", x)
# DDIM (eta = 0): deterministic, any subsequence of steps
for steps in (50, 10):
ts = np.linspace(T, 1, steps).round().astype(int)
x = rng.standard_normal((n, 2))
for i, t in enumerate(ts):
eps = eps_star(x, t)
x0_hat = (x - np.sqrt(1 - ab[t - 1]) * eps) / np.sqrt(ab[t - 1])
a_next = ab[ts[i + 1] - 1] if i + 1 < len(ts) else 1.0
x = np.sqrt(a_next) * x0_hat + np.sqrt(1 - a_next) * eps
report(f"DDIM, {steps} steps", x)data itself near a mode 0.996 covered 8/8 spread 0.0492 per mode [118, 109, 120, 114, 144, 129, 129, 133]
x_T ~ N(0, I) near a mode 0.010 covered 0/8 spread 0.0731 per mode [1, 0, 1, 2, 1, 1, 1, 3]
DDPM, 1000 steps near a mode 0.990 covered 8/8 spread 0.0449 per mode [135, 114, 145, 113, 122, 120, 121, 120]
DDIM, 50 steps near a mode 0.996 covered 8/8 spread 0.0361 per mode [142, 121, 115, 126, 122, 120, 122, 128]
DDIM, 10 steps near a mode 0.670 covered 8/8 spread 0.0397 per mode [71, 83, 82, 86, 90, 90, 72, 96]
Starting from , where 1 % of points happen to lie near a mode, 1000 DDPM steps give 99.0 % near a mode, all 8 modes with 113 to 145 samples each, and a spread of 0.0449, close to the data's own 0.0492. That is the reverse process working exactly as the theory says, with nothing learned. DDIM with 50 steps covers all modes just as well (99.6 %), but its blobs are too tight (0.0361): the coarse discretisation of the ODE pulls samples towards the centres. With 10 steps, only 67.0 % of samples land near a mode, and the rest sit between blobs. Fewer steps cost accuracy, and better ODE solvers (DPM-Solver and others) exist to reduce that cost. Compare the GAN on the same data, whose mode coverage depended on Adam's .
A trained denoiser in PyTorch (recorded)
Now the predictor is learned. The data is the course's two moons (600 points, noise 0.25), standardised. A 3-layer MLP with SiLU activations takes and predicts . With only 2 dimensions, steps with from to 0.1 is enough. Samples are judged in two ways. The first is the mean distance from each sample to its nearest training point. The second is the MMD (maximum mean discrepancy with a Gaussian kernel) to a separate draw of real data, which is close to 0 only when two point sets have the same distribution. Fresh real data and a standard-normal cloud set the scale. The example is recorded and ran on the CPU.
import math
import numpy as np
import torch
from torch import nn
from sklearn.datasets import make_moons
torch.manual_seed(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
X, _ = make_moons(n_samples=600, noise=0.25, random_state=0)
mean, std = X.mean(axis=0), X.std(axis=0)
data = torch.tensor((X - mean) / std, dtype=torch.float32, device=device) # standardised training data
fresh = lambda seed: torch.tensor((make_moons(n_samples=600, noise=0.25, random_state=seed)[0] - mean) / std,
dtype=torch.float32)
ref, real2 = fresh(1), fresh(2) # new real data, never trained on
T = 200
beta = torch.linspace(1e-4, 0.1, T, dtype=torch.float64) # T = 200, so larger steps
alpha = 1 - beta
ab = torch.cumprod(alpha, 0)
beta, alpha, ab = beta.float().to(device), alpha.float().to(device), ab.float().to(device)
def time_embedding(t, dim=32):
"""Sinusoidal embedding of the step t (as in transformers' positional encodings)."""
freqs = torch.exp(-math.log(1000.0) * torch.arange(dim // 2, device=t.device) / (dim // 2))
angles = t.float()[:, None] * freqs[None]
return torch.cat([torch.sin(angles), torch.cos(angles)], dim=1)
class Denoiser(nn.Module):
def __init__(self, hidden=128):
super().__init__()
self.net = nn.Sequential(nn.Linear(2 + 32, hidden), nn.SiLU(), nn.Linear(hidden, hidden), nn.SiLU(),
nn.Linear(hidden, hidden), nn.SiLU(), nn.Linear(hidden, 2))
def forward(self, x, t): # predicts the noise eps that was added to get x_t
return self.net(torch.cat([x, time_embedding(t)], dim=1))
model = Denoiser().to(device)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
running = 0.0
for step in range(1, 4501):
x0 = data[torch.randint(0, len(data), (256,), device=device)]
t = torch.randint(1, T + 1, (256,), device=device)
eps = torch.randn_like(x0)
a = ab[t - 1][:, None]
xt = a.sqrt() * x0 + (1 - a).sqrt() * eps
loss = ((model(xt, t) - eps) ** 2).mean() # the simple loss of DDPM
opt.zero_grad(); loss.backward(); opt.step()
running += loss.item()
if step % 1500 == 0:
print(f"steps {step - 1499:4d}-{step:4d} mean loss {running / 1500:.4f}")
running = 0.0
@torch.no_grad()
def ddpm(n):
x = torch.randn(n, 2, device=device)
for t in range(T, 0, -1):
tt = torch.full((n,), t, device=device)
eps = model(x, tt)
mean_ = (x - beta[t - 1] / (1 - ab[t - 1]).sqrt() * eps) / alpha[t - 1].sqrt()
var = beta[t - 1] * (1 - ab[t - 2]) / (1 - ab[t - 1]) if t > 1 else torch.tensor(0.0)
x = mean_ + var.sqrt() * torch.randn_like(x)
return x.cpu()
@torch.no_grad()
def ddim(n, steps):
ts = torch.linspace(T, 1, steps).round().long().tolist()
x = torch.randn(n, 2, device=device)
for i, t in enumerate(ts):
eps = model(x, torch.full((n,), t, device=device))
x0_hat = (x - (1 - ab[t - 1]).sqrt() * eps) / ab[t - 1].sqrt()
a_next = ab[ts[i + 1] - 1] if i + 1 < len(ts) else torch.tensor(1.0)
x = a_next.sqrt() * x0_hat + (1 - a_next).sqrt() * eps
return x.cpu()
def nn_dist(a, b): # mean distance from each point of a to its nearest in b
return torch.cdist(a, b).min(dim=1).values.mean().item()
def mmd(a, b, h=0.5): # kernel two-sample statistic, 0 for equal distributions
k = lambda u, v: torch.exp(-torch.cdist(u, v) ** 2 / (2 * h * h)).mean()
return (k(a, a) + k(b, b) - 2 * k(a, b)).item()
model.eval()
torch.manual_seed(1)
gauss = torch.randn(600, 2) # baseline: standard normal (the data is standardised)
for name, s in [("new real data", real2), ("Gaussian baseline", gauss), ("DDPM, 200 steps", ddpm(600)),
("DDIM, 20 steps", ddim(600, 20)), ("DDIM, 5 steps", ddim(600, 5))]:
print(f"{name:18s} NN distance to training data {nn_dist(s, data.cpu()):.3f} MMD to other real data {mmd(s, ref):.4f}")steps 1-1500 mean loss 0.2840
steps 1501-3000 mean loss 0.2691
steps 3001-4500 mean loss 0.2660
new real data NN distance to training data 0.081 MMD to other real data 0.0019
Gaussian baseline NN distance to training data 0.147 MMD to other real data 0.0191
DDPM, 200 steps NN distance to training data 0.084 MMD to other real data 0.0036
DDIM, 20 steps NN distance to training data 0.086 MMD to other real data 0.0086
DDIM, 5 steps NN distance to training data 0.070 MMD to other real data 0.0503
The mean loss levels off at 0.2660. As in the NumPy example, the floor is above 0, and there is no exact value to compare with for moons. A second draw of real data has an MMD of 0.0019 to the reference set. The Gaussian baseline has 0.0191. DDPM with all 200 steps reaches 0.0036, much closer to real data than to the baseline, and its mean nearest-neighbour distance (0.084) is about that of real data (0.081). DDIM with 20 steps is worse (MMD 0.0086), and with 5 steps much worse (0.0503). The 5-step DDIM shows why one metric is not enough. Its nearest-neighbour distance, 0.070, is better than that of real data, because its samples collapse onto the dense middle of the moons. A distance-to-data metric rewards that, and it would also reward copying the training set. MMD sees that the distribution is wrong. Report a distribution-level metric (MMD here, FID for images) next to any per-sample distance.
Guidance and latent diffusion
Conditioning. To generate a requested class or a text prompt , the denoiser takes as another input, : a class embedding added like the time embedding, or text-encoder outputs read through cross-attention (Attention from Scratch).
Classifier-free guidance (Ho and Salimans, 2022) trains one network both with and without the condition, by replacing with a "null" token for, say, 10 % of training examples. At sampling time it extrapolates from the unconditional prediction towards the conditional one:
is plain conditional sampling. Values of 3 to 8 are common for text-to-image: samples match the prompt more closely and look cleaner, at the cost of diversity. Each step needs two network evaluations, usually done as one batch of two.
Latent diffusion (Rombach et al., 2022, the basis of Stable Diffusion) runs the whole process in the latent space of a pretrained autoencoder instead of on pixels. The encoder downsamples, for example a image to a latent, which makes each denoiser step much cheaper. The decoder turns the final latent into an image. The autoencoder is trained first, with a reconstruction loss plus perceptual and adversarial terms (see GANs) and a light KL penalty, a mild form of the VAE objective.
The denoiser for images is usually a U-Net: a convolutional encoder-decoder with skip connections between the levels of the same resolution, with the time embedding added in every residual block and attention at the lower resolutions. Newer models replace it with a transformer over patches (DiT). U-Nets and segmentation are covered in Computer Vision.
Pitfalls
- Expecting the loss to go to zero. Its floor depends on the data and the schedule (0.196 for the ring above). Judge models by their samples.
- Mixing conventions between training and sampling. The sampler must use exactly the schedule, the indexing of and the target (, or ) of training.
- Clipping. For images in , many samplers clip to that range at each step, which helps with few steps. Applied to latents or to data with another range, it does harm.
- Too few sampler steps without checking. As above, 5 DDIM steps looked good on a per-sample metric and were wrong on the distribution.
- Training on a small set for too long. A strong denoiser can memorise the training images and reproduce them. Check samples against their nearest training examples.
Practice
- Why is the best predictor's loss exactly about 0 at but close to 1 at for the ring data?
Answer
At , , so and the predictor can return its input. At , the added noise has standard deviation , while each blob has standard deviation 0.05. Given , you cannot tell which part of the offset from the blob centre is data and which is noise, so is close to 0 and the loss stays near the variance of . The ratio is about , near the measured 0.950.
- Show that one DDIM step from to returns unchanged, and explain why DDIM is deterministic while DDPM is not.
Answer
With : . DDIM re-noises with the predicted noise, a function of , so the path depends only on . DDPM adds fresh noise at every step.
- With guidance weight , what does classifier-free guidance sample from? With ?
Answer
gives , the unconditional model, which ignores the prompt. gives the conditional prediction, sampling from the model's with no extra emphasis. Values above 1 push beyond it.
Test yourself
What does a DDPM network regress on during training?
- The clean image from the class label
- The noise that was added to make , given and
- The discriminator's output
- The next pixel of the image
The best possible noise predictor for the 8-blob ring has a simple loss of 0.196 averaged over . What follows for a trained network?
- It should reach 0 with enough training
- Its loss cannot go below 0.196 on this data, so a plateau above 0 is expected
- The schedule is wrong
- The data must be standardised again
How does DDIM differ from DDPM ancestral sampling?
- It needs a different trained network
- It is deterministic given and can skip steps, using the same trained network
- It adds more noise at each step
- It only works for 2-D data
In the moons example, 5 DDIM steps gave a smaller mean nearest-neighbour distance to the training data (0.070) than fresh real data (0.081). What does that indicate?
- 5 steps generate better samples than real data
- The samples are concentrated in dense regions (too little diversity), which a per-sample distance rewards; the MMD of 0.0503 shows the distribution is wrong
- The training data leaked into the sampler
- Nothing, the metrics agree
In classifier-free guidance with , what is computed at each step?
- Only the conditional prediction
- The unconditional prediction plus 5 times the difference between the conditional and unconditional predictions
- A separate classifier's gradient
- Five sampling chains