Lesson 5.3 — Denoising Diffusion Probabilistic Models
Previous lesson · 5.2 GANs & Normalizing Flows · Course overview · Next lesson · 5.4 Score-based Generative Models
Diffusion Modeling Overview
A diffusion model starts with a prescribed process that progressively corrupts the data. The model learns reverse transitions from artificially noised training examples. The training labels are noise draws from the forward process.

Imagine a clean signal that can sit at either of two equally likely positions. At a fixed noise level, each source gives a bell-shaped distribution of noisy readings. Place your finger at their intersection. The left source would have needed a positive noise draw to get here. The right source would have needed an equally large negative draw. The trainer knows which source it used, but the denoiser receives the same input in both cases.
Under squared error, its best prediction at this midpoint is zero. Both training histories used nonzero noise. Zero is the average of their equally plausible labels. Away from the midpoint the two curve heights differ, so the more plausible source contributes more to the prediction. A reverse step uses this local estimate to construct a transition. Sampling starts from a fresh noise draw and composes those transitions.
Here time increases from data to noise in the forward chain. Generation runs the model in decreasing time. A generated point is a new sample from the reverse chain. At finite the true terminal marginal can retain signal even when the sampler starts from a standard Gaussian.
See how the two-dimensional training distribution spreads with time
Gaussian Noise & Forward Process
Gaussian Markov Chain
At step , let and . Scale the current point and add independent, centered Gaussian noise.
The next state depends on the past through the immediately preceding state. Consecutive states remain correlated. If the preceding state has mean and covariance , the new mean is and the covariance is . This leaves the standard Gaussian invariant.
In two steps the independent noise contributions add in variance. Their summed variance is in each coordinate.
Closed-form Forward Diffusion
Let be the product of the retention factors up to time , with . The mean coefficient accumulates multiplicatively. The conditional variance recurs as .
The closed form samples a chosen noise level directly, making it possible to train on a random time step without tracing an entire forward trajectory. The noise vector represents the accumulated noise in standardized coordinates. The lab holds that vector fixed to compare marginal distributions across time. An actual Markov rollout draws fresh noise at every step and has different correlations across time.
Closed-form Diffusion Explorer
Noise Schedule and Signal-to-noise Ratio
The schedule chooses the variance added at each step. The accumulated retention controls the squared signal coefficient. The ratio below compares squared coefficients and coincides with a power ratio for unit-variance signal coordinates and unit-variance noise.
A linear schedule varies directly. A cosine schedule starts with the target curve and computes each from the ratio of adjacent values. Normalize the curve by and cap each variance at 0.999 to avoid a zero retention factor. The lab's linear schedule runs from 0.005 to 0.25 in 40 steps, giving visible corruption over a short timeline.
Noise Schedule & SNR
The Gaussian Reverse Posterior
For , the forward transition and the conditional distribution at the previous step are Gaussian. Conditioning on both the clean point and the noisy point makes their product a Gaussian in the previous state. Without the clean point, the true reverse conditional averages over possible clean points and can be a mixture.
Complete the square in . The quadratic coefficient is . Its reciprocal gives the variance. Multiply this variance by the combined linear coefficient to get the mean.
At the conditional posterior is a point mass at the known clean point, with variance zero. During generation the clean point is unknown. Substituting the noise prediction into the clean-point estimate gives the model mean.
Gaussian Reverse Posterior
Noise Prediction and the Variational Objective
The forward chain supplies a fixed variational distribution over the latent noisy states. The negative ELBO contains a reconstruction term, a terminal prior KL, and intermediate reverse-step KL terms.
When the model variance is fixed, the trainable part of each intermediate Gaussian KL depends on a squared difference of means. Substituting the noise parameterization gives a time-weighted noise-prediction error.
The simplified DDPM loss chooses a time step uniformly and drops the intermediate weights. The code averages squared errors over the batch and the two noise coordinates.
In the opening example, write the noisy point as with and . Choosing a possible clean source fixes its implied noise label . Weight these labels by the posterior probabilities of their sources to get the prediction the network can learn.
The population minimizer of squared error is the conditional expected noise given the noisy point and time. For the known teaching mixture, get that expectation by weighting the conditional estimates from the four modes by their posterior responsibilities. The analytical labs use this reference prediction to make the sampler mechanics visible. An error in predicted noise can be amplified in the clean-point estimate when the retained signal is small.
Compare the sampled noise label with its conditional expectation
Noise Prediction Objective
Reverse Sampling with DDPM and DDIM
Start from Gaussian noise, evaluate the model mean, and add fresh Gaussian noise scaled by the fixed posterior standard deviation. The final update adds no noise. An analytical conditional-mean predictor still uses a Gaussian approximation to the intermediate reverse transitions of the mixture.
Reverse Denoising Player
DDIM and alternative prediction targets
DDIM uses the same noise predictor to move directly from step to an earlier step . The parameter sets the random contribution.
At the path is deterministic given the initial point. With and adjacent steps, the update agrees with DDPM using the posterior variance, including the final deterministic step. A skipped grid changes the update sequence and evaluation cost. A separate prediction parameterization rotates the pair of clean and noise coordinates.
This is a linear combination of data and noise used as a regression target. Lesson 5.5 studies a time-dependent transport velocity along an interpolant. Changing prediction targets or weighting changes the training problem for a finite network.
DDPM vs. DDIM Sampling
Engineering Experiment · A Two-dimensional DDPM
The target is the four-mode Gaussian mixture from Lesson 5.2, with centers and standard deviation 0.30 per coordinate. There are 256 training points, 256 validation points, and 256 fixed starting noise vectors for generation evaluation. The noise network concatenates the two noisy coordinates, normalized time, signal coefficient, and noise coefficient. The 5–24–24–2 MLP has tanh hidden layers and 794 parameters. The default run uses 1000 Adam updates, batch size 32, and learning rate 0.005.
The fixed validation set of 256 corruptions samples pairs of validation points and time steps with replacement. Distribution metrics compare generated and validation sample sets with the 24 fixed projection directions and the same mode thresholds as Lesson 5.2. Values outside the displayed axes are included.
Live 2D DDPM Training
Results on the default split
Validation noise MSE falls from 1.031494 to 0.396260. At the final checkpoint, 40-step DDPM gives sliced Wasserstein-2 of 0.670263 and an in-radius fraction of 85.55%. The 10-step and 40-step DDIM samplers give 1.518804 and 1.449841. All three cover four modes by the threshold criterion, while the DDIM draws have strongly uneven mode counts. The results show why denoising error, coverage, and relative mode frequencies are examined together. The GAN and coupling flow use different networks and optimization budgets.
Reproducible PyTorch implementation
The script implements training, fixed validation corruptions, and both reverse samplers in CPU float64. It uses the same data, schedule, and distribution metrics as the browser experiment. To verify the sampler algebra, supply the same noise predictor and random increment to adjacent-step DDIM with and DDPM.
import math, torch
from torch import nn
torch.set_default_dtype(torch.float64);torch.set_num_threads(1)
def rng(seed):
def r():
nonlocal seed
seed=(1664525*seed+1013904223)&0xffffffff
return seed/4294967296
return r
def normal(r):return math.sqrt(-2*math.log(max(r(),1e-15)))*math.cos(2*math.pi*r())
def noise(r,n):return torch.tensor([[normal(r),normal(r)] for _ in range(n)])
CENTERS=torch.tensor([[-1.6,-1.6],[-1.6,1.6],[1.6,-1.6],[1.6,1.6]])
def data(seed,n=256):
r=rng(seed);return torch.tensor([[float(c)+.30*normal(r) for c in CENTERS[int(4*r())]] for _ in range(n)])
T=40
beta=torch.cat([torch.zeros(1),torch.linspace(.005,.25,T)])
abar=torch.cumprod(1-beta,0)
def feats(x,t):
a=abar[t];return torch.cat([x,(t/T).unsqueeze(-1),a.sqrt().unsqueeze(-1),(1-a).sqrt().unsqueeze(-1)],-1)
class Net(nn.Module):
def __init__(self,r):
super().__init__();self.layers=nn.ModuleList()
for ni,no in [(5,24),(24,24),(24,2)]:
l=nn.Linear(ni,no);l.weight.data.copy_(torch.tensor([.8*(r()-.5) for _ in range(ni*no)]).reshape(no,ni));l.bias.data.zero_();self.layers.append(l)
def forward(self,x,t):
h=feats(x,t);return self.layers[2](self.layers[1](self.layers[0](h).tanh()).tanh())
def flat(self):return torch.cat([p.flatten() for p in self.parameters()]).tolist()
def batch(r,X,n=32):
idx=[int(r()*len(X)) for _ in range(n)];t=torch.tensor([1+int(r()*T) for _ in range(n)]);e=noise(r,n);a=abar[t,None];return a.sqrt()*X[idx]+(1-a).sqrt()*e,t,e
def metrics(x,y):
a=torch.arange(24)*math.pi/24;d=torch.stack([a.cos(),a.sin()],1);sw=(torch.sort(x@d.T,dim=0).values-torch.sort(y@d.T,dim=0).values).square().mean().sqrt().item();dist=torch.cdist(x,CENTERS);v,i=dist.min(1);counts=torch.bincount(i[v<=.75],minlength=4);return dict(swd=sw,counts=counts.tolist(),valid=(v<=.75).double().mean().item(),coverage=int((counts>=13).sum()))
@torch.no_grad()
def sample(m,z,steps=40,eta=1,seed=99):
x=z.clone();r=rng(seed);times=[round(T*i/steps) for i in range(steps,-1,-1)]
for t,s in zip(times,times[1:]):
e=m(x,torch.full((len(x),),t,dtype=torch.long));a,b=abar[t],abar[s];x0=(x-(1-a).sqrt()*e)/a.sqrt();sig=eta*torch.sqrt((1-b)/(1-a)*(1-a/b));x=b.sqrt()*x0+torch.sqrt(torch.clamp(1-b-sig**2,min=0))*e
if sig>0:x=x+sig*noise(r,len(x))
return x
def run(seed=3,steps=1000,lr=.005):
tr,va=data(seed),data(seed+1000);z=noise(rng(seed+2000),256);val=batch(rng(seed+5000),va,256);m=Net(rng(seed+3000));opt=torch.optim.Adam(m.parameters(),lr=lr);r=rng(seed+4000);hist=[]
for i in range(steps+1):
if i%100==0 or i==steps:
with torch.no_grad():
x,t,e=val;loss=(m(x,t)-e).square().mean().item();hist.append(dict(i=i,loss=loss,p=m.flat(),ddim=metrics(sample(m,z,10,0),va)))
if i==steps:break
x,t,e=batch(r,tr);opt.zero_grad();loss=(m(x,t)-e).square().mean();loss.backward();opt.step()
hist[-1]['ddpm']=metrics(sample(m,z,40,1,seed+6000),va);hist[-1]['ddim40']=metrics(sample(m,z,40,0),va);return hist
if __name__=='__main__':
import json
h=run();print(json.dumps([{k:v for k,v in a.items() if k!='p'} for a in (h[0],h[-1])],indent=2))
References and Chapter Connection
| Mechanism | DDPM | DDIM (η = 0) |
|---|---|---|
| Training | Shared noise prediction objective | Shared noise prediction objective |
| Sampling | Stochastic adjacent steps | Deterministic given initial noise |
| Network evaluations | 40 in this experiment | 5–40 in this experiment |
- Ho, Jain, and Abbeel develop the forward process, variational objective, and noise parameterization. Denoising Diffusion Probabilistic Models
- Song, Meng, and Ermon develop alternative sampling paths and accelerated sampling. Denoising Diffusion Implicit Models
- Nichol and Dhariwal study learned variance and cosine schedules. Improved Denoising Diffusion Probabilistic Models
- Chapter 18 covers diffusion models. Understanding Deep Learning
- The course develops diffusion, scores, and continuous samplers together. MIT 6.S184
The next lesson describes continuous-time corruption and connects the learned noise predictor to the score of the noisy density.
Previous lesson · 5.2 GANs & Normalizing Flows · Course overview · Next lesson · 5.4 Score-based Generative Models