GyaanStack. Blog

Articles / generative-aideep-learningpython

Build a diffusion model from scratch in PyTorch: DDPM on MNIST

A small DDPM in PyTorch trained on MNIST on a Mac: closed-form noising, the noise schedule, the loss, the sampling loop, real timings and failure modes.

By Raghunath · · 18 min read

A denoising diffusion model learns one skill: given an image with a known amount of Gaussian noise mixed in, predict the noise. Everything else is bookkeeping. Generation starts from pure noise and applies that skill a thousand times, removing a little noise at each step until a digit (or a face, or a cat) is left.

This post builds the DDPM from Ho, Jain and Abbeel (2020) in about 150 lines of PyTorch and trains it on MNIST on a MacBook. It covers the closed-form forward process with worked numbers, the noise schedule, the training loss, the sampling loop, a cheap way to check the samples, and the things that go wrong. All code below was run on PyTorch 2.15.0 and torchvision 0.29.2 with the Apple MPS backend. The GPU was shared with a local LLM server during the run, so the timings are slower than an idle machine would give, and they are reported as measured.

The idea in one picture#

forward process q (fixed, no learning)
x_0 (digit) --> x_1 --> x_2 --> ... --> x_999 --> x_1000 (pure noise)
               +noise  +noise           +noise

reverse process p_theta (learned)
x_1000 (noise) --> x_999 --> ... --> x_1 --> x_0 (new digit)
           U-Net predicts the noise at each step, we subtract a bit of it

The forward process destroys an image by adding a small amount of Gaussian noise per step. It has no parameters. The reverse process is a neural network that undoes one step at a time. Because each step is small, each reverse step is close to Gaussian too, and a network only has to predict its mean. The paper shows that predicting the added noise is a convenient way to parameterize that mean.

Forward process and the closed-form shortcut#

One forward step scales the previous image down slightly and adds noise with variance beta_t:

q(x_t | x_{t-1}) = N( sqrt(1 - beta_t) * x_{t-1},  beta_t * I )

Stepping this a few hundred times inside a training loop would be slow. Because a sum of Gaussians is Gaussian, the paper derives a direct jump from the clean image to any step t. Define alpha_t = 1 - beta_t and alpha_bar_t as the product of alpha_1 through alpha_t. Then:

q(x_t | x_0) = N( sqrt(alpha_bar_t) * x_0,  (1 - alpha_bar_t) * I )

so  x_t = sqrt(alpha_bar_t) * x_0 + sqrt(1 - alpha_bar_t) * eps,   eps ~ N(0, I)

That one line is why DDPM training is cheap. Pick a random t, draw one noise tensor, and you have a training example in a single multiply-add.

The noise schedule#

The DDPM paper uses T = 1000 steps and a linear schedule for beta from 1e-4 to 0.02. Here is that schedule and every derived quantity the rest of the code needs:

import math
import torch
import torch.nn as nn
import torch.nn.functional as F

T = 1000  # number of diffusion steps, as in the DDPM paper


class Schedule:
    """Linear beta schedule from Ho et al. (2020), plus every derived quantity we need."""

    def __init__(self, T=T, beta_1=1e-4, beta_T=0.02, device="cpu"):
        self.T = T
        self.betas = torch.linspace(beta_1, beta_T, T, device=device)
        self.alphas = 1.0 - self.betas
        self.alpha_bars = torch.cumprod(self.alphas, dim=0)
        prev = torch.cat([torch.ones(1, device=device), self.alpha_bars[:-1]])
        # variance of q(x_{t-1} | x_t, x_0), the "beta tilde" in the paper
        self.posterior_var = self.betas * (1 - prev) / (1 - self.alpha_bars)

    def q_sample(self, x0, t, noise):
        """Closed form: x_t = sqrt(abar_t) * x0 + sqrt(1 - abar_t) * eps."""
        ab = self.alpha_bars[t].view(-1, 1, 1, 1)
        return ab.sqrt() * x0 + (1 - ab).sqrt() * noise

Indexing in code runs from 0 to 999 while the paper counts 1 to 1000. Keep that offset in mind when you compare against the equations.

Two checks are worth running before any training. The first prints how much of the original image survives at a few steps. The second confirms the closed form gives the same distribution as stepping the chain 500 times:

import torch
from ddpm import Schedule

torch.manual_seed(0)
s = Schedule()
for t in [0, 99, 249, 499, 999]:
    ab = s.alpha_bars[t].item()
    print(f"t={t+1:4d}  alpha_bar={ab:.5f}  signal coef={ab**0.5:.4f}  noise coef={(1-ab)**0.5:.4f}")

