Algorithm Search⌘K

Algorithmresearch

Diffusion posterior sampling

Also called DPS.

Sample from the posterior of an inverse problem by guiding each reverse step of a trained diffusion model with an approximate likelihood gradient.

Time
O(N (a + g)) worst
Space
O(n + m) extra
Where
N = the number of reverse steps; a = the cost of one call to A plus one call to its adjoint; g = the cost of one call to the score network plus one vector-Jacobian product through it (outside this page); m = the number of data values; n = the signal length
Properties
randomizednot exactiterativelearnedmatrix free
Origin
Hyungjin Chung, Jeongsol Kim, Michael T. McCann, Marc L. Klasky, Jong Chul Ye, 2023

Diffusion posterior sampling (DPS) draws approximate samples from the posterior p(x∣y)p(x \mid y) of an inverse problem y=A(x)+ny = A(x) + n, using a diffusion model trained only on clean signals. A diffusion model generates a signal by starting from noise and running NN reverse steps, each guided by a learned score s(x,t)≈∇log⁡pt(x)s(x, t) \approx \nabla\log p_t(x). DPS adds to each reverse step a gradient step on ∥y−A(x^0)∥2\|y - A(\hat x_0)\|^2, where x^0\hat x_0 is the denoised estimate of the current state by Tweedie's formula. Chung, Kim, McCann, Klasky and Ye (2023) introduced it. It needs no retraining for a new forward model and works for nonlinear AA, but it is an approximation: even with the exact score it does not sample the true posterior, as the example below shows in closed form.

In plain words

A diffusion model learns to remove a little noise from an image, many times in a row. If you start from pure noise and keep removing noise, a clean, realistic image slowly appears.

To reconstruct a measured image, DPS does the same, with one change. After each noise removal step, it makes a quick guess of what the final clean image will be. It takes the measurements of that guess and compares them with the real measurements. Then it pushes the current noisy image a little in the direction that makes the guess fit the measurements better. At the end you get a realistic image that also agrees with the data. Running it again with new random noise gives a different image, which shows how uncertain the answer is.

The problem

The model is y=A(x0)+ny = A(x_0) + n with n∼N(0,σ2I)n \sim N(0, \sigma^2 I), where AA may be linear or a differentiable nonlinear map. The prior is the distribution of training signals, known only through a score network. The forward diffusion is xt=αˉt x0+1−αˉt εx_t = \sqrt{\bar\alpha_t}\,x_0 + \sqrt{1 - \bar\alpha_t}\,\varepsilon with αˉt=∏s≤t(1−βs)\bar\alpha_t = \prod_{s \le t}(1 - \beta_s) for a schedule β1,…,βN\beta_1, \ldots, \beta_N, and αt=1−βt\alpha_t = 1 - \beta_t, αˉ0=1\bar\alpha_0 = 1.

The input is yy, functions for AA and the adjoint of its derivative (ATA^T for linear AA), a score function s(x,t)s(x, t) with its vector-Jacobian product v↦Js(x,t)Tvv \mapsto J_s(x, t)^Tv, the schedule, and step sizes. The output is one random signal x0x_0. The goal is that x0x_0 is a draw from p(x0∣y)p(x_0 \mid y); DPS reaches this only approximately.

The algorithm

The posterior score is ∇log⁡pt(xt∣y)=∇log⁡pt(xt)+∇log⁡p(y∣xt)\nabla\log p_t(x_t \mid y) = \nabla\log p_t(x_t) + \nabla\log p(y \mid x_t). The first term is the score network. The second is intractable, because p(y∣xt)=E[p(y∣x0)∣xt]p(y \mid x_t) = E[p(y \mid x_0) \mid x_t] is an integral over all clean signals. DPS replaces it by p(y∣x^0)p(y \mid \hat x_0), with x^0=E[x0∣xt]\hat x_0 = E[x_0 \mid x_t] from Tweedie's formula. This is Algorithm 1 of Chung et al., with steps indexed t=N,…,1t = N, \ldots, 1.

  1. DPS(y, A, A^T, s, J_s^T, ᾱ_1..ᾱ_N, ζ)
  2. 1x ← a draw from N(0, I)
  3. 2for t = N down to 1
  4. 3ŝ ← s(x, t) ▷ a given network
  5. 4x̂_0 ← (x + (1 - ᾱ_t) ŝ) / sqrt(ᾱ_t) ▷ Tweedie's formula
  6. 5x' ← c_x x + c_0 x̂_0 + sqrt(β̃_t) z, z from N(0, I) ▷ the DDPM step
  7. 6g ← ∇_x ||y - A(x̂_0)||^2 ▷ through x̂_0 and the network
  8. 7ζ_t ← ζ' / ||y - A(x̂_0)||
  9. 8x ← x' - ζ_t g
  10. 9return x

In line L5, cx=αt(1−αˉt−1)/(1−αˉt)c_x = \sqrt{\alpha_t}(1 - \bar\alpha_{t-1})/(1 - \bar\alpha_t), c0=αˉt−1βt/(1−αˉt)c_0 = \sqrt{\bar\alpha_{t-1}}\beta_t/(1 - \bar\alpha_t) and β~t=βt(1−αˉt−1)/(1−αˉt)\tilde\beta_t = \beta_t(1 - \bar\alpha_{t-1})/(1 - \bar\alpha_t): this is the reverse step of DDPM (Ho, Jain and Abbeel 2020) with x0x_0 replaced by x^0\hat x_0. The paper calls the noise level σ~t\tilde\sigma_t and leaves it to the DDPM sampler; the code uses β~t\tilde\beta_t. Line L6 is one backpropagation through the network, since x^0\hat x_0 depends on xx through ss:

