TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Diffusion Models: Training and Sampling

Diffusion Models: Training and Sampling

The previous lesson built the forward process: a schedule αˉt\bar{\alpha}_t and the one-step formula xt=αˉt x0+1−αˉt ϵ\mathbf{x}_t = \sqrt{\bar{\alpha}_t}\, \mathbf{x}_0 + \sqrt{1 - \bar{\alpha}_t}\, \boldsymbol{\epsilon}. This lesson does the learning and the generating. A network ϵθ(xt,t)\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t) is trained to predict the noise in a noisy input, and generation starts from pure noise and removes a little of it at each step. You will see that the training loss is a plain regression, why it can never reach zero, and two samplers: DDPM, which is stochastic and uses every step, and DDIM, which is deterministic and can skip steps. A NumPy sampler driven by the exact optimal noise predictor recovers an 8-mode distribution in the browser. A small trained PyTorch denoiser does the same for the two-moons data. The lesson ends with classifier-free guidance and latent diffusion, the two ideas behind text-to-image systems.

The training objective

Ho et al. (2020) showed that a weighted form of the ELBO for this model reduces to a regression on the noise. With weights dropped, it becomes the simple loss:

Lsimple(θ)=Et∼U{1,…,T}, x0∼pdata, ϵ∼N(0,I)∥ϵ−ϵθ(αˉt x0+1−αˉt ϵ, t)∥2\mathcal{L}_{\text{simple}}(\theta) = \mathbb{E}_{t \sim \mathcal{U}\{1, \dots, T\},\ \mathbf{x}_0 \sim p_{\text{data}},\ \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, I)} \left\lVert \boldsymbol{\epsilon} - \boldsymbol{\epsilon}_\theta\left(\sqrt{\bar{\alpha}_t}\, \mathbf{x}_0 + \sqrt{1 - \bar{\alpha}_t}\, \boldsymbol{\epsilon},\ t\right) \right\rVert^2

One training step draws a batch of images, a random tt and a fresh ϵ\boldsymbol{\epsilon} for each, builds xt\mathbf{x}_t in one step, and regresses the network's output on ϵ\boldsymbol{\epsilon}. There is no adversary and no sampling during training. That is a large part of why diffusion models train so reliably.

x_0 eps t x_t = sqrt(ab) x_0+ sqrt(1-ab) eps sin/cos embedding denoiserMLP or U-Net eps-hat squared error target: the same eps

The time input. The same network serves all TT noise levels, so it must know tt. The usual encoding is the sinusoidal one from transformers (Positional Encodings): sin⁡(t ωk)\sin(t\, \omega_k) and cos⁡(t ωk)\cos(t\, \omega_k) for geometrically spaced frequencies ωk\omega_k. Large networks pass it through a small MLP and add it to every block of the denoiser.

What the optimum is. For squared error, the best possible predictor is the conditional mean ϵ∗(xt,t)=E[ϵ∣xt]\boldsymbol{\epsilon}^*(\mathbf{x}_t, t) = \mathbb{E}[\boldsymbol{\epsilon} \mid \mathbf{x}_t]. Tweedie's formula ties it to the score of the noisy data distribution ptp_t:

ϵ∗(xt,t)=−1−αˉt  ∇xtlog⁡pt(xt)\boldsymbol{\epsilon}^*(\mathbf{x}_t, t) = -\sqrt{1 - \bar{\alpha}_t}\; \nabla_{\mathbf{x}_t} \log p_t(\mathbf{x}_t)

So a noise predictor is a scaled score estimator, the same object a denoising autoencoder approximates. For a Gaussian mixture, ptp_t is again a Gaussian mixture, with each mean scaled by αˉt\sqrt{\bar{\alpha}_t} and each variance αˉts2+1−αˉt\bar{\alpha}_t s^2 + 1 - \bar{\alpha}_t. Its score has a closed form, and so does ϵ∗\boldsymbol{\epsilon}^*. The next example uses this on the 8-blob ring from the GAN lesson to compute the loss the best possible network would reach, and it checks the time embedding.

python · try it yourself
import numpy as np

