Lecture 25 – CS 189, Fall 2026¶

In [ ]:
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import seaborn as sns
from sklearn.datasets import make_swiss_roll, make_moons


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

torch.manual_seed(189)
np.random.seed(189)

# The 2D models in this demo are tiny, so we keep everything on the CPU
device = torch.device('cpu')
print(f'Using device: {device}')

A 2D Dataset¶

The 2015 diffusion paper (Sohl-Dickstein et al.) tested its idea on a 2D swiss roll. Every point is a "clean image" $x_0$ with 2 pixels.

In [ ]:
# 2D swiss roll: keep the (x, z) coordinates and scale to roughly [-1, 1]
X, _ = make_swiss_roll(n_samples=10000, noise=0.3)
X = X[:, [0, 2]] / 10.0
x0_data = torch.tensor(X, dtype=torch.float32)

plt.figure(figsize=(4, 4))
plt.scatter(X[:, 0], X[:, 1], s=1, alpha=0.5)
plt.title('Training data $x_0$')
plt.axis('equal')
plt.show()

Forward Process: Destroy the Data with Noise¶

$x_t = \sqrt{\bar\alpha_t}\,x_0 + \sqrt{1-\bar\alpha_t}\,\epsilon$, with $\epsilon \sim \mathcal{N}(0, I)$

In [ ]:
T = 100                                     # number of diffusion steps
betas = torch.linspace(1e-4, 0.1, T)        # noise added at each step
alphas = 1.0 - betas
alphas_bar = torch.cumprod(alphas, dim=0)   # how much of x_0 survives at step t

print(f'Signal left at t=1:   {alphas_bar[0].sqrt():.3f}')
print(f'Signal left at t={T}: {alphas_bar[-1].sqrt():.3f}')
In [4]:
def add_noise(x0, t):
    """Jump straight to step t in one shot (no loop needed)."""
    eps = torch.randn_like(x0)
    ab = alphas_bar[t].unsqueeze(-1)
    return ab.sqrt() * x0 + (1 - ab).sqrt() * eps, eps
In [ ]:
steps = [0, 10, 25, 50, 99]
fig, axes = plt.subplots(1, len(steps), figsize=(15, 3))
for ax, t in zip(axes, steps):
    xt, _ = add_noise(x0_data, torch.full((len(x0_data),), t))
    ax.scatter(xt[:, 0], xt[:, 1], s=1, alpha=0.5)
    ax.set_title(f't = {t + 1}')
    ax.set_xlim(-3, 3); ax.set_ylim(-3, 3)
    ax.set_xticks([]); ax.set_yticks([])
plt.tight_layout()
plt.show()

The Denoising Network¶

Input: noisy point $x_t$ and the step $t$. Output: a guess of the noise $\epsilon$ that was added.

