Algorithm Search⌘K

Algorithmresearch

Approximate message passing

Also called AMP.

Iterative soft thresholding plus an Onsager correction term in the residual, which makes the error Gaussian for random matrices so that a scalar recursion, state evolution, predicts it.

Time
O(K m n) worst
Space
O(m + n) extra
Where
K = the number of iterations; m = the number of measurements; n = the length of the signal
Properties
deterministiciterativematrix free
Origin
David L. Donoho, Arian Maleki, Andrea Montanari, 2009

Approximate message passing (AMP) recovers a sparse vector x∈Rnx \in \mathbb{R}^n from y=Ax+wy = Ax + w with a random m×nm \times n matrix AA. Each step looks like a step of iterative shrinkage-thresholding: it applies soft thresholding η\eta to xt+ATztx^t + A^Tz^t. The difference is the residual: AMP adds the Onsager correction ∥xt+1∥0mzt\frac{\|x^{t+1}\|_0}{m}z^t to y−Axt+1y - Ax^{t+1}. For a matrix with i.i.d. Gaussian entries, this term makes the error in xt+ATztx^t + A^Tz^t behave like Gaussian noise of a known variance τt2\tau_t^2 in the large system limit. A scalar recursion, state evolution, then predicts the mean squared error of every iteration. Like ISTA, the fixed points of AMP solve a LASSO problem, but AMP reaches them in far fewer iterations. With a well chosen threshold, its phase transition for noiseless recovery is the same as that of basis pursuit, the Donoho-Tanner phase transition. Greedy methods such as iterative hard thresholding and CoSaMP have worst case guarantees for every matrix with a small restricted isometry constant; the theory of AMP is instead exact, but for Gaussian matrices and in the limit n→∞n \to \infty.

The problem

Given AA, yy and a threshold parameter, find an estimate of a sparse xx, where y=Ax+wy = Ax + w, AA has i.i.d. entries of mean 0 and variance 1/m1/m, and ww is noise of variance σ2\sigma^2 per entry. Write δ=m/n\delta = m/n for the undersampling ratio. The output is the estimate xKx^K, and with it the estimate τK=∥zK∥/m\tau_K = \|z^K\|/\sqrt m of the effective noise level. The column scaling matters: the theory assumes columns of norm close to 1.

The algorithm

η(v;θ)=sign⁡(v)max⁡(∣v∣−θ,0)\eta(v; \theta) = \operatorname{sign}(v)\max(|v| - \theta, 0) is soft thresholding, the proximal operator of θ∣⋅∣\theta|\cdot|, applied entry by entry.

  1. AMP(A, y, α, K)
  2. 1x ← 0, z ← y
  3. 2for t = 0 to K - 1
  4. 3τ ← ‖z‖ / √m ▷ estimate of the effective noise level
  5. 4θ ← α τ ▷ threshold proportional to the noise level
  6. 5x_new ← η(x + Aᵀ z; θ) ▷ soft thresholding, as in ISTA
  7. 6b ← ‖x_new‖₀ / m ▷ Onsager coefficient
  8. 7z ← y - A x_new + b z, x ← x_new ▷ residual with the correction term
  9. 8return x, z

Line L6 is the average derivative of η\eta divided by δ\delta: η′\eta' is 1 where the input passes the threshold and 0 elsewhere, so 1δ⟨η′⟩=∥xt+1∥0/m\frac1\delta\langle\eta'\rangle = \|x^{t+1}\|_0/m. Without the term bzb z in line L7, the loop is iterative soft thresholding with unit step and a varying threshold. The threshold rule θt=ατt\theta_t = \alpha\tau_t is the one of Donoho, Maleki and Montanari. A fixed θ\theta also works in the theory, but in practice it can make the loop diverge (see Pitfalls).

Example