K, s = 8, 0.05
angles = np.arange(K) * 2 * np.pi / K
mu = np.stack([2 * np.cos(angles), 2 * np.sin(angles)], axis=1)
T = 1000
ab = np.cumprod(1 - np.linspace(1e-4, 0.02, T))

def eps_star(x, t):                                     # optimal predictor; t may differ per row
    a = ab[np.broadcast_to(t, len(x)) - 1][:, None]     # (n, 1)
    m, v = np.sqrt(a)[:, :, None] * mu[None], a * s ** 2 + (1 - a)   # (n, K, 2), (n, 1)
    logw = -((x[:, None, :] - m) ** 2).sum(-1) / (2 * v)
    w = np.exp(logw - logw.max(axis=1, keepdims=True)); w /= w.sum(axis=1, keepdims=True)
    return -np.sqrt(1 - a) * (w[:, :, None] * (m - x[:, None, :])).sum(1) / v

rng = np.random.default_rng(0)
n = 4000
x0 = mu[rng.integers(0, K, n)] + s * rng.standard_normal((n, 2))
print("    t   loss of eps = 0   loss of the best possible predictor")
total = []
for t in (1, 10, 50, 200, 500, 1000):
    eps = rng.standard_normal((n, 2))
    xt = np.sqrt(ab[t - 1]) * x0 + np.sqrt(1 - ab[t - 1]) * eps
    best = np.mean((eps_star(xt, t) - eps) ** 2)
    print(f"{t:5d}   {np.mean(eps ** 2):15.3f}   {best:20.3f}")

# the simple loss averages over t drawn uniformly: estimate it for the best predictor
t = rng.integers(1, T + 1, n)
eps = rng.standard_normal((n, 2))
xt = np.sqrt(ab[t - 1])[:, None] * x0 + np.sqrt(1 - ab[t - 1])[:, None] * eps
best = np.mean((eps_star(xt, t) - eps) ** 2)
print(f"simple loss of the best predictor, t uniform: {best:.3f}  (a trained network cannot go below this)")

