Generative Models/Diffusion and Score-Based Models

Lesson 8.72,402 words

Diffusion and Score-Based Models

Corrupt a data point with Gaussian noise in small steps until only noise remains, then train a network to undo one step at a time. We derive the forward process and its closed-form marginal, reduce the variational bound to the single noise-prediction objective that makes diffusion trainable, and show the score-matching view that unifies it with Langevin sampling and the continuous SDE.

╌╌╌╌

The variational autoencoder learns one encoder that maps data to a latent code in a single jump, and a single decoder that jumps back. Diffusion models instead replace the one hard jump with a long chain of easy ones. Corrupt a datum by adding a little Gaussian noise, repeat hundreds of times until it is indistinguishable from white noise, then learn to reverse one small step at a time. Each step is a tiny, well-conditioned denoising problem, and the model is the same network applied over and over. The forward corruption has no parameters and a closed form; all the learning is in the reverse chain.1

The two chains

Diffusion defines a fixed forward process that gradually turns data into noise , and a learned reverse process that turns noise back into data.

Forward chain destroys the datum into Gaussian noise; the learned reverse chain rebuilds a sample from noise.

The forward chain supplies the training data. Because is fixed and tractable, at any step we can produce a noised sample from a clean and train the network to predict what was added. Training never simulates the reverse chain; it only denoises samples drawn from the forward chain.

The forward process

Each forward step adds Gaussian noise scaled by a small variance schedule, shrinking the signal by so the variance stays bounded:

The on the mean is what keeps the marginal from exploding: as grows the original signal is attenuated and replaced by noise, and after enough steps is essentially regardless of .

The closed-form marginal

Sampling by running steps of the chain would be wasteful. The chain of Gaussians collapses into a single Gaussian: given has a closed form, so we jump to any step in one shot.

This identity is what makes training practical: it lets us sample directly from with one noise draw,

so a training step picks a random , corrupts in one operation, and trains the network to recover .

The surviving signal decays as the noise level grows; their crossover sets where structure dissolves.

A common choice is the cosine schedule, which keeps from collapsing too fast near and spends more steps where the image still holds structure; the original DDPM used a linear ramp.2

A worked forward and reverse step

For example, work with a single scalar coordinate and a schedule where, at some step , the accumulated signal fraction is , so and . Forward: corrupt a clean value with a noise draw in one shot,

The signal has shrunk to and of noise now rides on top. Reverse: the network sees and (having been trained on exactly this construction) predicts the noise; suppose , close to the true . With single-step parameters (so , ) the DDPM reverse mean is

The reverse step nudges the value from toward , subtracting a sliver of the predicted noise; ancestral sampling then adds a small jitter (except on the final step). Reading the same prediction through the score view, : the score points in the direction here, indicating that density rises as decreases, which is the same drift the reverse mean applied. The two readings are equivalent views of one prediction.

The reverse process and the variational bound

To generate, we need , the true reverse step. It is intractable because it depends on the whole data distribution through Bayes' rule. We approximate it with a Gaussian whose mean is a network and whose variance is fixed (or learned):

A Gaussian reverse step is justified: when is small, the true reverse is itself approximately Gaussian, so matching it with a Gaussian is a tight approximation rather than a crude one.

The ELBO over the chain

As with the VAE, the marginal is intractable, so we maximize a variational bound. The forward chain plays the role of the approximate posterior, but it is fixed and parameter-free, which makes the bound far simpler to train.

Training this raw bound is high-variance because is noisy. The fix is to condition on . The forward posterior is tractable and Gaussian by Bayes' rule combined with the two closed-form marginals:

Rewriting in terms of this posterior groups it into per-step KL divergences between two Gaussians, each computable in closed form:

has no parameters (both ends are fixed Gaussians), is a reconstruction term, and the work is in the terms: match the learned reverse Gaussian to the tractable forward posterior at every step.3

The bound decomposes into a fixed prior-matching term , per-step denoising KLs , and a reconstruction term .

Reducing to noise prediction

Each is a KL between two Gaussians with the same fixed variance, so it reduces to the squared distance between their means, . The key step is to reparameterize the mean. From the marginal, ; substituting into rewrites the target in terms of the noise that produced :

So instead of predicting the mean we let the network predict the noise, , and set . The mean difference collapses to a noise difference, and the whole bound reduces to a single regression target:3

The objective is mean-squared error between true and predicted noise. Ho et al. found the unweighted loss trains better than the variational weighting, because dropping the -style factor up-weights the harder, high-noise steps relative to the trivial low-noise ones.3