# The closed form must match stepping x_t = sqrt(1-beta_t) x_{t-1} + sqrt(beta_t) eps, t times.
x0 = torch.full((200_000,), 0.8)
x = x0.clone()
for t in range(500):
    x = (1 - s.betas[t]).sqrt() * x + s.betas[t].sqrt() * torch.randn_like(x)
ab = s.alpha_bars[499]
print(f"\nafter 500 single steps: mean={x.mean():.4f} std={x.std():.4f}")
print(f"closed form predicts:   mean={(ab.sqrt()*0.8).item():.4f} std={(1-ab).sqrt().item():.4f}")
t=   1  alpha_bar=0.99990  signal coef=0.9999  noise coef=0.0100
t= 100  alpha_bar=0.89702  signal coef=0.9471  noise coef=0.3209
t= 250  alpha_bar=0.52409  signal coef=0.7239  noise coef=0.6899
t= 500  alpha_bar=0.07859  signal coef=0.2803  noise coef=0.9599
t=1000  alpha_bar=0.00004  signal coef=0.0064  noise coef=1.0000

after 500 single steps: mean=0.2222 std=0.9617
closed form predicts:   mean=0.2243 std=0.9599

Read the table as a worked example. A pixel at value 0.8 at step 250 becomes 0.72 times 0.8 = 0.58 of signal plus noise with standard deviation 0.69. By step 500 only 28 percent of the signal remains, and the second half of the schedule spends 500 steps grinding down that last fraction. Nichol and Dhariwal (2021) found that for 32x32 images the end of the linear schedule is so noisy it adds little to sample quality, and proposed a cosine schedule that decays alpha_bar more evenly. The last row matters too. At t = 1000 the signal coefficient is 0.0064, not zero, so the final training input still carries a trace of the image while sampling starts from noise that carries none. Lin et al. (2023) show this mismatch caused brightness problems in Stable Diffusion. For MNIST it is harmless, but it is a real bug at scale.

The noise predictor: a small U-Net#

The network takes a noisy 32x32 image and the step number t, and returns a tensor of the same shape: its guess for eps. A U-Net (Ronneberger et al., 2015) fits because it maps an image to an image and its skip connections carry fine detail from the encoder to the decoder.

The step number goes in through a sinusoidal embedding, the same trick Transformers use for positions, projected by a small MLP and added to every residual block. Without it the network would have to guess the noise level from the image alone, which works poorly at the extremes.

def time_embedding(t, dim):
    """Sinusoidal embedding of the integer step t (Transformer-style)."""
    half = dim // 2
    freqs = torch.exp(-math.log(10000) * torch.arange(half, device=t.device) / (half - 1))
    args = t.float()[:, None] * freqs[None, :]
    return torch.cat([args.sin(), args.cos()], dim=1)


class ResBlock(nn.Module):
    def __init__(self, c_in, c_out, t_dim):
        super().__init__()
        self.norm1 = nn.GroupNorm(8, c_in)
        self.conv1 = nn.Conv2d(c_in, c_out, 3, padding=1)
        self.t_proj = nn.Linear(t_dim, c_out)
        self.norm2 = nn.GroupNorm(8, c_out)
        self.conv2 = nn.Conv2d(c_out, c_out, 3, padding=1)
        self.skip = nn.Conv2d(c_in, c_out, 1) if c_in != c_out else nn.Identity()

    def forward(self, x, temb):
        h = self.conv1(F.silu(self.norm1(x)))
        h = h + self.t_proj(temb)[:, :, None, None]  # tell the block which step it is on
        h = self.conv2(F.silu(self.norm2(h)))
        return h + self.skip(x)