# sinusoidal time embedding: nearby steps get similar vectors, distant steps different ones
def time_embedding(t, dim=32):
    freqs = np.exp(-np.log(1000.0) * np.arange(dim // 2) / (dim // 2))
    ang = np.asarray(t, dtype=float)[:, None] * freqs[None]
    return np.concatenate([np.sin(ang), np.cos(ang)], axis=1)
E = time_embedding([500, 501, 510, 600, 900])
cos = E @ E[0] / (np.linalg.norm(E, axis=1) * np.linalg.norm(E[0]))
print("cosine similarity of t = 500 with t = 501, 510, 600, 900:", np.round(cos[1:], 3).tolist())
    t   loss of eps = 0   loss of the best possible predictor
    1             0.987                  0.950
   10             0.991                  0.571
   50             1.013                  0.078
  200             1.029                  0.555
  500             1.000                  0.145
 1000             0.983                  0.000
simple loss of the best predictor, t uniform: 0.196  (a trained network cannot go below this)
cosine similarity of t = 500 with t = 501, 510, 600, 900: [0.949, 0.529, 0.26, -0.02]

Predicting zero costs about 1 at every tt, the variance of ϵ\boldsymbol{\epsilon}. The best predictor's loss depends strongly on tt. At t=1000t = 1000 it is 0.000, because xT\mathbf{x}_T is almost pure noise and the noise is the input. At t=1t = 1 it is 0.950: the added noise (standard deviation 0.01) is much smaller than the blobs' own spread of 0.05, so it cannot be told apart from the data. At t=200t = 200 it is 0.555, where neighbouring blobs overlap and a point could belong to either. Averaged over a uniform tt, the minimum is 0.196, not 0. A diffusion loss curve that levels off is not necessarily a failure, and comparing it with 0 means nothing. The embedding gives t=501t = 501 a cosine similarity of 0.949 to t=500t = 500, t=510t = 510 only 0.529, and t=900t = 900 about 0. The network can tell nearby noise levels apart and still share what it learns between them.

Sampling: DDPM and DDIM

DDPM ancestral sampling runs the learned reverse chain. Start from xT∼N(0,I)\mathbf{x}_T \sim \mathcal{N}(\mathbf{0}, I) and for t=T,…,1t = T, \dots, 1 compute

xt−1=1αt(xt−βt1−αˉt ϵθ(xt,t))+σtz,z∼N(0,I),σt2=1−αˉt−11−αˉtβt\mathbf{x}_{t-1} = \frac{1}{\sqrt{\alpha_t}} \left( \mathbf{x}_t - \frac{\beta_t}{\sqrt{1 - \bar{\alpha}_t}}\, \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t) \right) + \sigma_t \mathbf{z}, \qquad \mathbf{z} \sim \mathcal{N}(\mathbf{0}, I), \quad \sigma_t^2 = \frac{1 - \bar{\alpha}_{t-1}}{1 - \bar{\alpha}_t} \beta_t

with no noise at the last step. The mean is the posterior mean of q(xt−1∣xt,x0)q(\mathbf{x}_{t-1} \mid \mathbf{x}_t, \mathbf{x}_0) with x0\mathbf{x}_0 replaced by its estimate. Ho et al. found σt2=βt\sigma_t^2 = \beta_t works about as well. It costs TT network evaluations per sample.

DDIM (Song, Meng and Ermon, 2020) uses the same trained network with a deterministic update between any two steps t>t′t > t'. First estimate the clean sample, then re-noise it to level t′t' with the predicted noise instead of fresh noise:

x^0=xt−1−αˉt ϵθ(xt,t)αˉt,xt′=αˉt′ x^0+1−αˉt′ ϵθ(xt,t)\hat{\mathbf{x}}_0 = \frac{\mathbf{x}_t - \sqrt{1 - \bar{\alpha}_t}\, \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t)}{\sqrt{\bar{\alpha}_t}}, \qquad \mathbf{x}_{t'} = \sqrt{\bar{\alpha}_{t'}}\, \hat{\mathbf{x}}_0 + \sqrt{1 - \bar{\alpha}_{t'}}\, \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t)

Because the update does not need consecutive steps, 50 or 20 network calls can replace 1000. Being deterministic, it maps each starting noise to one sample, which makes interpolation between noises meaningful. It is a discretisation of an ordinary differential equation (the probability-flow ODE), so with very few steps the discretisation error grows.

Both samplers, in NumPy, driven by the exact ϵ∗\boldsymbol{\epsilon}^* for the 8-blob ring. A sample is "near a mode" within 0.15 (3 standard deviations) of a centre, a mode is covered if it gets a quarter of its fair share, and "spread" is the per-coordinate standard deviation of the near samples around their centre.

python · try it yourself
import numpy as np

# Data: 8 Gaussian blobs on a ring of radius 2, standard deviation 0.05 (the GAN lesson's test set)
K, s = 8, 0.05
angles = np.arange(K) * 2 * np.pi / K
mu = np.stack([2 * np.cos(angles), 2 * np.sin(angles)], axis=1)

T = 1000
beta = np.linspace(1e-4, 0.02, T)
alpha = 1 - beta
ab = np.cumprod(alpha)

def eps_star(x, t):
    """The optimal noise predictor E[eps | x_t] for this data, in closed form (t = 1..T)."""
    a = ab[t - 1]
    m, v = np.sqrt(a) * mu, a * s ** 2 + (1 - a)        # x_t is a mixture of N(m_k, v I)
    logw = -((x[:, None, :] - m[None]) ** 2).sum(-1) / (2 * v)
    w = np.exp(logw - logw.max(axis=1, keepdims=True))
    w /= w.sum(axis=1, keepdims=True)                   # responsibilities of the 8 blobs
    score = (w[:, :, None] * (m[None] - x[:, None, :])).sum(1) / v   # gradient of log p_t(x)
    return -np.sqrt(1 - a) * score

def report(name, x):
    d = np.sqrt(((x[:, None, :] - mu[None]) ** 2).sum(-1))
    near = d.min(axis=1) < 3 * s
    counts = np.bincount(d.argmin(axis=1)[near], minlength=K)
    spread = np.sqrt((d.min(axis=1)[near] ** 2).mean() / 2)          # per-coordinate std around the blob
    print(f"{name:21s} near a mode {near.mean():.3f}  covered {int((counts > 0.25 * len(x) / K).sum())}/8"
          f"  spread {spread:.4f}  per mode {counts.tolist()}")

rng = np.random.default_rng(0)
n = 1000
report("data itself", mu[rng.integers(0, K, n)] + s * rng.standard_normal((n, 2)))
report("x_T ~ N(0, I)", rng.standard_normal((n, 2)))

# DDPM ancestral sampling: T steps, fresh noise at each step
x = rng.standard_normal((n, 2))
for t in range(T, 0, -1):
    eps = eps_star(x, t)
    mean = (x - beta[t - 1] / np.sqrt(1 - ab[t - 1]) * eps) / np.sqrt(alpha[t - 1])
    var = beta[t - 1] * (1 - ab[t - 2]) / (1 - ab[t - 1]) if t > 1 else 0.0   # posterior variance
    x = mean + np.sqrt(var) * rng.standard_normal((n, 2))
report("DDPM, 1000 steps", x)

# DDIM (eta = 0): deterministic, any subsequence of steps
for steps in (50, 10):
    ts = np.linspace(T, 1, steps).round().astype(int)
    x = rng.standard_normal((n, 2))
    for i, t in enumerate(ts):
        eps = eps_star(x, t)
        x0_hat = (x - np.sqrt(1 - ab[t - 1]) * eps) / np.sqrt(ab[t - 1])
        a_next = ab[ts[i + 1] - 1] if i + 1 < len(ts) else 1.0
        x = np.sqrt(a_next) * x0_hat + np.sqrt(1 - a_next) * eps
    report(f"DDIM, {steps} steps", x)
data itself           near a mode 0.996  covered 8/8  spread 0.0492  per mode [118, 109, 120, 114, 144, 129, 129, 133]
x_T ~ N(0, I)         near a mode 0.010  covered 0/8  spread 0.0731  per mode [1, 0, 1, 2, 1, 1, 1, 3]
DDPM, 1000 steps      near a mode 0.990  covered 8/8  spread 0.0449  per mode [135, 114, 145, 113, 122, 120, 121, 120]
DDIM, 50 steps        near a mode 0.996  covered 8/8  spread 0.0361  per mode [142, 121, 115, 126, 122, 120, 122, 128]
DDIM, 10 steps        near a mode 0.670  covered 8/8  spread 0.0397  per mode [71, 83, 82, 86, 90, 90, 72, 96]

Starting from N(0,I)\mathcal{N}(\mathbf{0}, I), where 1 % of points happen to lie near a mode, 1000 DDPM steps give 99.0 % near a mode, all 8 modes with 113 to 145 samples each, and a spread of 0.0449, close to the data's own 0.0492. That is the reverse process working exactly as the theory says, with nothing learned. DDIM with 50 steps covers all modes just as well (99.6 %), but its blobs are too tight (0.0361): the coarse discretisation of the ODE pulls samples towards the centres. With 10 steps, only 67.0 % of samples land near a mode, and the rest sit between blobs. Fewer steps cost accuracy, and better ODE solvers (DPM-Solver and others) exist to reduce that cost. Compare the GAN on the same data, whose mode coverage depended on Adam's β1\beta_1.

A trained denoiser in PyTorch (recorded)

Now the predictor is learned. The data is the course's two moons (600 points, noise 0.25), standardised. A 3-layer MLP with SiLU activations takes (xt,embedding(t))(\mathbf{x}_t, \text{embedding}(t)) and predicts ϵ\boldsymbol{\epsilon}. With only 2 dimensions, T=200T = 200 steps with β\beta from 10−410^{-4} to 0.1 is enough. Samples are judged in two ways. The first is the mean distance from each sample to its nearest training point. The second is the MMD (maximum mean discrepancy with a Gaussian kernel) to a separate draw of real data, which is close to 0 only when two point sets have the same distribution. Fresh real data and a standard-normal cloud set the scale. The example is recorded and ran on the CPU.

python · try it yourself
import math
import numpy as np
import torch
from torch import nn
from sklearn.datasets import make_moons

torch.manual_seed(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
X, _ = make_moons(n_samples=600, noise=0.25, random_state=0)
mean, std = X.mean(axis=0), X.std(axis=0)
data = torch.tensor((X - mean) / std, dtype=torch.float32, device=device)   # standardised training data
fresh = lambda seed: torch.tensor((make_moons(n_samples=600, noise=0.25, random_state=seed)[0] - mean) / std,
                                  dtype=torch.float32)
ref, real2 = fresh(1), fresh(2)                                           # new real data, never trained on

T = 200
beta = torch.linspace(1e-4, 0.1, T, dtype=torch.float64)                   # T = 200, so larger steps
alpha = 1 - beta
ab = torch.cumprod(alpha, 0)
beta, alpha, ab = beta.float().to(device), alpha.float().to(device), ab.float().to(device)

def time_embedding(t, dim=32):
    """Sinusoidal embedding of the step t (as in transformers' positional encodings)."""
    freqs = torch.exp(-math.log(1000.0) * torch.arange(dim // 2, device=t.device) / (dim // 2))
    angles = t.float()[:, None] * freqs[None]
    return torch.cat([torch.sin(angles), torch.cos(angles)], dim=1)

class Denoiser(nn.Module):
    def __init__(self, hidden=128):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(2 + 32, hidden), nn.SiLU(), nn.Linear(hidden, hidden), nn.SiLU(),
                                 nn.Linear(hidden, hidden), nn.SiLU(), nn.Linear(hidden, 2))
    def forward(self, x, t):                       # predicts the noise eps that was added to get x_t
        return self.net(torch.cat([x, time_embedding(t)], dim=1))

model = Denoiser().to(device)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
running = 0.0
for step in range(1, 4501):
    x0 = data[torch.randint(0, len(data), (256,), device=device)]
    t = torch.randint(1, T + 1, (256,), device=device)
    eps = torch.randn_like(x0)
    a = ab[t - 1][:, None]
    xt = a.sqrt() * x0 + (1 - a).sqrt() * eps
    loss = ((model(xt, t) - eps) ** 2).mean()      # the simple loss of DDPM
    opt.zero_grad(); loss.backward(); opt.step()
    running += loss.item()
    if step % 1500 == 0:
        print(f"steps {step - 1499:4d}-{step:4d}  mean loss {running / 1500:.4f}")
        running = 0.0

@torch.no_grad()
def ddpm(n):
    x = torch.randn(n, 2, device=device)
    for t in range(T, 0, -1):
        tt = torch.full((n,), t, device=device)
        eps = model(x, tt)
        mean_ = (x - beta[t - 1] / (1 - ab[t - 1]).sqrt() * eps) / alpha[t - 1].sqrt()
        var = beta[t - 1] * (1 - ab[t - 2]) / (1 - ab[t - 1]) if t > 1 else torch.tensor(0.0)
        x = mean_ + var.sqrt() * torch.randn_like(x)
    return x.cpu()

@torch.no_grad()
def ddim(n, steps):
    ts = torch.linspace(T, 1, steps).round().long().tolist()
    x = torch.randn(n, 2, device=device)
    for i, t in enumerate(ts):
        eps = model(x, torch.full((n,), t, device=device))
        x0_hat = (x - (1 - ab[t - 1]).sqrt() * eps) / ab[t - 1].sqrt()
        a_next = ab[ts[i + 1] - 1] if i + 1 < len(ts) else torch.tensor(1.0)
        x = a_next.sqrt() * x0_hat + (1 - a_next).sqrt() * eps
    return x.cpu()

def nn_dist(a, b):                                  # mean distance from each point of a to its nearest in b
    return torch.cdist(a, b).min(dim=1).values.mean().item()
def mmd(a, b, h=0.5):                               # kernel two-sample statistic, 0 for equal distributions
    k = lambda u, v: torch.exp(-torch.cdist(u, v) ** 2 / (2 * h * h)).mean()
    return (k(a, a) + k(b, b) - 2 * k(a, b)).item()

model.eval()
torch.manual_seed(1)
gauss = torch.randn(600, 2)                         # baseline: standard normal (the data is standardised)
for name, s in [("new real data", real2), ("Gaussian baseline", gauss), ("DDPM, 200 steps", ddpm(600)),
                ("DDIM, 20 steps", ddim(600, 20)), ("DDIM, 5 steps", ddim(600, 5))]:
    print(f"{name:18s} NN distance to training data {nn_dist(s, data.cpu()):.3f}   MMD to other real data {mmd(s, ref):.4f}")
steps    1-1500  mean loss 0.2840
steps 1501-3000  mean loss 0.2691
steps 3001-4500  mean loss 0.2660
new real data      NN distance to training data 0.081   MMD to other real data 0.0019
Gaussian baseline  NN distance to training data 0.147   MMD to other real data 0.0191
DDPM, 200 steps    NN distance to training data 0.084   MMD to other real data 0.0036
DDIM, 20 steps     NN distance to training data 0.086   MMD to other real data 0.0086
DDIM, 5 steps      NN distance to training data 0.070   MMD to other real data 0.0503

The mean loss levels off at 0.2660. As in the NumPy example, the floor is above 0, and there is no exact value to compare with for moons. A second draw of real data has an MMD of 0.0019 to the reference set. The Gaussian baseline has 0.0191. DDPM with all 200 steps reaches 0.0036, much closer to real data than to the baseline, and its mean nearest-neighbour distance (0.084) is about that of real data (0.081). DDIM with 20 steps is worse (MMD 0.0086), and with 5 steps much worse (0.0503). The 5-step DDIM shows why one metric is not enough. Its nearest-neighbour distance, 0.070, is better than that of real data, because its samples collapse onto the dense middle of the moons. A distance-to-data metric rewards that, and it would also reward copying the training set. MMD sees that the distribution is wrong. Report a distribution-level metric (MMD here, FID for images) next to any per-sample distance.

Guidance and latent diffusion

Conditioning. To generate a requested class or a text prompt cc, the denoiser takes cc as another input, ϵθ(xt,t,c)\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t, c): a class embedding added like the time embedding, or text-encoder outputs read through cross-attention (Attention from Scratch).

Classifier-free guidance (Ho and Salimans, 2022) trains one network both with and without the condition, by replacing cc with a "null" token for, say, 10 % of training examples. At sampling time it extrapolates from the unconditional prediction towards the conditional one:

ϵ~=ϵθ(xt,t,∅)+w(ϵθ(xt,t,c)−ϵθ(xt,t,∅))\tilde{\boldsymbol{\epsilon}} = \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t, \varnothing) + w \left( \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t, c) - \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t, \varnothing) \right)