Take δ=m/n=1/2\delta = m/n = 1/2, no noise, and a signal whose entries are 0 with probability 0.9 and +1+1 or −1-1 with probability 0.05 each. Use α=1.5\alpha = 1.5. State evolution starts with τ02=E[X2]/δ=0.1/0.5=0.2\tau_0^2 = E[X^2]/\delta = 0.1/0.5 = 0.2, because the first step sees ATy=x+(ATA−I)xA^Ty = x + (A^TA - I)x, whose error has variance ∥x∥2/m\|x\|^2/m per entry. Each later step sets τt+12=1δE[(η(X+τtZ;ατt)−X)2]\tau_{t+1}^2 = \frac1\delta E[(\eta(X + \tau_tZ; \alpha\tau_t) - X)^2] with a standard normal ZZ.

The table compares the predicted mean squared error per entry of xt+1x^{t+1} with the average over two runs with n=400n = 400, m=200m = 200 (seeds 10 and 11 of the test file), with and without the correction term. The run values are measurements.

tt τt2\tau_t^2 predicted MSE AMP, measured without correction, measured
0 0.2000 0.0586 0.0675 0.0675
1 0.1171 0.0402 0.0482 0.0756
2 0.0803 0.0289 0.0334 0.0687
3 0.0579 0.0211 0.0230 0.0859
4 0.0422 0.0155 0.0161 0.0911
5 0.0309 0.0113 0.0113 0.1132

The first step is the same for both, since z0=yz^0 = y. After that, AMP follows the prediction and its error falls by a roughly constant factor per step. Without the correction the error grows. The gap at t=0t = 0 comes from the finite size: the number of nonzero entries of xx itself varies by about 15 percent at n=400n = 400.

Correctness

The full proof is in proofs/correctness.md. It proves two facts that hold for every matrix:

  • The correction coefficient ∥xt+1∥0/m\|x^{t+1}\|_0/m equals 1δ⟨η′(xt+ATzt;θt)⟩\frac1\delta\langle\eta'(x^t + A^Tz^t; \theta_t)\rangle, the form in the paper.
  • If (x,z)(x, z) is a fixed point with threshold θ\theta and k=∥x∥0<mk = \|x\|_0 < m, then xx minimizes 12∥y−Ax∥2+λ∥x∥1\tfrac12\|y - Ax\|^2 + \lambda\|x\|_1 with λ=θ(1−k/m)\lambda = \theta(1 - k/m). The zz equation gives (1−k/m)z=y−Ax(1 - k/m)z = y - Ax, and the fixed point of soft thresholding says that ATzA^Tz is θ\theta times a subgradient of ∥x∥1\|x\|_1. Multiplying by 1−k/m1 - k/m gives the optimality condition of the LASSO.

The statement that the error follows state evolution is a theorem of Bayati and Montanari (2011): for i.i.d. Gaussian AA, n→∞n \to \infty with m/n→δm/n \to \delta and a fixed number of iterations, the empirical distribution of the pairs (xit+1,xi)(x^{t+1}_i, x_i) converges to that of (η(X+τtZ;θt),X)(\eta(X + \tau_tZ; \theta_t), X). It is cited, not proved here. The theorem says nothing about one finite matrix, and nothing about non-Gaussian matrices.

Proof: Every fixed point of AMP with soft thresholding solves a LASSO problem, and the Onsager coefficient is the average derivative of the threshold functionfull

Setting. AA is a real m×nm \times n matrix and y∈Rmy \in \mathbb{R}^m. The soft threshold function is η(v;θ)=sign⁡(v)max⁡(∣v∣−θ,0)\eta(v; \theta) = \operatorname{sign}(v)\max(|v| - \theta, 0) for θ>0\theta > 0, applied entry by entry to vectors. AMP starts from x0=0x^0 = 0, z0=yz^0 = y and repeats, for t=0,1,2,…t = 0, 1, 2, \dots,