Algorithm:TrainDDPM(ϵθ,D)\textsc{TrainDDPM}(\epsilon_\theta, \mathcal{D}) — minimize the noise-prediction loss
  1. 1
    repeat
  2. 2
    x0x_0 \gets sample from D\mathcal{D}
  3. 3
    tt \gets sample from Unif{1,,T}\mathrm{Unif}\{1, \dots, T\}
    a random diffusion step
  4. 4
    ϵ\epsilon \gets sample from N(0,I)\mathcal{N}(0, I)
    the target noise
  5. 5
    xtαˉtx0+1αˉtϵx_t \gets \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\, \epsilon
    one-shot corruption
  6. 6
    take a gradient step on θϵϵθ(xt,t)2\nabla_\theta \, \|\epsilon - \epsilon_\theta(x_t, t)\|^2
  7. 7
    until converged
  8. 8
    return θ\theta

Sampling runs the learned reverse step from down to , injecting fresh noise at every step except the last:

Algorithm:SampleDDPM(ϵθ)\textsc{SampleDDPM}(\epsilon_\theta) — ancestral sampling of the reverse chain
  1. 1
    xTx_T \gets sample from N(0,I)\mathcal{N}(0, I)
  2. 2
    for tTt \gets T down to 11 do
  3. 3
    zz \gets sample from N(0,I)\mathcal{N}(0, I) if t>1t > 1 else 00
    no noise on the last step
  4. 4
    xt11αt(xtβt1αˉtϵθ(xt,t))+σtzx_{t-1} \gets \dfrac{1}{\sqrt{\alpha_t}}\parens{x_t - \dfrac{\beta_t}{\sqrt{1 - \bar\alpha_t}}\, \epsilon_\theta(x_t, t)} + \sigma_t\, z
  5. 5
    return x0x_0

The score-based view

The same algorithm can be derived from a different starting point: model the score of the data density, , the direction in which probability rises fastest.

This is the score's advantage over the density itself: a model of sidesteps the partition function that makes energy-based models intractable. We cannot fit a score by regressing on because we never observe it; denoising score matching supplies a tractable surrogate. Perturb with Gaussian noise of scale to get . The score of the noised density has a closed form, and matching it reduces to predicting the noise:

A noise-predictor and a score-model are therefore the same object up to a known scale. If , then . DDPM's -prediction loss is denoising score matching at all noise scales at once, which is why the two literatures describe one method.4

Quantity-prediction viewScore view
Network outputpredicted noise score
Relation
Trainingregress on injected noisedenoising score matching
Samplingancestral reverse stepLangevin / reverse SDE

Langevin dynamics

Given a score field, Langevin dynamics samples from by gradient ascent on with calibrated noise, a stochastic walk that climbs density while the noise prevents collapse to the single mode:

As and the chain length grows, converges to a sample from . The noised-score view explains why a single scale fails and a schedule of scales is needed: in low-density regions the data score is badly estimated, so sampling starts at a large noise scale (smooth, well-estimated field) and anneals to small scales — the same annealing the reverse diffusion chain performs.4

Annealed sampling across noise scales. A large blurs the two modes into one broad basin with a reliable score; shrinking sharpens the field back to the true bimodal density.
Langevin dynamics follows the score field (arrows) from a random start, drifting toward the high-density mode while injected noise jitters the path.

The continuous limit: SDEs and the probability-flow ODE

Sending the step size to zero turns the discrete chain into a stochastic differential equation. The forward corruption is the SDE with a Wiener process; the discrete schedule is its Euler discretization. This SDE has an exact reverse-time SDE, written entirely in terms of the score:

Plug in the learned score and integrate backward from noise to data: this is diffusion sampling in continuous time, with DDPM a particular discretization. Every such SDE has a deterministic counterpart with the same marginals at every , the probability-flow ODE:

Because it is an ODE, sampling is deterministic given , the trajectory is unique, and any black-box ODE solver applies; it also gives an exact log-likelihood through the change-of-variables / continuous-flow identity, tying diffusion back to normalizing flows.5

Fast sampling with DDIM

DDPM sampling needs hundreds to thousands of sequential network passes, one per step. DDIM reduces this cost by abandoning the Markov assumption. It defines a family of non-Markovian forward processes that share the same marginals , so a network trained with the DDPM objective can be reused unchanged, yet whose reverse step is deterministic and can skip steps.6 The DDIM update first predicts the clean datum, then re-noises it to the next (possibly distant) step:

There is no added noise term, so the map from to is deterministic; it is in fact an Euler discretization of the probability-flow ODE. Determinism allows large step skips with little quality loss, cutting sampling to tens of steps.

PropertyDDPM (ancestral)DDIM
Reverse processMarkov, stochasticnon-Markov, deterministic
Added noise per stepnone
Typical steps
Same trained networkyesyes (identical objective)
Latent meaningnoise reservoirencodes the sample (invertible)
DDPM walks every step with re-injected noise; DDIM follows a deterministic trajectory that skips steps, reaching in far fewer passes.