w=1w = 1 is plain conditional sampling. Values of 3 to 8 are common for text-to-image: samples match the prompt more closely and look cleaner, at the cost of diversity. Each step needs two network evaluations, usually done as one batch of two.

Latent diffusion (Rombach et al., 2022, the basis of Stable Diffusion) runs the whole process in the latent space of a pretrained autoencoder instead of on pixels. The encoder downsamples, for example a 512×512×3512 \times 512 \times 3 image to a 64×64×464 \times 64 \times 4 latent, which makes each denoiser step much cheaper. The decoder turns the final latent into an image. The autoencoder is trained first, with a reconstruction loss plus perceptual and adversarial terms (see GANs) and a light KL penalty, a mild form of the VAE objective.

The denoiser for images is usually a U-Net: a convolutional encoder-decoder with skip connections between the levels of the same resolution, with the time embedding added in every residual block and attention at the lower resolutions. Newer models replace it with a transformer over patches (DiT). U-Nets and segmentation are covered in Computer Vision.

Pitfalls

  • Expecting the loss to go to zero. Its floor depends on the data and the schedule (0.196 for the ring above). Judge models by their samples.
  • Mixing conventions between training and sampling. The sampler must use exactly the schedule, the indexing of tt and the target (ϵ\boldsymbol{\epsilon}, x0\mathbf{x}_0 or v\mathbf{v}) of training.
  • Clipping. For images in [−1,1][-1, 1], many samplers clip x^0\hat{\mathbf{x}}_0 to that range at each step, which helps with few steps. Applied to latents or to data with another range, it does harm.
  • Too few sampler steps without checking. As above, 5 DDIM steps looked good on a per-sample metric and were wrong on the distribution.
  • Training on a small set for too long. A strong denoiser can memorise the training images and reproduce them. Check samples against their nearest training examples.