class TinyUNet(nn.Module):
    """32x32 -> 16x16 -> 8x8 and back, with skip connections. About 0.78M parameters."""

    def __init__(self, ch=32, t_dim=128):
        super().__init__()
        self.t_dim = t_dim
        self.t_mlp = nn.Sequential(nn.Linear(t_dim, t_dim), nn.SiLU(), nn.Linear(t_dim, t_dim))
        self.inp = nn.Conv2d(1, ch, 3, padding=1)
        self.d1 = ResBlock(ch, ch, t_dim)            # 32x32
        self.down1 = nn.Conv2d(ch, ch, 4, 2, 1)       # -> 16x16
        self.d2 = ResBlock(ch, 2 * ch, t_dim)
        self.down2 = nn.Conv2d(2 * ch, 2 * ch, 4, 2, 1)  # -> 8x8
        self.mid = ResBlock(2 * ch, 4 * ch, t_dim)
        self.up2 = nn.ConvTranspose2d(4 * ch, 2 * ch, 4, 2, 1)  # -> 16x16
        self.u2 = ResBlock(4 * ch, 2 * ch, t_dim)
        self.up1 = nn.ConvTranspose2d(2 * ch, ch, 4, 2, 1)      # -> 32x32
        self.u1 = ResBlock(2 * ch, ch, t_dim)
        self.out = nn.Sequential(nn.GroupNorm(8, ch), nn.SiLU(), nn.Conv2d(ch, 1, 3, padding=1))

    def forward(self, x, t):
        temb = self.t_mlp(time_embedding(t, self.t_dim))
        h1 = self.d1(self.inp(x), temb)
        h2 = self.d2(self.down1(h1), temb)
        h = self.mid(self.down2(h2), temb)
        h = self.u2(torch.cat([self.up2(h), h2], dim=1), temb)
        h = self.u1(torch.cat([self.up1(h), h1], dim=1), temb)
        return self.out(h)  # predicted noise, same shape as x

Two choices here differ from many tutorials. The blocks use GroupNorm instead of BatchNorm, as the DDPM paper does. GroupNorm normalizes each image on its own. BatchNorm pools statistics across a batch whose images sit at very different noise levels, and it switches to running averages under model.eval(), so sampling can behave differently from training. The model is also small: 0.78M parameters with channel widths of 32, 64 and 128. MNIST does not need channel widths up to 1024, and a network that wide is slow to train on a laptop.

The training loss#

The paper's simplified objective, L_simple, is plain mean squared error between the noise you added and the noise the network predicts, with t drawn uniformly:

def ddpm_loss(model, sched, x0):
    """L_simple from the paper: MSE between the true and predicted noise."""
    t = torch.randint(0, sched.T, (x0.shape[0],), device=x0.device)  # use the real batch size
    noise = torch.randn_like(x0)
    x_t = sched.q_sample(x0, t, noise)
    return F.mse_loss(model(x_t, t), noise)

Draw t with the batch's real size, x0.shape[0], not a BATCH_SIZE constant. MNIST has 60,000 training images, and 60,000 divided by 128 leaves a final batch of 96. A hard-coded size makes that batch fail with a shape error at the end of the first epoch, after you have waited for the whole epoch to run. L1 loss also trains, but MSE is what the paper derives from the variational bound, so this post uses it.

Training on a Mac#

Data is MNIST from torchvision, padded from 28x28 to 32x32 so the two 2x downsamples divide evenly, and scaled to [-1, 1] so it lives on the same scale as the noise. Padding keeps the original pixels, where resizing would blur them.

The first version of this script used a DataLoader with num_workers=2 and crashed immediately with "An attempt has been made to start a new process before the current process has finished its bootstrapping phase." On macOS, Python's multiprocessing starts worker processes with spawn, which re-imports the main script, so any script that uses worker processes needs an if __name__ == "__main__": guard. The whole dataset is only 245 MB as float32 at 32x32, so the version below skips the loader, keeps everything on the device and samples random batches by index:

import sys, time
import torch
import torch.nn.functional as F
from torchvision import datasets
from ddpm import Schedule, TinyUNet, ddpm_loss


def load_mnist(device):
    """All 60,000 training digits as one tensor in [-1, 1], padded 28x28 -> 32x32."""
    ds = datasets.MNIST("data", train=True, download=True)
    x = ds.data.float().div(255).unsqueeze(1)   # (60000, 1, 28, 28) in [0, 1]
    x = F.pad(x, (2, 2, 2, 2)) * 2 - 1          # (60000, 1, 32, 32) in [-1, 1]
    return x.to(device)


if __name__ == "__main__":
    STEPS = int(sys.argv[1]) if len(sys.argv) > 1 else 4000
    device = "mps" if torch.backends.mps.is_available() else "cpu"
    torch.manual_seed(0)
    data = load_mnist(device)
    sched = Schedule(device=device)
    model = TinyUNet().to(device)
    if len(sys.argv) > 2:                       # optional: resume from saved weights
        model.load_state_dict(torch.load(sys.argv[2], map_location=device))
    print(f"device={device} params={sum(p.numel() for p in model.parameters())/1e6:.2f}M")
    opt = torch.optim.AdamW(model.parameters(), lr=2e-4)

    t0, running = time.time(), 0.0
    for step in range(1, STEPS + 1):
        idx = torch.randint(0, data.shape[0], (128,), device=device)
        loss = ddpm_loss(model, sched, data[idx])
        opt.zero_grad(set_to_none=True)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        running += loss.item()
        if step % 500 == 0:
            print(f"step {step:5d}  loss {running/500:.4f}  {time.time()-t0:5.0f}s")
            running = 0.0
    torch.save(model.state_dict(), "tiny_unet.pt")
    print(f"trained {STEPS} steps in {time.time()-t0:.0f}s")