Conditioning and guidance

To make (an image given a label or caption), we steer the reverse chain toward the condition . Bayes' rule on the score splits the conditional score into the unconditional score plus the gradient of the classifier likelihood:

Classifier guidance instantiates this directly: train a separate classifier on noised inputs and add a scaled version of its gradient to the score at sampling time, with a guidance scale that exaggerates the steer:7

The drawback is the extra classifier, trained on noisy data, whose gradients are unreliable. Classifier-free guidance removes it. Train one network to be both conditional and unconditional by randomly dropping during training (replacing it with a null token), then at sampling time combine the two predictions to synthesize the same steer without any classifier:8

Guidance extrapolates past the conditional prediction along the line from the unconditional one, scale controlling how far the steer is pushed.

Latent diffusion

Diffusing in pixel space is expensive: every one of hundreds of reverse steps runs a full-resolution network. Latent diffusion (the model behind Stable Diffusion) moves the entire process into the compact latent space of a pretrained autoencoder. An encoder compresses to a latent at a fraction of the spatial size; diffusion trains and samples on ; a decoder maps the generated latent back to a pixel image .9

The autoencoder strips imperceptible high-frequency detail so the diffusion model spends its capacity on the semantically meaningful structure, and the smaller spatial resolution makes each denoising step cheap. The denoiser itself is a U-Net: a convolutional encoder-decoder with skip connections that join matching-resolution feature maps, so fine spatial detail is preserved across the bottleneck. Two ingredients adapt it to diffusion. The step index enters through a time embedding (a sinusoidal encoding fed to every block), telling the network the current noise level. The condition (e.g. a text embedding) enters through cross-attention layers, so the prompt modulates features throughout the network.

The U-Net denoiser: a downsampling encoder and upsampling decoder joined by skip connections, with time embedding and condition injected at every block.

Takeaways

  • A diffusion model fixes a parameter-free forward chain that destroys data into Gaussian noise, and learns a reverse chain that rebuilds it.
  • The forward marginal is closed-form, , derived by merging the chain's independent Gaussian increments, so any is one noise draw from .
  • The variational bound decomposes into per-step Gaussian KLs, and reparameterizing the mean reduces it to the simple objective: the network predicts the injected noise.
  • The score view identifies , so -prediction is denoising score matching, sampled by Langevin dynamics or, in continuous time, by the reverse SDE and its deterministic probability-flow ODE.
  • DDIM reuses the same network with a non-Markov deterministic reverse step that skips steps, cutting sampling from to tens of passes; classifier-free guidance steers samples toward a condition without an external classifier.
  • Latent diffusion runs the whole process in a pretrained autoencoder's latent space with a U-Net denoiser, time embedding, and cross-attention conditioning, the architecture behind modern text-to-image generation.

Footnotes

  1. Sohl-Dickstein, Weiss, Maheswaranathan & Ganguli (ICML 2015), Deep Unsupervised Learning using Nonequilibrium Thermodynamics — the original diffusion model: a learned reverse of a fixed Gaussian noising chain.
  2. Nichol & Dhariwal (ICML 2021), Improved Denoising Diffusion Probabilistic Models — the cosine variance schedule and learned reverse variances that sharpen samples and log-likelihood.
  3. Ho, Jain & Abbeel (NeurIPS 2020), Denoising Diffusion Probabilistic Models — DDPM; the reparameterization that turns the ELBO into the simple objective. 2 3
  4. Song & Ermon (NeurIPS 2019), Generative Modeling by Estimating Gradients of the Data Distribution — NCSN; denoising score matching across noise scales sampled by annealed Langevin dynamics. 2
  5. Song, Sohl-Dickstein, Kingma, Kumar, Ermon & Poole (ICLR 2021), Score-Based Generative Modeling through Stochastic Differential Equations — the forward/reverse SDE and the probability-flow ODE unifying diffusion and score models.
  6. Song, Meng & Ermon (ICLR 2021), Denoising Diffusion Implicit Models — DDIM; a non-Markov deterministic reverse process sharing DDPM's marginals, enabling few-step sampling.
  7. Dhariwal & Nichol (NeurIPS 2021), Diffusion Models Beat GANs on Image Synthesis — classifier guidance, adding a noised-input classifier's gradient to the score with a scale .
  8. Ho & Salimans (NeurIPS Workshop 2022), Classifier-Free Diffusion Guidance — jointly training a conditional and unconditional model and extrapolating between their predictions.
  9. Rombach, Blattmann, Lorenz, Esser & Ommer (CVPR 2022), High-Resolution Image Synthesis with Latent Diffusion Models — Stable Diffusion; diffusion in a pretrained autoencoder latent with a cross-attention U-Net.

╌╌ END ╌╌