25  Additional Material: Why the Diffusion Equations Work

Gaussian sums, the reverse conditional, conditional means, likelihood, and a guidance experiment

This optional route supplies the algebra behind the main chapter and one experiment that goes beyond it. You need means, variances, Gaussian densities, and completing a square. The likelihood section connects to maximum likelihood from Lesson 2. Nothing here is required to run the lab.

Section Supports which part of the chapter
Direct noising by induction The direct noising equation
The previous-state conditional The coefficients of the reverse step
From clean image to noise The mean written with the predicted noise
Conditional means The one-dimensional example and its tanh formula
Noise prediction and the score The pointer to score-based models
Relation to likelihood Why the simple loss is not a likelihood
Why a DDIM jump is consistent The deterministic sampler of the lab
Conditioning and guidance Conditional generation; an executable experiment

Throughout, \(\alpha_t=1-\beta_t\), \(\bar\alpha_t=\prod_{s=1}^t\alpha_s\), and \(\bar\alpha_0=1\). Images can be treated as vectors; the conditional covariance matrices below are scalar multiples of \(I\).

25.1 Direct noising by induction

The forward model is

\[ x_t=\sqrt{\alpha_t}x_{t-1}+\sqrt{\beta_t}z_t, \qquad z_t\overset{\mathrm{ind}}\sim\mathcal N(0,I). \]

For a fixed clean image, the first state has mean \(\sqrt{\alpha_1}x_0\) and variance \(\beta_1 I=(1-\bar\alpha_1)I\). Assume

\[ x_{t-1}\mid x_0\sim\mathcal N\big(\sqrt{\bar\alpha_{t-1}}x_0, (1-\bar\alpha_{t-1})I\big). \]

A linear combination of independent Gaussian variables is Gaussian. Its mean is \(\sqrt{\alpha_t\bar\alpha_{t-1}}x_0=\sqrt{\bar\alpha_t}x_0\), and its variance is

\[ \alpha_t(1-\bar\alpha_{t-1})I+\beta_tI =(1-\bar\alpha_t)I. \]

Thus

\[ q(x_t\mid x_0)=\mathcal N\big(\sqrt{\bar\alpha_t}x_0,(1-\bar\alpha_t)I\big). \]

Distinction. Pixels are independent conditional on a fixed \(x_0\). After averaging over the data distribution of \(x_0\), pixels generally remain dependent. Diffusion does not assume that clean images consist of independent pixels.

import torch
from dlbook.diffusion import cosine_schedule

schedule = cosine_schedule(64)
t = 27
left = schedule.alpha[t] * (1 - schedule.abar[t - 1]) + schedule.beta[t]
torch.testing.assert_close(left, 1 - schedule.abar[t])

# Check the collapsed distribution against a sequential scalar simulation.
g = torch.Generator().manual_seed(47)
x0 = 0.7
x = torch.full((50000,), x0)
for step in range(1, t + 1):
    z = torch.randn(x.shape, generator=g)
    x = schedule.alpha[step].sqrt() * x + schedule.beta[step].sqrt() * z
expected_mean = schedule.abar[t].sqrt() * x0
expected_variance = 1 - schedule.abar[t]
observed_variance = x.var(unbiased=False)
print(f"Mean: observed {x.mean():.4f}, theoretical {expected_mean:.4f}")
print(f"Variance: observed {observed_variance:.4f}, theoretical {expected_variance:.4f}")
assert abs(x.mean() - expected_mean) < 0.015
assert abs(observed_variance - expected_variance) < 0.015
Mean: observed 0.5487, theoretical 0.5488
Variance: observed 0.3874, theoretical 0.3854

25.2 Derive the previous-state conditional by completing a square

The quantity we can calculate exactly is \(q(x_{t-1}\mid x_t,x_0)\), which includes the clean image. The quantity needed for generation, \(q(x_{t-1}\mid x_t)\), averages over unknown clean images and is generally more complicated. The chapter’s figure on small steps shows it as a mixture.

