Take a Heun (2nd order) step of the diffusion ODE

Why it matters The Heun sampler from Karras et al. (EDM) gets good images in about 35 denoiser calls.

Karras-style samplers solve dx/dsigma = (x - D(x, sigma)) / sigma, where D is the denoiser. Heun's method adds a correction step.

Write heun_step(x, sigma, sigma_next, denoise). d = (x - denoise(x, sigma)) / sigma; Euler proposal x_e = x + (sigma_next - sigma) * d. If sigma_next == 0 return x_e. Otherwise d2 = (x_e - denoise(x_e, sigma_next)) / sigma_next and return x + (sigma_next - sigma) * (d + d2) / 2.

Signaturedef heun_step(x, sigma, sigma_next, denoise)

Example

with a denoiser that always returns 0, d = x / sigma, so stepping from sigma 2 to 1 scales x by 1/2 for Euler and also for Heun: heun_step([4], 2, 1, ...) is [2].

Understand the idea

Sampling a Karras style diffusion model means solving an ODE in sigma: the slope at x is d = (x - D(x, sigma)) / sigma, where D is the denoiser's clean guess. Euler's method takes one step along the starting slope. Heun's method then measures the slope again at the Euler landing point and steps along the average of the two slopes. Worked example: a denoiser that returns 0.5 * x, x = 4, sigma 2, sigma_next 1. d = (4 - 2) / 2 = 1. Euler: x_e = 4 + (1 - 2) * 1 = 3. Slope at x_e: d2 = (3 - 1.5) / 1 = 1.5. Heun: 4 + (1 - 2) * (1 + 1.5) / 2 = 4 - 1.25 = 2.75. Rule: d = (x - denoise(x, sigma)) / sigma; x_e = x + (sigma_next - sigma) * d; if sigma_next == 0 return x_e, since the slope at sigma 0 is undefined; else d2 = (x_e - denoise(x_e, sigma_next)) / sigma_next and return x + (sigma_next - sigma) * (d + d2) / 2. Used in: the Heun sampler in k-diffusion and EDM style samplers.

Shapes and data flow

x, sigma -> D(x) -> slope d
Euler: x_e = x + (s' - s) d
Heun: slope d2 at x_e -> average (d + d2) / 2
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: exampleheun_step([4.0], 2.0, 1.0, lambda x, s: np.zeros_like(x))
  • Sample 2: gaussian denoiserheun_step(_x, 2.0, 1.2, _den)