24  Lab 7: How Many Denoising Steps Do We Need?

Train once, change the sampler, inspect quality and cost

24.1 Lab contract

The concepts chapter separated three dials: training quality, the sampling rule, and sampling cost. This notebook turns the third one. It runs independently in a fresh kernel: it retrains the chapter’s 1200-update model with the packaged helpers, then freezes the weights. Your question is: how does reducing the number of network evaluations change the generated images? The main experiment changes one factor, the number of steps of a deterministic DDIM sampler.

Try → understand → improve: watch a tempting shortcut fail, find the equation it violates, implement and verify a sampler that is valid for jumps, then run a controlled comparison of sampling budgets.

Deliverable: the configuration, a verified sampler, unselected sample grids, a table of diagnostics, and a 150–300 word interpretation. The default run needs no files from the concepts notebook, no external data, and no pretrained weights. Allow about 3 hours including explanations and extensions; executing the default cells takes well under a minute.

ImportantPredict before running

Which change do you expect first as the sampling budget falls: speckle, a different size of the shapes, less diversity, or little visible change? Write down your prediction and your reason. Keep it even if the result surprises you.

24.2 Rebuild a reproducible training problem

The helpers in dlbook.diffusion package the mechanisms taught in the concepts chapter. We use the same image scaling, cosine schedule, architecture, optimizer, seeds, and update budget. Validation images never enter fit_noise_model.

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

from dlbook.diffusion import (
    TinyTimeUNet, cosine_schedule, make_disks, fit_noise_model,
    q_sample, predict_clean, posterior, denoising_errors, image_diagnostics,
    sample_ddpm, sample_ddim as packaged_ddim,
)
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
CONFIG = dict(steps=64, updates=1200, batch_size=32, width=8,
              train_seed=7, valid_seed=8, init_seed=17, update_seed=19,
              sample_seed=37, reverse_seed=31, samples=64)
for key, value in CONFIG.items():
    print(f"{key:>12s}: {value}")
train = make_disks(256, seed=CONFIG["train_seed"])
valid = make_disks(64, seed=CONFIG["valid_seed"])
schedule = cosine_schedule(CONFIG["steps"])
torch.manual_seed(CONFIG["init_seed"])
model = TinyTimeUNet(steps=CONFIG["steps"], width=CONFIG["width"])
       steps: 64
     updates: 1200
  batch_size: 32
       width: 8
  train_seed: 7
  valid_seed: 8
   init_seed: 17
 update_seed: 19
 sample_seed: 37
reverse_seed: 31
     samples: 64

24.2.1 Check the forward and denoising interfaces

Before spending the training budget, confirm that the pieces fit together: the shapes, the oracle inversion of the direct noising equation, and the flow of gradients into the time embedding.

g_check = torch.Generator().manual_seed(43)
clean = train[:4]
t = torch.tensor([1, 16, 32, 64])
noise = torch.randn(clean.shape, generator=g_check)
noisy = q_sample(clean, t, noise, schedule)
recovered = predict_clean(noisy, t, noise, schedule, clip=False)
# At large t, dividing by the small signal multiplier magnifies rounding error.
torch.testing.assert_close(recovered, clean, atol=2e-4, rtol=2e-4)
assert model(noisy, t).shape == noise.shape
F.mse_loss(model(noisy, t), noise).backward()
assert model.embedding[0].weight.grad.abs().sum() > 0
assert model.enc1.time.weight.grad.abs().sum() > 0
model.zero_grad(set_to_none=True)
print("Shape, time-gradient, and oracle-reconstruction checks passed.")
Shape, time-gradient, and oracle-reconstruction checks passed.

Explain — 5 minutes. Given the true noise, the oracle check recovers the clean image up to rounding error, even at \(t=64\). Why does this not show that a trained network can recover a clean image from pure noise in one step? Use the conditional mean from the chapter in your answer.

24.2.2 Train once, then freeze

history = fit_noise_model(
    model, train, schedule, updates=CONFIG["updates"],
    batch_size=CONFIG["batch_size"], seed=CONFIG["update_seed"],
)
fixed_times = (1, 16, 32, 48, 64)
errors = denoising_errors(model, valid, schedule, times=fixed_times)
print("Validation noise MSE by timestep:")
for step, mse in zip(fixed_times, errors.mean(1)):
    print(f"  t={step:2d}: {mse:.4f}")
