Diffusion on MNIST: Denoising Real Images¶

Same recipe as the 2D demo, with a small U-Net in place of the MLP. Run it on a GPU. To skip training in class, run the notebook beforehand and load the saved weights.

In [1]:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision as tv
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import seaborn as sns
import time


style.use('fivethirtyeight')
sns.set(style='whitegrid', color_codes=True)

torch.manual_seed(189)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'Using device: {device}')
Using device: cpu
In [2]:
# Pixels scaled to [-1, 1], so pure noise and images live on the same scale
mnist_tf = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
mnist = tv.datasets.MNIST(root='./data', train=True, download=True, transform=mnist_tf)
X_train = (mnist.data.float() / 255 * 2 - 1).unsqueeze(1).to(device)   # all 60k images on the device at once
print(f'Training images: {tuple(X_train.shape)}')

def show_grid(imgs, nrow, title=None, size=1.2):
    imgs = (imgs.detach().cpu().clamp(-1, 1) + 1) / 2
    grid = tv.utils.make_grid(imgs, nrow=nrow, padding=2, pad_value=1)
    plt.figure(figsize=(size * nrow, size * (len(imgs) + nrow - 1) // nrow))
    plt.imshow(grid.permute(1, 2, 0)); plt.axis('off')
    if title: plt.title(title)
    plt.show()
100%|██████████| 9.91M/9.91M [01:16<00:00, 129kB/s] 
100%|██████████| 28.9k/28.9k [00:00<00:00, 312kB/s]
100%|██████████| 1.65M/1.65M [00:15<00:00, 105kB/s] 
100%|██████████| 4.54k/4.54k [00:00<00:00, 1.97MB/s]
Training images: (60000, 1, 28, 28)

Noise Schedule and Forward Process¶

$x_t = \sqrt{\bar\alpha_t}\,x_0 + \sqrt{1-\bar\alpha_t}\,\epsilon$, exactly as in the 2D demo.

In [3]:
T = 200
betas = torch.linspace(1e-4, 0.05, T, device=device)
alphas = 1.0 - betas
alphas_bar = torch.cumprod(alphas, dim=0)
print(f'Signal left at t={T}: {alphas_bar[-1].sqrt():.3f}')

def add_noise(x0, t):
    eps = torch.randn_like(x0)
    ab = alphas_bar[t].view(-1, 1, 1, 1)
    return ab.sqrt() * x0 + (1 - ab).sqrt() * eps, eps
Signal left at t=200: 0.078
In [4]:
x0 = X_train[:6]
steps = [0, 10, 25, 50, 100, 150, 199]
rows = [add_noise(x0, torch.full((6,), s, device=device))[0] for s in steps]
show_grid(torch.stack(rows, dim=1).flatten(0, 1), nrow=len(steps),
          title='Forward process: t = ' + ', '.join(str(s + 1) for s in steps))
Six MNIST digits become progressively noisier over the forward diffusion steps

A Small U-Net¶

Image in, noise estimate out (same shape). The timestep $t$ is added to every block.

In [5]:
def time_embedding(t, dim=64):
    freqs = torch.exp(torch.linspace(0, np.log(1000), dim // 2, device=t.device))
    angles = t.float().unsqueeze(-1) / T * freqs
    return torch.cat([angles.sin(), angles.cos()], dim=-1)

class Block(nn.Module):
    def __init__(self, c_in, c_out, t_dim=64):
        super().__init__()
        self.conv1 = nn.Conv2d(c_in, c_out, 3, padding=1)
        self.conv2 = nn.Conv2d(c_out, c_out, 3, padding=1)
        self.norm1, self.norm2 = nn.GroupNorm(8, c_out), nn.GroupNorm(8, c_out)
        self.t_proj = nn.Linear(t_dim, c_out)

    def forward(self, x, t_emb):
        h = F.silu(self.norm1(self.conv1(x)))
        h = h + self.t_proj(t_emb)[:, :, None, None]   # tell every pixel how noisy the input is
        return F.silu(self.norm2(self.conv2(h)))
In [6]:
class UNet(nn.Module):
    def __init__(self, c=32):
        super().__init__()
        self.t_mlp = nn.Sequential(nn.Linear(64, 64), nn.SiLU(), nn.Linear(64, 64))
        self.down1, self.down2 = Block(1, c), Block(c, 2 * c)          # 28x28, 14x14
        self.mid = Block(2 * c, 2 * c)                                  # 7x7
        self.up2, self.up1 = Block(4 * c, c), Block(2 * c, c)          # concat skip connections
        self.out = nn.Conv2d(c, 1, 1)

    def forward(self, x, t):
        te = self.t_mlp(time_embedding(t))
        h1 = self.down1(x, te)
        h2 = self.down2(F.avg_pool2d(h1, 2), te)
        m = self.mid(F.avg_pool2d(h2, 2), te)
        u2 = self.up2(torch.cat([F.interpolate(m, scale_factor=2), h2], dim=1), te)
        u1 = self.up1(torch.cat([F.interpolate(u2, scale_factor=2), h1], dim=1), te)
        return self.out(u1)

unet = UNet().to(device)
print(f'Parameters: {sum(p.numel() for p in unet.parameters()):,}')
Parameters: 236,513

Training (Algorithm 1)¶

The loop is the same as the 2D demo: pick images, pick random steps, add noise, predict the noise.

In [7]:
EPOCHS = 10
BATCH = 128
steps_per_epoch = len(X_train) // BATCH
opt = optim.Adam(unet.parameters(), lr=2e-3)
sched = optim.lr_scheduler.OneCycleLR(opt, max_lr=2e-3, total_steps=EPOCHS * steps_per_epoch)
losses, start = [], time.time()
for epoch in range(EPOCHS):
    unet.train()
    perm = torch.randperm(len(X_train), device=device)
    for i in range(steps_per_epoch):
        x0 = X_train[perm[i * BATCH:(i + 1) * BATCH]]
        t = torch.randint(0, T, (len(x0),), device=device)
        xt, eps = add_noise(x0, t)
        loss = F.mse_loss(unet(xt, t), eps)
        opt.zero_grad(); loss.backward(); opt.step(); sched.step()
        losses.append(loss.item())
    print(f'Epoch {epoch + 1}: loss {np.mean(losses[-steps_per_epoch:]):.4f} ({time.time() - start:.0f}s)')
Epoch 1: loss 0.1607 (145s)
Epoch 2: loss 0.0526 (283s)
Epoch 3: loss 0.0446 (424s)
Epoch 4: loss 0.0411 (563s)
Epoch 5: loss 0.0384 (700s)
Epoch 6: loss 0.0369 (838s)
Epoch 7: loss 0.0358 (978s)
Epoch 8: loss 0.0349 (1116s)
Epoch 9: loss 0.0342 (1253s)
Epoch 10: loss 0.0339 (1397s)
In [8]:
# Optional: save the trained model so class can skip training (load it with the next cell)
torch.save(unet.state_dict(), 'mnist_unet.pt')
In [14]:
# unet.load_state_dict(torch.load('data/mnist_unet.pt', map_location=device))
Out[14]:
<All keys matched successfully>
In [9]:
plt.figure(figsize=(8, 3))
plt.plot(np.convolve(losses, np.ones(50) / 50, mode='valid'))
plt.xlabel('Training step'); plt.ylabel('MSE on the noise'); plt.title('Training History')
plt.show()
Moving average of noise prediction mean squared error over training steps

What the Network Sees at Each Step¶

Top: a noisy test digit $x_t$. Bottom: the network's one-shot guess of the clean image, $\hat x_0 = (x_t - \sqrt{1-\bar\alpha_t}\,\epsilon_\theta)/\sqrt{\bar\alpha_t}$.

In [10]:
@torch.no_grad()
def predict_x0(model, xt, t):
    ab = alphas_bar[t].view(-1, 1, 1, 1)
    return (xt - (1 - ab).sqrt() * model(xt, t)) / ab.sqrt()

unet.eval()
x0 = X_train[7:8].repeat(len(steps), 1, 1, 1)
tt = torch.tensor(steps, device=device)
xt, _ = add_noise(x0, tt)
show_grid(torch.cat([xt, predict_x0(unet, xt, tt)]), nrow=len(steps),
          title='Noisy input (top) and one-shot guess of x0 (bottom)')
Noisy inputs in the top row and single-step predictions of the clean digit in the bottom row

Sampling (Algorithm 2): Watch Images Appear¶

Each row is one sample; columns go from pure noise (left) to the final image (right).

In [11]:
@torch.no_grad()
def sample(model, n=8, keep=(199, 150, 100, 60, 30, 10, 0), add_back_noise=True):
    model.eval()
    x = torch.randn(n, 1, 28, 28, device=device)                 # x_T ~ N(0, I)
    snaps = []
    for t in reversed(range(T)):
        tt = torch.full((n,), t, device=device)
        eps_hat = model(x, tt)
        x = (x - betas[t] / (1 - alphas_bar[t]).sqrt() * eps_hat) / alphas[t].sqrt()
        if t > 0 and add_back_noise:
            x = x + betas[t].sqrt() * torch.randn_like(x)        # + sigma_t z
        if t in keep:
            snaps.append(x.clone())
    return x, torch.stack(snaps, dim=1)                          # (n, len(keep), 1, 28, 28)

torch.manual_seed(0)
final, traj = sample(unet)
show_grid(traj.flatten(0, 1), nrow=traj.shape[1], title='Reverse process: noise to digit')
Eight reverse diffusion trajectories from random noise to generated digits
In [12]:
torch.manual_seed(1)
samples, _ = sample(unet, n=64)
show_grid(samples, nrow=16, title='64 samples from 64 different noise images', size=0.8)
A grid of 64 generated MNIST digits, each sampled from independent starting noise

Same Failure as the 2D Demo: Drop $\sigma_t z$¶

In [13]:
torch.manual_seed(1)
no_noise, _ = sample(unet, n=32, add_back_noise=False)
show_grid(torch.cat([samples[:16], no_noise[:16]]), nrow=16,
          title='Top: with sigma_t z.  Bottom: without (same starting noise)', size=0.8)
Paired samples with reverse-step noise in the top row and without it in the bottom row, using the same starting noise