xt+1=η(xt+ATzt;θt),zt+1=y−Axt+1+∥xt+1∥0m zt.x^{t+1} = \eta(x^t + A^Tz^t; \theta_t),\qquad z^{t+1} = y - Ax^{t+1} + \frac{\|x^{t+1}\|_0}{m}\,z^t.

The threshold is either a fixed θ\theta or θt=ατt\theta_t = \alpha\tau_t with τt=∥zt∥/m\tau_t = \|z^t\|/\sqrt m.

This page proves two facts that hold for every matrix: the form of the correction term, and the fact that fixed points are LASSO solutions. The statement that the iterates follow state evolution is a theorem of Bayati and Montanari (2011) for Gaussian matrices in the large system limit; it is stated at the end and cited, not proved.

Part 1: the correction term

Donoho, Maleki and Montanari (2009) write the correction as 1δzt⟨η′(xt+ATzt;θt)⟩\frac1\delta z^t\langle\eta'(x^t + A^Tz^t; \theta_t)\rangle, with δ=m/n\delta = m/n and ⟨v⟩=1n∑ivi\langle v\rangle = \frac1n\sum_i v_i.

Lemma 1. For ∣v∣≠θ|v| \ne \theta, η′(v;θ)=1\eta'(v; \theta) = 1 if ∣v∣>θ|v| > \theta and 00 if ∣v∣<θ|v| < \theta. Hence, with u=xt+ATztu = x^t + A^Tz^t and no entry with ∣ui∣=θt|u_i| = \theta_t,

1δ⟨η′(u;θt)⟩=nm⋅#{i:∣ui∣>θt}n=∥xt+1∥0m.\frac1\delta\langle\eta'(u; \theta_t)\rangle = \frac nm\cdot\frac{\#\{i : |u_i| > \theta_t\}}{n} = \frac{\|x^{t+1}\|_0}{m}.

Proof. On v>θv > \theta the function is v−θv - \theta, on v<−θv < -\theta it is v+θv + \theta, and on ∣v∣<θ|v| < \theta it is 0. The entries with ∣ui∣>θt|u_i| > \theta_t are exactly the nonzero entries of xt+1=η(u;θt)x^{t+1} = \eta(u; \theta_t). □\square

An entry with ∣ui∣=θt|u_i| = \theta_t exactly gives xit+1=0x^{t+1}_i = 0, and counting it as 0 is the convention used by the implementation.

Part 2: fixed points are LASSO solutions

Lemma 2. For θ>0\theta > 0 and real numbers xx, gg: x=η(x+g;θ)x = \eta(x + g; \theta) if and only if g=θsign⁡(x)g = \theta\operatorname{sign}(x) when x≠0x \ne 0, and ∣g∣≤θ|g| \le \theta when x=0x = 0. In other words, g∈θ ∂∣x∣g \in \theta\,\partial|x|.

Proof. Let x≠0x \ne 0 and x=η(x+g;θ)x = \eta(x + g; \theta). A nonzero output has the sign of the input and magnitude ∣x+g∣−θ|x + g| - \theta, so x+g=x+θsign⁡(x)x + g = x + \theta\operatorname{sign}(x) and g=θsign⁡(x)g = \theta\operatorname{sign}(x). Conversely, if g=θsign⁡(x)g = \theta\operatorname{sign}(x), then ∣x+g∣=∣x∣+θ>θ|x + g| = |x| + \theta > \theta and η(x+g;θ)=x+g−θsign⁡(x)=x\eta(x + g; \theta) = x + g - \theta\operatorname{sign}(x) = x. Let x=0x = 0. Then 0=η(g;θ)0 = \eta(g; \theta) holds if and only if ∣g∣≤θ|g| \le \theta. □\square

Theorem. Let (x,z)(x, z) be a fixed point of the iteration with a fixed threshold θ>0\theta > 0, that is x=η(x+ATz;θ)x = \eta(x + A^Tz; \theta) and z=y−Ax+kmzz = y - Ax + \frac km z with k=∥x∥0k = \|x\|_0. If k<mk < m, then xx minimizes