g=2αˉt(I+(1−αˉt)JsT)AT(Ax^0−y).g = \frac{2}{\sqrt{\bar\alpha_t}}\big(I + (1 - \bar\alpha_t)J_s^T\big)A^T\big(A\hat x_0 - y\big).

Line L7 is the normalized step of the paper, with ζ′\zeta' a tuned constant; the paper reports values between 0.1 and 1. The step that follows from the reverse SDE with Gaussian noise is ζt=βt/(2σ2αt)\zeta_t = \beta_t/(2\sigma^2\sqrt{\alpha_t}), and the implementation accepts either.

Example

One step by hand. Take a one-dimensional prior N(0,1)N(0, 1), so that pt=N(0,1)p_t = N(0, 1) and the exact score is −x-x. Take αˉt=0.5\bar\alpha_t = 0.5, αˉt−1=0.8\bar\alpha_{t-1} = 0.8, so βt=1−0.5/0.8=0.375\beta_t = 1 - 0.5/0.8 = 0.375. Let xt=1x_t = 1, A=1A = 1, y=1y = 1 and ζ′=0.5\zeta' = 0.5.

  • L3 and L4: s^=−1\hat s = -1 and x^0=(1−0.5)/0.5=0.707107\hat x_0 = (1 - 0.5)/\sqrt{0.5} = 0.707107, which is E[x0∣xt=1]E[x_0 \mid x_t = 1].
  • L5: cx=0.625⋅0.2/0.5=0.316228c_x = \sqrt{0.625} \cdot 0.2/0.5 = 0.316228, c0=0.8⋅0.375/0.5=0.670820c_0 = \sqrt{0.8} \cdot 0.375/0.5 = 0.670820, so the mean is 0.316228+0.670820⋅0.707107=0.7905690.316228 + 0.670820 \cdot 0.707107 = 0.790569, and β~t=0.15=0.387298\sqrt{\tilde\beta_t} = \sqrt{0.15} = 0.387298.
  • L6: the residual is x^0−y=−0.292893\hat x_0 - y = -0.292893, and ∂x^0/∂x=(1−0.5)/0.5=0.707107\partial\hat x_0/\partial x = (1 - 0.5)/\sqrt{0.5} = 0.707107, so g=2⋅0.707107⋅(−0.292893)=−0.414214g = 2 \cdot 0.707107 \cdot (-0.292893) = -0.414214.
  • L7 and L8: ζt=0.5/0.292893=1.707107\zeta_t = 0.5/0.292893 = 1.707107 and xt−1=0.790569+0.707107+0.387298 z=1.497676+0.387298 zx_{t-1} = 0.790569 + 0.707107 + 0.387298\,z = 1.497676 + 0.387298\,z.

The guidance moved the state by 0.7071070.707107 toward the data. With the normalized step, the length of this move does not shrink as the residual goes to zero.

DPS is not the posterior. Keep the prior N(0,1)N(0, 1) with its exact score, and take A=1A = 1, σ2=0.25\sigma^2 = 0.25 and y=1y = 1. The true posterior is N(0.8,0.2)N(0.8, 0.2). For a Gaussian prior every step is linear plus Gaussian noise, so the law of the output can be computed exactly. With the DDPM schedule (N=1000N = 1000, β\beta from 10−410^{-4} to 0.020.02):

guidance step ζt\zeta_t output mean output variance
none (prior sampler) 0 0.99107
DPS, βt/(2σ2αt)\beta_t/(2\sigma^2\sqrt{\alpha_t}) 0.98197 0.12167
exact p(y∣xt)p(y \mid x_t), βt/(2(σ2+1−αˉt)αt)\beta_t/(2(\sigma^2 + 1 - \bar\alpha_t)\sqrt{\alpha_t}) 0.79999 0.19657
true posterior 0.8 0.2

The exact likelihood p(y∣xt)p(y \mid x_t) has the variance σ2+Var⁡(x0∣xt)\sigma^2 + \operatorname{Var}(x_0 \mid x_t), and DPS drops the second term. So DPS trusts the data too much: its mean is close to yy and its spread is too small. The small remaining gap in the variance of the third row comes from the DDPM step itself, whose noise is slightly too small, as the first row shows.

Correctness

