Looking for the lab runner…

Hands-on lab 06 of 10 · Diffusion

A diffusion model from scratch on 2-D toy data

Implement the pieces every diffusion model shares (DDPM training, DDIM sampling) and train a tiny MLP denoiser on a 2-D distribution: 8 Gaussian blobs on a ring. If everything is right, pure noise turns into points on the 8 blobs. The same maths drives DiT and Stable Diffusion; only the network (a transformer on image latents) is bigger.

Time: 60-90 minCheck: python labs/check.py 6The last step trains a model for about 5-20 s on a CPU.

The maths, step by step

T = 1000 noise levels, t = 0 .. T-1 (t = 0 is almost clean).

  1. 1
    Noise schedule (DDPM / DiT linear schedule)
    beta_t     = linspace(1e-4, 0.02, T)[t]          noise added at step t
    alpha_t    = 1 - beta_t
    abar_t     = alpha_0 * alpha_1 * ... * alpha_t   (cumulative product)

    abar_t falls from ~1 (clean) to ~4e-5 (pure noise).

  2. 2
    Forward noising in closed form, q(x_t | x_0):
    x_t = sqrt(abar_t) * x_0 + sqrt(1 - abar_t) * eps,   eps ~ N(0, I)

    No loop over t: any noise level is one line away.

  3. 3
    Training objective (epsilon prediction):
    sample x_0 from the data, t ~ Uniform{0..T-1}, eps ~ N(0, I)
    loss = || eps_theta(x_t, t) - eps ||^2   (mean squared error)

    The network learns to name the noise that was added.

  4. 4
    DDIM sampling (deterministic, sigma = 0), on a subsequence of steps,
    e.g. 50 steps: t = 999, 979, ..., 19 and then "t = -1" with abar = 1:
      eps_hat = eps_theta(x_t, t)
      x0_hat  = (x_t - sqrt(1 - abar_t) * eps_hat) / sqrt(abar_t)
      x_next  = sqrt(abar_next) * x0_hat + sqrt(1 - abar_next) * eps_hat

    Start from x_T ~ N(0, I); the last step (abar_next = 1) returns x0_hat.

Worked example from the guide (one pixel): x_0 = 0.8, eps = -1.2, t = 500:
     sqrt(abar) = 0.2789, sqrt(1 - abar) = 0.9603, x_500 = -0.9292,
     and one DDIM step to t = 250 with the true eps gives x_250 = -0.2525.

Read alongside

How to work on this page

  1. Write each function in its cell, in order. The hints open one at a time: try Hint 1 first.
  2. ▶ Run (Ctrl/⌘+Enter) defines the cell in this lab's Python process; variables persist between cells, as in a notebook. Try your functions in the scratch cell at the bottom.
  3. ✓ Run checks saves the file and runs python labs/check.py 6: each step turns from TODO to PASS. A FAIL shows what was expected.
  4. Save (Ctrl/⌘+S) writes all cells to labs/lab06_diffusion.py (the previous version is kept in labs/.backup/), so you can also continue in any editor. After ↺ Reset kernel, press ▶ Run all.

Editor keys: Tab / Shift+Tab indent and dedent by 4 spaces, Enter keeps the indentation, Shift+Enter runs the cell and moves to the next one.

Cells on this page:

0 Imports

Imports

run first

The lab file's imports. Run this cell first (or press Run all).

1 the noise schedule

linear_beta_schedule(T=1000, beta_start=0.0001, beta_end=0.02)

to write

betas [T] (float32), linearly spaced from beta_start to beta_end inclusive.

Hint 1
torch.linspace includes both end points.

alpha_bars_from_betas(betas)

to write

abar [T]: abar_t = prod_{s <= t} (1 - beta_s).

Hint 1
torch.cumprod(..., dim=0)

2 forward noising q(x_t | x_0)

q_sample(x0, t, noise, alpha_bars)

to write

x_t = sqrt(abar_t) x0 + sqrt(1 - abar_t) noise.

x0, noise: [B, ...] (any trailing shape: [B, 2] points or [B, C, H, W] images) t: [B] int64, one noise level per sample