F(w)=12∥y−Aw∥2+λ∥w∥1,λ=θ(1−km).F(w) = \tfrac12\|y - Aw\|^2 + \lambda\|w\|_1,\qquad \lambda = \theta\left(1 - \frac km\right).

The same holds for the adaptive rule θt=ατt\theta_t = \alpha\tau_t: at a fixed point zz does not change, so τt\tau_t and θt\theta_t are constant, and the theorem applies with θ=α∥z∥/m\theta = \alpha\|z\|/\sqrt m.

Proof. The second equation gives (1−k/m)z=y−Ax(1 - k/m)z = y - Ax. Since k<mk < m, the factor is positive and ATz=AT(y−Ax)/(1−k/m)A^Tz = A^T(y - Ax)/(1 - k/m). By Lemma 2 applied to each entry, the first equation says that (ATz)i∈θ ∂∣xi∣(A^Tz)_i \in \theta\,\partial|x_i| for all ii. Multiply by 1−k/m>01 - k/m > 0:

AT(y−Ax)∈λ ∂∥x∥1.A^T(y - Ax) \in \lambda\,\partial\|x\|_1.

This is the condition 0∈AT(Ax−y)+λ ∂∥x∥1=∂F(x)0 \in A^T(Ax - y) + \lambda\,\partial\|x\|_1 = \partial F(x). FF is convex, so a point where 00 is a subgradient is a global minimizer. □\square

If k≥mk \ge m, the factor 1−k/m1 - k/m is zero or negative, and the fixed point equation for zz either forces y=Axy = Ax or gives a negative weight, which is not a LASSO problem. In practice the iteration with a small fixed threshold then diverges: the correction coefficient k/mk/m reaches 1 and zz grows. The adaptive rule avoids this because θt\theta_t grows with ∥zt∥\|z^t\|.

The theorem does not say that AMP converges. For a general matrix it can diverge. It says that whenever the iteration stops at a fixed point, the result is a LASSO solution, with a weight λ\lambda that the user does not choose directly. Donoho, Maleki and Montanari (2009) give this correspondence, and the test file checks it against an independent coordinate descent solver.

Part 3: state evolution (cited)

Let AA have i.i.d. N(0,1/m)N(0, 1/m) entries, y=Ax+wy = Ax + w with noise of variance σ2\sigma^2 per entry, and let n→∞n \to \infty with m/n→δm/n \to \delta while the empirical distribution of the entries of xx converges to the law of a random variable XX (with the moment conditions of the theorem). Define τ02=σ2+E[X2]/δ\tau_0^2 = \sigma^2 + E[X^2]/\delta and

τt+12=σ2+1δE[(η(X+τtZ;θt)−X)2],Z∼N(0,1) independent of X.\tau_{t+1}^2 = \sigma^2 + \frac1\delta E\big[(\eta(X + \tau_tZ; \theta_t) - X)^2\big],\qquad Z \sim N(0, 1) \text{ independent of } X.

Bayati and Montanari (2011) prove that for each fixed tt, and for every pseudo-Lipschitz function ψ\psi, 1n∑iψ(xit+1,xi)→E[ψ(η(X+τtZ;θt),X)]\frac1n\sum_i\psi(x^{t+1}_i, x_i) \to E[\psi(\eta(X + \tau_tZ; \theta_t), X)] almost surely. With ψ(a,b)=(a−b)2\psi(a, b) = (a - b)^2 this says that the mean squared error of xt+1x^{t+1} is the state evolution prediction. The proof uses a conditioning technique for Gaussian matrices and needs the Onsager term: without it, the effective noise in xt+ATztx^t + A^Tz^t is not Gaussian with the predicted variance, and the prediction fails. The statement is for a fixed number of iterations as n→∞n \to \infty and for Gaussian matrices; it is not a statement about one finite matrix.