# This in-memory checkpoint is fixed for all subsequent experiments.
checkpoint = {key: value.detach().clone()
              for key, value in model.state_dict().items()}
g_start = torch.Generator().manual_seed(CONFIG["sample_seed"])
initial = torch.randn((CONFIG["samples"], 1, 16, 16), generator=g_start)
Validation noise MSE by timestep:
  t= 1: 0.0793
  t=16: 0.0228
  t=32: 0.0188
  t=48: 0.0130
  t=64: 0.0014

fit_noise_model draws its random numbers in the same order as the chapter’s training loop. With the same seeds it therefore reproduces the chapter’s 1200-update weights, and the validation errors above should match the row for 1200 updates in the chapter.

24.3 Try: skip timesteps in an unchanged DDPM loop

DDPM sampling calls the network 64 times. The obvious way to save work is to visit only every fourth timestep and leave the update as it is. Each update below is a correct DDPM step from \(t\) to \(t-1\); we merely apply it at \(t=64,60,56,\ldots,4\).

@torch.no_grad()
def naive_skip(model, initial_noise, schedule, stride, seed):
    """DDPM updates at every `stride`-th time label. Deliberately flawed."""
    g = torch.Generator().manual_seed(seed)
    model.eval()
    x = initial_noise.clone()
    labels = list(range(schedule.steps, 0, -stride))
    for position, step in enumerate(labels):
        t = torch.full((len(x),), step, dtype=torch.long)
        clean_estimate = predict_clean(x, t, model(x, t), schedule)
        # Mean and variance of the adjacent step from t to t - 1.
        mean, variance = posterior(x, t, clean_estimate, schedule)
        x = mean
        if position < len(labels) - 1:
            x = x + variance.sqrt() * torch.randn(x.shape, generator=g)
    return x


seed = CONFIG["reverse_seed"]
reference_ddpm = sample_ddpm(model, initial, schedule, seed=seed)
shortcut = naive_skip(model, initial, schedule, stride=4, seed=seed)
for name, images in [("DDPM, 64 evaluations", reference_ddpm),
                     ("Naive skip, 16 evaluations", shortcut)]:
    _, variation = image_diagnostics(images)
    print(f"{name:27s} range [{images.min():+.2f}, {images.max():+.2f}]"
          f"  neighbor variation {variation.mean():.3f}")
