72 min total

Computer Vision & OpenCV

Diffusion models

Diffusion models

Diffusion model is trained to denoise an image over a series of very small steps, noise is removed gradually to reconstruct the original data

Forward noising and reverse denoising of an image

Denoising Diffusion Probabilistic Models (DDPMs): is a type of diffusion model where forward process is a fixed Markov chain tha gradually adds noise to the data, and reverse process is trained to denoise using a neural network via variational lower bound ELBO objective, using mean squared error (MSE) loss.

DDPM Forward Diffusion process: we have an image that we corrupt gradually over t steps so (t=1000) that the image is indistinguishable from gaussian noise, will have zero mean and unit variance. We define a function q that adds small Gaussian noise with variance to an image to generate new . If we keep applying this function, we will generate a sequence of noisier iamges

We can write the update process as

Unit variance means Var(x) = 1

The scaling controls variance as noise accumulates. For normalized data with unit variance, the update preserves unit marginal variance; more generally, the process approaches the chosen Gaussian prior as the signal contribution diminishes.

The original variance discussion considers two undesirable extremes: signal scale collapsing toward zero and noise variance growing without bound. An unscaled sum of independent noise accumulates variance; repeated attenuation without compensating noise can collapse it. The DDPM update balances these effects, avoiding an additional burden of learning arbitrary input scales at each timestep.

For independent injected noise and unit marginal variance, αₜI+βₜI=I. The intended endpoint still loses the original signal and approaches Gaussian noise; stable variance does not mean the image remains unchanged.

Forward noising process q can be written as:

The forward process adds Gaussian noise according to a schedule βₜ ∈ (0,1). Its mean is a scaled previous sample and its covariance is βₜI.

The schedule shown in the notebook is increasing: β₁<β₂<⋯<βT, with each βt between zero and one. An increasing schedule is one design choice, not a requirement for every diffusion model.

βt controls the noise variance at step t; I is the identity matrix. The mean rescales the previous sample, and fresh Gaussian noise supplies the random part.

Forward process involves no learning, Backward process involves learning only.

DDPM Reverse Diffusion process: Given a noisy image reconstruct the original image step-by-step The true reverse process is intractable, so we learn a model to approximate it

The reverse model predicts the denoising distribution. Its mean is learned; the variance can be fixed or learned, depending on the parameterization.

A neural network, commonly a U-Net in the DDPM setup, receives the noisy image x_t and timestep t. It parameterizes the reverse mean, directly or through a noise prediction. Depending on the model, the reverse variance is fixed or learned; it is not necessarily a second freely predicted output.

Forward, reverse, and posterior diffusion transitions
AspectDiffusion modelsVariational autoencodersGANs
Core ideaIterative denoisingLatent-variable encoder/decoderAdversarial generator/discriminator
Typical objectiveDenoising loss or variational boundReconstruction plus KL regularizationAdversarial loss
SamplingMultiple reverse stepsDecode a latent sampleGenerator forward pass
Latent inferenceModel-dependentExplicit encoderUsually no inverse encoder
Common tradeoffSampling costReconstruction/regularization balanceTraining instability and mode collapse

Full comparison from the notebook

This table preserves all ten comparison categories. Statements about quality, stability, and speed are qualitative tendencies of the model families discussed here, not guarantees for every architecture, dataset, or sampler.

AspectDiffusion models (DDPM)Variational autoencodersGANs
Core ideaGradual noising and denoising via a Markov chainEncoder–decoder with latent-variable inferenceAdversarial generator and discriminator
Training objectiveDenoising objective / variational boundMaximize ELBO: reconstruction with KL regularizationAdversarial objective for generator and discriminator
Sampling processIterative reverse diffusion, often many stepsOne decoder forward pass from a latent sampleOne generator forward pass from latent noise
Sample qualityCan produce high-fidelity, realistic imagesBasic pixel-likelihood VAEs can look smoother or blurrierCan produce sharp, realistic images
Training stabilityOften stable with a suitable parameterizationOften stable, with reconstruction/regularization trade-offsCan be unstable; mode collapse is a concern
Latent spacePixel-space DDPM has a sequence of noisy latent states, not an ordinary AE bottleneckExplicit lower-dimensional latent representationNoise input; a standard GAN need not have an inverse encoder
Inference speedMany denoising evaluations can make sampling slowOften fast: one decoder passOften fast: one generator pass
Mode coverageOften good coverage; behavior depends on training and samplingRegularized latent modeling, with likelihood/reconstruction limitationsCan miss modes or collapse
ApplicationsImage synthesis, super-resolution, inpaintingRepresentation learning and generative modelingImage synthesis, style transfer, domain adaptation
Typical outputDetailed, potentially photorealistic texturesBasic configurations often trade detail for smooth reconstructionSharp images whose diversity depends on training

The source table called diffusion “stable and robust,” described VAE outputs as blurry, and described GAN outputs as sharp but sometimes less diverse. Those are contextual observations rather than universal properties. Latent diffusion, improved VAE decoders, and faster samplers can change the comparison.

The ELBO is a tractable lower bound on log evidence. For latent-variable models, marginalizing the joint distribution can be intractable, so training optimizes the variational bound instead.