Practice

  1. Why is the best predictor's loss exactly about 0 at t=Tt = T but close to 1 at t=1t = 1 for the ring data?
Answer

At t=Tt = T, αˉT≈0\bar{\alpha}_T \approx 0, so xT≈ϵ\mathbf{x}_T \approx \boldsymbol{\epsilon} and the predictor can return its input. At t=1t = 1, the added noise has standard deviation 1−αˉ1=0.01\sqrt{1 - \bar{\alpha}_1} = 0.01, while each blob has standard deviation 0.05. Given x1\mathbf{x}_1, you cannot tell which part of the offset from the blob centre is data and which is noise, so E[ϵ∣x1]\mathbb{E}[\boldsymbol{\epsilon} \mid \mathbf{x}_1] is close to 0 and the loss stays near the variance of ϵ\boldsymbol{\epsilon}. The ratio is about 0.052/(0.052+0.012)=0.960.05^2 / (0.05^2 + 0.01^2) = 0.96, near the measured 0.950.

  1. Show that one DDIM step from tt to t′=tt' = t returns xt\mathbf{x}_t unchanged, and explain why DDIM is deterministic while DDPM is not.
Answer

With t′=tt' = t: αˉt x^0+1−αˉt ϵθ=(xt−1−αˉt ϵθ)+1−αˉt ϵθ=xt\sqrt{\bar{\alpha}_t}\, \hat{\mathbf{x}}_0 + \sqrt{1 - \bar{\alpha}_t}\, \boldsymbol{\epsilon}_\theta = (\mathbf{x}_t - \sqrt{1 - \bar{\alpha}_t}\, \boldsymbol{\epsilon}_\theta) + \sqrt{1 - \bar{\alpha}_t}\, \boldsymbol{\epsilon}_\theta = \mathbf{x}_t. DDIM re-noises with the predicted noise, a function of xt\mathbf{x}_t, so the path depends only on xT\mathbf{x}_T. DDPM adds fresh noise σtz\sigma_t \mathbf{z} at every step.

  1. With guidance weight w=0w = 0, what does classifier-free guidance sample from? With w=1w = 1?
