Algorithmresearch
Compressed sensing with generative models
Also called CSGM.
Recover a signal from few linear measurements by searching the latent space of a trained generator for the output that best fits the measurements.
- Time
- O(s T (a + g)) worst
- Space
- O(n + m + k) extra
- Where
- T = the number of gradient steps per start; a = the cost of one call to A plus one call to its adjoint; g = the cost of one call to the generator plus one vector-Jacobian product (outside this page); k = the latent dimension; m = the number of measurements; n = the signal length; s = the number of starting codes
- Model
- Real RAM
- Properties
- deterministicnot exactiterativelearnedmatrix free
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ashish Bora, Ajil Jalal, Eric Price, Alexandros G. Dimakis, 2017
Compressed sensing with generative models (CSGM) recovers a signal from noisy linear measurements . Classical compressed sensing assumes that is sparse. CSGM assumes instead that is close to the range of a trained generator with , such as the decoder of a variational autoencoder or a GAN generator. It minimizes over the latent code by gradient descent from several random starts, and it returns . Bora, Jalal, Price and Dimakis (2017) proved that, for a Gaussian and an -Lipschitz generator, measurements are enough for any near minimizer to be close to . The search itself is nonconvex, and the bound says nothing about whether gradient descent finds a near minimizer.
In plain words
Suppose you want to take a picture of a face with far fewer sensor readings than there are pixels. In general this is impossible: many images fit the same readings. But faces are not arbitrary images. A trained generator can make a face from a short list of numbers, the code.
CSGM uses this. It looks for the code whose face, after you take the readings of it, matches the readings that you measured. It starts from a random code and changes it a little at a time to reduce the mismatch. Because the search can get stuck, it tries several random starts and keeps the best result. The answer is always a face that the generator can make, so it can only be as good as the generator is.
The problem
The input is the matrix (or functions that apply and ), the data , a generator with its vector-Jacobian product , a penalty weight , a step size , a number of steps and a list of starting codes. The output is , where is the code with the lowest final loss
This is the problem of sparse signal recovery with the set of sparse vectors replaced by , the image of a ball of codes. The penalty keeps the code where the generator was trained, since its codes were drawn from during training.
The algorithm
CSGM(y, A, G, J_G^T, starts, η, T, λ)- 1
best ← none, best_loss ← ∞ - 2
for each start z_0 in starts - 3
z ← z_0 - 4
for t = 1 to T - 5
g ← 2 J_G(z)^T A^T (A G(z) - y) + 2 λ z ▷ the gradient of f - 6
z ← z - η g - 7
if f(z) < best_loss then best ← z, best_loss ← f(z) - 8
return G(best)
Line L5 is the chain rule: the residual goes back through and then through the generator by one backpropagation pass. Line L6 is a gradient descent step; Bora et al. use the Adam optimizer instead, and any first-order method works here. Line L7 is the random restart rule: the run with the lowest loss wins, because the loss is the only thing the method can measure without .
Example
Take , , the generator , one measurement , no noise and no penalty. The true code is , so and . One measurement of two unknowns is not enough in general, but here is strictly increasing in , so only one code fits.
From with step : at the residual is and , so and . The next steps are:
| step | loss | |
|---|---|---|
| 1 | 0.734227 | 0.0907 |
| 2 | 0.674517 | 0.0567 |
| 3 | 0.620850 | 0.0303 |
| 4 | 0.576863 | 0.0134 |
| 5 | 0.544763 | 0.00484 |
| 10 | 0.501374 | |
| 20 | 0.500001 |
The first step overshoots, and the later steps approach from above. The output is exactly.
A non-example. With the measured value is . This function is 0 at , has its minimum near , and goes back to 0 as grows. So the value is fitted exactly by , which gives , and by , which gives . A start at finds the first and a start at finds the second. Both have zero loss, so the restart rule cannot choose between them. Here the measurement does not separate points of the range, which is exactly what the S-REC condition below forbids.
Correctness
The proof file proves the deterministic part of the guarantee (Bora et al., Lemma 4.3), which is a theorem.
Definition. satisfies if for all .
Theorem. Let satisfy , let be closest to , and suppose . If fits the data within of the best fit in , then
The proof uses S-REC once for and the triangle inequality twice. The first term is the error of the model: if is far from the range, no number of measurements helps. Bora et al. show (Lemma 4.1, a theorem) that a Gaussian with entries satisfies S-REC with near 1, with high probability, once for an -Lipschitz on codes of norm at most . For a -layer ReLU network, suffices with (Theorem 1.1). Their Theorem 1.2 states the combined result as with probability .
The bound is about any near minimizer. It does not say that lines L4 to L6 find one: is not convex in , and gradient descent can stop at a spurious stationary point or, with , run off to a region where the generator saturates. The tests show both cases on a seeded problem. That restarts find a good minimizer in practice is a heuristic; Bora et al. report it as an observation.
The proof file also shows that line L5 is the exact gradient of , so lines L5 and L6 are true gradient steps.
Proof: Under the set-restricted eigenvalue condition, any near minimizer of the CSGM loss is close to the signal, and the gradient steps use the exact gradientpartial
Setting. , a generator , a radius and the set , where is the ball of radius in . The data are for an unknown signal and noise . The signal need not lie in .
The status is partial: the deterministic error bound and the gradient are proved here; the statement that Gaussian matrices satisfy the condition with high probability is cited from Bora, Jalal, Price and Dimakis (2017, Lemmas 4.1 and 4.2), not proved. Nothing here says that gradient descent finds a near minimizer: the loss is not convex in , and the tests show a start that ends at a spurious stationary point.
Definition (S-REC). For and , the matrix satisfies if for all .
Theorem (deterministic part of Bora et al., Lemma 4.3). Suppose satisfies . Let be a point of closest to (or any point of ), and suppose . If satisfies , which holds in particular when , then
Proof. Both and lie in , so S-REC gives . By the triangle inequality and the assumption on ,
Since , the assumption on gives . Together,
Finally , and dividing the last display by gives the claim.
The probabilistic part (cited). Let have independent entries. For one fixed vector , has the chi-square law with degrees of freedom, so fails with probability ; apply this to , which does not depend on . Bora et al. (Lemma 4.1) prove: if is -Lipschitz and , then satisfies with probability . With fixed, this and the theorem give their Theorem 1.2: with , with probability , the error is at most a constant times ; the paper states the constants , , and for a suitable . Lemma 4.2 of the paper gives the same for a -layer ReLU network with and .
The gradient. Let and let be differentiable with Jacobian . Then
Proof. The differential of in a direction is , and that of is . For , entry by entry, , so ; this is the vector-Jacobian product in the implementation, and the tests check it against central differences. Lines L5 and L6 are therefore exact gradient steps on , and line L7 keeps the start with the lowest final loss.
The one-measurement example. For and , the map has the derivative , so it is strictly increasing and every in its range has exactly one code. Hence the minimizer of the noiseless loss is unique and equals the true code, although . For the map is not monotone on (it is 0 at , negative in between and tends to 0 as ), so two codes fit exactly. Here -REC fails for every and small: two different points of the range have the same measurement.
Complexity
The model is real-ram. Each gradient step calls once, its vector-Jacobian product once, once and once. With starts and steps per start, the time is , where is the cost of plus ( for a dense matrix) and is the cost of the generator plus one backward pass, which is outside this page. A backward pass costs a small constant times a forward pass. The extra space is for the current signal, residual and code, plus the activations that the backward pass of the generator stores.
The cost to compare is the lasso solved by ISTA, with per step and no network. CSGM trades this for the much smaller number of measurements that a good generator allows.
Properties
- Fewer measurements. The number of measurements scales with the latent dimension and the log of the Lipschitz constant, not with the sparsity level in a basis.
- Bounded by the generator. The output always lies in the range of . If is far from the range, the error stays large however many measurements you take.
- Not convex. The latent search can end at different points from different starts.
- Matrix free. The method needs only functions for , , and .
- Measured results. Bora et al. used a VAE with on MNIST () and a DCGAN with on celebA face images (). With a Gaussian , CSGM reached a given reconstruction error with 5 to 10 times fewer measurements than the lasso when was small. When was large, the lasso did better, because its error keeps going down while CSGM is limited by the range of the generator. These are measurements on those data sets.
Variants and improvements
- Sparse deviations. Allow with sparse, and penalize , so that signals just outside the range can be recovered (Dhar, Grover and Ermon 2018).
- Projected gradient. Alternate a gradient step on in signal space with a projection onto the range of , computed by an inner latent search or by a learned encoder (Shah and Hegde 2018).
- Untrained generators. Fit the weights of an untrained network instead of the code of a trained one; this is the deep image prior.
- Score-based priors. Replace the generator by a diffusion model and sample instead of minimize; see diffusion posterior sampling.
- Other measurement models. The same latent search works for any differentiable forward model, for example phase retrieval or one-bit measurements, by changing the data term.
When to use it
Use CSGM when signals of the target class are well described by a trained generator with a small latent space, when measurements are expensive, and when and the generator are both differentiable. Do not use it when the signals vary more than the generator can express, when you need recovery of fine detail that the generator did not learn, or when is large enough that the lasso or a variational method already works: then CSGM is slower and its error has a floor.
Pitfalls
- Representation error. A small loss means that fits the data, not that is close to . Check on test signals that the range of contains good approximations.
- No penalty. With the code can grow without bound where or other saturating layers are flat, and the gradient becomes too small to bring it back. A penalty keeps the code near the training distribution.
- Step size. The gradient scales with and with the Lipschitz constant of . A step that is too large oscillates; the example above already overshoots in step 1.
- Restarts are not free. The cost grows linearly in the number of starts. Run them in parallel when possible.
- Wrong scaling of . The theorems use entries. With entries the loss is times larger and the step must be times smaller.
Implementations
The generator is a given function: the code takes and its vector-Jacobian product as arguments and runs lines L1 to L8 around them. The tests build the generator by hand, as , or as a one-layer network with weights from a fixed seed; no generator is trained. The tests check the vector-Jacobian product and the gradient against central differences, the example values above and the convergence to , the two exact answers of the non-example, agreement with a fine grid search when , exact recovery of a signal with , and for four seeds, and a seeded start that fails without restarts, while the best of four starts recovers the signal.
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/compressed-sensing-generative-models/. The authors are listed in prov/ZV36YT.jsonl.
"""Compressed sensing with a generative model (CSGM) of Bora, Jalal, Price and Dimakis.
The generator is given: a function gen(z) from R^k to R^n and a function
gen_vjp(z, v) that returns J_G(z)^T v. The method minimizes
loss(z) = ||A G(z) - y||^2 + lam ||z||^2 by gradient steps from several
starting codes and returns G(z) for the code with the lowest loss.
Matrices are lists of rows; vectors are lists of floats.
"""
import math
def matvec(a, x):
"""The product A x."""
return [sum(v * w for v, w in zip(row, x)) for row in a]
def rmatvec(a, r):
"""The product A^T r."""
return [sum(a[i][j] * r[i] for i in range(len(a))) for j in range(len(a[0]))]
def loss(a, y, gen, z, lam):
"""||A G(z) - y||^2 + lam ||z||^2."""
r = [p - q for p, q in zip(matvec(a, gen(z)), y)]
return sum(v * v for v in r) + lam * sum(v * v for v in z)
def loss_grad(a, y, gen, gen_vjp, z, lam):
"""The gradient 2 J_G(z)^T A^T (A G(z) - y) + 2 lam z."""
r = [p - q for p, q in zip(matvec(a, gen(z)), y)]
g = gen_vjp(z, rmatvec(a, r))
return [2.0 * gi + 2.0 * lam * zi for gi, zi in zip(g, z)]
def csgm(a, y, gen, gen_vjp, starts, step, iters, lam=0.0):
"""Run iters gradient steps from each start code and keep the best.
Returns (x_hat, z_hat, loss). Each gradient step calls gen once,
gen_vjp once, A once and A^T once.
"""
best_z, best_loss = None, math.inf # @line L1
for z0 in starts: # @line L2
z = list(z0) # @line L3
for _ in range(iters): # @line L4
g = loss_grad(a, y, gen, gen_vjp, z, lam) # @line L5
z = [zi - step * gi for zi, gi in zip(z, g)] # @line L6
val = loss(a, y, gen, z, lam)
if val < best_loss: # @line L7
best_z, best_loss = z, val # @line L7
return gen(best_z), best_z, best_loss # @line L8
def tanh_generator(w, b):
"""The generator G(z) = tanh(W z + b) and its vector-Jacobian product.
J_G(z)^T v = W^T (v * (1 - tanh(W z + b)^2)), entry by entry.
"""
def gen(z):
return [math.tanh(s + bi) for s, bi in zip(matvec(w, z), b)]
def gen_vjp(z, v):
out = gen(z)
return rmatvec(w, [vi * (1.0 - oi * oi) for vi, oi in zip(v, out)])
return gen, gen_vjp
def gaussian_matrix(rng, m, n):
"""A with independent N(0, 1/m) entries, the design of the CSGM theorems."""
s = 1.0 / math.sqrt(m)
return [[rng.gauss(0.0, s) for _ in range(n)] for _ in range(m)]
test_compressed_sensing_generative_models.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/compressed-sensing-generative-models/. The authors are listed in prov/ZV36YT.jsonl.
import math
import random
from compressed_sensing_generative_models import (
csgm,
gaussian_matrix,
loss,
loss_grad,
matvec,
tanh_generator,
)
def seeded_problem(seed, n=20, k=2, m=5):
rng = random.Random(seed)
w = [[rng.gauss(0.0, 1.0 / math.sqrt(k)) for _ in range(k)] for _ in range(n)]
b = [rng.gauss(0.0, 0.1) for _ in range(n)]
gen, vjp = tanh_generator(w, b)
a = gaussian_matrix(rng, m, n)
z_true = [rng.gauss(0.0, 1.0) for _ in range(k)]
x_true = gen(z_true)
starts = [[rng.gauss(0.0, 1.0) for _ in range(k)] for _ in range(4)]
return a, gen, vjp, x_true, matvec(a, x_true), starts
def test_generator_jacobian_matches_finite_differences():
rng = random.Random(4)
n, k = 8, 3
w = [[rng.gauss(0.0, 1.0) for _ in range(k)] for _ in range(n)]
b = [rng.gauss(0.0, 0.5) for _ in range(n)]
gen, vjp = tanh_generator(w, b)
z = [rng.gauss(0.0, 1.0) for _ in range(k)]
v = [rng.gauss(0.0, 1.0) for _ in range(n)]
g = vjp(z, v)
h = 1e-6
for j in range(k):
zp, zm = list(z), list(z)
zp[j] += h
zm[j] -= h
fd = sum(vi * (p - q) for vi, p, q in zip(v, gen(zp), gen(zm))) / (2 * h)
assert abs(fd - g[j]) < 1e-7
def test_loss_gradient_matches_finite_differences():
a, gen, vjp, _, y, _ = seeded_problem(9, n=10, k=3, m=4)
z = [0.3, -0.7, 1.1]
g = loss_grad(a, y, gen, vjp, z, 0.1)
h = 1e-6
for j in range(3):
zp, zm = list(z), list(z)
zp[j] += h
zm[j] -= h
fd = (loss(a, y, gen, zp, 0.1) - loss(a, y, gen, zm, 0.1)) / (2 * h)
assert abs(fd - g[j]) < 1e-6
def test_one_measurement_of_a_curve():
gen, vjp = tanh_generator([[1.0], [2.0]], [0.0, 0.0])
a = [[1.0, 1.0]]
y = [math.tanh(0.5) + math.tanh(1.0)]
assert abs(y[0] - 1.2237113) < 1e-7
x1, z1, _ = csgm(a, y, gen, vjp, [[0.0]], 0.1, 1)
assert abs(z1[0] - 0.734227) < 1e-6
x, z, val = csgm(a, y, gen, vjp, [[0.0]], 0.1, 40)
assert abs(z[0] - 0.5) < 1e-9 and val < 1e-18
assert abs(x[0] - math.tanh(0.5)) < 1e-9 and abs(x[1] - math.tanh(1.0)) < 1e-9
def test_a_bad_measurement_has_two_answers():
gen, vjp = tanh_generator([[1.0], [2.0]], [0.0, 0.0])
a = [[1.0, -1.0]]
y = [-0.2]
xa, za, la = csgm(a, y, gen, vjp, [[0.1]], 0.2, 3000)
xb, zb, lb = csgm(a, y, gen, vjp, [[2.0]], 0.2, 3000)
assert la < 1e-16 and lb < 1e-16
assert abs(za[0] - 0.224106) < 1e-5 and abs(zb[0] - 1.008746) < 1e-5
assert math.dist(xa, xb) > 0.6
def test_grid_search_agrees_for_one_latent_variable():
rng = random.Random(12)
n, m = 12, 3
w = [[rng.gauss(0.0, 1.0)] for _ in range(n)]
b = [rng.gauss(0.0, 0.2) for _ in range(n)]
gen, vjp = tanh_generator(w, b)
a = gaussian_matrix(rng, m, n)
y = [v + rng.gauss(0.0, 0.05) for v in matvec(a, gen([0.8]))]
lam = 0.01
grid = [-3.0 + i * 0.0005 for i in range(12001)]
best = min(grid, key=lambda t: loss(a, y, gen, [t], lam))
starts = [[-2.0], [-0.5], [0.5], [2.0]]
_, z, val = csgm(a, y, gen, vjp, starts, 0.02, 2000, lam)
assert val <= loss(a, y, gen, [best], lam) + 1e-9
assert abs(z[0] - best) < 1e-3
def test_recovery_from_fewer_measurements_than_unknowns():
for seed in (1, 2, 3, 4):
a, gen, vjp, x_true, y, starts = seeded_problem(seed)
x, _, val = csgm(a, y, gen, vjp, starts[:3], 0.02, 800)
assert val < 1e-12
assert math.dist(x, x_true) < 1e-6
def test_bad_starts_and_restarts():
a, gen, vjp, x_true, y, starts = seeded_problem(5)
# Without the penalty this start runs off to where tanh saturates.
x_bad, z_bad, val_bad = csgm(a, y, gen, vjp, [starts[1]], 0.02, 800)
assert val_bad > 19.0 and abs(z_bad[0]) > 10.0
assert math.dist(x_bad, x_true) > 1.0
# With lam = 0.1 it stops at a spurious stationary point.
_, z_loc, val_loc = csgm(a, y, gen, vjp, [starts[1]], 0.02, 3000, 0.1)
assert val_loc > 20.0 and math.hypot(*loss_grad(a, y, gen, vjp, z_loc, 0.1)) < 1e-8
# The best of four starts finds the true code.
x, _, val = csgm(a, y, gen, vjp, starts, 0.02, 800)
assert val < 1e-12 and math.dist(x, x_true) < 1e-6
History
Compressed sensing (Candes, Romberg and Tao 2006; Donoho 2006) recovers sparse signals from few random measurements, and model-based compressed sensing extended it to structured sparsity. Bora, Jalal, Price and Dimakis (2017) replaced sparsity by the range of a deep generator and gave the S-REC analysis. Later work proved that, for random ReLU generators with enough expansion, the latent loss has no stationary points except near the true code and near one negative multiple of it (Hand and Voroninski 2018), studied mismatch between the signal and the range, and moved from generators to score-based and diffusion priors.
References
- Ashish Bora, Ajil Jalal, Eric Price and Alexandros G. Dimakis, Compressed sensing using generative models, Proceedings of the 34th International Conference on Machine Learning, PMLR 70, 2017, pages 537 to 546 (Definition 1 of S-REC, Lemmas 4.1 to 4.3 and Theorems 1.1 and 1.2 for the bounds, Section 6 and Figure 1 for the experiments)
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 | W2 basic |
|
Tag ZV36YT Edit this page History Report an error Markdown