Imports
run firstThe lab file's imports. Run this cell first (or press Run all).
Hands-on lab 06 of 10 · Diffusion
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.
T = 1000 noise levels, t = 0 .. T-1 (t = 0 is almost clean).
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).
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.
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.
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.
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:
The lab file's imports. Run this cell first (or press Run all).
linear_beta_schedule(T=1000, beta_start=0.0001, beta_end=0.02)betas [T] (float32), linearly spaced from beta_start to beta_end inclusive.
alpha_bars_from_betas(betas)abar [T]: abar_t = prod_{s <= t} (1 - beta_s).
q(x_t | x_0)q_sample(x0, t, noise, alpha_bars)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
epsilon_loss(model, x0, t, noise, alpha_bars)Scalar MSE between model(x_t, t) and the noise that produced x_t.
timestep_embedding(t, dim, max_period=10000.0)Sinusoidal embedding of integer timesteps: [B] → [B, dim] (as in DiT).
class Denoiser(nn.Module)eps_theta(x_t, t): a 3-hidden-layer MLP on [x_t, embed(t)]. Tiny stand-in for a DiT.
make_ring_data(n, generator=None, n_modes=8, radius=2.0, std=0.1)n points [n, 2]: a mixture of n_modes Gaussians evenly spaced on a circle.
train_denoiser(model, data, alpha_bars, steps=3000, batch_size=512, lr=0.002, seed=0)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).
ddim_timesteps(T, num_steps)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]
ddim_step(x_t, eps_hat, abar_t, abar_next)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).
ddim_sample(model, x_T, alpha_bars, num_steps=50)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).
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).