Answer

w=0w = 0 gives ϵθ(xt,t,∅)\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t, \varnothing), the unconditional model, which ignores the prompt. w=1w = 1 gives the conditional prediction, sampling from the model's p(x∣c)p(\mathbf{x} \mid c) with no extra emphasis. Values above 1 push beyond it.

Test yourself

What does a DDPM network regress on during training?

  1. The clean image from the class label
  2. The noise ϵ\boldsymbol{\epsilon} that was added to make xt\mathbf{x}_t, given xt\mathbf{x}_t and tt
  3. The discriminator's output
  4. The next pixel of the image

The best possible noise predictor for the 8-blob ring has a simple loss of 0.196 averaged over tt. What follows for a trained network?

  1. It should reach 0 with enough training
  2. Its loss cannot go below 0.196 on this data, so a plateau above 0 is expected
  3. The schedule is wrong
  4. The data must be standardised again

How does DDIM differ from DDPM ancestral sampling?

  1. It needs a different trained network
  2. It is deterministic given xT\mathbf{x}_T and can skip steps, using the same trained network
  3. It adds more noise at each step
  4. It only works for 2-D data

In the moons example, 5 DDIM steps gave a smaller mean nearest-neighbour distance to the training data (0.070) than fresh real data (0.081). What does that indicate?

  1. 5 steps generate better samples than real data
  2. The samples are concentrated in dense regions (too little diversity), which a per-sample distance rewards; the MMD of 0.0503 shows the distribution is wrong
  3. The training data leaked into the sampler
  4. Nothing, the metrics agree

In classifier-free guidance with w=5w = 5, what is computed at each step?

  1. Only the conditional prediction
  2. The unconditional prediction plus 5 times the difference between the conditional and unconditional predictions
  3. A separate classifier's gradient
  4. Five sampling chains