Session S25
VAEs train stably but blur; GANs are sharp but unstable. Diffusion adds noise to data step by step and trains a network to remove it. What does the noising do to the data, what must its schedule get right, what does the network learn and why does it train stably, how do we judge what it generates, and how is sampling made faster, steerable and practical for images?
Deep Learning · CS 4715/5715 · University of Idaho
No class next week (Fall Recess).
Before the material, the course calendar around the break.
Two generative families so far, each with one strength and one weakness:
| how it trains | its samples | per sample | |
|---|---|---|---|
| VAE (S23) | maximizes a likelihood bound: stable | blurry | one decoder pass |
| GAN (S24) | a generator against a discriminator, a game: unstable | sharp; can collapse onto a few modes | one forward pass |
Today, as S24 announced: diffusion, trained with a plain regression loss and no game. Its weakness is slow sampling.
Five parts, each answering one clause of the title page's question; a sixth closes.
| part | the question it answers |
|---|---|
| 1 · Forward process | What does the noising do to the data? One noising step, then a formula that jumps to any step; both are checked on two moons. |
| 2 · The schedule | What must its schedule get right? With too few steps the noising stops short of pure noise; we find the cause and repair it. |
| 3 · Reverse process | What does the network learn, and why is training stable? It predicts the noise; sampling runs its step backwards. |
| 4 · A tiny model | How do we judge what it generates? We train a small model, sample from it, and compare its samples with the data in a table. |
| 5 · Faster, steered, at scale | How is sampling made faster, steerable and practical? A sampler that needs fewer steps, a label that steers the samples, and a latent space for images. |
| 6 · Close | The three families compared, six common mistakes, and today's answer. |
Parts 1, 3 and 4 each end on a self-check. First, the forward process.
Part 1 · The forward process. The idea in one figure (reading 4.3):
Part 1 is the forward half: fixed, with nothing to train.
(4000, 2) for today's 4,000 points in 2-D; \(\boldsymbol{\varepsilon}_t\sim\mathcal{N}(\mathbf{0},\mathbf{I})\) is a fresh draw of the same shape. Both operations are elementwise.The step multiplies \(\mathbf{x}_{t-1}\) by \(\sqrt{1-\beta_t}\) before it adds the noise. The reason is the variance of each coordinate:
One step barely changes \(\mathbf{x}\), and the variance of each coordinate stays 1.
Substitute one step into the next; two independent Gaussian noises sum to one Gaussian:
Two steps have the form of one step, with the product \(\alpha_t\alpha_{t-1}\) in place of \(\alpha_t\).
The previous page merged two steps into \(\mathbf{x}_t=\sqrt{\alpha_t\alpha_{t-1}}\,\mathbf{x}_{t-2}+\sqrt{1-\alpha_t\alpha_{t-1}}\;\boldsymbol{\varepsilon}\), one step of the same form.
Jump straight from \(\mathbf{x}_0\) to any \(\mathbf{x}_t\), without simulating the steps in between.
\(\sqrt{\bar\alpha_t}\) scales the signal and \(\sqrt{1-\bar\alpha_t}\) the noise; \(\bar\alpha_t\) falls from near 1 toward 0 as \(t\) grows.
Whether the noising finishes is worth seeing in numbers, not trusting.
Reading 4.3's toy data, used for the rest of today:
import torch
torch.manual_seed(0)
# Two-moons data, generated in-code and standardized
def two_moons(n):
t = torch.rand(n) * torch.pi
outer = torch.stack([torch.cos(t[: n // 2]), torch.sin(t[: n // 2])], dim=1)
inner = torch.stack([1 - torch.cos(t[n // 2 :]), 0.5 - torch.sin(t[n // 2 :])], dim=1)
x = torch.cat([outer, inner]) + 0.05 * torch.randn(n, 2)
return (x - x.mean(0)) / x.std(0)
x0 = two_moons(4000)
x0 is (4000, 2): rows 0–1999 are the outer moon (blue in every panel today), rows 2000–3999 the inner moon (orange). The figure draws every 16th point.x.mean(0) and x.std(0) run over the 4,000 rows, so each coordinate is standardized to mean 0 and standard deviation 1: the previous page's unit-variance case.two_moons, t is an angle along each half circle, not a diffusion step.To see whether the noising finishes, a script forms \(\mathbf{x}_t\) with the closed form at chosen steps and prints three statistics:
def report(T, beta_max, ts):
betas = torch.linspace(1e-4, beta_max, T) # T evenly spaced values: beta_1 .. beta_T
alpha_bar = torch.cumprod(1 - betas, dim=0) # running product: every alpha-bar_t
print(f"T = {T}, betas 1e-4 .. {beta_max}")
print(f"{'t':>4} {'sqrt(a_bar)':>12} {'std(x_t)':>9} {'corr(x_t, x0)':>14}")
for t in ts:
eps = torch.randn_like(x0)
xt = alpha_bar[t].sqrt() * x0 + (1 - alpha_bar[t]).sqrt() * eps
corr = torch.corrcoef(torch.stack([xt[:, 0], x0[:, 0]]))[0, 1] # correlation, first coordinates
print(f"{t:>4} {alpha_bar[t].sqrt().item():>12.4f} "
f"{xt.std().item():>9.4f} {corr.item():>14.4f}")
# The DDPM paper's schedule: T=1000, betas from 1e-4 to 0.02
report(1000, 0.02, [0, 249, 499, 749, 999])
alpha_bar[t] is one number, so xt is (4000, 2), like x0. Code counts steps from 0: alpha_bar[T - 1] is \(\bar\alpha_T\).Predict: at the last index, t = 999, about what are sqrt(a_bar) and corr(x_t, x0)?
The printed table, one panel per row: the points \(\mathbf{x}_t\) the script computed, and the row's numbers.
corr(x_t, x0), how much of the data is left, is −0.0082 at t = 999: statistically zero, so \(\mathbf{x}_T\) is pure noise. For unit-variance data it equals \(\sqrt{\bar\alpha_t}\) up to sampling error, so the sqrt(a_bar) and corr rows nearly agree. std(x_t), the scale, stays near 1.0.Under DDPM's schedule the noising finishes: \(\mathbf{x}_T\) is pure noise.
Three questions on Part 1.
(a) With \(\bar\alpha_t=0.64\), write the closed form for \(\mathbf{x}_t\) with its two numbers. What is the standard deviation of \(\mathbf{x}_t\) for unit-variance data?
(b) Part 3's training will need \(\mathbf{x}_t\) at a randomly chosen step \(t\) for every example. Why not get it by running the forward steps one at a time?
(c) In the \(T=1000\) table, what do corr falling to about 0 and std(x_t) staying near 1 each show?
(a) \(\mathbf{x}_t=0.8\,\mathbf{x}_0+0.6\,\boldsymbol{\varepsilon}\), from \(\sqrt{0.64}\) and \(\sqrt{0.36}\); \(0.64+0.36=1\), so the standard deviation is 1.
(b) The closed form gives any \(\mathbf{x}_t\) in one draw; stepping there takes \(t\) steps.
(c) No data is left at the end; the overall scale is held at 1.
Any step is one draw away, and under DDPM's schedule nothing of the data survives to \(T\).
Part 2 · The schedule. Does any schedule finish the noising? Generation runs the network once per step, so fewer steps make sampling faster. Here are 200 steps instead of 1000, with \(\beta\) still from 1e-4 to 0.02, in Part 1's report:
# Same beta range but only 200 steps: noising never finishes
report(200, 0.02, [0, 99, 199])
Take logs of \(\bar\alpha_T=(1-\beta_1)(1-\beta_2)\cdots(1-\beta_T)\), and use \(\ln(1-\beta)\approx-\beta\) for small \(\beta\):
Five times fewer steps over the same \(\beta\) range leave a fifth of the area, so \(\sqrt{\bar\alpha_T}\) rises from 0.0064 to 0.3636. \(T\) and the \(\beta\) range set the endpoint together.
Keep 200 steps and raise the last \(\beta\) to 0.05, the reading's repair (Part 4 trains on it). Part 1's report checks it:
# 200 steps with beta_max rescaled: noising completes again
report(200, 0.05, [0, 99, 199])
\(T\) and the \(\beta\) range are one design decision, not two. A schedule fails silently; only the statistics of \(\mathbf{x}_T\) show whether the noising finishes, so print them whenever either changes.
Part 3 · The reverse process. What does the network learn? Generation runs the noising backwards, and undoing a step needs the noise that was added. So DDPM's network \(\boldsymbol{\varepsilon}_\theta(\mathbf{x}_t,t)\) looks at \(\mathbf{x}_t\) and \(t\) and estimates the noise \(\boldsymbol{\varepsilon}\) that was mixed in:
\[L=\mathbb{E}_{t,\mathbf{x}_0,\boldsymbol{\varepsilon}}\big[\lVert\boldsymbol{\varepsilon}-\boldsymbol{\varepsilon}_\theta(\mathbf{x}_t,t)\rVert^2\big],\qquad \mathbf{x}_t=\sqrt{\bar\alpha_t}\,\mathbf{x}_0+\sqrt{1-\bar\alpha_t}\,\boldsymbol{\varepsilon}\]The target is noise we drew ourselves, so every example comes with its answer.
S24's discriminator changed as the generator trained. Here nothing changes but the network's parameters \(\theta\):
| GAN (S24) | diffusion | |
|---|---|---|
| what the network is trained toward | a discriminator that is itself training | noise we drew, which training does not change |
| the loss | a two-player game | mean squared error |
| one minibatch | one move in the game | a fresh supervised problem with known answers |
Stable, because it is regression onto a target that training does not change.
Given \(\mathbf{x}_t\), either target determines the other: solve the closed form for \(\mathbf{x}_0\), with the predicted noise \(\hat{\boldsymbol{\varepsilon}}=\boldsymbol{\varepsilon}_\theta(\mathbf{x}_t,t)\) in place of \(\boldsymbol{\varepsilon}\):
\[\hat{\mathbf{x}}_0=\frac{\mathbf{x}_t-\sqrt{1-\bar\alpha_t}\;\hat{\boldsymbol{\varepsilon}}}{\sqrt{\bar\alpha_t}}\]Both targets carry the same information; the noise target has the same scale at every step, and the next page shows how the two weight the steps.
The second difference between the targets is the weighting. Subtract the closed form, solved for \(\mathbf{x}_0\) with the true \(\boldsymbol{\varepsilon}\), from the previous page's \(\hat{\mathbf{x}}_0\), and square:
t = 0 and about 160 at t = 199 (the curve). So an \(\mathbf{x}_0\) loss counts the last steps about 160 times more than the noise loss does, and the first steps almost not at all.Choosing the noise target is a choice of weighting: every step counts equally.
The training loss averages over every \(t\), and at some steps the noise cannot be told apart from the data:
The loss has a floor above zero; a flat loss means converged.
Part 3, continued · Sampling. Training is done; the trained network now generates a sample. Start from \(\mathbf{x}_T\sim\mathcal{N}(\mathbf{0},\mathbf{I})\). With \(\alpha_t=1-\beta_t\) and \(\hat{\boldsymbol{\varepsilon}}=\boldsymbol{\varepsilon}_\theta(\mathbf{x}_t,t)\), each step is:
\[\mathbf{x}_{t-1}=\frac{1}{\sqrt{\alpha_t}}\Big(\mathbf{x}_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\hat{\boldsymbol{\varepsilon}}\Big)+\sqrt{\beta_t}\;\mathbf{z},\qquad \mathbf{z}\sim\mathcal{N}(\mathbf{0},\mathbf{I})\]The network estimates all the noise in \(\mathbf{x}_t\), but one sampling step should remove only what step \(t\) added. How much is that? \(\boldsymbol{\varepsilon}_t\) is step \(t\)'s own fresh noise; \(\boldsymbol{\varepsilon}\) is the closed form's total noise, which \(\hat{\boldsymbol{\varepsilon}}\) estimates.
Put the share from the previous page, \(\sqrt{\beta_t}\,\boldsymbol{\varepsilon}_t\approx(\beta_t/\sqrt{1-\bar\alpha_t})\,\hat{\boldsymbol{\varepsilon}}\) on average, into the undone step \(\mathbf{x}_{t-1}=(\mathbf{x}_t-\sqrt{\beta_t}\,\boldsymbol{\varepsilon}_t)/\sqrt{\alpha_t}\):
\[\mathbb{E}[\mathbf{x}_{t-1}\mid\mathbf{x}_t]\approx\frac{1}{\sqrt{\alpha_t}}\Big(\mathbf{x}_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\hat{\boldsymbol{\varepsilon}}\Big)\]Check: at \(t=1\), \(\bar\alpha_1=\alpha_1\). What share of the noise is step 1's, and what does the step return?
All of it: \(\beta_1/(1-\alpha_1)=1\). The step returns \((\mathbf{x}_1-\sqrt{\beta_1}\,\hat{\boldsymbol{\varepsilon}})/\sqrt{\alpha_1}\), Part 3's \(\hat{\mathbf{x}}_0\) at \(t=1\).
Each sampling step subtracts the average share of the noise that step \(t\) added, then adds fresh noise around that mean.
Two questions on Part 3.
(a) For a minibatch of 256 points in 2-D, what are the shapes of t, eps, xt and the network's output? Is the loss a vector?
(b) The loss is the mean of \((\hat{\boldsymbol{\varepsilon}}-\boldsymbol{\varepsilon})^2\), where \(\boldsymbol{\varepsilon}\) is drawn from \(\mathcal{N}(\mathbf{0},\mathbf{I})\). Suppose a network ignores its input and predicts \(\hat{\boldsymbol{\varepsilon}}=\mathbf{0}\) for both coordinates. What value does the loss take, on average?
(a) t is (256,); the other three are (256, 2), one noise estimate per coordinate. The loss is one number, the mean over the batch and both coordinates.
(b) With \(\hat{\boldsymbol{\varepsilon}}=\mathbf{0}\) the loss is the mean of \(\varepsilon^2\), the variance of standard normal noise: about 1. A network that has learned anything must score below 1.
Regression onto noise we drew trains stably, and its loss stays above zero.
Part 4 · A tiny model. How do we judge what a diffusion model generates? We train a small network on two moons, sample from it, and compare the samples with the data. The setup reuses Part 1's two_moons and Part 2's repaired schedule (reading 4.3's script):
import torch
import torch.nn as nn
torch.manual_seed(0)
data = two_moons(4000)
T = 200
betas = torch.linspace(1e-4, 0.05, T) # beta_max rescaled so noising completes in 200 steps
alphas = 1 - betas
alpha_bar = torch.cumprod(alphas, dim=0)
The rest of the setup gives the step as five features and builds the network that predicts the noise:
def t_embed(t): # t: (n,) integer timesteps -> (n, 5) features
ts = t.float() / T
return torch.stack([ts, torch.sin(2 * torch.pi * ts), torch.cos(2 * torch.pi * ts),
torch.sin(8 * torch.pi * ts), torch.cos(8 * torch.pi * ts)], dim=1)
net = nn.Sequential(nn.Linear(7, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(),
nn.Linear(128, 2)) # predicts the noise eps
opt = torch.optim.Adam(net.parameters(), lr=1e-3)
t_embed gives the step as \(t/T\) and four sines and cosines: (n, 5), the same idea as S16's sinusoidal positional encodings.nn.Linear(7, 128) takes 7 inputs: the 2 coordinates of xt and the 5 step features. The last layer returns 2 values, one noise estimate per coordinate.Each pass is the training step of Part 3, on a batch of 256:
for step in range(4000):
x0 = data[torch.randint(0, len(data), (256,))]
t = torch.randint(0, T, (256,))
eps = torch.randn_like(x0)
xt = alpha_bar[t, None].sqrt() * x0 + (1 - alpha_bar[t, None]).sqrt() * eps
pred = net(torch.cat([xt, t_embed(t)], dim=1))
loss = ((pred - eps) ** 2).mean() # mean over batch and both coordinates
opt.zero_grad(); loss.backward(); opt.step()
if step % 1000 == 0 or step == 3999:
print(f"step {step:4d} denoising loss {loss.item():.4f}")
step 0 denoising loss 0.9931
step 1000 denoising loss 0.3516
step 2000 denoising loss 0.3581
step 3000 denoising loss 0.3481
step 3999 denoising loss 0.3213
alpha_bar[t, None] is (256, 1), broadcast over the two coordinates of x0, (256, 2).xt beside t_embed(t), (256, 7); pred is (256, 2), one noise estimate per coordinate.Start 2,000 points at pure noise and apply the sampling step 200 times (this step-by-step sampler is called ancestral sampling):
# Ancestral sampling: start from pure noise, denoise step by step
with torch.no_grad():
x = torch.randn(2000, 2)
for t in reversed(range(T)):
tt = torch.full((2000,), t) # 2,000 copies of t
eps_hat = net(torch.cat([x, t_embed(tt)], dim=1))
x = (x - betas[t] / (1 - alpha_bar[t]).sqrt() * eps_hat) / alphas[t].sqrt()
if t > 0:
x = x + betas[t].sqrt() * torch.randn_like(x)
tt is (2000,), so t_embed(tt) is (2000, 5) and eps_hat, the \(\hat{\boldsymbol{\varepsilon}}\), is (2000, 2).t runs 199 down to 0, the math's \(t=T\) down to 1. The x = (x - ...) line is the formula's first term; if t > 0 adds \(\sqrt{\beta_t}\,\mathbf{z}\) at every step but the last. Sampling needs no gradients.One batch of samples costs 200 network calls, one per step.
A scatter plot shows that samples look right, but not how far off they are, and images cannot be plotted this way. So the code compares the samples with the data twice, first by means, spreads and correlation, then by each point's distance to its nearest data point.
def stats(name, s):
corr = torch.corrcoef(s.T)[0, 1] # s.T is (2, 2000): one row per coordinate
print(f"{name:>10} mean ({s[:, 0].mean():+.4f}, {s[:, 1].mean():+.4f}) "
f"std ({s[:, 0].std():.4f}, {s[:, 1].std():.4f}) corr(x1,x2) {corr:+.4f}")
stats("data", data)
stats("samples", x)
stats("N(0, I)", torch.randn(2000, 2))
# Average distance from each sample to its nearest data point
holdout = two_moons(2000) # fresh points, never trained on
for name, s in [("held-out data", holdout), ("model samples", x),
("N(0, I) noise", torch.randn(2000, 2))]:
d = torch.cdist(s, data).min(dim=1).values.mean()
print(f"mean nearest-data distance, {name:>14}: {d.item():.4f}")
torch.cdist(s, data) is (2000, 4000), every sample's distance to every data point; .min(dim=1).values keeps each row's smallest.Before the printout, a prediction.
Held-out data shows what a perfect model scores, and plain noise what the starting point scores before any denoising. Where should good samples land?
data mean (+0.0000, +0.0000) std (1.0000, 1.0000) corr(x1,x2) -0.4531
samples mean (+0.0429, -0.0370) std (0.9788, 1.0005) corr(x1,x2) -0.4410
N(0, I) mean (+0.0095, +0.0371) std (0.9841, 0.9846) corr(x1,x2) -0.0200
mean nearest-data distance, held-out data: 0.0162
mean nearest-data distance, model samples: 0.0480
mean nearest-data distance, N(0, I) noise: 0.2544
The three point sets behind the previous page's distances, then its printout on two number lines:
Both facts came from a table, which still works when the data has too many dimensions to plot.
Two questions on Part 4.
(a) Another model's samples sit at the held-out distance, 0.016, but their coordinate correlation is near 0, not −0.45. What might they be doing?
(b) The loss levels off near 0.35. Should you tune to push it lower?
(a) Lying on the data without covering it: for example, all on one moon, S24's mode collapse (a whole moon is symmetric about its own middle, so its correlation is near 0: 0.01 for the outer moon, −0.04 for the inner).
(b) No: most of it is Part 3's floor, the noise that cannot be recovered at small \(t\). Judge by the samples' table.
A table against held-out data and noise judges the samples, but sampling took 200 calls.
Part 5 · Faster, steered, at scale. How is sampling made faster? Sampling took 200 network calls per batch here, against one in a GAN (S24). DDIM (Denoising Diffusion Implicit Models; Song, Meng & Ermon, ICLR 2021) keeps the trained network and changes only the sampler:
A first guess of the clean point from pure noise is poor. So DDIM repeats: at each step it visits, ask the network once, guess the clean point, and mix that guess with the same noise at the next step's level; the network then sees a slightly cleaner input.
The steps one batch of samples passes through, from \(t=T\) on the left down to the sample on the right:
| sampler | network calls | steps it visits |
|---|---|---|
| DDPM | 200 | every step |
| DDIM, 50 steps | 50 | about every 4th |
| DDIM, 20 steps | 20 | about every 10th |
| DDIM, 10 steps | 10 | about every 22nd |
Training is unchanged; the sampler visits 50, 20 or 10 steps instead of 200.
Reading 4.3's sampler, run with the network trained in Part 4:
def ddim_sample(n, n_steps):
ts = torch.linspace(T - 1, 0, n_steps).long() # strided timestep subsequence
x = torch.randn(n, 2)
for i, t in enumerate(ts):
tt = torch.full((n,), t.item())
eps_hat = net(torch.cat([x, t_embed(tt)], dim=1))
x0_hat = (x - (1 - alpha_bar[t]).sqrt() * eps_hat) / alpha_bar[t].sqrt()
ab_prev = alpha_bar[ts[i + 1]] if i + 1 < len(ts) else torch.tensor(1.0)
x = ab_prev.sqrt() * x0_hat + (1 - ab_prev).sqrt() * eps_hat # eta = 0
return x
ts is the strided list, (n_steps,); .long() drops the fraction, so 10 steps visit 199, 176, 154, …, 0 (the previous page's figure). The x0_hat line guesses the clean point; the last line mixes it with the same eps_hat at the next step's level, with ab_prev as \(\bar\alpha_s\).ab_prev is 1: the sample is x0_hat itself.Reading 4.3's script retrains Part 4's network (same seed, so the same weights) and scores 2,000 points per row, with random draws of its own. NN dist is Part 4's mean nearest-data distance (NN: nearest neighbor):
sampler NN dist corr(x1,x2) (denoiser calls)
held-out data 0.0152 -0.4166
DDPM 200 0.0485 -0.4417 (200)
DDIM 50 0.0482 -0.4485 (50)
DDIM 20 0.0521 -0.4755 (20)
DDIM 10 0.0574 -0.4899 (10)
DDIM 5 0.0900 -0.5854 (5)
DDIM 2 0.2489 +0.0386 (2)
So far we sample a point, not one we ask for: nothing says which moon it comes from. Classifier-free guidance (Ho & Salimans, 2022) lets us ask:
Dropping the label in training is what lets one network make both predictions.
Sampling combines the previous page's two predictions with a guidance scale \(s\) (from here on \(s\) is this scale, no longer DDIM's step):
\[\boldsymbol{\varepsilon}_{\text{guided}}=\boldsymbol{\varepsilon}_{\text{uncond}}+s\,\big(\boldsymbol{\varepsilon}_{\text{cond}}-\boldsymbol{\varepsilon}_{\text{uncond}}\big)\]A larger \(s\) amplifies the part of the prediction that the label is responsible for.
How does training drop the label? It keeps every example and changes only the label that the network sees:
\[L=\mathbb{E}\big[\lVert\boldsymbol{\varepsilon}-\boldsymbol{\varepsilon}_\theta(\mathbf{x}_t,t,\tilde c)\rVert^2\big]\]nn.Linear(8, 128)).Every example stays in the batch and in the loss; only its label input is set to 0, with probability 0.15.
The previous page's three changes in code; the full script is in reading 4.3:
for step in range(4000):
idx = torch.randint(0, len(data), (256,))
x0, y = data[idx], labels[idx]
c = torch.where(y == 0, 1.0, -1.0)
c = c * (torch.rand(256) > 0.15).float() # drop the label 15% of the time
t = torch.randint(0, T, (256,))
eps = torch.randn_like(x0)
xt = alpha_bar[t, None].sqrt() * x0 + (1 - alpha_bar[t, None]).sqrt() * eps
pred = net(torch.cat([xt, t_embed(t), c[:, None]], dim=1))
loss = ((pred - eps) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step()
labels holds each point's moon, 0 for the outer and 1 for the inner, so torch.where(y == 0, 1.0, -1.0) makes c +1 on the outer moon and −1 on the inner.(torch.rand(256) > 0.15).float() is 0 for about 15% of the batch, so those examples get c = 0, which means no label; they stay in the batch and in the loss.Where does the guided prediction enter sampling? This is Part 4's sampling loop with three new lines: the network runs with the label (eps_c), runs with 0 for no label (eps_u), and the previous page's formula combines them (eps_hat).
def sample_guided(n, scale, target=1.0):
"""DDPM sampling with classifier-free guidance toward c = target."""
x = torch.randn(n, 2)
for t in reversed(range(T)):
tt = torch.full((n,), t)
feats = t_embed(tt)
eps_c = net(torch.cat([x, feats, torch.full((n, 1), target)], dim=1))
eps_u = net(torch.cat([x, feats, torch.zeros(n, 1)], dim=1))
eps_hat = eps_u + scale * (eps_c - eps_u)
x = (x - betas[t] / (1 - alpha_bar[t]).sqrt() * eps_hat) / alphas[t].sqrt()
if t > 0:
x = x + betas[t].sqrt() * torch.randn_like(x)
return x
torch.full((n, 1), target) is a column of n copies of target (1.0, the outer moon), and scale is \(s\).Reading 4.3's script draws 2,000 samples at each of five scales, always asking for the outer moon. Purity is the share of samples whose nearest data point is on the outer moon; NN dist is the mean distance to the nearest outer-moon point; spread is the mean per-coordinate standard deviation.
scale purity NN dist spread
0.0 0.468 0.4389 1.0041
1.0 0.997 0.0232 0.7140
2.0 1.000 0.0161 0.6390
4.0 1.000 0.0140 0.5776
8.0 1.000 0.0137 0.5155
outer-moon data spread: 0.7294
Three rows of the previous page's table as pictures: every 8th of the 2,000 samples in purple, over the data in gray (the outer moon darker); the outer moon's own spread is 0.73.
A larger \(s\) raises purity and lowers the spread: the samples match the label more closely and cover less of the moon.
A photograph has hundreds of thousands of values, so every one of the many network calls is expensive. Stable Diffusion keeps today's steps and changes the components:
DDIM cuts the calls, guidance trades diversity for adherence, a latent space cuts compute.
Part 6 · Close. Which of the three families should you use? Compare them across S23–S25 (reading 4.3); coverage and fidelity are S24's recall and precision:
| family | training | sampling | strength | weakness |
|---|---|---|---|---|
| VAE | stable (a likelihood bound) | one decoder pass | a usable latent space | blur |
| GAN | an adversarial game | one forward pass | sharp samples | unstable training, mode collapse |
| diffusion | stable (regression on noise) | many steps | coverage and fidelity | slow, iterative sampling |
Modern systems combine them. A VAE supplies the latent space and diffusion generates in it; some also train a second network adversarially to imitate the sampler in 1–4 steps (adversarial distillation), for speed.
No family is best in every column, so modern systems combine them.
Reading 4.3's pitfalls; the second (in bold) is the one today's Part 2 worked through:
| symptom | cause | fix |
|---|---|---|
| the loss levels off above zero, and you keep tuning | the noise objective has a floor well above zero | judge by sampling and distribution statistics |
| nothing errors, yet \(\mathbf{x}_T\) still correlates with the data (corr 0.35 at \(T=200\), Part 2) | \(T\) changed, \(\beta\) schedule kept: the noising does not finish | check sqrt(a_bar) and corr(x_T, x0); rescale beta_max with \(T\) |
| DDPM sampling gives over-smoothed samples | the fresh noise \(\mathbf{z}\) omitted, or the wrong variance | implement the chosen variance exactly; do not mix in DDIM's update |
| training diverges or starts at an enormous loss | a data scale far from the noise's unit scale | standardize first, undo it after sampling |
| striding DDPM's sampling step degrades samples even at many steps | its coefficients hold only for adjacent steps | use DDIM's update for a strided list |
| guided samples score well but all look alike | a high guidance scale shrinks the spread | sweep \(s\); report purity and spread at a stated scale |
Back to the title page's question.