DDPM: noise prediction, reverse variance and what is actually learned
去噪扩散概率模型
Train a Gaussian denoiser to its analytic optimum, then separate variance choices, prior mismatch and sampling error.
ddpmPredicting noise leaves a second question unanswered
Suppose a synthetic measurement comes from a Gaussian distribution with mean .7 and variance .36. Repeatedly shrink it a little and add independent Gaussian noise. Eventually the original measurement becomes hard to identify. A model trained to predict the added noise can help reverse this process, but it must also decide how much uncertainty to put back at each step.
That second choice matters. In the worked example below, we learn the optimal noise predictor to numerical precision, yet one reverse-variance choice produces variance .27854 instead of .36. A correct conditional mean does not determine a conditional distribution.
Denoising Diffusion Probabilistic Models, by Ho, Jain and Abbeel, develops a noise-prediction parameterization and a practical simplified objective. The paper appeared at NeurIPS 2020; we use its December 2020 revision. This article follows the finite probabilistic chain. Start with diffusion models, Gaussian distributions and the ELBO; DDIM separately studies how to change the sampling path.
A forward chain whose noisy marginals are known
Let x0 be a D-dimensional observation. Choose fixed noise variances βt between zero and one, and write αt=1−βt. The forward process is Markovian: each step depends only on the preceding state.
Composing independent Gaussian increments gives a direct way to obtain any noisy training level. We use A for the cumulative product to keep it distinct from the single-step α:
Training can therefore choose one random t and form xt directly; it need not simulate every earlier step. The reverse model instead starts from a simple prior, usually a standard Gaussian, and uses learned conditional means with a declared variance policy. At finite T, the true forward terminal distribution need not exactly equal that prior.
Conditioning on both xt and the original x0 makes the forward posterior tractable. Multiplying the two Gaussian factors and completing the square gives, for t>1:
At t=1, conditioning on x0 makes this a point mass at x0. This is not the same as knowing only x1 and trying to infer an unknown observation. Equations 5–7 use the x0-conditioned posterior to organize the variational bound:
This is an upper bound on expected negative log-likelihood when the stated generative conditionals and endpoint decoder define that likelihood. The image paper uses a discretized endpoint decoder. Our continuous teaching sampler does not implement that decoder or report an image ELBO.
From the posterior mean to a noise target
Substitute the noisy-marginal expression for x0 into the posterior mean. The result suggests predicting ε rather than predicting the mean directly:
For fixed, positive reverse variance σt² and t>1, the part of the Gaussian KL depending on the mean becomes a weighted noise-prediction error. C below is independent of θ:
The simplified objective removes that time-dependent weight and draws t uniformly. It is not numerically identical to the complete variational bound:
Squared-error regression learns the conditional expectation of its target. Even the optimal predictor generally cannot recover the particular noise draw used for one corrupted observation:
For our Gaussian data, this optimum has an independent closed form. Let m0=.7 and v0=.36. Cov(ε,xt)=√(1−At), so Gaussian conditioning yields:
This permits an exact test of learning the mean, followed by a separate test of the variance. For continuous Gaussian data, the true reverse conditional variance is:
It exceeds the x0-conditioned variance because the unknown x0 contributes uncertainty. The paper discusses βt and the posterior variance as fixed choices; neither should be renamed “the exact reverse variance” for arbitrary data.
Learn 48 coefficients and check the reverse chain
Save as ddpm.py, using Python 3.12 and NumPy 1.26.4. There are 24 noise levels with β increasing linearly from .02 to .25, and two independent regression coefficients per level. This is a Gaussian teaching model, not a U-Net. A 9-by-9 product Gaussian quadrature evaluates the distribution-level quadratic objective; its required polynomial moments are exact up to floating-point error. It is not a randomly drawn finite training dataset.
The program trains all 48 coefficients with explicit gradients, then compares three variance policies. posterior uses the x0-conditioned variance; beta uses β but omits noise at the final display step; exact-gaussian uses the continuous Gaussian reference variance, including the last step. The latter is a reference calculation, not the noiseless endpoint in Algorithm 2. No x0 clipping or discrete-pixel decoder is implemented.
The author implementation is useful for checking cumulative products, posterior coefficients and the zero-based final-step noise mask. It also offers x0 clipping, which our Gaussian example does not use. We read the fixed source as a reference; no upstream code is copied or executed, and a root reuse license was not established.
With Q quadrature nodes per Gaussian variable, a gradient step costs O(TQ²) and stored training arrays take O(TQ²) space. A batch of N generated scalars takes O(TN) time and O(N+T) space. For an image denoiser, replace the scalar update cost with the actual network cost; counting T calls alone omits most arithmetic.
"""Original Gaussian DDPM lesson: train48 coefficients and expose variance choices."""
import json
import numpy as np
MU, VAR = .7, .36
def schedule(steps=24):
if type(steps) is not int or not 2 <= steps <= 256:
raise ValueError('steps must be an integer in [2,256].')
beta = np.linspace(.02, .25, steps)
alpha = 1-beta
cumulative = np.cumprod(alpha)
previous = np.r_[1., cumulative[:-1]]
return beta, alpha, cumulative, previous
def coefficients(steps=24):
beta, alpha, abar, prev = schedule(steps)
return (np.sqrt(prev)*beta/(1-abar), np.sqrt(alpha)*(1-prev)/(1-abar), beta*(1-prev)/(1-abar))
def training_data(steps=24):
# Product Gaussian quadrature, exact for this quadratic regression objective.
_, _, abar, _ = schedule(steps)
nodes, weights = np.polynomial.hermite.hermgauss(9)
z = np.sqrt(2)*nodes; weights = weights/np.sqrt(np.pi)
clean, noise = np.meshgrid(MU+np.sqrt(VAR)*z, z, indexing='ij')
clean, noise = clean.ravel(), noise.ravel()
x = np.sqrt(abar[:, None])*clean+np.sqrt(1-abar[:, None])*noise
return x, np.broadcast_to(noise, x.shape), np.outer(weights, weights).ravel()
def objective(theta, data):
theta = np.asarray(theta, float)
x, noise, weight = data
if theta.shape != (len(x), 2) or not np.all(np.isfinite(theta)) or np.max(np.abs(theta)) > 20:
raise ValueError('Expected finite Tx2 coefficients of magnitude <=20.')
residual = theta[:, :1]*x+theta[:, 1:]-noise
loss = np.mean(np.sum(weight*residual**2, axis=1))
gradient = 2/len(x)*np.column_stack([np.sum(weight*residual*x, axis=1), np.sum(weight*residual, axis=1)])
return float(loss), gradient
def optimal(steps=24):
_, _, abar, _ = schedule(steps)
mean, variance = np.sqrt(abar)*MU, abar*VAR+1-abar
slope = np.sqrt(1-abar)/variance
return np.column_stack([slope, -slope*mean])
def train():
data = training_data(); theta = np.zeros((24, 2)); history = [objective(theta, data)[0]]
for step in range(1200):
theta -= 2.*objective(theta, data)[1]
if (step+1) % 200 == 0: history.append(objective(theta, data)[0])
return theta, history
def reverse_parameters(theta, variance='posterior'):
theta = np.asarray(theta, float)
if theta.ndim != 2 or theta.shape[1] != 2 or not np.all(np.isfinite(theta)) or np.max(np.abs(theta)) > 20:
raise ValueError('Expected finite Tx2 parameters of magnitude <=20.')
beta, alpha, abar, prev = schedule(len(theta))
slope = (1-beta*theta[:, 0]/np.sqrt(1-abar))/np.sqrt(alpha)
offset = -beta*theta[:, 1]/np.sqrt(alpha*(1-abar))
if variance == 'posterior':
noise_var = coefficients(len(theta))[2]
elif variance == 'beta':
noise_var = beta.copy(); noise_var[0] = 0 # Algorithm2 noiseless display step.
elif variance == 'exact-gaussian':
# Reference reverse conditional for continuous Gaussian data, including t=1.
noise_var = beta*(prev*VAR+1-prev)/(abar*VAR+1-abar)
else:
raise ValueError('Unknown reverse variance choice.')
return slope, offset, noise_var
def reverse_moments(theta, variance='posterior', terminal='true'):
_, _, abar, _ = schedule(len(theta))
if terminal == 'true': mean, var = np.sqrt(abar[-1])*MU, abar[-1]*VAR+1-abar[-1]
elif terminal == 'standard': mean, var = 0., 1.
else: raise ValueError('terminal must be true or standard.')
slope, offset, noise_var = reverse_parameters(theta, variance)
for a, b, v in zip(slope[::-1], offset[::-1], noise_var[::-1]):
mean, var = a*mean+b, a*a*var+v
return np.array([mean, var])
def sample(theta, seed=12, count=16384, variance='posterior'):
if type(count) is not int or not 1 <= count <= 65536: raise ValueError('count must be in [1,65536].')
rng = np.random.default_rng(seed); x = rng.normal(size=count)
for a, b, v in zip(*(v[::-1] for v in reverse_parameters(theta, variance))):
x = a*x+b+np.sqrt(v)*rng.normal(size=count)
return x
def demo():
theta, history = train(); oracle = optimal(); samples = sample(theta)
beta, alpha, abar, prev = schedule()
return dict(training_mse=history, coefficient_error=float(np.max(np.abs(theta-oracle))),
cumulative_last=float(abar[-1]), target=[MU, VAR],
reverse={v:reverse_moments(oracle, v).tolist() for v in ['posterior','beta','exact-gaussian']},
standard_prior_moments=reverse_moments(theta, terminal='standard').tolist(),
sample_moments=[float(samples.mean()),float(samples.var())],
terminal_kl_to_standard=float(.5*(abar[-1]*VAR+1-abar[-1]+abar[-1]*MU**2-1-np.log(abar[-1]*VAR+1-abar[-1]))))
if __name__ == '__main__': print(json.dumps(demo(), indent=2))
Where the remaining error comes from
From zero coefficients, 1,200 updates at learning rate 2 reduce mean squared noise error from 1 to .292416864606. The maximum difference from the analytic coefficients is about 1.55×10⁻¹⁵. The remaining MSE is the conditional prediction uncertainty, not evidence of an unfinished optimization.
Starting from the true terminal distribution isolates reverse-variance choices. All three chains retain mean .7; their final variances are .278538637299 for posterior, .360982056182 for beta with a noiseless last step, and .36 for the continuous Gaussian reference. These values come from exact affine moment propagation, not noisy sample estimates.
The default sampler instead starts from N(0,1). Its analytic final mean and variance are .692685027335 and .278608526377. The true terminal distribution has KL divergence .00706625751716 to that standard prior. With seed 12 and 16,384 generated points, sample mean .686656689755 and variance .281079883048 agree with the implemented chain within sampling uncertainty. They should be compared with that chain’s moments before being compared with the desired data moments.
The checks also complete the square independently, compare every learned gradient with finite differences and verify the weighted KL/MSE identity. They distinguish learning error, prior mismatch, reverse-variance approximation and Monte Carlo error.
A short scalar chain is not an image result
Our Gaussian data makes the optimal denoiser linear and the true reverse conditionals Gaussian. Real image data need not have either property at a coarse noise step. A shared neural network may also trade accuracy across noise levels, so changing loss weights can change its fitted solution. Independent coefficients per time avoid that issue only in this example.
Noise schedules, clipping, learned versus fixed variance, endpoint decoding and numerical precision all affect the final model. The scalar demonstration does not reproduce the paper’s image architecture, training data, image likelihood or sample-quality benchmark. Its relatively large β values make the finite-step distinctions visible rather than hiding them behind a very long chain.
Separate the four sources of error
- Forward noise. If x0 is fixed and β1=.02, what are the first-step mean and variance? Answer: The mean is √.98 x0 and the variance is .02. This is conditional on a fixed x0; a random x0 adds its scaled data variance.
- Conditioning. Why is the posterior variance zero at the last denoising step when x0 is supplied? Answer: The variable being recovered is x0 itself, which is already conditioned on. Knowing only x1 leaves uncertainty; the continuous Gaussian reference has positive conditional variance there.
- Training. An optimal ε predictor has positive MSE. Must its optimizer have failed? Answer: No. It predicts E[ε|xt,t], and multiple clean/noise pairs can yield the same xt. The example reaches its analytic optimum while MSE remains about .29242.
- Evaluation. The final variance is too small even with the analytic denoiser and the true terminal distribution. Which part should be examined first? Answer: The reverse variance and endpoint policy. Those conditions already remove denoiser fitting and prior mismatch as explanations; inspect them before changing network size or blaming Monte Carlo variation.
Read the loss and the sampler together
Compare Equations 5–14 and Algorithms 1–2 with the fixed posterior and sampling implementation. Keep one-based mathematical t and zero-based code indices distinct. The article’s derivations and tests cover those selected methods; they do not stand in for reviewing every experiment or appendix. DDIM changes the sampling construction, while score-based SDEs provide a continuous-time framework.
Make a prediction, then check
Does an optimal noise predictor uniquely determine the correct reverse variance?
Learning objectives
- Derive noisy marginals and x0-conditioned posteriors.
- Relate noise MSE to weighted variational terms.
- Fit all48 coefficients and verify the optimum.
- Separate mean learning, variance and prior errors.
Prerequisites & connections
Explore related knowledge →References
- Denoising Diffusion Probabilistic Models (v2): chain, variance and loss
Jonathan Ho; Ajay Jain; Pieter Abbeel · 2020 - DDPM posterior and sampler at1e0dceb
Jonathan Ho and diffusion contributors · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked DDPM v2 selected equations5-14, algorithms1-2 and fixed author posterior/sampling code. Ten paired equations/four explained exercises; original48-parameter population Gaussian regression with all gradients, posterior precision, KL weighting and reverse-variance/prior counterexamples. No image benchmark or endpoint decoder reproduction.
- Single AI author checked DDPM v2 selected equations5-14, algorithms1-2 and fixed author posterior/sampling code. Ten paired equations/four explained exercises; original48-parameter population Gaussian regression with all gradients, posterior precision, KL weighting and reverse-variance/prior counterexamples. No image benchmark or endpoint decoder reproduction.
- Four computed SVG variants per topic. Fifteen numeric/geometry tests and24 responsive cases passed; eight final Chinese-mobile/English-desktop screenshots actually inspected. Axis and evidence corrections retained. Full article-page acceptance recorded separately.
Source locations checked:
- Denoising Diffusion Probabilistic Models (v2): chain, variance and loss · Read selected Sections2/3, Equations5–14, Algorithms1–2, decoder and final noiseless display; visually inspected PDF pages3–4. First2020-06-19; v2 dated2020-12-16, NeurIPS2020. No image benchmark or complete appendix review.
- DDPM posterior and sampler at1e0dceb · Read lines77–91,121–140,153–194: posterior coefficients, variance-log floor, noise MSE, optional x0 clipping and zero-based final noise mask. Commit2020-06-22. Root license not identified; reference only, no copied code or upstream execution.
Related topics