The device line picks Apple's MPS backend when it exists and falls back to CPU. On a CUDA machine, change it to "cuda".

The run happened in two parts, because the GPU was busy serving a local LLM at the same time. The first 500 steps:

device=mps params=0.78M
step   500  loss 0.0655    273s
trained 500 steps in 275s

Then 1,500 more steps, resumed from those weights (the first run's tiny_unet.pt, copied to tiny_unet_500.pt) with python train.py 1500 tiny_unet_500.pt:

device=mps params=0.78M
step   500  loss 0.0264    317s
step  1000  loss 0.0231    626s
step  1500  loss 0.0215    795s
trained 1500 steps in 795s

That is 2,000 steps in total, about 4.3 passes over the training set, in 1,070 seconds, or just under 18 minutes of wall-clock time.

About 0.55 seconds per step at batch 128 is slow for a model this small. That number reflects the shared GPU, not what MPS can do on an idle machine. The resumed run starts AdamW from fresh optimizer state, which is a small shortcut; saving opt.state_dict() alongside the weights avoids it.

The sampling loop#

Sampling is Algorithm 2 from the paper. Start from x_1000 drawn from N(0, I). At each step, use the predicted noise to estimate the mean of x_{t-1}, then add fresh noise scaled by sigma_t, except at the very last step:

mean    = (x_t - beta_t / sqrt(1 - alpha_bar_t) * eps_theta(x_t, t)) / sqrt(alpha_t)
x_{t-1} = mean + sigma_t * z,    z ~ N(0, I),  z = 0 when t = 1

The paper reports similar results with sigma_t^2 = beta_t and sigma_t^2 = beta_tilde_t, the posterior variance computed in Schedule. This code uses beta_tilde:

@torch.no_grad()
def sample(model, sched, n, device, generator=None):
    """Algorithm 2 of the DDPM paper (sigma_t^2 = beta tilde)."""
    x = torch.randn(n, 1, 32, 32, device=device, generator=generator)
    for i in reversed(range(sched.T)):
        t = torch.full((n,), i, device=device, dtype=torch.long)
        eps = model(x, t)
        a, ab, b = sched.alphas[i], sched.alpha_bars[i], sched.betas[i]
        mean = (x - b / (1 - ab).sqrt() * eps) / a.sqrt()
        if i > 0:
            z = torch.randn(x.shape, device=device, generator=generator)
            x = mean + sched.posterior_var[i].sqrt() * z
        else:
            x = mean
    return x.clamp(-1, 1)

Generating 16 digits takes 1,000 forward passes of the U-Net. That took 37 seconds while the GPU was shared and 5 seconds once it was free. This cost is the main practical complaint about DDPM. DDIM keeps the same trained model and samples with far fewer steps; its authors report 10x to 50x faster wall-clock sampling.

Checking the samples#

Loss values alone say little about sample quality, because the loss averages over all noise levels. Look at the samples, and add two cheap numbers: the fraction of "ink" pixels compared with real digits, and the distance from each sample to its nearest training image. A sample that is very close to a training image suggests memorization. Samples much farther away than real digits are from each other usually means blobs.

import sys, time
import torch
from ddpm import Schedule, TinyUNet, sample
from train import load_mnist

device = "mps" if torch.backends.mps.is_available() else "cpu"
model = TinyUNet().to(device)
model.load_state_dict(torch.load(sys.argv[1], map_location=device))
model.eval()
sched = Schedule(device=device)
g = torch.Generator(device=device).manual_seed(int(sys.argv[2]) if len(sys.argv) > 2 else 1)

t0 = time.time()
x = sample(model, sched, 16, device, generator=g)
print(f"sampled 16 images x 1000 steps in {time.time()-t0:.0f}s")
torch.save(x.cpu(), sys.argv[1].replace(".pt", "_samples.pt"))

def ascii_digit(img):
    chars = " .:-=+*#%@"
    img = (img[0, 2:30, 2:30] + 1) / 2                     # crop the padding, map to [0, 1]
    img = img.reshape(14, 2, 28).mean(1)                    # halve height so it looks square in text
    return "\n".join("".join(chars[min(9, int(v * 10))] for v in row) for row in img)

for i in range(2):
    print(ascii_digit(x[i].cpu())); print("-" * 28)

# Cheap checks: ink coverage vs real digits, and distance to the nearest training image.
real = load_mnist("cpu")
gen = x.cpu()
ink = lambda t: (t > 0).float().mean().item()
print(f"ink fraction  real={ink(real[:5000]):.3f}  generated={ink(gen):.3f}")
d = torch.cdist(gen.flatten(1), real.flatten(1))          # (16, 60000) L2 distances
r = torch.cdist(real[:16].flatten(1), real[16:].flatten(1))
print(f"nearest-train L2  generated median={d.min(1).values.median():.2f}  real-vs-real median={r.min(1).values.median():.2f}")

Output after the full 2,000 steps, first two of the 16 samples:

              =-
             %@@=
             #@@#
             @@@.
             @@@.
            -@@@-
            +@@@-
            .@@@%
             %@@#
             :%@#
----------------------------
         :-=+%@@@*.
       .%@@@*.  =@@:
       :@@#    -@@#
        #@@#***@@=
         :=+=#@@+
              #@@
              -@@=
              :@@@
               @@@=
              *@@#:
              .::
----------------------------
ink fraction  real=0.101  generated=0.102
nearest-train L2  generated median=11.60  real-vs-real median=8.25

The first sample is a clean, slightly slanted 1. The second is a readable 9 with a closed loop and a long tail. Viewed as a 4x4 image grid, about half of the 16 are clearly readable (two 1s, a 7, an 8 and several 9s). The rest have clean, digit-like strokes that do not settle into a digit: a 3 that never closes, a 4 with a bent arm, a hook that could be a 2 or a 7. That is a fair result for a 0.78M-parameter model after four passes over the data, and more training steps would be the first thing to try. The ink fraction matches real data. The median distance to the nearest training image (11.60) is larger than the distance between two real digits (8.25), so these samples are new images rather than copies of training digits, though the gap also says they are not yet as clean as real ones.

A stronger check is to train a small MNIST classifier and measure how confidently it labels the samples and whether all ten digits show up. FID is the standard metric at scale, but it needs thousands of samples to be stable, which was out of scope for this run.

Failure modes#

These are the problems you are most likely to hit, roughly in the order you will hit them.

Symptom Likely cause Fix
Crash at the end of epoch 1 t drawn with a fixed batch size, last batch is smaller Use x0.shape[0]
DataLoader crash on macOS Worker processes spawn and re-import the script Add a __main__ guard or use num_workers=0
Samples are flat grey Data left in [0, 1] while noise is N(0, 1), or no clamp before display Scale to [-1, 1], clamp, map back with (x + 1) / 2
Samples are pure static Sampling loop uses wrong coefficients, or t indexing is off by one Compare one step against the equations; check that t runs 999 down to 0
Loss drops fast, samples are blobs Undertrained; the loss is dominated by easy high-noise steps Train longer; the loss value moves little while samples keep improving
Good in training, bad after model.eval() BatchNorm statistics Use GroupNorm
Training is very slow per epoch Model far too large for the data Start with a sub-1M-parameter U-Net for MNIST
Images too uniformly mid-grey at scale Terminal SNR is not zero Rescale the schedule (Lin et al.)
Sampling takes too long 1,000 sequential network calls DDIM or a learned-variance sampler with fewer steps

The "loss drops fast" row deserves a number. In this run the loss was 0.0655 after 500 steps, and the samples at that point looked like this:

                   --...
                  .#%#**
               -+%#:
             .%@@%*
             %@#.
            :@@-
            %@@=
       .-+++@#+ :==.
       .#@*:  -*@@#.
       #@+    =@%=
       -:     .%#.

The strokes are thick and digit-like, and this one is close to a 6 with a broken loop. The ink fraction already matched real data (0.099 against 0.101), while the nearest-training-image distance was 11.96 against 8.25 for real digits. So the model had learned how much ink a digit has before it had learned clean shapes.

Where to go from here#

The same recipe scales by changing three things: a bigger U-Net with attention layers, a cosine schedule, and a faster sampler. Text-to-image systems add a text encoder and condition the U-Net on it, and latent diffusion runs the whole process in a compressed latent space instead of pixels. The training loss stays the same MSE on predicted noise.

If you want to keep the trained weights, the guide to saving PyTorch models safely covers state_dict, safetensors and a load-time test. For training on Apple Silicon without PyTorch, see the MLX fine-tuning walkthrough.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.