Diffusion Models: From Noise to Image
The DDPM forward (noising) and reverse (denoising) processes, the closed-form noisy sample, noise schedules (linear vs. cosine), the simple ε-prediction loss, the U-Net denoiser, and DDIM for fast deterministic sampling.
Every modern image generator you have heard of (Stable Diffusion, DALL·E 2/3, Imagen, Midjourney-style systems, FLUX) and most video generators are built on one idea: it is easy to destroy an image with noise, and a neural network can learn to undo that destruction step by step. This lesson builds that idea from the ground up, following the DDPM paper (Ho et al., 2020)[2], which itself made practical an idea from Sohl-Dickstein et al. (2015)[1].
The forward process: adding noise
Start with a clean training image x₀ (pixels scaled to [−1, 1]). Over T steps (T = 1000 in DDPM), add a little Gaussian noise each time. The amount at step t is set by βₜ, and the list β₁…β_T is the Noise schedule. Each step slightly shrinks the signal and adds fresh noise, so the total variance stays about 1.
- q(xₜ | xₜ₋₁)
- the forward (noising) distribution of step t given step t − 1; fixed, nothing is learned
- N
- a Gaussian (normal) distribution, written N(value ; mean, covariance)
- xₜ
- the image after t noising steps
- xₜ₋₁
- the image after t − 1 steps
- ;
- separates the random variable from the mean and covariance
- √(1 − βₜ)
- shrink factor applied to the previous image (just below 1)
- βₜ
- beta: noise variance added at step t (from 0.0001 up to 0.02 in DDPM)
- I
- identity matrix: every pixel gets independent noise of the same variance
▸Worked example
The key trick: because a sum of Gaussians is Gaussian, you can jump directly from x₀ to any step t in one shot, without simulating all the steps in between. Define αₜ = 1 − βₜ and ᾱₜ = α₁·α₂·…·αₜ (the fraction of signal variance that survives). Then:
- xₜ
- the noisy image at step t
- x₀
- the clean image (pixels scaled to [−1, 1])
- ᾱₜ
- alpha-bar: the product of (1 − βₛ) for all s ≤ t; fraction of signal variance left (1 → 0)
- √ᾱₜ
- signal weight
- √(1 − ᾱₜ)
- noise weight
- ε
- Gaussian noise with the same shape as the image
- ~
- 'is sampled from'
- N(0, I)
- standard normal: mean 0, variance 1, independent per pixel
▸Worked example
- SNR(t)
- signal-to-noise ratio at step t
- ᾱₜ
- fraction of the variance that is signal
- SNR_dB
- the same ratio in decibels
- log₁₀
- base-10 logarithm
▸Worked example
Noise schedules: linear vs. cosine
DDPM used a linear schedule: βₜ rises linearly from 0.0001 to 0.02. Nichol & Dhariwal (2021)[4] noticed that with this schedule the image is essentially pure noise long before t = T, so the last few hundred steps are wasted, especially for small images. Their cosine schedule defines ᾱₜ directly so that it falls slowly at both ends and roughly linearly in the middle.
- ᾱₜ
- fraction of signal variance left at step t
- f(t)
- the unnormalized schedule curve
- f(0)
- its value at t = 0; dividing by it makes ᾱ₀ = 1
- cos²
- cosine squared
- t
- current step
- T
- total number of steps (1000)
- s
- small offset, 0.008
- π/2
- a quarter turn: the cosine goes from 1 at 0 to 0 at π/2
▸Worked example
| t | ᾱₜ linear | ᾱₜ cosine | What you see (linear) |
|---|---|---|---|
| 0 | 1.00 | 1.00 | Clean image |
| 250 | ≈ 0.52 | ≈ 0.85 | Noisy but clearly recognizable |
| 500 | ≈ 0.08 | ≈ 0.49 | Only faint large shapes remain |
| 750 | ≈ 0.003 | ≈ 0.14 | Looks like pure noise |
| 1000 | ≈ 0.00004 | 0 | Pure noise |
- With the linear schedule, set t = 250, 500 and 750. Compare with the table: by t ≈ 500 the image is nearly gone, and everything after ≈ 700 looks the same.
- Switch to cosine at the same t values. The ᾱₜ curve falls more gently, so structure stays visible much longer: more steps carry useful information.
- Find where the SNR readout crosses 1 (0 dB), i.e. where the ᾱₜ and 1 − ᾱₜ curves intersect: around t ≈ 260 for linear vs. t ≈ 500 for cosine.
- Play the reverse animation from t = T. Coarse layout and colours appear first; fine edges and texture appear only in the last steps. Note the widget uses an oracle denoiser that knows the true noise; a trained network only estimates it.
- Change the image and repeat: the noise pattern ε is fixed by a seed, so the same t always gives the same noisy picture. This is why a fixed Seed (random seed) reproduces a generation.
The reverse process: learning to denoise
To generate, we need q(xₜ₋₁ | xₜ): how to take one step back. For small βₜ this reverse step is also approximately Gaussian, so we learn a network that predicts its mean. Ho et al.[2] found that the best way is to have the network predict the noise ε that was added. Training then becomes a remarkably simple regression: noise an image to a random t, ask the network 'which noise did I add?', and minimize the squared error.
- L_simple
- the simplified DDPM training loss
- E_{x₀, ε, t}
- average over training images x₀, noise ε ~ N(0, I) and steps t drawn uniformly from 1 … T
- ε
- the noise that was actually added: the target
- ε_θ
- the network's noise prediction; θ are its weights
- √ᾱₜ·x₀ + √(1 − ᾱₜ)·ε
- the noisy image xₜ, built with the closed form
- ‖
- the bars ‖ … ‖² mean squared length: sum of the squared entries
▸Worked example
- xₜ₋₁
- the slightly cleaner image after this step
- 1/√αₜ
- undoes the √αₜ shrink of the forward step
- αₜ
- alpha: 1 − βₜ
- xₜ
- the current noisy image
- βₜ
- noise variance of step t in the schedule
- ᾱₜ
- fraction of signal left at step t
- ε_θ(xₜ, t)
- the network's noise prediction
- σₜ
- standard deviation of the fresh noise (DDPM uses σₜ² = βₜ)
- z
- fresh standard-normal noise; set to 0 at the last step
- N(0, I)
- standard normal distribution
▸Worked example
- x̂₀
- x-hat-zero: the predicted clean image
- xₜ
- the current noisy image
- √(1 − ᾱₜ)
- noise weight at step t
- ε_θ(xₜ, t)
- the network's noise prediction
- √ᾱₜ
- signal weight at step t
▸Worked example
- Training loop: pick x₀ from the data, t uniformly in 1…T, and ε ~ N(0, I); compute xₜ; take a gradient step on ‖ε − ε_θ(xₜ, t)‖².
- Sampling loop: start from x_T ~ N(0, I); for t = T down to 1, predict ε and apply the reverse step; output x₀.
- With T = 1000, original DDPM sampling needs 1000 network evaluations per image, which is why faster samplers matter.
The denoiser network: a U-Net
ε_θ must output a tensor the same size as its input, so diffusion models borrow the U-Net from medical image segmentation (Ronneberger et al., 2015)[5]: a convolutional encoder that downsamples, a decoder that upsamples, and skip connections that copy high-resolution features across. Diffusion U-Nets add residual blocks, Self-attention at low resolutions, and a timestep embedding (sinusoidal, like transformer Positional encoding) injected into every block, so the same network knows whether it is removing heavy noise (large t) or polishing details (small t). Newer models replace the U-Net with a transformer (Diffusion Transformer (DiT)), covered in the next lesson.
DDIM: fewer steps, deterministic sampling
Song et al. (2020)[3] showed that the DDPM training objective is compatible with a whole family of reverse processes, including a non-Markovian, deterministic one: DDIM (Denoising Diffusion Implicit Models). Crucially, DDIM uses the same trained network; only the sampler changes. It can skip timesteps (e.g. use 50 of the 1000), producing comparable quality 10–50× faster. With η = 0 the mapping from starting noise to image is deterministic, which enables smooth interpolation between seeds and inversion (running the process backwards to find the noise that produces a given real image, the basis of many editing methods).
- xₜ₋₁
- the next, cleaner sample
- ᾱₜ₋₁
- signal fraction at the target step
- x̂₀
- current estimate of the clean image
- σₜ²
- variance of the fresh noise
- ε_θ(xₜ, t)
- predicted noise
- σₜ
- standard deviation of the fresh noise
- z
- fresh standard-normal noise
- η
- eta: 0 = deterministic DDIM, 1 = DDPM-like stochastic sampling
- ᾱₜ
- signal fraction at the current step
▸Worked example
- What it is
- Number of noise levels defined during training.
- ↑ If you increase it
- Finer steps make each reverse step closer to Gaussian (the theory's assumption); little extra training cost because t is sampled randomly. Sampling with all T steps gets slower.
- ↓ If you decrease it
- Each step must remove more noise; with very few steps the Gaussian reverse-step assumption breaks and quality drops.
- Typical values
- 1000 (DDPM, Stable Diffusion). Continuous-time models (flow matching, EDM) use t ∈ [0, 1] instead.
- What it is
- How fast signal is destroyed across t: the shape of the ᾱₜ curve.
- ↑ If you increase it
- A faster/more aggressive schedule (e.g. linear on small images) spends many steps at near-pure noise: wasted capacity and worse sample quality.
- ↓ If you decrease it
- A gentler schedule (cosine) spreads useful SNR levels more evenly. But if the final step still contains signal (ᾱ_T > 0), the model never learns to start from pure noise, causing washed-out or mid-grey images ('zero terminal SNR' fixes this).
- Typical values
- linear (β 1e-4 → 0.02) in DDPM; cosine (
squaredcos_cap_v2in diffusers) in improved DDPM; Stable Diffusion 1.x/2.x/XL use a 'scaled_linear' schedule.
- What it is
- How many denoising network evaluations are used to generate one image.
- ↑ If you increase it
- More accurate integration of the reverse process: finer detail and fewer artifacts, with diminishing returns; time grows linearly.
- ↓ If you decrease it
- Faster, but too few steps give blurry, noisy or 'unfinished' images, unless the model was distilled for few steps.
- Typical values
- 1000 for original DDPM; 50–100 for DDIM; 20–30 with modern solvers (DPM-Solver++); 1–4 for distilled models.
- What it is
- DDIM's stochasticity knob: how much fresh noise is injected at each reverse step.
- ↑ If you increase it
- η → 1 behaves like DDPM: each run with the same starting noise differs slightly; can correct accumulated errors but needs more steps.
- ↓ If you decrease it
- η = 0: fully deterministic, so the same seed gives the same image, and it works well with few steps. Required for exact inversion.
- Typical values
- 0.0 (default in diffusers' DDIMScheduler.step).
import torch
import torch.nn.functional as F
from diffusers import DDPMScheduler, UNet2DModel
model = UNet2DModel(
sample_size=32, in_channels=3, out_channels=3,
block_out_channels=(64, 128, 256),
down_block_types=("DownBlock2D", "AttnDownBlock2D", "DownBlock2D"),
up_block_types=("UpBlock2D", "AttnUpBlock2D", "UpBlock2D"),
)
scheduler = DDPMScheduler(num_train_timesteps=1000, beta_schedule="squaredcos_cap_v2") # cosine
opt = torch.optim.AdamW(model.parameters(), lr=1e-4)
def train_step(x0): # x0: (B, 3, 32, 32)
noise = torch.randn_like(x0) # epsilon
t = torch.randint(0, scheduler.config.num_train_timesteps, (x0.size(0),), device=x0.device)
xt = scheduler.add_noise(x0, noise, t) # sqrt(abar_t)*x0 + sqrt(1-abar_t)*eps
eps_pred = model(xt, t).sample # the U-Net predicts the noise
loss = F.mse_loss(eps_pred, noise) # L_simple
opt.zero_grad(); loss.backward(); opt.step()
return loss.item()from diffusers import DDIMScheduler
sampler = DDIMScheduler.from_config(scheduler.config)
sampler.set_timesteps(50) # 50 timesteps, high noise -> low noise
x = torch.randn(4, 3, 32, 32, generator=torch.Generator().manual_seed(0)) # fixed seed
model.eval()
with torch.no_grad():
for t in sampler.timesteps:
eps = model(x, t).sample
x = sampler.step(eps, t, x, eta=0.0).prev_sample # eta=0 -> deterministic
images = (x.clamp(-1, 1) + 1) / 2 # back to [0, 1] for viewing▸Go deeper: scores, prediction targets and guidance
Score view. The noise predictor is secretly a scaled estimate of the score, the gradient of the log-density of noisy data: ∇ₓ log p(xₜ) ≈ −ε_θ(xₜ, t) / √(1 − ᾱₜ). Sampling therefore 'climbs' towards regions of high data probability while noise keeps it exploring. Song et al. later unified DDPM and score matching as discretizations of a stochastic differential equation, whose deterministic counterpart (the probability-flow ODE) is what DDIM and modern solvers integrate.
Prediction targets. Predicting ε, x₀, or the 'velocity' v = √ᾱₜ·ε − √(1 − ᾱₜ)·x₀ are mathematically interchangeable but weight the timesteps differently. v-prediction is used by Stable Diffusion 2.x (768 px) and helps at high noise levels; flow-matching models predict a velocity too. Nichol & Dhariwal[4] also showed that learning the reverse variance improves likelihood and allows fewer steps.
Guidance. Dhariwal & Nichol (2021) steered sampling with the gradient of a separately trained noisy-image classifier (classifier guidance) and beat GANs on ImageNet. Classifier-free guidance, which needs no extra classifier and powers every text-to-image system, is covered in the next lesson. For a careful step-by-step derivation of everything here, read Lilian Weng's post[6].
Quiz
References
- [1]Deep Unsupervised Learning using Nonequilibrium ThermodynamicsPaperSohl-Dickstein et al.2015arxiv.org
- [2]Denoising Diffusion Probabilistic ModelsPaperHo et al.2020arxiv.org
- [3]Denoising Diffusion Implicit ModelsPaperSong et al.2020arxiv.org
- [4]Improved Denoising Diffusion Probabilistic ModelsPaperNichol & Dhariwal2021arxiv.org
- [5]U-Net: Convolutional Networks for Biomedical Image SegmentationPaperRonneberger et al.2015arxiv.org
- [6]What are Diffusion Models?ArticleLilian Weng2021lilianweng.github.io