For \(t\ge2\), let \(u=x_{t-1}\). Bayes’ rule gives, up to factors that do not depend on \(u\),

\[ q(u\mid x_t,x_0)\propto q(x_t\mid u)\,q(u\mid x_0). \]

Ignoring constants, negative twice its log density is

\[ \frac{\|x_t-\sqrt{\alpha_t}u\|^2}{\beta_t} +\frac{\|u-\sqrt{\bar\alpha_{t-1}}x_0\|^2}{1-\bar\alpha_{t-1}}. \]

Expanding the squares leaves \(A\|u\|^2-2b^\top u+C\), where

\[ A=\frac{\alpha_t}{\beta_t}+\frac{1}{1-\bar\alpha_{t-1}} =\frac{1-\bar\alpha_t}{\beta_t(1-\bar\alpha_{t-1})}, \qquad b=\frac{\sqrt{\alpha_t}}{\beta_t}x_t +\frac{\sqrt{\bar\alpha_{t-1}}}{1-\bar\alpha_{t-1}}x_0. \]

Complete the square: \(A\|u-A^{-1}b\|^2+C'\). The Gaussian mean is \(A^{-1}b\) and its covariance is \(A^{-1}I\). Therefore,

\[ \boxed{\tilde\beta_t=\frac{\beta_t(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}}, \qquad \boxed{\tilde\mu_t= \frac{\beta_t\sqrt{\bar\alpha_{t-1}}}{1-\bar\alpha_t}x_0 +\frac{\sqrt{\alpha_t}(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}x_t}. \]

The intermediate precision expression divides by \(1-\bar\alpha_{t-1}\), so it is not defined at \(t=1\). The final coefficients have a well-defined endpoint: \(\tilde\beta_1=0\) and \(\tilde\mu_1=x_0\). Conditional on \(x_0\), there is no uncertainty about \(x_0\) itself.

from dlbook.diffusion import posterior

# Independent Gaussian-conditioning formula from the joint mean and covariance.
step = 27
ap = schedule.abar[step - 1].double()
a = schedule.alpha[step].double()
beta = schedule.beta[step].double()
var_previous = 1 - ap
var_current = a * var_previous + beta
covariance = a.sqrt() * var_previous
x0 = torch.tensor([[[[0.7]]]], dtype=torch.float64)
xt = torch.tensor([[[[-0.2]]]], dtype=torch.float64)
gain = covariance / var_current
joint_mean = ap.sqrt() * x0 + gain * (xt - (a * ap).sqrt() * x0)
joint_variance = (var_previous - gain * covariance).reshape(1, 1, 1, 1)
mean, variance = posterior(xt, torch.tensor([step]), x0, schedule)
torch.testing.assert_close(mean, joint_mean, atol=2e-6, rtol=2e-6)
torch.testing.assert_close(variance.double(), joint_variance, atol=2e-6, rtol=2e-6)
print("Posterior agrees with conditioning a joint Gaussian.")
Posterior agrees with conditioning a joint Gaussian.

25.3 From clean-image prediction to noise prediction

Substitute \(x_0=(x_t-\sqrt{1-\bar\alpha_t}\epsilon)/\sqrt{\bar\alpha_t}\) into \(\tilde\mu_t\). The coefficient of \(\epsilon\) becomes

\[ -\frac{\beta_t}{\sqrt{\alpha_t}\sqrt{1-\bar\alpha_t}}, \]

and the coefficient of \(x_t\) simplifies to \(1/\sqrt{\alpha_t}\). Hence

\[ \tilde\mu_t=\frac1{\sqrt{\alpha_t}} \left(x_t-\frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\epsilon\right). \]

Replace \(\epsilon\) by \(\epsilon_\theta(x_t,t)\) to parameterize the model mean. This algebra assumes the clean estimate has not been clipped. In the chapter’s implementation, clipping is followed by recomputation of the mean using the two posterior coefficients.

25.4 The best squared-error prediction is a conditional mean

The chapter stated that a denoiser trained with squared error returns an average over all explanations of its input. Here is the argument, followed by the formula for the two-point dataset.

Fix one input \((x_t,t)\) and let \(m=\mathbb E[\epsilon\mid x_t]\) be the average of the noise over all pairs of clean image and noise that produce this input. For any candidate prediction \(a\),

\[ \mathbb E\big[\|\epsilon-a\|^2\mid x_t\big] =\mathbb E\big[\|\epsilon-m\|^2\mid x_t\big]+\|m-a\|^2 , \]

because the cross term \(2(m-a)^\top\mathbb E[\epsilon-m\mid x_t]\) vanishes. The first term does not depend on \(a\), and the second is smallest at \(a=m\). So the best prediction at every input is the conditional mean, and the remaining error \(\mathbb E\|\epsilon-m\|^2\) is the part of the noise that the input simply does not determine. No network can go below it. Since \(x_0\) and \(\epsilon\) are linked linearly once \(x_t\) is given, the same holds for clean-image prediction: the best \(\hat x_0\) is \(\mathbb E[x_0\mid x_t]\).

25.4.1 The two-point dataset

Let \(x_0=\pm1\) with probability one half each, and write \(a_t=\sqrt{\bar\alpha_t}\) and \(\sigma_t^2=1-\bar\alpha_t\). Given \(x_0\), the noisy value \(x_t\) is Gaussian with mean \(\pm a_t\) and variance \(\sigma_t^2\). Bayes’ rule with equal prior probabilities compares the two densities:

\[ \frac{P(x_0=+1\mid x_t)}{P(x_0=-1\mid x_t)} =\frac{\exp\!\big(-(x_t-a_t)^2/2\sigma_t^2\big)}{\exp\!\big(-(x_t+a_t)^2/2\sigma_t^2\big)} =\exp\!\left(\frac{2a_tx_t}{\sigma_t^2}\right). \]

Hence \(P(x_0=+1\mid x_t)=\operatorname{sigmoid}(2a_tx_t/\sigma_t^2)\): a logistic model, as in Lesson 2, whose slope grows as the noise shrinks. The conditional mean is the probability-weighted average of \(+1\) and \(-1\):

\[ \mathbb E[x_0\mid x_t]=2\operatorname{sigmoid}\!\left(\frac{2a_tx_t}{\sigma_t^2}\right)-1 =\tanh\!\left(\frac{\sqrt{\bar\alpha_t}\,x_t}{1-\bar\alpha_t}\right). \]

The chapter checked this formula against a simulation. The next cell checks the optimality claim instead: scaling the exact estimate up or down must increase the squared error.

g = torch.Generator().manual_seed(61)
n, t_mid = 200_000, 32
abar_mid = schedule.abar[t_mid]
clean_values = torch.where(torch.rand(n, generator=g) < 0.5, -1.0, 1.0)
noisy_values = (abar_mid.sqrt() * clean_values
                + (1 - abar_mid).sqrt() * torch.randn(n, generator=g))
exact_estimate = torch.tanh(abar_mid.sqrt() * noisy_values / (1 - abar_mid))
losses = {scale: (clean_values - scale * exact_estimate).square().mean().item()
          for scale in (0.8, 1.0, 1.2)}
for scale, value in losses.items():
    print(f"estimate scaled by {scale:.1f}: squared error {value:.4f}")
assert losses[1.0] < losses[0.8] and losses[1.0] < losses[1.2]
estimate scaled by 0.8: squared error 0.4798
estimate scaled by 1.0: squared error 0.4581
estimate scaled by 1.2: squared error 0.4798

Optional exercise. Replace the two-point dataset by Gaussian data, \(x_0\sim\mathcal N(m,v)\) in one dimension. Show that the best estimate is linear in the noisy value,

\[ \mathbb E[x_0\mid x_t]=m+\frac{\sqrt{\bar\alpha_t}\,v}{\bar\alpha_t v+1-\bar\alpha_t}\,\big(x_t-\sqrt{\bar\alpha_t}\,m\big), \]

and describe its behavior for \(\bar\alpha_t\to1\) and \(\bar\alpha_t\to0\). Which of the two limits is the “mean image”?

25.5 Noise prediction estimates a gradient: the score

Let \(q(x_t)\) be the density of noisy images at level \(t\), averaged over all clean images. Its score is the gradient of its logarithm with respect to the noisy image, \(\nabla_{x_t}\log q(x_t)\). The score points in the direction in which noisy images become more probable.

Write \(q(x_t)=\mathbb E_{x_0}\big[q(x_t\mid x_0)\big]\) and differentiate. Each Gaussian \(q(x_t\mid x_0)\) has the gradient \(-q(x_t\mid x_0)\,(x_t-\sqrt{\bar\alpha_t}x_0)/(1-\bar\alpha_t)\). Dividing by \(q(x_t)\) turns the average over \(x_0\) into a conditional expectation given \(x_t\), and \(x_t-\sqrt{\bar\alpha_t}x_0=\sqrt{1-\bar\alpha_t}\,\epsilon\). Therefore

\[ \nabla_{x_t}\log q(x_t) =-\frac{\mathbb E[\epsilon\mid x_t]}{\sqrt{1-\bar\alpha_t}} . \]

A perfectly trained noise predictor is a rescaled, sign-flipped score. Removing predicted noise moves a sample toward more probable noisy images, and the reverse process alternates such moves with fresh noise. This identity connects DDPM to score-based generative models, where it underlies continuous-time formulations of diffusion (Y. Song et al. 2021), and to an older observation that denoising and score estimation are two sides of one problem (Vincent 2011).

For the two-point dataset we know both sides exactly. Automatic differentiation computes the left side from the mixture density; the tanh formula gives the right side.

t_score = 32
abar_score = schedule.abar[t_score].double()
points = torch.linspace(-2, 2, 9, dtype=torch.float64, requires_grad=True)
# Log density of the noisy value, up to a constant: a mixture of two Gaussians.
log_density = torch.logsumexp(torch.stack([
    -(points - sign * abar_score.sqrt()) ** 2 / (2 * (1 - abar_score))
    for sign in (-1.0, 1.0)
]), dim=0)
score, = torch.autograd.grad(log_density.sum(), points)

clean_mean = torch.tanh(abar_score.sqrt() * points / (1 - abar_score))
noise_mean = (points - abar_score.sqrt() * clean_mean) / (1 - abar_score).sqrt()
rescaled = (-noise_mean / (1 - abar_score).sqrt()).detach()
torch.testing.assert_close(score, rescaled)
print("The score from autograd equals the rescaled best noise prediction.")
The score from autograd equals the rescaled best noise prediction.

25.6 Why squared noise error is related to likelihood

In logistic regression, each observation had an easily evaluated probability. A diffusion generator introduces latent noisy states:

\[ p_\theta(x_{0:T})=p(x_T)\prod_{t=1}^T p_\theta(x_{t-1}\mid x_t). \]

Obtaining \(p_\theta(x_0)\) requires integrating out all of \(x_{1:T}\). Instead, use the known forward distribution \(q(x_{1:T}\mid x_0)\) to construct an upper bound on negative log-likelihood. With the required expectations over forward states, its terms can be written as

\[ \begin{aligned} -\log p_\theta(x_0)\ \le\ & D_{\mathrm{KL}}\big(q(x_T\mid x_0)\,\|\,p(x_T)\big)\\ &+\sum_{t=2}^T\mathbb E_{q(x_t\mid x_0)} D_{\mathrm{KL}}\big(q(x_{t-1}\mid x_t,x_0)\,\|\,p_\theta(x_{t-1}\mid x_t)\big)\\ &-\mathbb E_{q(x_1\mid x_0)}\log p_\theta(x_0\mid x_1). \end{aligned} \]

\(D_{\mathrm{KL}}\) is a nonnegative measure of distributional discrepancy, zero when the distributions agree (up to sets of probability zero). The inequality follows by expressing the marginal likelihood as an expectation under \(q\) and applying Jensen’s inequality to \(-\log\). You do not need this result for the main lab.

For \(t\ge2\), choose a Gaussian reverse transition with fixed positive variance \(\sigma_t^2 I\). The part of its KL term that depends on the predicted mean is

\[ \frac{1}{2\sigma_t^2}\|\tilde\mu_t-\mu_\theta(x_t,t)\|^2 =\frac{\beta_t^2}{2\sigma_t^2\alpha_t(1-\bar\alpha_t)} \|\epsilon-\epsilon_\theta(x_t,t)\|^2. \]

This explains the connection to a weighted noise-prediction objective. The practical simple loss drops these timestep-dependent weights, averages over entries, and uses uniformly sampled timesteps including \(t=1\). It changes the relative emphasis of noise levels. The terminal prior term is independent of the network, and the \(t=1\) reconstruction term requires its own output-density specification. Our clipped deterministic last step is a sampling choice, not an implementation for reporting exact image likelihoods. Do not label the notebook’s MSE as a likelihood value.

25.7 Why a DDIM jump is consistent

The lab’s deterministic sampler moves from time \(t\) to an earlier time \(s\) by recombining its two estimates, \(x_s=\sqrt{\bar\alpha_s}\hat x_0+\sqrt{1-\bar\alpha_s}\hat\epsilon\). To see why this is reasonable, suppose the estimates were exact, \(\hat x_0=x_0\) and \(\hat\epsilon=\epsilon\). Then \(x_s=\sqrt{\bar\alpha_s}x_0+\sqrt{1-\bar\alpha_s}\epsilon\) with \(\epsilon\sim\mathcal N(0,I)\), which is precisely a draw from \(q(x_s\mid x_0)\). The jump lands on a state with the correct noise level for any pair \(s<t\), because the direct noising equation refers only to the level it produces.

Two remarks keep this honest. First, the states \(x_t\) and \(x_s\) built from one shared \(\epsilon\) have the right distribution individually. Together they are not a trajectory of the forward chain, whose increments are independent; the chapter’s forward figure made the same point. DDIM needs only the individual distributions, which is why it may skip. Second, the estimates of a real network are conditional means, not the truth. Each jump therefore incurs an error that grows with the size of the jump. How large it may become is the empirical question of the lab.

25.8 Conditioning and guidance: ask for a disk on one side

The chapter described conditional generation and classifier-free guidance in words. This experiment makes both concrete on our disks. The condition is as simple as possible: should the disk lie in the left or the right half of the image?

Predict first. With guidance weight \(w=0\) the label is ignored. What fraction of disks should then land on the requested side? What do you expect for \(w=1\), and what could a large weight cost?

25.8.1 Labels from the data, and a network with one more input

We derive the label from each training image: the sign of its brightness-weighted horizontal position. The network is the chapter’s TinyTimeUNet with one addition, an embedding of the label that is added to the time embedding. A third embedding entry stands for “no condition”.

import matplotlib.pyplot as plt
from torch import nn
from torch.nn import functional as F

from dlbook.diffusion import (
    TinyTimeUNet, image_diagnostics, make_disks, q_sample, sample_ddpm,
    time_features,
)
from dlbook.plotting import show_plot

torch.set_num_threads(1)
PAGE_WIDTH = 6.3  # figure width in inches; fits the printed page as well
train = make_disks(256, seed=7)
LEFT, RIGHT, NONE = 0, 1, 2


def horizontal_center(images):
    """Brightness-weighted mean column position in [-1, 1]; negative is left."""
    brightness = ((images + 1) / 2).clamp(0, 1)[:, 0]  # (N, H, W)
    columns = torch.linspace(-1, 1, images.shape[-1])
    total = brightness.sum((1, 2)).clamp_min(1e-6)
    return (brightness.sum(1) * columns).sum(1) / total


labels = (horizontal_center(train) > 0).long()
print(f"Training images labeled RIGHT: {labels.float().mean():.1%}")


class LabelTimeUNet(TinyTimeUNet):
    """The chapter's denoiser with an additional label input."""
    def __init__(self, classes=2, **kwargs):
        super().__init__(**kwargs)
        self.label = nn.Embedding(classes + 1, 32)  # the extra entry is NONE

    def forward(self, x, t, c):
        e = self.embedding(time_features(t, self.steps)) + self.label(c)
        s1 = self.enc1(x, e)
        s2 = self.enc2(F.avg_pool2d(s1, 2), e)
        h = self.middle(F.avg_pool2d(s2, 2), e)
        h = F.interpolate(h, size=s2.shape[-2:], mode="nearest")
        h = self.dec2(torch.cat((h, s2), 1), e)
        h = F.interpolate(h, size=s1.shape[-2:], mode="nearest")
        h = self.dec1(torch.cat((h, s1), 1), e)
        return self.output(h)
Training images labeled RIGHT: 48.8%

25.8.2 Train one network for both tasks

Training is Algorithm 1 of the chapter with two changes. Each image is presented with its label, and for about one example in five the label is replaced by NONE. The same weights thereby learn a conditional and an unconditional noise prediction.

torch.manual_seed(17)
conditional = LabelTimeUNet(steps=64)
g = torch.Generator().manual_seed(23)
optimizer = torch.optim.Adam(conditional.parameters(), lr=0.002)
conditional.train()
for _ in range(900):
    index = torch.randint(len(train), (32,), generator=g)
    x0, c = train[index], labels[index].clone()
    c[torch.rand(32, generator=g) < 0.2] = NONE  # hide the label
    t = torch.randint(1, 65, (32,), generator=g)
    noise = torch.randn(x0.shape, generator=g)
    prediction = conditional(q_sample(x0, t, noise, schedule), t, c)
    loss = F.mse_loss(prediction, noise)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
print(f"Final minibatch noise MSE: {loss.item():.4f}")
Final minibatch noise MSE: 0.0219

25.8.3 Guide the sampler

Guidance needs no new sampler. We wrap the conditional network so that it looks like an ordinary noise predictor \(\epsilon(x_t,t)\) and hand it to the DDPM sampler from the chapter. The wrapper evaluates the network without and with the label and extrapolates:

\[ \tilde\epsilon=\epsilon_\theta(x_t,t,\varnothing) +w\,\big(\epsilon_\theta(x_t,t,c)-\epsilon_\theta(x_t,t,\varnothing)\big). \]

class Guided(nn.Module):
    """Presents a conditional network to a sampler as a noise predictor."""
    def __init__(self, network, label, weight):
        super().__init__()
        self.network, self.label, self.weight = network, label, weight

    def forward(self, x, t):
        unconditional = self.network(x, t, torch.full((len(x),), NONE))
        if self.weight == 0:
            return unconditional
        with_label = self.network(x, t, torch.full((len(x),), self.label))
        return unconditional + self.weight * (with_label - unconditional)


g_start = torch.Generator().manual_seed(37)
initial = torch.randn((64, 1, 16, 16), generator=g_start)
settings = [(0, RIGHT), (1, LEFT), (1, RIGHT), (3, LEFT), (3, RIGHT)]
runs = {}
for weight, label in settings:
    guided = Guided(conditional, label, weight)
    runs[(weight, label)] = sample_ddpm(guided, initial, schedule, seed=31)

print("Weight  Side   On requested side  Spread of position  "
      "Bright area  Empty")
for (weight, label), images in runs.items():
    area, _ = image_diagnostics(images)
    center = horizontal_center(images)[area > 0]
    on_side = ((center > 0).long() == label).float().mean()
    name = "any" if weight == 0 else ("left" if label == LEFT else "right")
    empty = (area == 0).sum().item()
    print(f"  {weight}     {name:5s}       {on_side:6.1%}            "
          f"{center.std():.3f}            {area.mean():.3f}       {empty}")
Weight  Side   On requested side  Spread of position  Bright area  Empty
  0     any          48.4%            0.250            0.077       0
  1     left         90.6%            0.165            0.066       0
  1     right        95.3%            0.204            0.085       0
  3     left        100.0%            0.075            0.058       0
  3     right       100.0%            0.085            0.098       0

For the row with weight zero the label is ignored; its “on requested side” entry reports how often an unguided disk happens to lie on the right. The spread is the standard deviation of the horizontal position among non-empty images.

names = ["w = 0", "w = 1, left", "w = 1, right", "w = 3, left", "w = 3, right"]
fig, axes = plt.subplots(5, 8, figsize=(PAGE_WIDTH, 4.1))
for row, (key, name) in enumerate(zip(settings, names)):
    for col in range(8):
        axes[row, col].imshow(runs[key][col, 0], cmap="gray", vmin=-1, vmax=1)
        axes[row, col].set_xticks([])
        axes[row, col].set_yticks([])
    axes[row, 0].set_ylabel(name, fontsize=7)
fig.tight_layout()
show_plot(fig)

Five rows of eight generated disks that share their starting noise by column. Without a label the disks lie on either side. With the label left or right at weight one, most disks lie on the requested side. At weight three all disks lie on the requested side and their positions are more alike.

Five rows of eight generated disks that share their starting noise by column. Without a label the disks lie on either side. With the label left or right at weight one, most disks lie on the requested side. At weight three all disks lie on the requested side and their positions are more alike.

Figure 25.1: The first eight draws under five sampling settings of one conditional network. Each column shares its starting noise and reverse-noise draws; only the requested side and the guidance weight differ.

25.8.4 Interpret with care

In our reference run, about half of the unguided disks lie on the right, as they should when the label is ignored. With the label at \(w=1\) roughly nine in ten land on the requested side. At \(w=3\) all of them do, but the spread of their positions shrinks to less than half of its value at \(w=1\), and the bright area drifts away from that of the data. Stronger guidance buys adherence to the condition and pays with variety and, eventually, with fidelity. That is the trade-off behind the “guidance scale” setting of text-to-image systems (Ho and Salimans 2022).

The limits are the usual ones. This is one training seed, one batch of 64 starts, and a condition with two values. The network trained for 900 updates and is itself imperfect, so part of the effect of guidance here is the correction of a weak conditional model. Treat the numbers as an illustration of the mechanism.

Questions.

  1. Why can the guidance weight be changed without retraining? Which of the three dials from the chapter does it turn?
  2. Each guided step evaluates the network twice. Restate the cost of the \(w=3\) runs in network evaluations per batch.
  3. The training data contain disks close to the vertical center line. How should a perfect conditional model treat them, and what does strong guidance do instead?
  4. Design a control that separates the effect of the label from the effect of the weight: which two rows of the table would you compare, and what is held fixed?

25.9 Sources

The model formulation and objective originate in Ho et al. (2020); these calculations spell out the Gaussian algebra for this course. The lab’s shorter deterministic sampling paths use J. Song et al. (2021). The cosine schedule is from Nichol and Dhariwal (2021), the score identity is discussed in Vincent (2011) and Y. Song et al. (2021), and classifier-free guidance is from Ho and Salimans (2022). No external implementation or figure is copied.