Complexity

Each iteration costs one product with AA and one with ATA^T, which is O(mn)O(mn) for a dense matrix, and O(n)O(n) for the threshold and the counts. So KK iterations cost O(Kmn)O(Kmn) time and O(m+n)O(m + n) extra memory, the same as ISTA. With a fast operator the products are cheaper, but the theory then no longer applies directly. Under state evolution with a fixed point τ∗=0\tau^* = 0 (noiseless recovery below the phase transition), the error decreases geometrically, so the number of iterations for accuracy ε\varepsilon is O(log⁡(1/ε))O(\log(1/\varepsilon)) in the large system limit. ISTA on the same problems is much slower.

Properties

  • Each step is as cheap as a step of ISTA, and the only extra work is the count in line L6.
  • The effective observation xt+ATztx^t + A^Tz^t is close to x+τtZx + \tau_tZ with Gaussian ZZ, so each step is a scalar denoising problem. This is why the threshold can be set from τt\tau_t, and why other denoisers can replace η\eta.
  • Fixed points are LASSO solutions, and the map from α\alpha to the LASSO weight λ\lambda is given by the fixed point of state evolution.
  • The predictions are exact only in the large system limit and only for i.i.d. Gaussian matrices (and, by later work, other i.i.d. sub-Gaussian matrices). For structured or ill-conditioned matrices AMP can diverge.
  • It is not a descent method. The LASSO objective need not decrease at every step.

Variants and improvements

  • Bayes-optimal AMP replaces η\eta by the posterior mean of XX given X+τZ=vX + \tau Z = v for a known prior, with the correction coefficient the average derivative of that denoiser. Its state evolution predicts the minimum mean squared error in the regimes where AMP reaches it.
  • Generalized AMP (GAMP, Rangan) handles nonlinear and non-Gaussian measurement channels, such as quantized or Poisson data.
  • Denoising AMP uses an image denoiser in place of η\eta, with the derivative estimated by a Monte Carlo trace estimate. It is close in spirit to plug-and-play methods.
  • Vector AMP and orthogonal AMP extend the theory to right rotationally invariant matrices, which include many ill-conditioned ones, at the cost of a linear solve or an SVD per step.
  • Damping, which averages the new and the old iterate, is a common heuristic fix for divergence on matrices that are not i.i.d. It has no general guarantee.
  • LISTA and learned AMP unroll a fixed number of iterations and train the matrices and thresholds.

When to use it

Use AMP when the matrix is random with i.i.d. entries, or close to it, and the problem is large: it then reaches the LASSO solution or a Bayes-optimal estimate in tens of iterations, and state evolution predicts the error in advance, which helps to choose α\alpha or the number of measurements. For partial Fourier or other structured matrices from imaging, use vector AMP, damping, or a convex solver such as FISTA or ADMM instead. When a worst case guarantee for one given matrix is needed, use methods with restricted isometry guarantees, such as CoSaMP or basis pursuit.

Pitfalls

  • AMP diverges on many matrices that are not i.i.d. Gaussian, for example ill-conditioned matrices, matrices with nonzero mean entries and some structured transforms. Check the residual and stop if it grows.
  • The columns must have norm close to 1, which means entries of variance 1/m1/m. With another scale, the effective noise is wrong and the threshold rule fails.
  • A fixed small threshold can drive the number of nonzeros up to mm. Then the coefficient ∥x∥0/m\|x\|_0/m reaches 1 and zz blows up. In 10 runs on random Gaussian 32×6432 \times 64 matrices with θ=0.1\theta = 0.1 and about 10 nonzeros, all 64 entries became nonzero and ∥z∥\|z\| passed 102810^{28} within 200 iterations in every run. The adaptive rule θt=ατt\theta_t = \alpha\tau_t avoids it in practice.
  • State evolution predicts averages over the entries in the large system limit. At small nn the agreement is rough, as the example shows.
  • Dropping the correction term gives a different algorithm with a different error. Do not compare "AMP" runs where the term is missing or uses the wrong count.

