Diffusion Models for Images
Imagine trying to teach a machine to paint a photorealistic sunset from nothing but random noise. This is the concrete problem diffusion models solve. They solve it with a surprisingly simple trick. First, destroy an image slowly and predictably. Then train a network to undo the destruction one small step at a time. Rather than asking a network to leap from pure static to a finished photograph in one shot, diffusion models break that impossible leap. They split it into hundreds of tiny, learnable steps. This idea matters because it sidesteps the notorious instability of earlier generative approaches. Generative adversarial networks pit two networks against each other in a minimax game. That game is prone to mode collapse and training collapse. Variational autoencoders optimize a bound that often blurs fine detail. Diffusion models instead optimize a stable, well-behaved regression objective — predict the noise that was added. This objective trains reliably at massive scale. It produces images with striking fidelity and diversity. The big picture is a Markov chain running in two directions. A forward process gradually corrupts a real image into pure Gaussian noise over many timesteps. A reverse process, implemented by a trained neural network, learns to walk backward along that same chain. It transforms noise into a coherent image. Once trained, sampling is just repeated denoising. Start from noise, apply the learned reverse step many times, and a novel image emerges. This article builds the mathematics of the forward and reverse processes from scratch. It gives working pseudocode for training and sampling. It derives the training objective and its complexity. It also traces a concrete numerical example through several denoising steps. It closes by connecting this machinery to the systems — DALL·E 2, Stable Diffusion, Imagen. These are the systems that make diffusion models the dominant paradigm in modern image generation.
- Diffusion models generate images by reversing a gradual noising process, one small denoising step at a time.
- The forward process adds Gaussian noise across timesteps until the image becomes indistinguishable from pure noise.
- A neural network (usually a U-Net) is trained to predict the noise added at each timestep, given the noisy image and .
- Training reduces to a simple mean-squared-error regression loss — far more stable than adversarial training.
- Sampling reverses the chain step by step, so generation costs many network evaluations, unlike one-shot GAN sampling.
- These ideas generalize directly into latent diffusion and text-conditioned generation with CLIP-style guidance.
A diffusion model learns to reverse a fixed, gradual noising process, converting pure noise into a realistic image through many small, stable denoising steps.
The idea
A diffusion model is a generative model built from two coupled Markov chains over a sequence of latent variables , where is a real image and is (approximately) pure Gaussian noise. The forward diffusion process is fixed, not learned: it adds a small amount of Gaussian noise at every step according to a variance schedule . Because each step only adds noise, this process has a closed form that lets us jump directly from to any without simulating every intermediate step — a critical efficiency property exploited during training. The reverse diffusion process is what we actually learn. It is parameterized as a Gaussian whose mean is predicted by a neural network, typically a Convolutional Neural Network-based U-Net augmented with self-attention and a timestep embedding. Rather than predicting the mean directly, the standard parameterization (from Ho, Jain, and Abbeel's Denoising Diffusion Probabilistic Models, DDPM) trains the network to predict the noise that was added to produce from . This reframing turns a complex generative modeling problem into a simple supervised denoising regression, closely related to Image Generation Fundamentals ideas of learning data distributions through tractable surrogate objectives. Two properties make the framework tractable. First, the forward process has a fixed, non-learned form, so we never need to infer it — we simply construct noisy training pairs on the fly. Second, because both the forward and idealized reverse transitions are Gaussian for small step sizes, the reverse process can be well-approximated by a Gaussian too, which is what justifies parameterizing as Gaussian in the first place. This connects diffusion models to Probability distributions machinery: everything is built from conditional Gaussians chained together, with the entire model trained by maximizing a variational lower bound on the data likelihood — the same evidence lower bound (ELBO) logic underlying variational autoencoders, but applied across a much longer, smoother chain of latent variables.
How it works
Forward process. Define a variance schedule , typically small () at the start and larger () near the end, over steps. The forward transition is
Let and . Because the composition of Gaussians is Gaussian, one can show by induction that
which lets us sample any in one step:
As , , so converges to pure standard Gaussian noise regardless of .
Reverse process. We want . Using Bayes' rule, the true (but intractable to sample without knowing ) posterior is itself Gaussian with a known mean that depends linearly on and . Substituting the noise-based expression for in terms of and yields a mean that depends only on , , and — exactly what the network predicts. The result, after Ho et al.'s simplification, is:
The variance is usually fixed to or a related closed-form value, though later work (e.g., improved DDPM) learns it too.
Training. Sample a real image , a random timestep , and Gaussian noise ; construct in closed form; train the network to predict from using simple mean-squared error. This is the "simple" DDPM loss, a tight and empirically effective surrogate for the full variational bound. ```
# TRAINING function TRAIN(dataset, T, beta_schedule, network eps_theta): precompute alpha_t, alpha_bar_t for t = 1..T from beta_schedule repeat until convergence: x0 <- sample a real image from dataset t <- sample uniformly from {1, ..., T} eps <- sample from Normal(0, I), same shape as x0 xt <- sqrt(alpha_bar_t[t]) x0 + sqrt(1 - alpha_bar_t[t]) eps eps_pred <- eps_theta(xt, t) loss <- MeanSquaredError(eps, eps_pred) update network parameters theta by gradient descent on loss return eps_theta
# SAMPLING (ancestral sampling, DDPM) function SAMPLE(T, beta_schedule, eps_theta): x_T <- sample from Normal(0, I) for t = T down to 1: z <- sample from Normal(0, I) if t > 1 else 0 eps_pred <- eps_theta(x_t, t) mu <- (1 / sqrt(alpha_t[t])) (x_t - (beta_t[t] / sqrt(1 - alpha_bar_t[t])) eps_pred) sigma_t <- sqrt(beta_t[t]) # or a learned/tuned variance x_{t-1} <- mu + sigma_t * z return x_0 ``` The timestep is fed to the network via a sinusoidal or learned embedding, analogous to positional encodings in transformers, so a single network handles all noise levels. The U-Net's multi-scale convolutional structure with skip connections lets it reason about both fine texture and global structure at every noise level.
Complexity & correctness
Training time and space. Each training step performs one forward and one backward pass of the U-Net, so per-step cost is where is the cost of a single network evaluation — dominated by the convolutional and attention layers, typically per convolutional layer for images of resolution , plus for any full self-attention layers at low resolution. Because the closed-form shortcut lets us sample any directly, training needs exactly one network evaluation per gradient step, independent of — a crucial efficiency win over naively simulating the whole chain. Memory is for activations, same as training any comparable image CNN.
Sampling time. Naive ancestral sampling (the DDPM sampler above) requires one full network evaluation per timestep, so generating one image costs — with often 1000, this is the well-known weakness of diffusion models relative to GANs' single forward pass. Deterministic or higher-order samplers (DDIM, DPM-Solver) exploit the fact that the reverse process can be viewed as integrating an ordinary differential equation, allowing accurate sampling in steps (often 20–50), trading a small amount of quality for a – speedup. Space at sampling time is for the single image being iteratively refined, plus the fixed network parameter memory.
Correctness argument. The training objective is derived, not merely asserted, from a variational bound on the log-likelihood of the data. Writing and applying Jensen's inequality with the fixed forward process as the variational posterior gives:
Because both and factor as products of Gaussian transitions across the chain, decomposes into a sum of KL divergences between Gaussians at each timestep, each of which has a closed-form expression. Ho et al. show that reparameterizing the mean prediction as a noise prediction, and dropping certain reweighting constants, produces the simple objective:
which upper-bounds (up to reweighting) the true negative log-likelihood. Minimizing this loss therefore directly improves a bound on how well the model explains real image data — this is the formal justification that training actually pushes toward the true data distribution, not merely a heuristic. As with correspondingly small steps, the discrete chain converges to a continuous-time diffusion process (a stochastic differential equation), and the reverse process is provably the time-reversal of that diffusion under mild regularity conditions — this is the theoretical bedrock (Anderson's theorem on time-reversed diffusions) beneath the entire framework.
Tradeoffs. The dominant cost is the many-step sampling loop; likelihood estimates from diffusion models are usually competitive but not always state-of-the-art compared to autoregressive models; and the fixed, non-learned forward process, while mathematically convenient, is not necessarily the most efficient possible noising schedule — an active area of follow-up research (learned schedules, flow matching, consistency models) aims squarely at this bottleneck.
Worked example
Consider a toy one-dimensional "image" — a single pixel intensity (on a scale) — diffused with a schedule of steps and . We trace the forward process and one denoising update with an idealized, already-trained network.
| 1 | 0.10 | 0.90 | 0.900 | 0.949 | 0.316 |
| 2 | 0.20 | 0.80 | 0.720 | 0.849 | 0.529 |
| 3 | 0.30 | 0.70 | 0.504 | 0.710 | 0.704 |
| 4 | 0.40 | 0.60 | 0.302 | 0.550 | 0.836 |
Forward pass, drawing one fixed noise sample at each for illustration (in practice a fresh is drawn per sample; here we hold it fixed to make the arithmetic traceable):
Notice is not simply "more noise piled on " — it is recomputed directly from using the closed-form shortcut, exactly as the training loop does; this is why we can train on any without simulating intermediate steps first.
Reverse pass at . Suppose the trained network, given , correctly predicts (matching the true noise used above, since we assumed an idealized network). Then:
Sampling noise , say , and :
Compare to the true forward : the discrepancy is expected because injects fresh stochastic variation (diffusion sampling is not deterministic reconstruction, it is a stochastic reverse walk), and because our toy network and schedule are illustrative, not trained on real data. Repeating this update from down to eventually yields a reconstructed estimate; in a real high-resolution image, this same arithmetic is applied per-pixel-channel, simultaneously, at every spatial location, with the network's convolutional structure coupling neighboring pixels so that the recovered image is spatially coherent rather than independent per-pixel noise removal.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Treating as a free lunch | More steps improve quality but linearly multiply sampling cost | Use DDIM/DPM-Solver for fast sampling with fewer steps |
| Wrong noise schedule at inference | Using training values but a different, mismatched for sampling | Recompute consistently, or use a sampler designed for schedule respacing |
| Forgetting the timestep embedding | Network cannot tell how much noise is present, degrading all outputs | Always condition the network on via an embedding |
| Treating output as the image | Confusing noise-prediction with direct image prediction breaks the sampler math | Convert to (or -estimate) using the correct closed-form formula |
| Ignoring variance schedule at sampling | Setting everywhere collapses to a deterministic (DDIM-like) process unintentionally | Match the sampler type (stochastic DDPM vs deterministic DDIM) to the intended sampling formula |
| Training at one resolution, sampling at another | U-Net receptive field and positional statistics assume training resolution | Use resolution-consistent training or explicit multi-scale training |
Pioneers & history
Diffusion models draw on a much older idea in statistical physics: nonequilibrium thermodynamics describes how a system relaxes from an ordered state toward disorder, and this relaxation can in principle be reversed given the right dynamics. Sohl-Dickstein and collaborators first proposed applying this physical intuition to generative modeling of images in 2015, framing generation as learning to reverse a diffusion process. The idea lay relatively dormant until Jonathan Ho, Ajay Jain, and Pieter Abbeel's 2020 Denoising Diffusion Probabilistic Models paper showed that a simplified noise-prediction objective could match or beat GANs on image sample quality, triggering rapid adoption across the field.
Origins · 1 minJonathan Ho and how this was discovered
Jonathan Ho's 2020 paper with Ajay Jain and Pieter Abbeel demonstrated that a carefully simplified variational objective — essentially, training a network to predict added Gaussian noise — could produce image samples rivaling state-of-the-art GANs while training far more stably. This single reframing turned an elegant but underperforming theoretical idea from statistical physics into the dominant practical paradigm for image generation.
Where this matters
Diffusion models now underpin most leading image-generation systems in production. Stable Diffusion runs the diffusion process in a compressed latent space (learned by an autoencoder) rather than raw pixels, dramatically cutting compute while preserving fidelity — a direct extension of the mechanism described here. DALL·E 2 and Imagen condition the reverse process on text embeddings, often derived from CLIP, so that the denoising network is steered toward images matching a caption; this is the natural next step beyond this article, covered under Text-to-Image with CLIP and Latent Diffusion. Diffusion is also used for image inpainting, super-resolution, and image-to-image translation, since the same noise-removal machinery can be conditioned on a partially masked or low-resolution input. Beyond static images, diffusion techniques extend to video generation, 3D shape and scene synthesis (score distillation for neural fields), audio synthesis, and even protein structure generation, all reusing the same forward-noising/reverse-denoising skeleton. Because the core objective is a stable regression loss, diffusion models have proven far easier to scale reliably to billions of parameters and training images than adversarial alternatives, which is a major reason they now dominate commercial generative image products.
Ask the tutor: Can you walk me through how classifier-free guidance changes the sampling loop's math, step by step?
Why not just predict the clean image x0 directly instead of the noise ε?
Both parameterizations are mathematically equivalent, since and are linearly related given and via . Empirically, Ho et al. found that predicting gives a better-conditioned loss landscape: at large , is nearly pure noise, so predicting directly forces the network to guess fine detail from almost no signal, producing a high-variance target. Predicting keeps the target's scale roughly constant across all timesteps, which empirically improves training stability and final sample quality. Some later methods (v-prediction, used in some Stable Diffusion variants) blend both parameterizations for further stability, especially near the end of the schedule where -prediction becomes numerically ill-conditioned.
How many timesteps T are actually used in practice?
Original DDPM used for both training and naive ancestral sampling. Training with 1000 timesteps is cheap because each step samples one random per image via the closed-form shortcut. Naive sampling with , however, requires 1000 sequential network passes per generated image, which is slow. Practical systems almost always use accelerated samplers — DDIM, PNDM, DPM-Solver++ — that reformulate sampling as solving an ordinary differential equation, achieving comparable quality in 20 to 50 steps. Some very recent methods (consistency models, distilled diffusion) reduce this further to a handful of steps or even one step, trading a small amount of quality for large speedups, though 1000-step training schedules remain common for the underlying base models.
How does classifier-free guidance fit into this framework?
Classifier-free guidance trains a single network to model both the conditional score (conditioned on text or class label ) and the unconditional score , typically by randomly dropping the condition during training. At sampling time, the two predictions are linearly extrapolated, , with guidance weight pushing samples more strongly toward the condition at the cost of some diversity. This technique dramatically improves text-image alignment in systems like DALL·E 2 and Stable Diffusion without requiring a separate classifier network, and it plugs directly into the sampling loop described in this article by simply replacing the noise prediction with this guided combination.
Are diffusion models the same as score-based generative models?
They are two derivations of essentially the same object. Score-based models (Song and Ermon) train a network to estimate the gradient of the log data density, , at various noise levels, and sample via Langevin dynamics. It can be shown that this score is proportional to the negative of the noise divided by , so noise prediction and score prediction are mathematically equivalent up to a known scaling factor. The continuous-time limit of both formulations is described by the same stochastic differential equation, unifying DDPM-style discrete-time diffusion and score-based continuous-time diffusion into one theoretical framework.
Why do diffusion models tend to avoid mode collapse, unlike GANs?
GANs are trained via an adversarial minimax game, where the generator can learn to exploit blind spots in the discriminator, collapsing onto a narrow subset of the data distribution that fools it. Diffusion models instead optimize a direct regression objective — matching the noise or score at every noise level for every training example — with no adversarial component and no discriminator to fool. Because every training example at every timestep contributes an explicit gradient signal toward reconstructing that example's own noise, there is no mechanism analogous to generator-discriminator exploitation, which empirically yields broader mode coverage and more stable, non-oscillating training curves.
What role does the U-Net architecture play, and could another architecture work?
The U-Net's encoder-decoder structure with skip connections lets the network combine coarse, global structure (from deep, downsampled layers) with fine, local detail (passed through skip connections from shallow layers), which matches the multi-scale nature of natural images well. Self-attention layers at low-resolution bottlenecks let the network model long-range dependencies, such as symmetric structures across an image. Other architectures do work: diffusion transformers (DiT) replace the U-Net with a pure transformer operating on image patches, following the same forward/reverse mathematics but changing only the network computing , showing the diffusion framework is architecture-agnostic.
Does the forward noising schedule need to be linear in β_t?
No — the linear schedule in the original DDPM paper was a practical choice, not a mathematical requirement. Nichol and Dhariwal's improved DDPM showed that a cosine-based schedule, which adds noise more slowly near and , improves sample quality and log-likelihood, especially for lower-resolution images where the linear schedule destroys structure too quickly. Any schedule is valid as long as , ensuring is close to pure noise, and stays small enough per step that the Gaussian reverse-step approximation remains accurate.