Diffusion Models: DDPM, DDIM and Noise Schedules
Diffusion models power DALLΒ·E, Stable Diffusion, and Midjourney. Their training recipe is almost suspiciously simple: add Gaussian noise to an image until it is pure static, then train a network to predict the noise it added. Generation happens by running that prediction in reverse β start from static and denoise step by step until an image emerges. No adversarial games, no likelihood estimation, just a learned reversal of a fixed corruption process.
That simplicity is the appeal. GANs require balancing two networks that fight each other; diffusion requires one network trained with a plain regression loss. The cost is sampling: a naive sampler needs a thousand network evaluations per image, which is why much of the practical research effort has gone into noise schedules, fewer-step samplers like DDIM, and guidance techniques.
This lesson explains the forward process and its closed-form solution, the training loss, the reverse sampler with its actual equations, and the DDIM variant that cuts sampling steps by an order of magnitude. It also covers noise schedules β the design choice with outsized impact on sample quality β and how the U-Net denoiser is conditioned on timestep.
The forward process you never train
Diffusion defines a forward Markov chain that gradually destroys data. At each step t, a small amount of Gaussian noise is mixed in according to a schedule of variances. A remarkable property of this chain is that you can jump directly to any timestep without simulating the steps in between: after t steps the corrupted image is a linear blend of the original and pure noise, scaled by two cumulative products of the schedule.
import torch
import torch.nn as nn
class DDPM:
def __init__(self, denoiser: nn.Module, T: int = 1000,
beta_start: float = 1e-4, beta_end: float = 0.02):
self.model = denoiser
self.T = T
self.betas = torch.linspace(beta_start, beta_end, T)
self.alphas = 1.0 - self.betas
self.alpha_bar = torch.cumprod(self.alphas, dim=0)
def q_sample(self, x0: torch.Tensor, t: torch.Tensor,
noise: torch.Tensor = None) -> torch.Tensor:
if noise is None:
noise = torch.randn_like(x0)
ab = self.alpha_bar[t].view(-1, 1, 1, 1)
return ab.sqrt() * x0 + (1 - ab).sqrt() * noise
def training_loss(self, x0: torch.Tensor) -> torch.Tensor:
t = torch.randint(0, self.T, (x0.shape[0],), device=x0.device)
noise = torch.randn_like(x0)
x_t = self.q_sample(x0, t, noise)
predicted = self.model(x_t, t)
return nn.functional.mse_loss(predicted, noise)
The training loss deserves attention because it is so easy to misread. We are not training the network to output the clean image β we train it to output the noise that was added. From the predicted noise, the clean image can be algebraically recovered, and predicting noise keeps the target distribution stationary (unit Gaussian) at every timestep, which stabilizes training. Each batch samples random timesteps, so one model learns the denoising task at all noise levels simultaneously.
Running the reverse chain
Sampling starts from x_T, a tensor of pure Gaussian noise. At each step the model predicts the noise component, the code removes most of it using the schedule's coefficients, and a fresh noise sample is injected (except at the final step). The mean formula subtracts the predicted noise direction scaled by the ratio of the betas to the square root of the remaining signal.
@torch.no_grad()
def p_sample(self, x_t: torch.Tensor, t: int) -> torch.Tensor:
t_batch = torch.full((x_t.shape[0],), t, device=x_t.device, dtype=torch.long)
predicted_noise = self.model(x_t, t_batch)
alpha_t = self.alphas[t]
ab_t = self.alpha_bar[t]
beta_t = self.betas[t]
mean = (1 / alpha_t.sqrt()) * (
x_t - (beta_t / (1 - ab_t).sqrt()) * predicted_noise
)
if t > 0:
return mean + beta_t.sqrt() * torch.randn_like(x_t)
return mean
@torch.no_grad()
def sample(self, shape) -> torch.Tensor:
x = torch.randn(shape)
for t in reversed(range(self.T)):
x = self.p_sample(x, t)
return x
A thousand steps means a thousand forward passes through the denoiser for one image. That is the number DDPM used, and for a long time it was treated as necessary. It is not β the intermediate states of the chain are mathematically redundant, and DDIM was the work that made this exploitable.
DDIM: sampling without the full chain
DDIM (Denoising Diffusion Implicit Models) reinterprets the same training objective as a family of non-Markovian processes. Instead of stepping t to tβ1, you can step from t to any earlier tβ² in one jump while preserving the same marginal distribution. Deterministically skipping noise entirely (eta = 0) turns sampling into an ordinary ODE solve β which also makes the mapping from noise to image continuous, enabling latent-space interpolation.
class DDIMSampler:
def __init__(self, ddpm: DDPM, steps: int = 50, eta: float = 0.0):
self.ddpm = ddpm
self.steps = steps
self.eta = eta
self.schedule = torch.linspace(0, ddpm.T - 1, steps).long()
@torch.no_grad()
def sample(self, shape) -> torch.Tensor:
x = torch.randn(shape)
for i in reversed(range(self.steps)):
t = int(self.schedule[i])
t_prev = int(self.schedule[i - 1]) if i > 0 else -1
t_batch = torch.full((shape[0],), t, device=x.device, dtype=torch.long)
eps = self.ddpm.model(x, t_batch)
ab_t = self.ddpm.alpha_bar[t]
ab_prev = (self.ddpm.alpha_bar[t_prev] if t_prev >= 0
else torch.tensor(1.0))
x0_pred = ((x - (1 - ab_t).sqrt() * eps) / ab_t.sqrt()).clamp(-1, 1)
sigma = self.eta * (
((1 - ab_prev) / (1 - ab_t)).sqrt()
* (1 - ab_t / ab_prev).sqrt()
)
direction = (1 - ab_prev - sigma ** 2).clamp(min=0).sqrt() * eps
noise = torch.randn_like(x) if t_prev >= 0 else torch.zeros_like(x)
x = ab_prev.sqrt() * x0_pred + direction + sigma * noise
return x
With fifty steps instead of a thousand, generation is twenty times faster with a modest β sometimes unnoticeable β quality difference. The eta parameter interpolates between fully deterministic (0) and fully stochastic (1) sampling; deterministic sampling gives reproducible images for a given starting noise, which is invaluable for debugging and for interpolation. Modern solvers such as DPM-Solver push further, reaching 10β20 steps on a schedule trained with 1000.
The denoiser: time-conditioned U-Net
The network that predicts noise is almost always a U-Net: an encoder that downsamples while widening channels, a decoder that upsamples while narrowing them, and skip connections that carry spatial detail past the bottleneck. Skip connections are not optional here β pixel-accurate noise prediction needs high-resolution feature maps that would otherwise be destroyed by downsampling.
The distinctive requirement is timestep conditioning. Because one model serves all noise levels, the current t must be an input. The standard trick embeds t as a sinusoidal position vector, passes it through a small MLP, and adds the resulting vector to the feature maps at every block:
class TimeConditionedBlock(nn.Module):
def __init__(self, in_ch: int, out_ch: int, time_dim: int = 256):
super().__init__()
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
self.time_proj = nn.Linear(time_dim, out_ch)
self.norm1 = nn.GroupNorm(8, out_ch)
self.norm2 = nn.GroupNorm(8, out_ch)
def forward(self, x: torch.Tensor, t_emb: torch.Tensor) -> torch.Tensor:
h = self.conv1(x)
h = self.norm1(h)
h = h + self.time_proj(t_emb)[:, :, None, None]
h = nn.functional.silu(h)
h = self.conv2(self.norm2(h))
return nn.functional.silu(h)
Adding the time embedding (rather than concatenating) keeps channel counts stable and has become the default everywhere. In text-to-image models the U-Net also takes cross-attention over text token embeddings, which is where the conditioning on a prompt enters β the noise predictor learns to remove noise in a way consistent with the described content.
Latent diffusion: where production models actually run
Everything so far assumes the diffusion process happens in pixel space, and that is exactly what Stable Diffusion's predecessors did β expensively. At 512Γ512 with three color channels, one image is nearly a million values per step, and every denoiser forward pass operates on tensors of that size. Latent diffusion changes the venue: train a variational autoencoder to compress the image into a small latent representation (typically a 64Γ64 grid with four channels), run the entire diffusion process there, and decode to pixels only once at the end.
The compression factor is roughly 48Γ fewer values per step, which is most of why consumer GPU inference became possible. Text conditioning enters through cross-attention layers inside the U-Net, where queries come from the spatial latent and keys and values come from an encoded text prompt β the mechanism that binds a sentence to regions of the emerging image. The choice has a visible consequence worth knowing: because the autoencoder defines what the latent space can represent, artifacts it cannot encode (fine text rendering, extremely intricate geometry) will never be recovered no matter how many denoising steps you run. Quality ceilings in latent models often trace back to the autoencoder, not the diffusion process.
Noise schedules and guidance
The beta schedule decides how aggressively information is destroyed at each step. The original linear schedule (betas from 0.0001 to 0.02 over 1000 steps) works, but it destroys too much signal too early: most of the meaningful structure is gone by step 200 while hundreds of steps remain with little to do. The cosine schedule spreads corruption more evenly across the timestep range and consistently improves sample quality.
Beyond the schedule, two operational knobs dominate perceived quality. Exponential moving average of the model weights reduces variance across checkpoints and is standard in every serious implementation. Classifier-free guidance controls how strongly generation follows the conditioning signal: train with conditioning dropped on 10β20% of batches, then extrapolate between the conditional and unconditional noise predictions at sampling time. Higher guidance gives sharper, more literal images at the cost of diversity and, past a point, oversaturated artifacts.
| Sampler | Steps | Stochastic? | Notes |
|---|---|---|---|
| DDPM ancestral | 1000 | Yes | Original baseline; slow |
| DDIM | 20β100 | Optional (eta) | Deterministic at eta = 0; enables interpolation |
| DPM-Solver / ++ | 10β25 | No | Fast ODE solvers; current default in practice |
| Consistency models | 1β4 | No | Direct one-step mapping; quality still improving |
Common Mistakes
Predicting the clean image instead of the noise
Fix: Train against the injected noise β its stationary unit-Gaussian target is what stabilizes loss across timesteps.
Using a linear schedule on a small number of steps
Fix: Fewer steps with a linear schedule destroys signal too early; switch to a cosine schedule.
Forgetting EMA of model weights
Fix: Maintain an exponential moving average for sampling; raw checkpoint weights are noticeably noisier.
Keeping eta = 1 when you need reproducible outputs
Fix: Set eta = 0 for deterministic DDIM β same seed, same image, which makes iteration possible.
Pushing guidance scale past its useful range
Fix: Guidance above roughly 8β12 saturates contrast and collapses diversity; tune within a sweep, not by instinct.
Key Takeaways
- Diffusion training adds noise at random timesteps and regresses the network on the noise that was added.
- Sampling reverses the chain step by step; a naive sampler costs one network forward pass per step.
- DDIM reframes sampling as a deterministic ODE, cutting steps from 1000 to 50 with little quality loss.
- The denoiser is a time-conditioned U-Net: skip connections preserve detail, and t is injected as an additive embedding.
- Cosine noise schedules, weight EMA, and classifier-free guidance are the three highest-leverage quality improvements in practice.