Diffusion Models: The Noising Process
GANs generate in one shot and train as an unstable game. VAEs train stably but give blurry samples. Diffusion models (Sohl-Dickstein et al., 2015; Ho, Jain and Abbeel, 2020, "DDPM") get stable training and sharp samples by splitting generation into many small steps. A fixed forward process destroys an image by adding a little Gaussian noise at each of steps (typically ) until only noise is left. A network then learns the reverse process, one denoising step at a time. The forward process has no parameters, but its details (the noise schedule, the closed form for jumping to any step, and what the network is asked to predict) decide much of how well the reverse process can be learned. This lesson is about that part. Diffusion Models: Training and Sampling trains the network and samples from it.
The chain
The forward process
A variance schedule with small values in defines each step:
The scaling by matters. If has unit variance, then has variance , so the data is not just buried under ever-growing noise but slowly replaced by noise, and the end point is a standard normal. With and , composing Gaussians gives the closed form that makes training cheap:
A proof by induction: if , one more step multiplies the mean by and gives a noise variance of , because independent Gaussian noises add their variances. A training example therefore never needs the chain: pick , draw one , and compute directly.
The signal-to-noise ratio summarises the schedule. It falls from very large at to nearly 0 at , and its value in decibels, , is a convenient way to compare schedules.
Linear and cosine schedules
DDPM used a linear schedule, from to . Nichol and Dhariwal (2021) noticed that it destroys small images too early. They proposed a cosine schedule defined through directly,
with each clipped at to avoid a singular last step. Both, computed in NumPy:
import numpy as np
T = 1000
beta_lin = np.linspace(1e-4, 0.02, T) # Ho et al. (2020), t = 1..T
alpha_bar_lin = np.cumprod(1 - beta_lin)
s = 0.008 # Nichol and Dhariwal (2021)
f = np.cos((np.arange(T + 1) / T + s) / (1 + s) * np.pi / 2) ** 2
beta_cos = np.clip(1 - f[1:] / f[:-1], 0, 0.999) # clipped as in the paper
alpha_bar_cos = np.cumprod(1 - beta_cos)
print(" t alpha_bar lin alpha_bar cos SNR lin (dB) SNR cos (dB)")
for t in (1, 50, 100, 250, 500, 750, 1000):
a_l, a_c = alpha_bar_lin[t - 1], alpha_bar_cos[t - 1]
snr = lambda a: 10 * np.log10(a / (1 - a))
print(f"{t:5d} {a_l:13.5f} {a_c:13.5f} {snr(a_l):12.1f} {snr(a_c):12.1f}")
print("first t with alpha_bar < 0.5: linear", int(np.argmax(alpha_bar_lin < 0.5)) + 1,
" cosine", int(np.argmax(alpha_bar_cos < 0.5)) + 1)
print("steps with SNR below -20 dB: linear", int(np.sum(alpha_bar_lin / (1 - alpha_bar_lin) < 0.01)),
" cosine", int(np.sum(alpha_bar_cos / (1 - alpha_bar_cos) < 0.01)))
print(f"largest beta: linear {beta_lin.max():.4f} cosine {beta_cos.max():.4f}") t alpha_bar lin alpha_bar cos SNR lin (dB) SNR cos (dB)
1 0.99990 0.99996 40.0 43.8
50 0.97102 0.99201 15.3 20.9
100 0.89702 0.97209 9.4 15.4
250 0.52409 0.84701 0.4 7.4
500 0.07859 0.49384 -10.7 -0.1
750 0.00335 0.14427 -24.7 -7.7
1000 0.00004 0.00000 -43.9 -86.1
first t with alpha_bar < 0.5: linear 260 cosine 497
steps with SNR below -20 dB: linear 326 cosine 64
largest beta: linear 0.0200 cosine 0.9990
The linear schedule passes (0 dB, as much signal as noise) at step 260, and 326 of its 1000 steps have an SNR below dB, where the image is close to pure noise. Those steps teach the network little. The cosine schedule reaches only at step 497, falls almost linearly through the middle and spends only 64 steps below dB. Its largest is the clipped 0.999 at the very last step, which takes to dB. Both end close enough to for sampling to start from pure noise. (Lin et al., 2024, showed that a non-zero terminal SNR can still bias generation in large models. That is a fine point beyond this lesson.)
One step equals the whole chain
The closed form is an exact statement about distributions, which makes it easy to test. The code below runs 20,000 independent chains of 1000 steps from the same two-pixel and compares the empirical means and variances with and . Then it samples in one step.
import numpy as np
rng = np.random.default_rng(0)
T = 1000
beta = np.linspace(1e-4, 0.02, T)
alpha_bar = np.cumprod(1 - beta)
x0 = np.array([1.5, -0.5]) # two "pixels"
n = 20_000
x = np.tile(x0, (n, 1)) # n independent chains, all starting at x0
print(" t chain mean closed-form mean chain var closed-form var")
for t in range(1, T + 1):
x = np.sqrt(1 - beta[t - 1]) * x + np.sqrt(beta[t - 1]) * rng.standard_normal(x.shape) # q(x_t | x_{t-1})
if t in (10, 100, 500, 1000):
m = np.sqrt(alpha_bar[t - 1]) * x0
print(f"{t:4d} [{x[:, 0].mean():6.3f}, {x[:, 1].mean():6.3f}] [{m[0]:6.3f}, {m[1]:6.3f}]"
f" {x.var(axis=0).mean():.4f} {1 - alpha_bar[t - 1]:.4f}")
# the same distribution in one step, for t = 500
t = 500
eps = rng.standard_normal((n, 2))
x_direct = np.sqrt(alpha_bar[t - 1]) * x0 + np.sqrt(1 - alpha_bar[t - 1]) * eps
print(f"one-step sample at t = {t}: mean [{x_direct[:, 0].mean():.3f}, {x_direct[:, 1].mean():.3f}]"
f" var {x_direct.var(axis=0).mean():.4f} correlation between pixels {np.corrcoef(x_direct.T)[0, 1]:.3f}") t chain mean closed-form mean chain var closed-form var
10 [ 1.499, -0.500] [ 1.499, -0.500] 0.0019 0.0019
100 [ 1.421, -0.476] [ 1.421, -0.474] 0.1026 0.1030
500 [ 0.422, -0.133] [ 0.421, -0.140] 0.9266 0.9214
1000 [-0.009, 0.008] [ 0.010, -0.003] 0.9973 1.0000
one-step sample at t = 500: mean [0.412, -0.143] var 0.9259 correlation between pixels 0.005
At , the chain's mean matches , and its variance 0.1026 matches 0.1030. At , the mean is and the variance 1 up to sampling error. With 20,000 chains, the standard error of a mean at large is about , and every gap in the table is within three standard errors. The one-step sample at has the same mean and variance as the chain, and its two pixels are uncorrelated (0.005), as the covariance says.
Seeing it, and what to predict
The next example noises one digit (pixels scaled to , the usual range for diffusion) with one fixed noise draw at several under both schedules, and draws the result. The table below the figure is about the network's job. Given and , a network can be trained to predict any one of three equivalent targets, because each determines the others through :
| Target | Recover from it | Used by |
|---|---|---|
| noise | DDPM, Stable Diffusion 1 | |
| clean data | directly | some image and audio models, the analysis of samplers |
| velocity | progressive distillation, Imagen Video, Stable Diffusion 2 |
They differ in how a prediction error is weighted across :
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
T = 1000
ab_lin = np.cumprod(1 - np.linspace(1e-4, 0.02, T))
f = np.cos((np.arange(T + 1) / T + 0.008) / 1.008 * np.pi / 2) ** 2
ab_cos = np.cumprod(1 - np.clip(1 - f[1:] / f[:-1], 0, 0.999))
X, y = load_digits(return_X_y=True)
x0 = X[0] / 8.0 - 1.0 # a 0, pixels scaled to [-1, 1] as diffusion models expect
rng = np.random.default_rng(0)
eps = rng.standard_normal(64) # one noise draw, reused for every t
ts = [0, 50, 100, 250, 500, 1000]
fig, axes = plt.subplots(2, len(ts), figsize=(9, 3.4))
for row, (name, ab) in enumerate([("linear", ab_lin), ("cosine", ab_cos)]):
for col, t in enumerate(ts):
a = 1.0 if t == 0 else ab[t - 1]
xt = np.sqrt(a) * x0 + np.sqrt(1 - a) * eps # q(x_t | x_0) in one step
axes[row, col].imshow(xt.reshape(8, 8), cmap="gray", vmin=-2, vmax=2)
axes[row, col].set_xticks([]); axes[row, col].set_yticks([])
axes[row, col].set_title(f"{name} t={t}", fontsize=8)
plt.tight_layout()
plt.show()
# what the network could predict, and what an error of 0.1 in the prediction costs
print(" t sqrt(ab) sqrt(1-ab) x0 error from eps error 0.1 eps error from x0 error 0.1")
for t in (10, 100, 500, 900):
a = ab_lin[t - 1]
print(f"{t:5d} {np.sqrt(a):8.4f} {np.sqrt(1 - a):10.4f} {0.1 * np.sqrt((1 - a) / a):27.4f} {0.1 * np.sqrt(a / (1 - a)):27.4f}")
# v-prediction: v = sqrt(ab) eps - sqrt(1-ab) x0 recovers both x0 and eps from x_t
a = ab_lin[499]
xt = np.sqrt(a) * x0 + np.sqrt(1 - a) * eps
v = np.sqrt(a) * eps - np.sqrt(1 - a) * x0
x0_back = np.sqrt(a) * xt - np.sqrt(1 - a) * v
eps_back = np.sqrt(1 - a) * xt + np.sqrt(a) * v
print("v-parameterisation round trip exact to 1e-12:", bool(np.allclose(x0_back, x0, atol=1e-12) and np.allclose(eps_back, eps, atol=1e-12))) t sqrt(ab) sqrt(1-ab) x0 error from eps error 0.1 eps error from x0 error 0.1
10 0.9991 0.0435 0.0044 2.2951
100 0.9471 0.3209 0.0339 0.2951
500 0.2803 0.9599 0.3424 0.0292
900 0.0166 0.9999 6.0271 0.0017
v-parameterisation round trip exact to 1e-12: True
In the figure, at the 0 is still clear under the cosine schedule () and already faint under the linear one (0.72). By the linear version is gone (). The table explains the usual choice. An error of 0.1 in a predicted becomes an error of only 0.0044 in at , but 6.0271 at , where the signal coefficient is 0.0166. Predicting has the opposite problem: at the noise is almost invisible, and a small error in becomes a large error (2.2951) in the implied noise. Noise prediction works well in practice because the simple training loss on weights the steps in a useful way (Ho et al. found it gave better samples than the full ELBO weighting), and its target always has unit variance. The target mixes the two, so that its own scale stays the same at every , which helps at very high and very low SNR. The last line confirms that and together recover both and exactly.
The same in PyTorch (recorded)
In a training loop, every image in a batch gets its own random . The schedule lives in a module as buffers (Parameters, Buffers, Custom Layers and Hooks): they move with .to(device) and are saved in the state_dict, but they are not trained. The schedule is computed in float64 and stored in float32, because the cumulative product over 1000 factors loses precision in float32. The per-example coefficients are reshaped to (B, 1, 1, 1) so they broadcast over images. This example is recorded and ran on the CPU. It uses all 1797 digits, since nothing is evaluated here.
import math
import numpy as np
import torch
from torch import nn
from sklearn.datasets import load_digits
class ForwardDiffusion(nn.Module):
"""q(x_t | x_0) for a whole batch, each example with its own t (t = 1..T)."""
def __init__(self, T=1000, schedule="cosine"):
super().__init__()
if schedule == "linear":
beta = torch.linspace(1e-4, 0.02, T, dtype=torch.float64)
else:
steps = torch.arange(T + 1, dtype=torch.float64) / T
f = torch.cos((steps + 0.008) / 1.008 * math.pi / 2) ** 2
beta = (1 - f[1:] / f[:-1]).clamp(0, 0.999)
alpha_bar = torch.cumprod(1 - beta, dim=0)
# buffers: saved in the state_dict and moved by .to(device), but not trained
self.register_buffer("sqrt_ab", alpha_bar.sqrt().float())
self.register_buffer("sqrt_1mab", (1 - alpha_bar).sqrt().float())
self.T = T
def forward(self, x0, t, eps=None):
eps = torch.randn_like(x0) if eps is None else eps
shape = (-1,) + (1,) * (x0.dim() - 1) # broadcast (B,) over (B, C, H, W)
xt = self.sqrt_ab[t - 1].view(shape) * x0 + self.sqrt_1mab[t - 1].view(shape) * eps
return xt, eps
torch.manual_seed(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
X, _ = load_digits(return_X_y=True)
x0 = torch.from_numpy(X / 8.0 - 1.0).float().reshape(-1, 1, 8, 8).to(device) # [-1, 1]
q = ForwardDiffusion().to(device)
print("device:", device, " buffers:", [name for name, _ in q.named_buffers()], " parameters:", len(list(q.parameters())))
t = torch.randint(1, q.T + 1, (len(x0),), device=device) # one random t per image: a training batch
xt, eps = q(x0, t)
print("x0", tuple(x0.shape), " t", tuple(t.shape), " x_t", tuple(xt.shape), " target eps", tuple(eps.shape))
# check the statistics at a fixed t over all 1797 images x 64 pixels
for t_fixed in (100, 500, 900):
xt, eps = q(x0, torch.full((len(x0),), t_fixed, device=device))
a, b = x0.flatten().double(), xt.flatten().double()
slope = ((a - a.mean()) * (b - b.mean())).mean() / a.var()
resid = (b - slope * a).std()
print(f"t = {t_fixed}: slope of x_t on x_0 {slope.item():.3f} (sqrt(ab) = {q.sqrt_ab[t_fixed - 1].item():.3f}),"
f" residual std {resid.item():.3f} (sqrt(1-ab) = {q.sqrt_1mab[t_fixed - 1].item():.3f})")device: cpu buffers: ['sqrt_ab', 'sqrt_1mab'] parameters: 0
x0 (1797, 1, 8, 8) t (1797,) x_t (1797, 1, 8, 8) target eps (1797, 1, 8, 8)
t = 100: slope of x_t on x_0 0.987 (sqrt(ab) = 0.986), residual std 0.167 (sqrt(1-ab) = 0.167)
t = 500: slope of x_t on x_0 0.704 (sqrt(ab) = 0.703), residual std 0.709 (sqrt(1-ab) = 0.711)
t = 900: slope of x_t on x_0 0.154 (sqrt(ab) = 0.155), residual std 0.992 (sqrt(1-ab) = 0.988)
The module has two buffers and no parameters, and it maps a batch of 1797 images with 1797 different values to noisy images and noise targets of the same shape. These triples are exactly what the denoiser is trained on in the next lesson. Fitting against over all pixels recovers the schedule's coefficients: at , slope 0.704 against and residual standard deviation 0.709 against 0.711.
Pitfalls
- Off-by-one in . Papers index , arrays from 0. Decide once (here
alpha_bar[t - 1]) and test it, for example with the regression check above. - Data not scaled to . The schedule assumes roughly unit-scale data. Pixels in would keep a large SNR far into the chain, and the end point would not be .
- Computing in float16 or float32 over thousands of steps. Compute the schedule in float64 once and store the result.
- Adding noise without the factor. The variance then grows without bound (a "variance exploding" process). That is a legitimate family of models, but its formulas and samplers differ, so mixing the two conventions breaks sampling.
- Comparing schedules by alone. What matters is how the SNR is spread over the steps. Two schedules with the same can waste very different numbers of steps, as the 326 against 64 above shows.
Practice
- Show by induction that the variance of given is , starting from .
Answer
For the variance is . If , then with independent has variance .
- Using the table, at which step does the linear schedule's SNR cross 0 dB, and why is that bad for an or image?
Answer
Between (0.4 dB) and , where first drops below 0.5. After that, most of the remaining 740 steps are at low SNR, and 326 are below dB, where the image is essentially gone. The network spends a third of its training steps on inputs that carry almost no information, while the steps where structure forms are crowded together.
- A network predicts . Write in terms of and , and check it against the code.
Answer
. Substituting and gives , since the terms cancel. It is the line eps_back = np.sqrt(1 - a) * xt + np.sqrt(a) * v.
Test yourself
Why does the forward step scale by before adding noise of variance ?
- To make the process reversible without a network
- To keep unit-variance data at unit variance, so the chain ends at
- To speed up training
- It is required by the cosine schedule only
What is the distribution of given in DDPM?
- It has no closed form; the chain must be simulated
Compared with the linear schedule (from to , ), what does the cosine schedule change?
- It adds less noise in total
- It spreads the SNR more evenly, so far fewer steps are wasted at near-zero SNR (64 instead of 326 below dB)
- It removes the need for
- It makes smaller
At large (low SNR), why is a small error in the predicted noise a problem for the implied ?
- It is not a problem
- divides by a small , which amplifies the error
- The noise is not Gaussian at large
- The network cannot see