Implementations

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.

approximate_message_passing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/approximate-message-passing/. The authors are listed in prov/SKJZMH.jsonl.
"""Approximate message passing (AMP) with soft thresholding, and its state evolution.

A is a list of m rows of length n, scaled so that the columns have norm
close to 1 (i.i.d. N(0, 1/m) entries in the theory). The iteration of
Donoho, Maleki and Montanari (2009) is

    x^{t+1} = eta(x^t + A^T z^t; theta_t)
    z^{t+1} = y - A x^{t+1} + (||x^{t+1}||_0 / m) z^t

where eta is soft thresholding and the last term is the Onsager correction.
"""

import math


def soft(v, theta):
    """Soft thresholding eta(v; theta) = sign(v) max(|v| - theta, 0)."""
    if v > theta:
        return v - theta
    if v < -theta:
        return v + theta
    return 0.0


def _matvec(a, x):
    return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]


def _rmatvec(a, z):
    out = [0.0] * len(a[0])
    for row, zi in zip(a, z):
        if zi != 0.0:
            for j, aij in enumerate(row):
                out[j] += aij * zi
    return out


def amp(a, y, alpha=None, theta=None, iters=30, onsager=True, tol=0.0):
    """Run AMP. Returns (x, z, history).

    Give either alpha (threshold theta_t = alpha * ||z^t|| / sqrt(m), the rule
    of the paper) or a fixed threshold theta. With onsager=False the
    correction term is dropped, which gives plain iterative soft
    thresholding with the same thresholds. history holds (x^t, tau_t) with
    tau_t = ||z^t|| / sqrt(m), the estimate of the effective noise level.
    The loop stops early when ||x^{t+1} - x^t|| <= tol.
    """
    if (alpha is None) == (theta is None):
        raise ValueError("give exactly one of alpha and theta")
    m, n = len(a), len(a[0])
    x = [0.0] * n  # @line L1
    z = list(y)
    history = []
    for _ in range(iters):  # @line L2
        tau = math.sqrt(sum(v * v for v in z) / m)  # @line L3
        th = alpha * tau if alpha is not None else theta  # @line L4
        history.append((x, tau))
        r = _rmatvec(a, z)
        x_new = [soft(xj + rj, th) for xj, rj in zip(x, r)]  # @line L5
        b = sum(1 for v in x_new if v != 0.0) / m if onsager else 0.0  # @line L6
        ax = _matvec(a, x_new)
        z = [yi - axi + b * zi for yi, axi, zi in zip(y, ax, z)]  # @line L7
        step = math.sqrt(sum((p - q) ** 2 for p, q in zip(x_new, x)))
        x = x_new
        if step <= tol:
            break
    history.append((x, math.sqrt(sum(v * v for v in z) / m)))
    return x, z, history  # @line L8


def _gauss_expect(f, mu, tau, points=801, width=8.0):
    """E[f(mu + tau Z)] for Z ~ N(0, 1), by Simpson's rule on [-width, width]."""
    h = 2.0 * width / (points - 1)
    total = 0.0
    for k in range(points):
        u = -width + k * h
        w = 1.0 if k in (0, points - 1) else (4.0 if k % 2 else 2.0)
        total += w * f(mu + tau * u) * math.exp(-0.5 * u * u)
    return total * h / 3.0 / math.sqrt(2.0 * math.pi)


def mse_soft(prior, tau, theta):
    """E[(eta(X + tau Z; theta) - X)^2] for a discrete prior [(value, prob), ...]."""
    return sum(p * _gauss_expect(lambda w, x0=x0: (soft(w, theta) - x0) ** 2, x0, tau) for x0, p in prior)