The likelihood pθ(x₀) requires integrating over all latent noisy states x₁,…,xₜ. Directly optimizing that integral is difficult. The known forward process supplies a tractable variational distribution, allowing a lower bound on log likelihood to be optimized instead. The bound exposes reconstruction and KL terms that can be estimated from sampled data and timesteps.

Deriving the evidence lower bound

Introduce an approximate posterior q(z|x) whose support covers the joint density:

By Jensen’s inequality for the concave logarithm:

ELBO derivation: every transformation

First define the generative process: sample z from p(z), then sample x from p(x|z). Thus p(x,z)=p(z)p(x|z). Marginalizing z produces the evidence p(x).

Introduce q(z|x) by multiplying and dividing by the same density wherever the integrand has support:

This is an expectation because q supplies the probability weights. Taking logarithms turns products into sums, which is useful when optimizing likelihoods.

Jensen’s inequality for a concave function f states f(E[X])≥E[f(X)]. Apply it to the logarithm:

Diffusion as a latent-variable model

Expanding the diffusion ELBO

Step 1: express the KL as an integral under the forward distribution.

Step 2: combine the two terms under the same expectation.

Step 3: use the product rule for the joint distribution and the subtraction rule for logarithms.

Step 4: expand the forward and reverse Markov factorizations.

Step 5: turn logarithms of products into sums.

This factorization makes a per-step training objective possible. The next rearrangement replaces each forward transition with its posterior target.

Decomposing the diffusion loss

Substituting this identity into the variational bound makes the forward marginal terms telescope. The negative ELBO becomes:

The three terms match the terminal distribution to the prior, match each learned reverse transition to its posterior target, and reconstruct the clean image. Minimizing this loss maximizes the ELBO.

Bayes, telescoping, and the negative ELBO

The forward chain is Markov, so conditioning additionally on x₀ does not change a transition once xₜ₋₁ is given.

Apply the identity for t≥2 and keep the reconstruction boundary t=1 separate:

The third term telescopes; every intermediate log marginal appears once positively and once negatively.

The +log q(x₁|x₀) term cancels the denominator at t=1. It must not remain in the reconstruction term.

Negating the bound produces the loss L=−E: a terminal-prior KL, a sum of reverse-transition KLs, and a negative reconstruction log-likelihood. Minimize L or maximize E; the two sign conventions should not be mixed.

Closed-form diffusion transitions

For Gaussian distributions q and p of dimension k, the KL divergence is:

With fixed isotropic reverse variance σₜ²I, the trainable mean term is a squared error weighted by 1/(2σₜ²). Reparameterize the noisy image to train a noise predictor instead:

From the posterior mean to the noise-prediction loss

The reverse network models a slightly less noisy sample from x_t. The forward process adds scheduled Gaussian noise to x₀. Because that process is linear and Gaussian, x_t can be sampled directly from x₀ without computing x₁,…,xₜ₋₁. This saves the time and memory of explicitly simulating every earlier step.

During training, x₀ is known. Bayes’ rule therefore gives an exact Gaussian target for the reverse transition. Its mean is a linear combination of the clean image and noisy image; the coefficients below need not sum to one.

Training compares the exact posterior q(xₜ₋₁|xₜ,x₀) with the learned reverse distribution pθ(xₜ₋₁|xₜ). For fixed reverse covariance σₜ²I, the part of the Gaussian KL that depends on the learned mean is:

C is independent of the mean parameters when the covariance is fixed. The source’s squared matrix-norm denominator is not the correct general weighting; for a general fixed covariance, the mean error is a Mahalanobis quadratic form.

The simplified objective drops this timestep-dependent weighting and predicts the sampled noise directly. It changes the weighting of the variational objective; it is not merely an algebraic cancellation. The network receives x_t and t and learns which noise corrupted x₀.

The reverse-transition Gaussian KL derivation applies to t≥2. The t=1 boundary is handled separately by the reconstruction likelihood.

DDPM paper — variational bound and noise-prediction objective

DDPM training and sampling

Training samples a clean image, a timestep, and Gaussian noise; the network learns to predict the added noise.

text
repeat:
    x0 ~ data
    t ~ Uniform({1, ..., T})
    epsilon ~ Normal(0, I)
    xt = sqrt(alpha_bar[t]) * x0 + sqrt(1 - alpha_bar[t]) * epsilon
    update theta to minimize ||epsilon - epsilon_theta(xt, t)||^2

Sampling starts from Gaussian noise and repeatedly applies the learned reverse update.

Use z ∼ N(0,I) for t > 1 and z = 0 for the final step, with αₜ = 1−βₜ and ᾱₜ = ∏ₛ₌₁ᵗ αₛ.

Complete reverse-sampling pseudocode

python
def sample_ddpm(T, image_shape, epsilon_theta, beta, alpha, alpha_bar, sigma):
    x = sample_standard_normal(image_shape)  # x_T
    for t in range(T, 0, -1):
        z = sample_standard_normal(image_shape) if t > 1 else zeros(image_shape)
        predicted_noise = epsilon_theta(x, t)
        mean = (x - beta[t] / sqrt(1 - alpha_bar[t]) * predicted_noise) / sqrt(alpha[t])
        x = mean + sigma[t] * z
    return x  # x_0

Paper: Denoising Diffusion Probabilistic Models