Hint 1
alpha_bars[t] is [B]; it must broadcast against [B, ...].
Hint 2
ab = alpha_bars[t].view(-1, *([1] * (x0.dim() - 1))) -> [B, 1, ...]
Hint 3
return ab.sqrt() * x0 + (1 - ab).sqrt() * noise

3 the epsilon-prediction loss

epsilon_loss(model, x0, t, noise, alpha_bars)

to write

Scalar MSE between model(x_t, t) and the noise that produced x_t.

Hint 1
build x_t with your q_sample, run the model, compare with the noise.
Hint 2
return F.mse_loss(model(q_sample(x0, t, noise, alpha_bars), t), noise)

G Given: the denoiser network and the toy data

timestep_embedding(t, dim, max_period=10000.0)

given

Sinusoidal embedding of integer timesteps: [B] → [B, dim] (as in DiT).

Show the given code (it is already written: just run it)

class Denoiser(nn.Module)

given

eps_theta(x_t, t): a 3-hidden-layer MLP on [x_t, embed(t)]. Tiny stand-in for a DiT.

Show the given code (it is already written: just run it)

make_ring_data(n, generator=None, n_modes=8, radius=2.0, std=0.1)

given

n points [n, 2]: a mixture of n_modes Gaussians evenly spaced on a circle.

Show the given code (it is already written: just run it)

4 the training loop

train_denoiser(model, data, alpha_bars, steps=3000, batch_size=512, lr=0.002, seed=0)

to write

Train model with epsilon_loss on random minibatches of data [N, 2].

Each step: pick batch_size random rows of data, t ~ Uniform{0..T-1}, noise ~ N(0, I), loss = epsilon_loss(...), Adam update. Use a torch.Generator seeded with seed for every random draw. Returns the list of per-step losses (Python floats).

Hint 1
g = torch.Generator().manual_seed(seed); opt = torch.optim.Adam(model.parameters(), lr=lr)
Hint 2
per step: idx = torch.randint(0, len(data), (batch_size,), generator=g) t = torch.randint(0, len(alpha_bars), (batch_size,), generator=g) noise = torch.randn(batch_size, data.shape[1], generator=g)
Hint 3
loss = epsilon_loss(model, data[idx], t, noise, alpha_bars) opt.zero_grad(); loss.backward(); opt.step(); losses.append(loss.item())

5 DDIM sampling

ddim_timesteps(T, num_steps)

to write

Descending int64 timesteps with stride T // num_steps, ending at stride - 1.

ddim_timesteps(1000, 50) → [999, 979, 959, ..., 39, 19] (50 values) ddim_timesteps(1000, 4) → [999, 749, 499, 249]

Hint 1
stride = T // num_steps; the values are k * stride - 1 for k = num_steps .. 1.
Hint 2
torch.arange(num_steps, 0, -1) * stride - 1

ddim_step(x_t, eps_hat, abar_t, abar_next)

to write

One deterministic DDIM update from level abar_t to level abar_next.

abar_t, abar_next: floats or 0-dim tensors. Returns x_next (same shape as x_t).

Hint 1
two lines: estimate x0, then re-noise it to the next level using the SAME eps_hat (that is what makes DDIM deterministic).
Hint 2
abar_t = torch.as_tensor(abar_t) lets you call .sqrt() on floats too.

ddim_sample(model, x_T, alpha_bars, num_steps=50)

to write

Run DDIM from x_T [n, ...] (pure noise) to x_0.

Visit t in ddim_timesteps(T, num_steps). At each t call model(x, t_batch) with t_batch = an int64 tensor [n] filled with t; the next level is the next timestep in the list, and after the last one it is abar = 1.0 (clean).

Hint 1
ts = ddim_timesteps(len(alpha_bars), num_steps); loop with enumerate.
Hint 2
t_batch = torch.full((x.shape[0],), int(t), dtype=torch.long)
Hint 3
abar_next = alpha_bars[ts[i + 1]] if i + 1 < len(ts) else 1.0 x = ddim_step(x, model(x, t_batch), alpha_bars[t], abar_next)

✎ Scratch cell

Experiment here: print shapes, call your functions on small inputs. This cell runs in the same Python process as the cells above, is not part of Run all and is not saved to the lab file (your browser keeps it).