Run a deterministic DDIM sampler over a strided timestep subsequence

DDIM lets a model trained with many diffusion steps sample in far fewer by jumping between a subsequence of timesteps. With eta = 0 each jump is deterministic: predict the clean sample, then re-noise it to the next (smaller) noise level along the predicted noise direction.

Write ddim_sample(x_T, alpha_bar, timesteps, eps_fn, clip).
- alpha_bar: full schedule array, alpha_bar[t] for t = 0..T-1.
- timesteps: strictly decreasing list of ints to visit, e.g. [999, 749, 499, 249, 0].
- eps_fn(x, t): returns the model's noise prediction (same shape as x).
For each position i with t = timesteps[i]:
1. a = alpha_bar[t]. a_prev = alpha_bar[timesteps[i + 1]] if there is a next timestep, else 1.0.
2. eps = eps_fn(x, t); x0 = (x - sqrt(1 - a) * eps) / sqrt(a).
3. If clip is True: x0 = clip(x0, -1, 1), then recompute eps = (x - sqrt(a) * x0) / sqrt(1 - a) so the direction matches the clipped x0.
4. x = sqrt(a_prev) * x0 + sqrt(1 - a_prev) * eps.
Return the final x as a NumPy float array. With the final a_prev = 1.0, the result equals the last predicted x0.

Signaturedef ddim_sample(x_T, alpha_bar, timesteps, eps_fn, clip)

Example

alpha_bar = [0.9, 0.5], timesteps [1, 0], eps_fn returns zeros, x_T = [1.0]. Step 1: x0 = 1 / sqrt(0.5), x = sqrt(0.9) * x0 = 1.3416... Step 2: x0 = x / sqrt(0.9) = 1.4142..., returned.

Understand the idea

DDIM samples from a diffusion model in far fewer steps by jumping along a short list of timesteps. Each deterministic jump does two things: estimate the clean sample x0 from the current noisy x and the predicted noise, then place that x0 at the next, lower noise level using the same noise direction. Worked example: alpha_bar = [0.8, 0.4], timesteps [1, 0], the model always predicts noise 0.5, x_T = [1.0]. Step t = 1: a = 0.4, a_prev = 0.8. x0 = (1 - sqrt(0.6) * 0.5) / sqrt(0.4) = (1 - 0.3873) / 0.6325 = 0.9688. x = sqrt(0.8) * 0.9688 + sqrt(0.2) * 0.5 = 0.8665 + 0.2236 = 1.0901. Step t = 0: a = 0.8, a_prev = 1.0. x0 = (1.0901 - 0.2236) / 0.8944 = 0.9688, returned. Rule: x0 = (x - sqrt(1 - a) * eps) / sqrt(a); optionally clip x0 to [-1, 1] and recompute eps = (x - sqrt(a) * x0) / sqrt(1 - a); x = sqrt(a_prev) * x0 + sqrt(1 - a_prev) * eps, with a_prev = 1 after the last step. Take a_prev from the next listed timestep, not t - 1. A standard fast image sampler.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: worked exampleddim_sample([1.0], [0.9, 0.5], [1, 0], _zero, False)
  • Sample 2: 5 strided stepsddim_sample(_x, _ab, [999, 749, 499, 249, 0], _eps, False)