DDPM, 64 evaluations        range [-1.00, +1.00]  neighbor variation 0.039
Naive skip, 16 evaluations  range [-1.84, +1.66]  neighbor variation 0.239
fig, axes = plt.subplots(2, 8, figsize=(PAGE_WIDTH, 1.9))
rows = [("DDPM\n64 NFE", reference_ddpm), ("Naive skip\n16 NFE", shortcut)]
for row, (name, images) in enumerate(rows):
    for col in range(8):
        axes[row, col].imshow(images[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=8)
fig.tight_layout()
show_plot(fig)

Two rows of eight images from the same starting noise. The first row, from full DDPM sampling, shows clean disks. The second row, from the shortcut, shows heavy speckle with at most a faint brighter region.

Two rows of eight images from the same starting noise. The first row, from full DDPM sampling, shows clean disks. The second row, from the shortcut, shows heavy speckle with at most a faint brighter region.

Figure 24.1: The same eight starting noises under full DDPM sampling and under the shortcut that applies unchanged DDPM updates at every fourth time label. Both use the same frozen weights.

Diagnose — 10 minutes. The network and the starting noise are the same in both rows, so the difference comes from the loop. After the first update at label 64, which noise level does the state actually have? Which label does the loop attach to it next? Write down the first time label at which the image and its label disagree, and explain why the disagreement grows.

The coefficients of a DDPM update describe one adjacent step. After the update the state has the noise level of \(t-1\), yet the shortcut treats it as \(t-4\). The network is asked to remove the small amount of noise appropriate for a cleaner image than it received, and the loop ends while most of the noise is still present.

A second tempting change is to build a new 16-step schedule for sampling. That alters the relation between the label \(t\) and the noise level that the network learned. We want to keep the training schedule and evaluate the network at a subset of its original timesteps.

Checkpoint. For this 64-step model, write the first two time labels you would use in a four-evaluation sampler. Which two signal levels must appear in the update that connects them?

24.4 Understand: a deterministic DDIM jump

Denoising diffusion implicit models (DDIM) are a family of samplers for the same noise-prediction network (Song et al. 2021). We use the deterministic member, usually written \(\eta=0\). Its randomness comes entirely from the starting noise.

At a selected time \(t\), estimate \(\hat x_0\) as before. For an earlier selected time \(s<t\), recombine the clean estimate and the noise estimate using the signal and noise levels of \(s\):

\[ \hat x_0=\frac{x_t-\sqrt{1-\bar\alpha_t}\,\epsilon_\theta(x_t,t)}{\sqrt{\bar\alpha_t}}, \qquad x_s=\sqrt{\bar\alpha_s}\,\hat x_0+\sqrt{1-\bar\alpha_s}\,\hat\epsilon. \]

Without clipping, \(\hat\epsilon=\epsilon_\theta(x_t,t)\). As in the chapter, we clip \(\hat x_0\) to \([-1,1]\). To keep the two parts consistent with the current state, recompute the noise estimate after clipping:

\[ \hat\epsilon=\frac{x_t-\sqrt{\bar\alpha_t}\,\hat x_0}{\sqrt{1-\bar\alpha_t}} . \]

At \(s=0\) the signal level is \(\bar\alpha_0=1\) and the result is \(\hat x_0\). Note that this is a different sampling rule from DDPM even when it visits every timestep. Neither skipping labels in an unchanged DDPM loop nor changing the trained schedule implements this equation.

@torch.no_grad()
def sample_ddim(model, initial_noise, schedule, evaluations):
    if not 1 <= evaluations <= schedule.steps:
        raise ValueError("Choose between 1 and T evaluations.")
    # T is always the first label. The clean endpoint zero is appended below.
    grid = torch.linspace(schedule.steps, 1, evaluations).round().long()
    grid = grid.tolist()
    model.eval()
    x = initial_noise.clone()
    for step, earlier in zip(grid, grid[1:] + [0]):
        t = torch.full((len(x),), step, dtype=torch.long)
        a, b = schedule.abar[step], schedule.abar[earlier]
        predicted_noise = model(x, t)
        x0_hat = (x - (1 - a).sqrt() * predicted_noise) / a.sqrt()
        x0_hat = x0_hat.clamp(-1, 1)
        consistent_noise = (x - a.sqrt() * x0_hat) / (1 - a).sqrt()
        x = b.sqrt() * x0_hat + (1 - b).sqrt() * consistent_noise
    return x


starts = initial[:4]
example = sample_ddim(model, starts, schedule, evaluations=4)
# Same result as the packaged sampler, and the same result when repeated.
packaged = packaged_ddim(model, starts, schedule, evaluations=4)
repeated = sample_ddim(model, starts, schedule, evaluations=4)
torch.testing.assert_close(example, packaged)
torch.testing.assert_close(example, repeated)
assert torch.isfinite(example).all() and example.shape == starts.shape
grid = torch.linspace(64, 1, 4).round().long().tolist()
print("Four-evaluation grid:", grid, "then 0")
Four-evaluation grid: [64, 43, 22, 1] then 0

24.4.1 Verify the sampler before trusting pictures

A finite output with the right shape proves little, as the shortcut above also produced one. Test the sampler with an oracle in place of the network. The oracle is told one clean image and returns exactly the noise that explains the current state. A correct sampler must then return that image for any starting noise and any number of evaluations, and it must call the network exactly as often as requested.

class Oracle(nn.Module):
    """Not a learned model: knows one clean image, records its time labels."""
    def __init__(self, clean, schedule):
        super().__init__()
        self.clean, self.schedule, self.labels = clean, schedule, []

    def forward(self, x, t):
        self.labels.append(t[0].item())
        a = self.schedule.abar[t].reshape(-1, 1, 1, 1)
        return (x - a.sqrt() * self.clean) / (1 - a).sqrt()


target = valid[:1]
for evaluations in (64, 16, 4, 1):
    oracle = Oracle(target, schedule)
    result = sample_ddim(oracle, starts, schedule, evaluations=evaluations)
    deviation = (result - target).abs().max()
    # One jump from t = 64 divides by a tiny signal multiplier,
    # which magnifies rounding error.
    assert deviation < 2e-3
    assert len(oracle.labels) == evaluations
    assert oracle.labels[0] == CONFIG["steps"]
    print(f"{evaluations:2d} evaluations: deviation {deviation:.1e}; "
          f"labels start {oracle.labels[:3]}, end {oracle.labels[-1]}")
64 evaluations: deviation 3.0e-09; labels start [64, 63, 62], end 1
16 evaluations: deviation 3.0e-09; labels start [64, 60, 56], end 1
 4 evaluations: deviation 3.0e-09; labels start [64, 43, 22], end 1
 1 evaluations: deviation 1.5e-04; labels start [64], end 64

Explain — 5 minutes. With the oracle, even a single evaluation recovers the image up to rounding error. Why can a trained network not do the same? Which property of its prediction at \(t=64\) differs from the oracle’s?

24.5 Improve: a controlled sampling-cost experiment

Field Predeclared choice
Hypothesis A moderate reduction may preserve visible structure; an aggressive reduction may change size, shape, or smoothness.
Independent variable DDIM network evaluations: 64, 16, 4
Fixed controls One checkpoint, the original 64-step schedule, 64 identical Gaussian starts, the deterministic update, clipping of the clean estimate
Cost measure Network evaluations per generated batch (NFE)
Distribution diagnostics Bright-area mean and spread; mean absolute difference between neighboring pixels
Paired diagnostic Euclidean distance between each image and the 64-evaluation image from the same start
Visual check The first 16 draws in their original order, including all failures
Repetitions Default: one training seed and one batch of 64 starts; extension: three training seeds
Stopping rule Exactly 1200 optimizer updates; no selection by looking at samples
budgets = (64, 16, 4)
samples = {k: sample_ddim(model, initial, schedule, evaluations=k)
           for k in budgets}
for key, value in model.state_dict().items():
    assert torch.equal(value, checkpoint[key]), "Sampling changed the weights."

print("Group       NFE  Bright area, mean ± SD  "
      "Neighbor variation  Change from 64")
groups = [("Validation", valid, "--")]
groups += [(f"DDIM {k}", samples[k], str(k)) for k in budgets]
for name, images, nfe in groups:
    area, variation = image_diagnostics(images)
    if nfe in ("--", "64"):
        change = "--"
    else:  # median distance to the 64-evaluation image from the same start
        distance = (images - samples[64]).flatten(1).norm(dim=1)
        change = f"{distance.median():.2f}"
    spread = area.std(unbiased=False)
    print(f"{name:11s} {nfe:>3s}     {area.mean():.4f} ± {spread:.4f}"
          f"          {variation.mean():.4f}          {change:>5s}")
Group       NFE  Bright area, mean ± SD  Neighbor variation  Change from 64
Validation   --     0.0679 ± 0.0199          0.0384             --
DDIM 64      64     0.0831 ± 0.0362          0.0416             --
DDIM 16      16     0.0849 ± 0.0363          0.0420           0.45
DDIM 4        4     0.0944 ± 0.0479          0.0526           2.99

Bright area is the fraction of pixels above mid-gray (brightness above \(0.5\), equivalently \(x>0\)). Neighbor variation averages the absolute brightness differences between horizontally and vertically adjacent pixels; the helper computes both in brightness units \([0,1]\). An all-black image scores zero on both, so neither should simply be minimized. Compare their distributions with those of validation images and inspect the samples.

The last column uses the fact that deterministic DDIM maps a starting noise to one image. It measures how far the result moves when the budget shrinks. The 64-evaluation image serves as a reference point, not as ground truth: a small change means the cheaper sampler reproduces the expensive one, not that either image is correct.

fig, axes = plt.subplots(6, 8, figsize=(PAGE_WIDTH, 4.9))
for half in range(2):  # two blocks of eight starts, each at all three budgets
    for position, k in enumerate(budgets):
        row = 3 * half + position
        for col in range(8):
            image = samples[k][8 * half + col, 0]
            axes[row, col].imshow(image, cmap="gray", vmin=-1, vmax=1)
            axes[row, col].set_xticks([])
            axes[row, col].set_yticks([])
        axes[row, 0].set_ylabel(f"{k} NFE", fontsize=8)
fig.tight_layout()
show_plot(fig)

Six rows of eight generated images in two blocks of three rows. Within a block, the rows show 64, 16, and 4 network evaluations for the same eight starting noises, so each column compares one start across budgets.

Six rows of eight generated images in two blocks of three rows. Within a block, the rows show 64, 16, and 4 network evaluations for the same eight starting noises, so each column compares one start across budgets.

Figure 24.2: The first 16 Gaussian starts at three DDIM budgets. Rows 1–3 show starts 1–8 with 64, 16, and 4 evaluations; rows 4–6 show starts 9–16. All runs use the same trained weights and training schedule, and images in the same column of a block share their starting noise.
fig, axes = plt.subplots(1, 2, figsize=(PAGE_WIDTH, 2.9))
for name, images, _ in groups:
    for ax, values in zip(axes, image_diagnostics(images)):
        fraction = torch.arange(1, len(values) + 1) / len(values)
        ax.step(values.sort().values, fraction, where="post", label=name)
axes[0].set(xlabel="bright-area fraction",
            ylabel="fraction of images at or below x")
axes[1].set(xlabel="mean neighbor variation")
axes[1].legend(fontsize=7)
fig.tight_layout()
show_plot(fig)

Two cumulative distribution plots compare validation images with DDIM samples made with 64, 16, and 4 evaluations: one for the bright-area fraction and one for the mean variation between neighboring pixels.

Two cumulative distribution plots compare validation images with DDIM samples made with 64, 16, and 4 evaluations: one for the bright-area fraction and one for the mean variation between neighboring pixels.

Figure 24.3: Bright-area and neighbor-variation distributions for 64 validation images and 64 draws per DDIM budget. Agreement on two summaries is useful evidence but cannot certify image quality.

These are empirical cumulative distribution curves: at horizontal value \(a\), the vertical axis gives the fraction of images whose diagnostic is at most \(a\). A curve shifted to the right of the validation curve means larger shapes or rougher images than in the data; a curve shifted to the left means smaller or smoother ones.

Interpret — 15 minutes. Report one gain in cost, one observed change (or lack of change), and one remaining difference from the validation data. A 16-evaluation run uses a quarter of the network calls of a 64-evaluation run; this does not promise a fourfold wall-clock speedup. If two budgets give nearly the same images and curves, say so and do not invent a quality loss. A small, easy dataset may tolerate fewer steps than a realistic one, and one batch of 64 draws cannot support universal conclusions.

Compare the first figure of this lab with the last ones. The shortcut and DDIM both used 16 evaluations of the same network. What differed was the update rule.

The validation set and these samples are development evidence. After selecting a configuration, generate a fresh reference set with make_disks(256, seed=101) and fresh sampling starts with seed 103 for one final assessment. If you then make further choices, call this validation again and reserve another final assessment.

24.6 Exercises

24.6.1 Core: demonstrate individual understanding

  1. Annotate every tensor shape in one training update. Mark the three independent random choices.
  2. Explain why changing the timestep label without changing the image’s noise level is a silent error: which checks still pass?
  3. Report the DDIM comparison without changing training. Include the complete configuration and all prescribed draws.
  4. Explain why a validation denoising score cannot choose a sampling budget by itself.

24.6.2 Mathematics bridge: recover the coefficients

Read the additional material. Verify the two-step variance identity, then derive one coefficient of the reverse conditional. You may work pixel by pixel before writing a vector expression. Show why its variance is zero at the clean endpoint.

24.6.3 Coding bridge: break the sampler, then catch it

In a copy of sample_ddim, replace schedule.abar[earlier] by schedule.abar[step - 1]. Rerun the oracle check. Three of the four budgets still pass. Explain why the final jump hides the error at 16 and 4 evaluations, why 64 evaluations can never expose it, and why the single-evaluation run does. Then write a second check that catches the error at 16 and 4 evaluations. Use a network that returns the same constant noise value everywhere, switch clipping off, and show that the implied clean estimate must stay the same along a correctly respaced path. The packaged tests in tests/test_diffusion.py illustrate both kinds of check without training anything.

24.6.4 Controlled extension: does an undertrained model tolerate fewer steps?

Only after the fixed-checkpoint comparison, retrain with 600 instead of 1200 updates. Keep the data, initialization, optimizer, schedule, and evaluation draws fixed, and repeat the 64/16/4 comparison. Count empty images at each budget for both checkpoints. Report this as a separate experiment about training quality: it changes a different dial than the sampling budget. To report variability, repeat the complete experiment with at least three training seeds.

24.6.5 Stretch: remove time information

Train a second model that replaces the time features with zeros, using the same initialization and update budget. Predict which noise levels will suffer. Compare denoising errors by timestep as well as generated samples. The ablation tests access to time information; it does not show that one particular embedding is optimal.

24.7 Submission

Include the notebook, seeds and software versions, the interface and oracle checks, NFE and diagnostics, unselected sample grids, and your interpretation. Identify what changed in the sampler and what remained fixed in training. End with one limitation and one follow-up experiment that could challenge your conclusion.