def state_evolution(prior, delta, sigma2, alpha, steps):
    """tau_t^2 for t = 0..steps, from tau_{t+1}^2 = sigma2 + mse(tau_t, alpha tau_t) / delta.

    The start is tau_0^2 = sigma2 + E[X^2] / delta (the iteration starts at x = 0).
    Returns (taus2, mses) with mses[t] the predicted per-entry MSE of x^{t+1}.
    """
    taus2 = [sigma2 + sum(p * x0 * x0 for x0, p in prior) / delta]
    mses = []
    for _ in range(steps):
        tau = math.sqrt(taus2[-1])
        e = mse_soft(prior, tau, alpha * tau)
        mses.append(e)
        taus2.append(sigma2 + e / delta)
    return taus2, mses
test_approximate_message_passing.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/approximate-message-passing/. The authors are listed in prov/SKJZMH.jsonl.

import math
import random

from approximate_message_passing import amp, mse_soft, soft, state_evolution


def gauss_matrix(rng, m, n):
    return [[rng.gauss(0.0, 1.0) / math.sqrt(m) for _ in range(n)] for _ in range(m)]


def matvec(a, x):
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def lasso_cd(a, y, lam, sweeps=3000):
    """Reference LASSO solver: cyclic coordinate descent on 1/2 ||y - A x||^2 + lam ||x||_1."""
    m, n = len(a), len(a[0])
    cols = [[a[i][j] for i in range(m)] for j in range(n)]
    sq = [sum(v * v for v in c) for c in cols]
    x = [0.0] * n
    r = list(y)
    for _ in range(sweeps):
        change = 0.0
        for j in range(n):
            c = cols[j]
            rho = sum(ci * ri for ci, ri in zip(c, r)) + sq[j] * x[j]
            new = soft(rho, lam) / sq[j]
            d = new - x[j]
            if d != 0.0:
                r = [ri - d * ci for ri, ci in zip(r, c)]
                x[j] = new
                change = max(change, abs(d))
        if change < 1e-14:
            break
    return x


def test_soft_threshold():
    assert soft(3.0, 1.0) == 2.0
    assert soft(-3.0, 1.0) == -2.0
    assert soft(0.5, 1.0) == 0.0


def test_mse_of_soft_threshold_matches_closed_form_at_zero():
    # For X = 0: E[eta(tau Z; theta)^2] = 2 [(tau^2 + theta^2) Q(c) - tau theta phi(c)], c = theta / tau.
    tau, theta = 0.7, 1.1
    c = theta / tau
    q = 0.5 * math.erfc(c / math.sqrt(2.0))
    phi = math.exp(-0.5 * c * c) / math.sqrt(2.0 * math.pi)
    exact = 2.0 * ((tau * tau + theta * theta) * q - tau * theta * phi)
    # Simpson's rule loses accuracy at the two kinks of eta, so the tolerance is 1e-6.
    assert abs(mse_soft([(0.0, 1.0)], tau, theta) - exact) <= 1e-6


def test_fixed_point_solves_the_lasso():
    # At a fixed point with k = ||x||_0 < m, x solves the LASSO with
    # lambda = theta (1 - k/m). Check the KKT conditions and compare with
    # an independent coordinate descent solver.
    for seed in range(3):
        rng = random.Random(seed)
        m, n = 32, 64
        a = gauss_matrix(rng, m, n)
        x0 = [rng.gauss(0.0, 1.0) if rng.random() < 0.15 else 0.0 for _ in range(n)]
        y = [v + rng.gauss(0.0, 0.05) for v in matvec(a, x0)]
        x, z, hist = amp(a, y, alpha=2.0, iters=1000, tol=1e-13)
        assert len(hist) < 1001
        theta = 2.0 * hist[-2][1]
        k = sum(1 for v in x if v != 0.0)
        assert k < m
        lam = theta * (1.0 - k / m)
        r = [yi - v for yi, v in zip(y, matvec(a, x))]
        g = [sum(a[i][j] * r[i] for i in range(m)) for j in range(n)]
        for j in range(n):
            if x[j] != 0.0:
                assert abs(g[j] - lam * math.copysign(1.0, x[j])) <= 1e-9
            else:
                assert abs(g[j]) <= lam + 1e-9
        ref = lasso_cd(a, y, lam)
        assert math.sqrt(sum((p - q) ** 2 for p, q in zip(x, ref))) <= 1e-7