In [6]:
def time_embedding(t, dim=16):
    """Sinusoidal encoding of the step t (same idea as transformer positions)."""
    freqs = torch.exp(torch.linspace(0, np.log(1000), dim // 2))
    angles = t.float().unsqueeze(-1) / T * freqs
    return torch.cat([angles.sin(), angles.cos()], dim=-1)
In [ ]:
class NoisePredictor(nn.Module):
    def __init__(self, hidden=128, t_dim=16):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(2 + t_dim, hidden), nn.SiLU(),
            nn.Linear(hidden, hidden), nn.SiLU(),
            nn.Linear(hidden, hidden), nn.SiLU(),
            nn.Linear(hidden, hidden), nn.SiLU(),
            nn.Linear(hidden, 2),
        )

    def forward(self, xt, t):
        return self.net(torch.cat([xt, time_embedding(t)], dim=-1))

model = NoisePredictor().to(device)
print(f'Parameters: {sum(p.numel() for p in model.parameters()):,}')

Training (Algorithm 1)¶

Pick a clean point, pick a random step $t$, add noise, ask the network to predict that noise.

In [8]:
def train(model, data, n_steps=6000, batch_size=512, lr=3e-3):
    opt = optim.Adam(model.parameters(), lr=lr)
    sched = optim.lr_scheduler.CosineAnnealingLR(opt, n_steps)
    losses = []
    for step in range(n_steps):
        x0 = data[torch.randint(len(data), (batch_size,))]  # x_0 ~ q(x_0)
        t = torch.randint(0, T, (batch_size,))                # t ~ Uniform
        xt, eps = add_noise(x0, t)                            # eps ~ N(0, I)
        loss = ((model(xt, t) - eps) ** 2).mean()             # || eps - eps_theta ||^2
        opt.zero_grad(); loss.backward(); opt.step(); sched.step()
        losses.append(loss.item())
    return losses
In [ ]:
losses = train(model, x0_data)

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()

Sampling (Algorithm 2)¶

Start from pure noise and take $T$ small denoising steps. At each step, remove a little noise and add a little back.

From lecture: Reverse diffusion sampling algorithm from the lecture

What's in code is the same equivalent. Equivalent reverse diffusion update used in the code

In [10]:
@torch.no_grad()
def sample(model, n=2000, add_back_noise=True, keep=()):
    x = torch.randn(n, 2)                                    # x_T ~ N(0, I)
    snapshots = {}
    for t in reversed(range(T)):
        tt = torch.full((n,), t)
        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:
            snapshots[t] = x.clone()
    return x, snapshots
In [ ]:
samples, snaps = sample(model, keep=(99, 75, 50, 25, 0))

fig, axes = plt.subplots(1, 5, figsize=(15, 3))
for ax, t in zip(axes, [99, 75, 50, 25, 0]):
    ax.scatter(snaps[t][:, 0], snaps[t][:, 1], s=1, alpha=0.5, color='C2')
    ax.set_title(f't = {t + 1}')
    ax.set_xlim(-3, 3); ax.set_ylim(-3, 3)
    ax.set_xticks([]); ax.set_yticks([])
plt.tight_layout()
plt.show()

Failure 1: Why Not Denoise in One Big Step?¶

From pure noise, use the network's noise estimate to jump straight to $\hat{x}_0$.

In [ ]:
@torch.no_grad()
def one_step(model, n=2000):
    xT = torch.randn(n, 2)
    t = torch.full((n,), T - 1)
    ab = alphas_bar[-1]
    return (xT - (1 - ab).sqrt() * model(xT, t)) / ab.sqrt()

x_one = one_step(model)

fig, axes = plt.subplots(1, 2, figsize=(8, 4))
axes[0].scatter(x_one[:, 0], x_one[:, 1], s=1, alpha=0.5, color='C1')
axes[0].set_title('One big step')
axes[1].scatter(samples[:, 0], samples[:, 1], s=1, alpha=0.5, color='C2')
axes[1].set_title(f'{T} small steps')
for ax in axes:
    ax.set_xlim(-3, 3); ax.set_ylim(-3, 3)
plt.tight_layout()
plt.show()
In [ ]:
print(f'Data spread (std):         {x0_data.std(0).mean():.2f}')
print(f'One-step samples (std):    {x_one.std(0).mean():.2f}')
print(f'{T}-step samples (std):     {samples.std(0).mean():.2f}')

Failure 2: Remove the "Add Noise Back" Line¶

Same model, same steps, but skip $+\,\sigma_t z$.

In [ ]:
samples_no_noise, _ = sample(model, add_back_noise=False)

fig, axes = plt.subplots(1, 2, figsize=(8, 4))
axes[0].scatter(samples_no_noise[:, 0], samples_no_noise[:, 1], s=1, alpha=0.5, color='C1')
axes[0].set_title('Without $\\sigma_t z$')
axes[1].scatter(samples[:, 0], samples[:, 1], s=1, alpha=0.5, color='C2')
axes[1].set_title('With $\\sigma_t z$')
for ax in axes:
    ax.set_xlim(-3, 3); ax.set_ylim(-3, 3)
plt.tight_layout()
plt.show()
In [ ]:
print(f'Without sigma_t z (std): {samples_no_noise.std(0).mean():.2f}')
print(f'With sigma_t z (std):    {samples.std(0).mean():.2f}')

Conditioning and Classifier-Free Guidance¶

Two moons, two classes. One network learns both $\epsilon_C$ (given the class) and $\epsilon_U$ (class replaced by a "null" token).

In [ ]:
Xm, ym = make_moons(n_samples=10000, noise=0.06)
Xm = (Xm - Xm.mean(0)) / 1.2
xm_data = torch.tensor(Xm, dtype=torch.float32)
ym_data = torch.tensor(ym)

plt.figure(figsize=(4, 4))
plt.scatter(Xm[:, 0], Xm[:, 1], c=ym, s=1, cmap='coolwarm')
plt.title('Class 0 (blue), class 1 (red)')
plt.axis('equal')
plt.show()
In [17]:
NULL = 2  # the "empty prompt" token

class CondNoisePredictor(NoisePredictor):
    def __init__(self, hidden=128, t_dim=16, n_classes=3, c_dim=8):
        super().__init__(hidden, t_dim)
        self.label_emb = nn.Embedding(n_classes, c_dim)
        self.net[0] = nn.Linear(2 + t_dim + c_dim, hidden)

    def forward(self, xt, t, y):
        h = torch.cat([xt, time_embedding(t), self.label_emb(y)], dim=-1)
        return self.net(h)
In [18]:
def train_cfg(model, data, labels, n_steps=6000, batch_size=512, p_drop=0.2):
    opt = optim.Adam(model.parameters(), lr=3e-3)
    sched = optim.lr_scheduler.CosineAnnealingLR(opt, n_steps)
    for step in range(n_steps):
        idx = torch.randint(len(data), (batch_size,))
        x0, y = data[idx], labels[idx].clone()
        y[torch.rand(batch_size) < p_drop] = NULL      # sometimes hide the label
        t = torch.randint(0, T, (batch_size,))
        xt, eps = add_noise(x0, t)
        loss = ((model(xt, t, y) - eps) ** 2).mean()
        opt.zero_grad(); loss.backward(); opt.step(); sched.step()
    return model

cond_model = train_cfg(CondNoisePredictor(), xm_data, ym_data)
In [19]:
@torch.no_grad()
def sample_cfg(model, y, gamma, n=2000):
    x = torch.randn(n, 2)
    yc = torch.full((n,), y)
    yu = torch.full((n,), NULL)
    for t in reversed(range(T)):
        tt = torch.full((n,), t)
        eps_c, eps_u = model(x, tt, yc), model(x, tt, yu)
        eps_hat = eps_u + gamma * (eps_c - eps_u)       # classifier-free guidance
        x = (x - betas[t] / (1 - alphas_bar[t]).sqrt() * eps_hat) / alphas[t].sqrt()
        if t > 0:
            x = x + betas[t].sqrt() * torch.randn_like(x)
    return x
In [ ]:
gammas = [0, 1, 3, 7]
fig, axes = plt.subplots(1, len(gammas), figsize=(16, 4))
for ax, g in zip(axes, gammas):
    xs = sample_cfg(cond_model, y=0, gamma=g)
    ax.scatter(Xm[:, 0], Xm[:, 1], s=1, color='lightgray')
    ax.scatter(xs[:, 0], xs[:, 1], s=1, alpha=0.5, color='C0')
    ax.set_title(f'Asking for class 0, $\\gamma$ = {g}')
    ax.set_xlim(-2.2, 2.2); ax.set_ylim(-1.6, 1.6)
plt.tight_layout()
plt.show()
In [ ]:
# Fraction of samples that land on the class-0 moon (nearest training point is class 0)
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5).fit(Xm, ym)
for g in gammas:
    xs = sample_cfg(cond_model, y=0, gamma=g).numpy()
    on_class0 = (knn.predict(xs) == 0).mean()
    print(f'gamma = {g}: {on_class0:.0%} on class 0, spread (std) = {xs.std(0).mean():.2f}')