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.
- Solves
- Sparse signal recovery
- 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
- Model
- Real RAM
- Properties
- deterministiciterativematrix free
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David L. Donoho, Arian Maleki, Andrea Montanari, 2009
Approximate message passing (AMP) recovers a sparse vector from with a random matrix . Each step looks like a step of iterative shrinkage-thresholding: it applies soft thresholding to . The difference is the residual: AMP adds the Onsager correction to . For a matrix with i.i.d. Gaussian entries, this term makes the error in behave like Gaussian noise of a known variance 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 .
The problem
Given , and a threshold parameter, find an estimate of a sparse , where , has i.i.d. entries of mean 0 and variance , and is noise of variance per entry. Write for the undersampling ratio. The output is the estimate , and with it the estimate of the effective noise level. The column scaling matters: the theory assumes columns of norm close to 1.
The algorithm
is soft thresholding, the proximal operator of , applied entry by entry.
AMP(A, y, α, K)- 1
x ← 0, z ← y - 2
for t = 0 to K - 1 - 3
τ ← ‖z‖ / √m ▷ estimate of the effective noise level - 4
θ ← α τ ▷ threshold proportional to the noise level - 5
x_new ← η(x + Aᵀ z; θ) ▷ soft thresholding, as in ISTA - 6
b ← ‖x_new‖₀ / m ▷ Onsager coefficient - 7
z ← y - A x_new + b z, x ← x_new ▷ residual with the correction term - 8
return x, z
Line L6 is the average derivative of divided by : is 1 where the input passes the threshold and 0 elsewhere, so . Without the term in line L7, the loop is iterative soft thresholding with unit step and a varying threshold. The threshold rule is the one of Donoho, Maleki and Montanari. A fixed also works in the theory, but in practice it can make the loop diverge (see Pitfalls).
Example
Take , no noise, and a signal whose entries are 0 with probability 0.9 and or with probability 0.05 each. Use . State evolution starts with , because the first step sees , whose error has variance per entry. Each later step sets with a standard normal .
The table compares the predicted mean squared error per entry of with the average over two runs with , (seeds 10 and 11 of the test file), with and without the correction term. The run values are measurements.
| 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 . 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 comes from the finite size: the number of nonzero entries of itself varies by about 15 percent at .
Correctness
The full proof is in proofs/correctness.md. It proves two facts that hold for every matrix:
- The correction coefficient equals , the form in the paper.
- If is a fixed point with threshold and , then minimizes with . The equation gives , and the fixed point of soft thresholding says that is times a subgradient of . Multiplying by 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 , with and a fixed number of iterations, the empirical distribution of the pairs converges to that of . 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. is a real matrix and . The soft threshold function is for , applied entry by entry to vectors. AMP starts from , and repeats, for ,
The threshold is either a fixed or with .
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 , with and .
Lemma 1. For , if and if . Hence, with and no entry with ,
Proof. On the function is , on it is , and on it is 0. The entries with are exactly the nonzero entries of .
An entry with exactly gives , and counting it as 0 is the convention used by the implementation.
Part 2: fixed points are LASSO solutions
Lemma 2. For and real numbers , : if and only if when , and when . In other words, .
Proof. Let and . A nonzero output has the sign of the input and magnitude , so and . Conversely, if , then and . Let . Then holds if and only if .
Theorem. Let be a fixed point of the iteration with a fixed threshold , that is and with . If , then minimizes
The same holds for the adaptive rule : at a fixed point does not change, so and are constant, and the theorem applies with .
Proof. The second equation gives . Since , the factor is positive and . By Lemma 2 applied to each entry, the first equation says that for all . Multiply by :
This is the condition . is convex, so a point where is a subgradient is a global minimizer.
If , the factor is zero or negative, and the fixed point equation for either forces 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 reaches 1 and grows. The adaptive rule avoids this because grows with .
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 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 have i.i.d. entries, with noise of variance per entry, and let with while the empirical distribution of the entries of converges to the law of a random variable (with the moment conditions of the theorem). Define and
Bayati and Montanari (2011) prove that for each fixed , and for every pseudo-Lipschitz function , almost surely. With this says that the mean squared error of 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 is not Gaussian with the predicted variance, and the prediction fails. The statement is for a fixed number of iterations as and for Gaussian matrices; it is not a statement about one finite matrix.
Complexity
Each iteration costs one product with and one with , which is for a dense matrix, and for the threshold and the counts. So iterations cost time and 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 (noiseless recovery below the phase transition), the error decreases geometrically, so the number of iterations for accuracy is 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 is close to with Gaussian , so each step is a scalar denoising problem. This is why the threshold can be set from , and why other denoisers can replace .
- Fixed points are LASSO solutions, and the map from to the LASSO weight 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 by the posterior mean of given 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 , 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 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 . 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 . Then the coefficient reaches 1 and blows up. In 10 runs on random Gaussian matrices with and about 10 nonzeros, all 64 entries became nonzero and passed within 200 iterations in every run. The adaptive rule avoids it in practice.
- State evolution predicts averages over the entries in the large system limit. At small 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.
# 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 , 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 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W1 outline |
|
Tag SKJZMH Edit this page History Report an error Markdown