def test_noiseless_recovery_below_the_phase_transition():
    for seed in range(3):
        rng = random.Random(20 + seed)
        m, n, s = 64, 128, 6
        a = gauss_matrix(rng, m, n)
        x0 = [0.0] * n
        for i in rng.sample(range(n), s):
            x0[i] = rng.choice([-1.0, 1.0])
        x, _, _ = amp(a, matvec(a, x0), alpha=1.5, iters=200, tol=1e-13)
        assert math.sqrt(sum((p - q) ** 2 for p, q in zip(x, x0))) <= 1e-8


def test_state_evolution_predicts_the_mse_and_the_onsager_term_matters():
    # Prior: 0 with probability 0.9, +1 or -1 with probability 0.05 each.
    # delta = m/n = 1/2, no noise, alpha = 1.5. The prediction is for the
    # large system limit; at n = 400 the agreement is within about 25 percent.
    eps, alpha, n, m, steps = 0.1, 1.5, 400, 200, 6
    prior = [(0.0, 1.0 - eps), (1.0, eps / 2.0), (-1.0, eps / 2.0)]
    _, se = state_evolution(prior, m / n, 0.0, alpha, steps)
    with_term = [0.0] * steps
    without = [0.0] * steps
    trials = 2
    for tr in range(trials):
        rng = random.Random(10 + tr)
        a = gauss_matrix(rng, m, n)
        x0 = [rng.choice([1.0, -1.0]) if rng.random() < eps else 0.0 for _ in range(n)]
        y = matvec(a, x0)
        for ons, acc in ((True, with_term), (False, without)):
            _, _, hist = amp(a, y, alpha=alpha, iters=steps, onsager=ons)
            for t in range(steps):
                xt = hist[t + 1][0]
                acc[t] += sum((p - q) ** 2 for p, q in zip(xt, x0)) / n / trials
    for t in range(steps):
        assert abs(with_term[t] - se[t]) <= 0.3 * se[t]
    # State evolution decreases; without the Onsager term the error does not follow it.
    assert all(se[t + 1] < se[t] for t in range(steps - 1))
    assert without[-1] > 3.0 * se[-1]

History

The correction term has its origin in statistical physics: it is the Onsager reaction term of the Thouless-Anderson-Palmer equations for spin glasses (1977). Similar iterations appeared for CDMA multiuser detection, for example in the work of Kabashima (2003). Donoho, Maleki and Montanari (2009) derived AMP for compressed sensing from belief propagation on the dense bipartite graph of AA, by keeping only the leading terms of the messages. They introduced state evolution as a prediction of its error and showed that, with the threshold tuned to the sparsity, the phase transition of AMP matches the Donoho-Tanner transition of ℓ1\ell_1 minimization. Bayati and Montanari (2011) proved state evolution for Gaussian matrices. Later work extended the method to general priors, nonlinear channels and rotationally invariant matrices, and used it to compute the asymptotic risk of the LASSO.

References

  1. David L. Donoho, Arian Maleki and Andrea Montanari, Message-passing algorithms for compressed sensing, Proceedings of the National Academy of Sciences 106(45), 2009, pages 18914 to 18919 (the iteration with the correction term, state evolution and the phase transition)
  2. Mohsen Bayati and Andrea Montanari, The dynamics of message passing on dense graphs, with applications to compressed sensing, IEEE Transactions on Information Theory 57(2), 2011, pages 764 to 785 (the state evolution theorem for Gaussian matrices)

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 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)
WritingW1 outline
  • In plain words