DPS has no theorem that it samples the posterior, and the example shows that it does not, even with the exact score. The proof file proves what each line computes:

  1. With the exact score, line L4 is E[x0∣xt]E[x_0 \mid x_t] (Tweedie's formula, Proposition 1 of the paper; a theorem).
  2. Line L5 is a draw from the Gaussian q(xt−1∣xt,x0)q(x_{t-1} \mid x_t, x_0) at x0=x^0x_0 = \hat x_0. With the exact score its mean is the true reverse mean, and its variance is too small by a term in Var⁡(x0∣xt)\operatorname{Var}(x_0 \mid x_t).
  3. Line L6 is the exact gradient of ∥y−A(x^0(x))∥2\|y - A(\hat x_0(x))\|^2, by the chain rule.
  4. For a Gaussian prior and fixed steps, the output is Gaussian with a mean and a variance given by a linear recursion, which gives the table above.

The guidance replaces E[p(y∣x0)∣xt]E[p(y \mid x_0) \mid x_t] by p(y∣E[x0∣xt])p(y \mid E[x_0 \mid x_t]), which is the gap in Jensen's inequality. Theorem 1 of the paper bounds this gap by a constant times the posterior mean absolute deviation of x0x_0 given xtx_t. This is a theorem, but the deviation is large at early steps, so it does not give a sampling guarantee. That the samples look good on images is a measurement.

Proof: Each DPS step is the DDPM step plus the exact gradient of the DPS data term, and for a Gaussian prior the output law is known in closed form and is not the posteriorpartial

Setting. The forward diffusion is xt=αˉt x0+1−αˉt εx_t = \sqrt{\bar\alpha_t}\,x_0 + \sqrt{1 - \bar\alpha_t}\,\varepsilon with ε∼N(0,I)\varepsilon \sim N(0, I), for t=1,…,Nt = 1, \ldots, N, where αˉt=∏s≤t(1−βs)\bar\alpha_t = \prod_{s \le t}(1 - \beta_s), αt=1−βt\alpha_t = 1 - \beta_t and αˉ0=1\bar\alpha_0 = 1. Let ptp_t be the density of xtx_t. The data are y=Ax0+ny = Ax_0 + n with n∼N(0,σ2I)n \sim N(0, \sigma^2 I). The score network s(x,t)s(x, t) is a given function; the statements below say what the algorithm does with it, and the exactness results assume s(x,t)=∇log⁡pt(x)s(x, t) = \nabla\log p_t(x).

The status is partial on purpose. DPS does not sample the posterior p(x0∣y)p(x_0 \mid y), even with the exact score and infinitely many steps; Part 4 shows this on a Gaussian example. What can be proved is that each line computes what it claims to compute.

Part 1 (Tweedie's formula, Proposition 1 of Chung et al.). E[x0∣xt]=(xt+(1−αˉt)∇log⁡pt(xt))/αˉtE[x_0 \mid x_t] = \big(x_t + (1 - \bar\alpha_t)\nabla\log p_t(x_t)\big)/\sqrt{\bar\alpha_t}.

Proof. Write k(xt∣x0)k(x_t \mid x_0) for the density of N(αˉtx0,(1−αˉt)I)N(\sqrt{\bar\alpha_t}x_0, (1 - \bar\alpha_t)I). Then pt(xt)=∫k(xt∣x0)p0(x0) dx0p_t(x_t) = \int k(x_t \mid x_0)p_0(x_0)\,dx_0 and ∇xtk(xt∣x0)=−xt−αˉtx01−αˉtk(xt∣x0)\nabla_{x_t}k(x_t \mid x_0) = -\frac{x_t - \sqrt{\bar\alpha_t}x_0}{1 - \bar\alpha_t}k(x_t \mid x_0). Differentiating under the integral sign and dividing by pt(xt)p_t(x_t) gives

∇log⁡pt(xt)=−xt−αˉt E[x0∣xt]1−αˉt,\nabla\log p_t(x_t) = -\frac{x_t - \sqrt{\bar\alpha_t}\,E[x_0 \mid x_t]}{1 - \bar\alpha_t},

because k(xt∣x0)p0(x0)/pt(xt)k(x_t \mid x_0)p_0(x_0)/p_t(x_t) is the conditional density of x0x_0 given xtx_t. Solving for E[x0∣xt]E[x_0 \mid x_t] gives the formula. So with the exact score, line L4 computes x^0=E[x0∣xt]\hat x_0 = E[x_0 \mid x_t].

Part 2 (the DDPM step). Given both xtx_t and x0x_0, the variable xt−1x_{t-1} is Gaussian with mean αt(1−αˉt−1)1−αˉtxt+αˉt−1βt1−αˉtx0\frac{\sqrt{\alpha_t}(1 - \bar\alpha_{t-1})}{1 - \bar\alpha_t}x_t + \frac{\sqrt{\bar\alpha_{t-1}}\beta_t}{1 - \bar\alpha_t}x_0 and variance β~t=1−αˉt−11−αˉtβt\tilde\beta_t = \frac{1 - \bar\alpha_{t-1}}{1 - \bar\alpha_t}\beta_t (Ho, Jain and Abbeel 2020; it follows from Bayes' rule for two Gaussian factors). Line L5 is a draw from this law with x0x_0 replaced by x^0\hat x_0. With the exact score, its mean equals the mean of the true reverse step E[xt−1∣xt]E[x_{t-1} \mid x_t], since that mean is linear in x0x_0 and x^0=E[x0∣xt]\hat x_0 = E[x_0 \mid x_t]. Its variance is too small by the term (αˉt−1βt1−αˉt)2Var⁡(x0∣xt)\big(\frac{\sqrt{\bar\alpha_{t-1}}\beta_t}{1 - \bar\alpha_t}\big)^2\operatorname{Var}(x_0 \mid x_t), which is why the unguided sampler in the tests ends with variance 0.92 instead of 1 for N=100N = 100 and 0.99 for N=1000N = 1000. At t=1t = 1, αˉ0=1\bar\alpha_0 = 1 gives β~1=0\tilde\beta_1 = 0 and a mean of exactly x^0\hat x_0; the test test_schedule_and_last_step checks this.

The paper writes the noise of this step as σ~iz\tilde\sigma_i z without a formula for σ~i\tilde\sigma_i; the code uses β~t\tilde\beta_t, the choice of Ho et al.

Part 3 (the guidance gradient). Let x^0(x)=(x+(1−αˉt)s(x,t))/αˉt\hat x_0(x) = \big(x + (1 - \bar\alpha_t)s(x, t)\big)/\sqrt{\bar\alpha_t} and ϕ(x)=∥y−Ax^0(x)∥2\phi(x) = \|y - A\hat x_0(x)\|^2. If s(⋅,t)s(\cdot, t) is differentiable with Jacobian JJ, then

∇ϕ(x)=2αˉt(I+(1−αˉt)JT)AT(Ax^0(x)−y).\nabla\phi(x) = \frac{2}{\sqrt{\bar\alpha_t}}\big(I + (1 - \bar\alpha_t)J^T\big)A^T\big(A\hat x_0(x) - y\big).

Proof. The Jacobian of x^0\hat x_0 is (I+(1−αˉt)J)/αˉt(I + (1 - \bar\alpha_t)J)/\sqrt{\bar\alpha_t}, and the chain rule for ∥Ax^0−y∥2\|A\hat x_0 - y\|^2 gives twice its transpose applied to AT(Ax^0−y)A^T(A\hat x_0 - y). The code computes u=ATru = A^T r once and JTuJ^Tu by one call of the given vector-Jacobian product, so line L6 is this formula; the test compares it with central differences for a nonlinear score. Line L8 subtracts ζt∇ϕ\zeta_t\nabla\phi, with ζt=ζ′/∥y−Ax^0∥\zeta_t = \zeta'/\|y - A\hat x_0\| in the normalized form of Algorithm 1 of Chung et al.

Why this is the DPS approximation. By Bayes' rule ∇log⁡pt(xt∣y)=∇log⁡pt(xt)+∇log⁡p(y∣xt)\nabla\log p_t(x_t \mid y) = \nabla\log p_t(x_t) + \nabla\log p(y \mid x_t), and p(y∣xt)=E[p(y∣x0)∣xt]p(y \mid x_t) = E[p(y \mid x_0) \mid x_t]. DPS replaces this by p(y∣x^0)=p(y∣E[x0∣xt])p(y \mid \hat x_0) = p(y \mid E[x_0 \mid x_t]), so it moves the expectation inside a nonlinear function. For Gaussian noise ∇log⁡p(y∣x^0(xt))=−12σ2∇ϕ(xt)\nabla\log p(y \mid \hat x_0(x_t)) = -\frac{1}{2\sigma^2}\nabla\phi(x_t). In a reverse step of length βt\beta_t the score enters with the factor βt/αt\beta_t/\sqrt{\alpha_t}, so the step ζt=βt/(2σ2αt)\zeta_t = \beta_t/(2\sigma^2\sqrt{\alpha_t}) follows the approximate posterior score; the normalized step of the paper is a tuned replacement. Theorem 1 of Chung et al. bounds the error of the swap, the Jensen gap, by a constant times the posterior mean absolute deviation ∫∥x0−x^0∥p(x0∣xt) dx0\int\|x_0 - \hat x_0\|p(x_0 \mid x_t)\,dx_0. This deviation is large at large tt, so the bound does not make the method exact.

Part 4 (closed form for a Gaussian prior, and the gap). Let x0∼N(0,v0)x_0 \sim N(0, v_0) in one dimension, A=aA = a a scalar, and the steps ζt\zeta_t not normalized. Then pt=N(0,αˉtv0+1−αˉt)p_t = N(0, \bar\alpha_tv_0 + 1 - \bar\alpha_t), the exact score is −x/vt-x/v_t with vt=αˉtv0+1−αˉtv_t = \bar\alpha_tv_0 + 1 - \bar\alpha_t, and x^0=ctxt\hat x_0 = c_tx_t with ct=αˉtv0/vtc_t = \sqrt{\bar\alpha_t}v_0/v_t. Line L6 gives 2cta(actxt−y)2c_ta(ac_tx_t - y), so a whole step is

xt−1=ktxt+bt+β~t zt,kt=αt(1−αˉt−1)1−αˉt+αˉt−1βt1−αˉtct−2ζtct2a2,bt=2ζtctay.x_{t-1} = k_tx_t + b_t + \sqrt{\tilde\beta_t}\,z_t,\qquad k_t = \tfrac{\sqrt{\alpha_t}(1 - \bar\alpha_{t-1})}{1 - \bar\alpha_t} + \tfrac{\sqrt{\bar\alpha_{t-1}}\beta_t}{1 - \bar\alpha_t}c_t - 2\zeta_tc_t^2a^2,\qquad b_t = 2\zeta_tc_tay.

By induction from xN∼N(0,1)x_N \sim N(0, 1), every xtx_t is Gaussian, with the mean μt−1=ktμt+bt\mu_{t-1} = k_t\mu_t + b_t and the variance Vt−1=kt2Vt+β~tV_{t-1} = k_t^2V_t + \tilde\beta_t. The function linear_dps_moments computes this recursion, and the test draws 1500 samples from the code and checks that the sample mean and variance agree with it within 4 and 5 standard errors.

Now take v0=1v_0 = 1, a=1a = 1, σ2=0.25\sigma^2 = 0.25 and y=1y = 1. The posterior is N(0.8,0.2)N(0.8, 0.2). With the DDPM schedule (N=1000N = 1000, β\beta from 10−410^{-4} to 0.020.02) and ζt=βt/(2σ2αt)\zeta_t = \beta_t/(2\sigma^2\sqrt{\alpha_t}), the recursion gives the output law N(0.98197,0.12167)N(0.98197, 0.12167). The exact likelihood here is p(y∣xt)=N(y; ctxt, σ2+1−αˉt)p(y \mid x_t) = N(y;\ c_tx_t,\ \sigma^2 + 1 - \bar\alpha_t), since Var⁡(x0∣xt)=1−αˉt\operatorname{Var}(x_0 \mid x_t) = 1 - \bar\alpha_t for v0=1v_0 = 1. Using its gradient instead, that is ζt=βt/(2(σ2+1−αˉt)αt)\zeta_t = \beta_t/(2(\sigma^2 + 1 - \bar\alpha_t)\sqrt{\alpha_t}), gives N(0.79999,0.19657)N(0.79999, 0.19657), close to the posterior. The difference between the two is exactly the term Var⁡(x0∣xt)\operatorname{Var}(x_0 \mid x_t) that the swap p(y∣xt)≈p(y∣x^0)p(y \mid x_t) \approx p(y \mid \hat x_0) drops. So, even with the exact score, DPS with the natural step trusts the data too much: its mean is near yy and its variance is about 0.6 of the posterior variance. This is a theorem about this example, computed in closed form, not a measurement.

Complexity

The model is real-ram. Each of the NN steps calls the score network once, its vector-Jacobian product once, AA once and ATA^T once. So the time is O(N(a+g))O(N(a + g)), where aa is the cost of AA plus ATA^T and gg is the cost of a forward and a backward pass through the network, which is outside this page; the backward pass costs a small constant times the forward pass. The extra space is O(n+m)O(n + m) for the state, the estimate and the residual, plus the activations of one forward pass that the backward pass stores. The prior sampler without guidance has the same number of steps but no backward pass, so DPS costs about two to three times as much per sample. The paper uses N=1000N = 1000 network evaluations on FFHQ.

Properties

  • Training free. The score network is trained once on clean signals. A new forward model or noise level needs no retraining.
  • General forward models. Only AA and the adjoint of its derivative are needed, so nonlinear problems such as phase retrieval and nonuniform deblurring fit.
  • Stochastic. Different random seeds give different outputs; the spread is a rough, not a calibrated, measure of uncertainty.
  • Not exact. Even with the exact score and many steps, the output law differs from the posterior, as computed above.
  • Soft data fit. The data are not enforced exactly. With the normalized step the residual of the output is of the size of the last step, not zero.
  • Measured results. Chung et al. report experiments on FFHQ and ImageNet images of 256×256256 \times 256 pixels for inpainting, super-resolution, Gaussian and motion deblurring, phase retrieval and nonuniform deblurring, with Gaussian and Poisson noise, and compare with earlier diffusion and plug-and-play methods. These are measurements on those data sets.

Variants and improvements

  • Poisson noise. Replace the squared residual by a weighted residual with weights from the data; the paper treats this case.
  • Other samplers. The guidance step can be added to DDIM or to a discretized reverse SDE instead of the DDPM step.
  • Projection methods. For linear AA, earlier methods replace the guidance by a projection onto the data-consistent set after each step, as in score-based inpainting (Song et al. 2021); this enforces noiseless data exactly but handles noise poorly.
  • Better likelihood approximations. Use a Gaussian approximation of p(x0∣xt)p(x_0 \mid x_t) with a nonzero covariance, as the exact column of the table does, to reduce the overconfidence.
  • Optimization instead of sampling. CSGM searches the latent space of a generator for one best fit, and plug-and-play priors use a denoiser inside an optimization method.

When to use it

Use DPS when a good diffusion model for the signal class exists, when the forward model changes between tasks or is nonlinear, and when realistic samples matter more than a calibrated posterior. Do not use it when you need correct uncertainty, for example error bars for a measurement; then use a Markov chain Monte Carlo method such as the Metropolis-adjusted Langevin algorithm on a model with a known density, or the closed form of a linear Gaussian problem. Do not use it when the time budget allows only a few network evaluations per image.

Pitfalls

  • Step size. Too small a step ignores the data; too large a step makes the iterates leave the region where the score network was trained, and the output has artifacts. The best ζ′\zeta' depends on the task.
  • Overconfidence. The output fits the data more tightly than the posterior would, as the example shows. Do not read the sample spread as a posterior variance.
  • Forgetting the network in the gradient. Line L6 differentiates through x^0\hat x_0, which contains the network. Dropping JsJ_s gives a cheaper but different method.
  • Noise level. With the normalized step, σ\sigma does not enter the algorithm at all, so the method cannot tell low noise from high noise.
  • Prior mismatch. The prior is only as good as the training set. For a signal unlike the training data, DPS still returns a realistic signal of the training class.

Implementations

The score network is a given function: the code takes s(x,t)s(x, t) and its vector-Jacobian product as arguments, with functions for AA and ATA^T, and runs lines L1 to L9 around them. The tests build the score by hand, as the exact score of a Gaussian prior or as a small tanh⁡\tanh network with weights from a fixed seed; no network is trained. The tests check the schedule and that the last step returns x^0\hat x_0, Tweedie's formula against the exact posterior mean, the guidance gradient against central differences, the exact mean and variance of the sampler against 1500 samples, the two rows of the table, that the unobserved entry of a noiseless inpainting problem follows the prior sampler exactly, and that each step calls the network, AA and ATA^T once.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

diffusion_posterior_sampling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diffusion-posterior-sampling/. The authors are listed in prov/K0GFYT.jsonl.
"""Diffusion posterior sampling (DPS) of Chung, Kim, McCann, Klasky and Ye.

The score network is given: a function score(x, t) that approximates the
gradient of log p_t at x, and a function score_vjp(x, t, v) that returns
J^T v for the Jacobian J of score(., t) at x. The forward operator is given
by apply_a and apply_at. Steps are indexed t = N, ..., 1 with alpha_bars[t - 1]
the product of (1 - beta_s) for s <= t, and alpha_bar_0 = 1.
Vectors are lists of floats.
"""

import math


def schedule(alpha_bars, t):
    """Return (alpha_bar_t, alpha_bar_{t-1}, beta_t) for 1 <= t <= N."""
    ab = alpha_bars[t - 1]
    ab_prev = alpha_bars[t - 2] if t > 1 else 1.0
    return ab, ab_prev, 1.0 - ab / ab_prev


def tweedie(x, s, ab):
    """The denoised estimate (x + (1 - ab) s) / sqrt(ab)."""
    c = 1.0 / math.sqrt(ab)
    return [c * (xi + (1.0 - ab) * si) for xi, si in zip(x, s)]


def guidance_gradient(x, t, ab, x0, y, apply_a, apply_at, score_vjp):
    """The gradient of ||y - A x0(x)||^2 with respect to x, and the residual.

    x0(x) = (x + (1 - ab) score(x, t)) / sqrt(ab), so its Jacobian is
    (I + (1 - ab) J) / sqrt(ab) and the gradient is 2 times its transpose
    applied to A^T (A x0 - y).
    """
    r = [p - q for p, q in zip(apply_a(x0), y)]
    u = apply_at(r)
    ju = score_vjp(x, t, u)
    c = 2.0 / math.sqrt(ab)
    return [c * (ui + (1.0 - ab) * ji) for ui, ji in zip(u, ju)], r


def dps(y, apply_a, apply_at, score, score_vjp, alpha_bars, zeta, rng,
        normalize=True, x_start=None, n=None):
    """Run DPS from x_N ~ N(0, I) and return x_0.

    zeta is a number or a list with zeta[t - 1] for step t. With
    normalize=True the step is zeta / ||y - A x0||, as in the paper;
    with normalize=False it is zeta itself. Each step calls score once,
    score_vjp once, A once and A^T once.
    """
    big_n = len(alpha_bars)
    if x_start is None:
        x = [rng.gauss(0.0, 1.0) for _ in range(n)]  # @line L1
    else:
        x = list(x_start)  # @line L1
    for t in range(big_n, 0, -1):  # @line L2
        ab, ab_prev, beta = schedule(alpha_bars, t)
        s = score(x, t)  # @line L3
        x0 = tweedie(x, s, ab)  # @line L4
        c_x = math.sqrt(1.0 - beta) * (1.0 - ab_prev) / (1.0 - ab)  # @line L5
        c_0 = math.sqrt(ab_prev) * beta / (1.0 - ab)  # @line L5
        sd = math.sqrt((1.0 - ab_prev) / (1.0 - ab) * beta)  # @line L5
        xp = [c_x * xi + c_0 * x0i + sd * rng.gauss(0.0, 1.0)  # @line L5
              for xi, x0i in zip(x, x0)]
        g, r = guidance_gradient(x, t, ab, x0, y, apply_a, apply_at, score_vjp)  # @line L6
        z = zeta[t - 1] if isinstance(zeta, (list, tuple)) else zeta
        if normalize:  # @line L7
            norm = math.sqrt(sum(v * v for v in r))  # @line L7
            z = z / norm if norm > 0.0 else 0.0  # @line L7
        x = [a - z * b for a, b in zip(xp, g)]  # @line L8
    return x  # @line L9


def linear_alpha_bars(big_n, beta_min, beta_max):
    """alpha_bar_t for a linear beta schedule from beta_min to beta_max."""
    out, prod = [], 1.0
    for t in range(big_n):
        beta = beta_min + (beta_max - beta_min) * t / max(big_n - 1, 1)
        prod *= 1.0 - beta
        out.append(prod)
    return out


def gaussian_score(alpha_bars, prior_var):
    """The exact score of p_t when x_0 ~ N(0, diag(prior_var)).

    p_t = N(0, ab * prior_var + 1 - ab) in each coordinate, so the score is
    -x / v and its Jacobian is diagonal with entries -1 / v.
    """
    def var(t, j):
        ab = alpha_bars[t - 1]
        return ab * prior_var[j] + 1.0 - ab

    def score(x, t):
        return [-xi / var(t, j) for j, xi in enumerate(x)]

    def score_vjp(x, t, v):
        return [-vi / var(t, j) for j, vi in enumerate(v)]

    return score, score_vjp


def linear_dps_moments(a_scalar, y, alpha_bars, prior_var, zetas):
    """Exact mean and variance of DPS output for a 1D Gaussian prior.

    With A = a_scalar, the exact score of N(0, prior_var) and the unnormalized
    step zetas[t - 1], every step is x <- k x + b + sd * noise, so the mean and
    the variance follow a linear recursion from N(0, 1).
    """
    mean, var = 0.0, 1.0
    for t in range(len(alpha_bars), 0, -1):
        ab, ab_prev, beta = schedule(alpha_bars, t)
        v = ab * prior_var + 1.0 - ab
        c = math.sqrt(ab) * prior_var / v  # x0 = c x, Tweedie for a Gaussian
        c_x = math.sqrt(1.0 - beta) * (1.0 - ab_prev) / (1.0 - ab)
        c_0 = math.sqrt(ab_prev) * beta / (1.0 - ab)
        sd2 = (1.0 - ab_prev) / (1.0 - ab) * beta
        z = zetas[t - 1]
        # g = 2 c a (a c x - y)
        k = c_x + c_0 * c - z * 2.0 * c * c * a_scalar * a_scalar
        b = z * 2.0 * c * a_scalar * y
        mean = k * mean + b
        var = k * k * var + sd2
    return mean, var
test_diffusion_posterior_sampling.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/diffusion-posterior-sampling/. The authors are listed in prov/K0GFYT.jsonl.

import math
import random

from diffusion_posterior_sampling import (
    dps,
    gaussian_score,
    guidance_gradient,
    linear_alpha_bars,
    linear_dps_moments,
    schedule,
    tweedie,
)

N = 100
AB = linear_alpha_bars(N, 1e-3, 0.2)
BETAS = [schedule(AB, t)[2] for t in range(1, N + 1)]


def identity(x):
    return list(x)


def likelihood_steps(sig2, extra=None):
    """beta_t / (2 (sig2 + extra_t) sqrt(1 - beta_t)), the step of the reverse SDE."""
    out = []
    for t, bt in enumerate(BETAS, start=1):
        e = 0.0 if extra is None else extra(t)
        out.append(bt / (2.0 * (sig2 + e) * math.sqrt(1.0 - bt)))
    return out


def test_schedule_and_last_step():
    assert abs(AB[0] - 0.999) < 1e-15 and AB[-1] < 1e-4
    for t in range(2, N + 1):
        assert abs(schedule(AB, t)[0] - (1.0 - schedule(AB, t)[2]) * AB[t - 2]) < 1e-15
    # With one step and no guidance the output is the Tweedie estimate.
    score, vjp = gaussian_score([0.6], [2.0])
    x = dps([0.0], identity, identity, score, vjp, [0.6], 0.0, random.Random(0),
            normalize=False, x_start=[1.5])
    v = 0.6 * 2.0 + 0.4
    assert abs(x[0] - math.sqrt(0.6) * 2.0 / v * 1.5) < 1e-12


def test_tweedie_is_the_posterior_mean_for_a_gaussian_prior():
    prior = [0.5, 3.0]
    score, _ = gaussian_score(AB, prior)
    for t in (1, 10, 50, 100):
        ab = AB[t - 1]
        x = [0.7, -1.3]
        got = tweedie(x, score(x, t), ab)
        for j in range(2):
            exact = math.sqrt(ab) * prior[j] / (ab * prior[j] + 1.0 - ab) * x[j]
            assert abs(got[j] - exact) < 1e-12


def test_guidance_gradient_matches_finite_differences():
    rng = random.Random(3)
    n, m = 3, 2
    u = [[rng.gauss(0.0, 0.5) for _ in range(n)] for _ in range(n)]
    w = [[rng.gauss(0.0, 0.5) for _ in range(n)] for _ in range(n)]
    a = [[rng.gauss(0.0, 1.0) for _ in range(n)] for _ in range(m)]
    y = [0.4, -0.9]

    def score(x, t):
        h = [math.tanh(sum(wr[j] * x[j] for j in range(n))) for wr in w]
        return [-x[i] + sum(u[i][k] * h[k] for k in range(n)) for i in range(n)]

    def score_vjp(x, t, v):
        h = [math.tanh(sum(wr[j] * x[j] for j in range(n))) for wr in w]
        q = [(1.0 - h[k] ** 2) * sum(u[i][k] * v[i] for i in range(n)) for k in range(n)]
        return [-v[j] + sum(w[k][j] * q[k] for k in range(n)) for j in range(n)]

    def apply_a(x):
        return [sum(r[j] * x[j] for j in range(n)) for r in a]

    def apply_at(r):
        return [sum(a[i][j] * r[i] for i in range(m)) for j in range(n)]

    ab, t = 0.4, 7

    def objective(x):
        x0 = tweedie(x, score(x, t), ab)
        return sum((p - q) ** 2 for p, q in zip(apply_a(x0), y))

    x = [0.3, -0.5, 1.2]
    g, _ = guidance_gradient(x, t, ab, tweedie(x, score(x, t), ab), y,
                             apply_a, apply_at, score_vjp)
    h = 1e-6
    for j in range(n):
        xp, xm = list(x), list(x)
        xp[j] += h
        xm[j] -= h
        assert abs((objective(xp) - objective(xm)) / (2 * h) - g[j]) < 1e-6


def test_monte_carlo_matches_the_exact_law_of_the_sampler():
    score, vjp = gaussian_score(AB, [1.0])
    steps = likelihood_steps(0.25)
    mean, var = linear_dps_moments(1.0, 1.0, AB, 1.0, steps)
    assert abs(mean - 0.98458) < 1e-5 and abs(var - 0.09976) < 1e-5
    rng = random.Random(1)
    count = 1500
    xs = [dps([1.0], identity, identity, score, vjp, AB, steps, rng,
              normalize=False, n=1)[0] for _ in range(count)]
    m = sum(xs) / count
    v = sum((x - m) ** 2 for x in xs) / (count - 1)
    assert abs(m - mean) < 4.0 * math.sqrt(var / count)
    assert abs(v - var) < 5.0 * var * math.sqrt(2.0 / count)


def test_dps_is_not_the_exact_posterior():
    # Prior N(0, 1), A = 1, noise variance 0.25, y = 1: posterior N(0.8, 0.2).
    long_ab = linear_alpha_bars(1000, 1e-4, 0.02)
    long_b = [schedule(long_ab, t)[2] for t in range(1, 1001)]
    dps_steps = [b / (0.5 * math.sqrt(1.0 - b)) for b in long_b]
    mean, var = linear_dps_moments(1.0, 1.0, long_ab, 1.0, dps_steps)
    assert abs(mean - 0.98197) < 1e-5 and abs(var - 0.12167) < 1e-5
    # The same sampler with the exact p(y | x_t), whose variance is
    # 0.25 + Var(x_0 | x_t) = 0.25 + 1 - alpha_bar_t, is close to the posterior.
    exact_steps = [b / (2.0 * (1.25 - long_ab[t]) * math.sqrt(1.0 - b))
                   for t, b in enumerate(long_b)]
    mean_e, var_e = linear_dps_moments(1.0, 1.0, long_ab, 1.0, exact_steps)
    assert abs(mean_e - 0.8) < 1e-4 and abs(var_e - 0.2) < 0.005


def test_normalized_step_on_a_noiseless_inpainting_problem():
    # Prior N(0, I_2), observe the first entry exactly: y = 1.
    score, vjp = gaussian_score(AB, [1.0, 1.0])
    apply_a = lambda x: [x[0]]
    apply_at = lambda r: [r[0], 0.0]
    rng, free = random.Random(4), random.Random(4)
    for _ in range(200):
        x = dps([1.0], apply_a, apply_at, score, vjp, AB, 0.1, rng, n=2)
        z = dps([1.0], apply_a, apply_at, score, vjp, AB, 0.0, free, n=2)
        # The step has length about 2 zeta, so the error does not go below it.
        assert abs(x[0] - 1.0) < 0.21
        # The unobserved entry gets no guidance and follows the prior sampler.
        assert x[1] == z[1]


def test_one_call_of_each_operator_per_step():
    calls = {"score": 0, "vjp": 0, "a": 0, "at": 0}
    score, vjp = gaussian_score(AB, [1.0])

    def counted(name, f):
        def g(*args):
            calls[name] += 1
            return f(*args)
        return g

    dps([0.5], counted("a", identity), counted("at", identity), counted("score", score),
        counted("vjp", vjp), AB, 0.3, random.Random(2), n=1)
    assert calls == {"score": N, "vjp": N, "a": N, "at": N}

History

Score-based and diffusion models (Song and Ermon 2019; Ho, Jain and Abbeel 2020; Song et al. 2021) generate samples by reversing a noising process. Early uses for inverse problems either projected onto the data after each step or trained a conditional model for one task. Chung et al. (2022) added a manifold constraint, and in 2023 Chung, Kim, McCann, Klasky and Ye proposed DPS, which uses the Tweedie estimate to approximate the likelihood of a noisy state and handles noise and nonlinear forward models. Later methods improved the likelihood approximation and the speed.

References

  1. Hyungjin Chung, Jeongsol Kim, Michael T. McCann, Marc L. Klasky and Jong Chul Ye, Diffusion posterior sampling for general noisy inverse problems, International Conference on Learning Representations (ICLR), 2023, Algorithm 1 (the sampler for Gaussian noise), Proposition 1 (Tweedie's formula for the denoised estimate), Theorem 1 (the bound on the Jensen gap), and the experiments on FFHQ and ImageNet
  2. Jonathan Ho, Ajay Jain and Pieter Abbeel, Denoising diffusion probabilistic models, Advances in Neural Information Processing Systems 33, 2020, the forward process, the posterior q(x_{t-1} | x_t, x_0) of the reverse step, and the sampling algorithm
  3. Bradley Efron, Tweedie's formula and selection bias, Journal of the American Statistical Association 106(496), 2011, Tweedie's formula for the posterior mean under Gaussian noise

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of correctness
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example