Algorithm Search⌘K

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
Properties
deterministicnot exactiterativelearnedmatrix free
Origin
Ashish Bora, Ajil Jalal, Eric Price, Alexandros G. Dimakis, 2017

Compressed sensing with generative models (CSGM) recovers a signal x∗∈Rnx^* \in \mathbb{R}^n from m≪nm \ll n noisy linear measurements y=Ax∗+ηy = Ax^* + \eta. Classical compressed sensing assumes that x∗x^* is sparse. CSGM assumes instead that x∗x^* is close to the range of a trained generator G:Rk→RnG : \mathbb{R}^k \to \mathbb{R}^n with k≪nk \ll n, such as the decoder of a variational autoencoder or a GAN generator. It minimizes ∥AG(z)−y∥2+λ∥z∥2\|AG(z) - y\|^2 + \lambda\|z\|^2 over the latent code zz by gradient descent from several random starts, and it returns G(z^)G(\hat z). Bora, Jalal, Price and Dimakis (2017) proved that, for a Gaussian AA and an LL-Lipschitz generator, m=O(klog⁡(Lr/δ))m = O(k\log(Lr/\delta)) measurements are enough for any near minimizer to be close to x∗x^*. 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 A∈Rm×nA \in \mathbb{R}^{m \times n} (or functions that apply AA and ATA^T), the data y∈Rmy \in \mathbb{R}^m, a generator GG with its vector-Jacobian product v↦JG(z)Tvv \mapsto J_G(z)^Tv, a penalty weight λ≥0\lambda \ge 0, a step size η\eta, a number of steps TT and a list of starting codes. The output is x^=G(z^)\hat x = G(\hat z), where z^\hat z is the code with the lowest final loss

f(z)=∥AG(z)−y∥2+λ∥z∥2.f(z) = \|AG(z) - y\|^2 + \lambda\|z\|^2.

This is the problem of sparse signal recovery with the set of sparse vectors replaced by S=G(Bk(r))S = G(B^k(r)), the image of a ball of codes. The penalty λ∥z∥2\lambda\|z\|^2 keeps the code where the generator was trained, since its codes were drawn from N(0,I)N(0, I) during training.

The algorithm

  1. CSGM(y, A, G, J_G^T, starts, η, T, λ)
  2. 1best ← none, best_loss ← ∞
  3. 2for each start z_0 in starts
  4. 3z ← z_0
  5. 4for t = 1 to T
  6. 5g ← 2 J_G(z)^T A^T (A G(z) - y) + 2 λ z ▷ the gradient of f
  7. 6z ← z - η g
  8. 7if f(z) < best_loss then best ← z, best_loss ← f(z)
  9. 8return G(best)

Line L5 is the chain rule: the residual AG(z)−yAG(z) - y goes back through ATA^T 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 x∗x^*.

Example

Take n=2n = 2, k=1k = 1, the generator G(z)=(tanh⁡z,tanh⁡2z)G(z) = (\tanh z, \tanh 2z), one measurement A=(1  1)A = (1\ \ 1), no noise and no penalty. The true code is z∗=0.5z^* = 0.5, so x∗=(0.462117,0.761594)x^* = (0.462117, 0.761594) and y=1.2237113y = 1.2237113. One measurement of two unknowns is not enough in general, but here AG(z)=tanh⁡z+tanh⁡2zAG(z) = \tanh z + \tanh 2z is strictly increasing in zz, so only one code fits.

From z0=0z_0 = 0 with step η=0.1\eta = 0.1: at z=0z = 0 the residual is −1.2237-1.2237 and JG(0)TAT=1+2=3J_G(0)^TA^T = 1 + 2 = 3, so g=2⋅3⋅(−1.2237)=−7.3423g = 2 \cdot 3 \cdot (-1.2237) = -7.3423 and z1=0.734227z_1 = 0.734227. The next steps are:

step tt ztz_t loss f(zt)f(z_t)
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 z∗=0.5z^* = 0.5 from above. The output is G(0.5)=x∗G(0.5) = x^* exactly.

A non-example. With A=(1  −1)A = (1\ \ {-1}) the measured value is tanh⁡z−tanh⁡2z\tanh z - \tanh 2z. This function is 0 at z=0z = 0, has its minimum −0.30028-0.30028 near z=0.531z = 0.531, and goes back to 0 as zz grows. So the value y=−0.2y = -0.2 is fitted exactly by z=0.22411z = 0.22411, which gives x=(0.22043,0.42043)x = (0.22043, 0.42043), and by z=1.00875z = 1.00875, which gives x=(0.76524,0.96524)x = (0.76524, 0.96524). A start at 0.10.1 finds the first and a start at 22 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. AA satisfies S-REC(S,γ,δ)\text{S-REC}(S, \gamma, \delta) if ∥A(x1−x2)∥≥γ∥x1−x2∥−δ\|A(x_1 - x_2)\| \ge \gamma\|x_1 - x_2\| - \delta for all x1,x2∈Sx_1, x_2 \in S.

Theorem. Let AA satisfy S-REC(S,γ,δ)\text{S-REC}(S, \gamma, \delta), let xˉ∈S\bar x \in S be closest to x∗x^*, and suppose ∥A(x∗−xˉ)∥≤2∥x∗−xˉ∥\|A(x^* - \bar x)\| \le 2\|x^* - \bar x\|. If x^∈S\hat x \in S fits the data within ε\varepsilon of the best fit in SS, then

∥x^−x∗∥≤(4γ+1)min⁡x∈S∥x∗−x∥+1γ(2∥η∥+ε+δ).\|\hat x - x^*\| \le \Big(\frac4\gamma + 1\Big)\min_{x \in S}\|x^* - x\| + \frac1\gamma\big(2\|\eta\| + \varepsilon + \delta\big).

The proof uses S-REC once for x^−xˉ\hat x - \bar x and the triangle inequality twice. The first term is the error of the model: if x∗x^* is far from the range, no number of measurements helps. Bora et al. show (Lemma 4.1, a theorem) that a Gaussian AA with N(0,1/m)N(0, 1/m) entries satisfies S-REC with γ\gamma near 1, with high probability, once m=Ω(klog⁡(Lr/δ))m = \Omega(k\log(Lr/\delta)) for an LL-Lipschitz GG on codes of norm at most rr. For a dd-layer ReLU network, m=O(kdlog⁡n)m = O(kd\log n) suffices with δ=0\delta = 0 (Theorem 1.1). Their Theorem 1.2 states the combined result as ∥G(z^)−x∗∥≤6min⁡∥z∥≤r∥G(z)−x∗∥+3∥η∥+2ε+2δ\|G(\hat z) - x^*\| \le 6\min_{\|z\| \le r}\|G(z) - x^*\| + 3\|\eta\| + 2\varepsilon + 2\delta with probability 1−e−Ω(m)1 - e^{-\Omega(m)}.

The bound is about any near minimizer. It does not say that lines L4 to L6 find one: ff is not convex in zz, and gradient descent can stop at a spurious stationary point or, with λ=0\lambda = 0, 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 ff, 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∈Rm×nA \in \mathbb{R}^{m \times n}, a generator G:Rk→RnG : \mathbb{R}^k \to \mathbb{R}^n, a radius r>0r > 0 and the set S=G(Bk(r))S = G(B^k(r)), where Bk(r)B^k(r) is the ball of radius rr in Rk\mathbb{R}^k. The data are y=Ax∗+ηy = Ax^* + \eta for an unknown signal x∗∈Rnx^* \in \mathbb{R}^n and noise η\eta. The signal need not lie in SS.

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 zz, and the tests show a start that ends at a spurious stationary point.

Definition (S-REC). For γ>0\gamma > 0 and δ≥0\delta \ge 0, the matrix AA satisfies S-REC(S,γ,δ)\text{S-REC}(S, \gamma, \delta) if ∥A(x1−x2)∥≥γ∥x1−x2∥−δ\|A(x_1 - x_2)\| \ge \gamma\|x_1 - x_2\| - \delta for all x1,x2∈Sx_1, x_2 \in S.

Theorem (deterministic part of Bora et al., Lemma 4.3). Suppose AA satisfies S-REC(S,γ,δ)\text{S-REC}(S, \gamma, \delta). Let xˉ∈S\bar x \in S be a point of SS closest to x∗x^* (or any point of SS), and suppose ∥A(x∗−xˉ)∥≤2∥x∗−xˉ∥\|A(x^* - \bar x)\| \le 2\|x^* - \bar x\|. If x^∈S\hat x \in S satisfies ∥y−Ax^∥≤∥y−Axˉ∥+ε\|y - A\hat x\| \le \|y - A\bar x\| + \varepsilon, which holds in particular when ∥y−Ax^∥≤min⁡x∈S∥y−Ax∥+ε\|y - A\hat x\| \le \min_{x \in S}\|y - Ax\| + \varepsilon, then

∥x^−x∗∥≤(4γ+1)∥x∗−xˉ∥+1γ(2∥η∥+ε+δ).\|\hat x - x^*\| \le \Big(\frac4\gamma + 1\Big)\|x^* - \bar x\| + \frac1\gamma\big(2\|\eta\| + \varepsilon + \delta\big).

Proof. Both x^\hat x and xˉ\bar x lie in SS, so S-REC gives γ∥x^−xˉ∥≤∥A(x^−xˉ)∥+δ\gamma\|\hat x - \bar x\| \le \|A(\hat x - \bar x)\| + \delta. By the triangle inequality and the assumption on x^\hat x,

∥A(x^−xˉ)∥≤∥Ax^−y∥+∥y−Axˉ∥≤2∥y−Axˉ∥+ε.\|A(\hat x - \bar x)\| \le \|A\hat x - y\| + \|y - A\bar x\| \le 2\|y - A\bar x\| + \varepsilon.

Since y−Axˉ=A(x∗−xˉ)+ηy - A\bar x = A(x^* - \bar x) + \eta, the assumption on xˉ\bar x gives ∥y−Axˉ∥≤2∥x∗−xˉ∥+∥η∥\|y - A\bar x\| \le 2\|x^* - \bar x\| + \|\eta\|. Together,

γ∥x^−xˉ∥≤4∥x∗−xˉ∥+2∥η∥+ε+δ.\gamma\|\hat x - \bar x\| \le 4\|x^* - \bar x\| + 2\|\eta\| + \varepsilon + \delta.

Finally ∥x^−x∗∥≤∥x^−xˉ∥+∥xˉ−x∗∥\|\hat x - x^*\| \le \|\hat x - \bar x\| + \|\bar x - x^*\|, and dividing the last display by γ\gamma gives the claim.

The probabilistic part (cited). Let AA have independent N(0,1/m)N(0, 1/m) entries. For one fixed vector vv, m∥Av∥2/∥v∥2m\|Av\|^2/\|v\|^2 has the chi-square law with mm degrees of freedom, so ∥Av∥≤2∥v∥\|Av\| \le 2\|v\| fails with probability e−Ω(m)e^{-\Omega(m)}; apply this to v=x∗−xˉv = x^* - \bar x, which does not depend on AA. Bora et al. (Lemma 4.1) prove: if GG is LL-Lipschitz and m=Ω((k/α2)log⁡(Lr/δ))m = \Omega\big((k/\alpha^2)\log(Lr/\delta)\big), then AA satisfies S-REC(G(Bk(r)),1−α,δ)\text{S-REC}(G(B^k(r)), 1 - \alpha, \delta) with probability 1−e−Ω(α2m)1 - e^{-\Omega(\alpha^2 m)}. With α\alpha fixed, this and the theorem give their Theorem 1.2: with m=O(klog⁡(Lr/δ))m = O(k\log(Lr/\delta)), with probability 1−e−Ω(m)1 - e^{-\Omega(m)}, the error is at most a constant times min⁡∥z∥≤r∥G(z)−x∗∥+∥η∥+ε+δ\min_{\|z\| \le r}\|G(z) - x^*\| + \|\eta\| + \varepsilon + \delta; the paper states the constants 66, 33, 22 and 22 for a suitable α\alpha. Lemma 4.2 of the paper gives the same for a dd-layer ReLU network with m=Ω((1/α2)kdlog⁡n)m = \Omega\big((1/\alpha^2) k d\log n\big) and δ=0\delta = 0.

The gradient. Let f(z)=∥AG(z)−y∥2+λ∥z∥2f(z) = \|AG(z) - y\|^2 + \lambda\|z\|^2 and let GG be differentiable with Jacobian JG(z)∈Rn×kJ_G(z) \in \mathbb{R}^{n \times k}. Then

∇f(z)=2JG(z)TAT(AG(z)−y)+2λz.\nabla f(z) = 2J_G(z)^TA^T\big(AG(z) - y\big) + 2\lambda z.

Proof. The differential of z↦∥AG(z)−y∥2z \mapsto \|AG(z) - y\|^2 in a direction uu is 2⟨AG(z)−y,AJG(z)u⟩=⟨2JG(z)TAT(AG(z)−y),u⟩2\langle AG(z) - y, AJ_G(z)u\rangle = \langle 2J_G(z)^TA^T(AG(z) - y), u\rangle, and that of λ∥z∥2\lambda\|z\|^2 is ⟨2λz,u⟩\langle 2\lambda z, u\rangle. For G(z)=tanh⁡(Wz+b)G(z) = \tanh(Wz + b), entry by entry, JG(z)=diag⁡(1−G(z)2) WJ_G(z) = \operatorname{diag}(1 - G(z)^2)\,W, so JG(z)Tv=WT(v⊙(1−G(z)2))J_G(z)^Tv = W^T\big(v \odot (1 - G(z)^2)\big); 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 ff, and line L7 keeps the start with the lowest final loss.

The one-measurement example. For G(z)=(tanh⁡z,tanh⁡2z)G(z) = (\tanh z, \tanh 2z) and A=(1  1)A = (1\ \ 1), the map z↦AG(z)=tanh⁡z+tanh⁡2zz \mapsto AG(z) = \tanh z + \tanh 2z has the derivative (1−tanh⁡2z)+2(1−tanh⁡22z)>0(1 - \tanh^2 z) + 2(1 - \tanh^2 2z) > 0, so it is strictly increasing and every yy in its range has exactly one code. Hence the minimizer of the noiseless loss is unique and equals the true code, although m=1<n=2m = 1 < n = 2. For A=(1  −1)A = (1\ \ {-1}) the map tanh⁡z−tanh⁡2z\tanh z - \tanh 2z is not monotone on z>0z > 0 (it is 0 at z=0z = 0, negative in between and tends to 0 as z→∞z \to \infty), so two codes fit y=−0.2y = -0.2 exactly. Here SS-REC fails for every γ>0\gamma > 0 and δ\delta small: two different points of the range have the same measurement.

Complexity

The model is real-ram. Each gradient step calls GG once, its vector-Jacobian product once, AA once and ATA^T once. With ss starts and TT steps per start, the time is O(sT(a+g))O(sT(a + g)), where aa is the cost of AA plus ATA^T (O(mn)O(mn) for a dense matrix) and gg 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 O(n+m+k)O(n + m + k) 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 O(mn)O(mn) 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 kk 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 GG. If x∗x^* 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 AA, ATA^T, GG and JGTJ_G^T.
  • Measured results. Bora et al. used a VAE with k=20k = 20 on MNIST (λ=0.1\lambda = 0.1) and a DCGAN with k=100k = 100 on celebA face images (λ=0.001\lambda = 0.001). With a Gaussian AA, CSGM reached a given reconstruction error with 5 to 10 times fewer measurements than the lasso when mm was small. When mm 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 x=G(z)+νx = G(z) + \nu with ν\nu sparse, and penalize ∥ν∥1\|\nu\|_1, so that signals just outside the range can be recovered (Dhar, Grover and Ermon 2018).
  • Projected gradient. Alternate a gradient step on ∥Ax−y∥2\|Ax - y\|^2 in signal space with a projection onto the range of GG, 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 AA 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 mm 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 AG(z^)AG(\hat z) fits the data, not that G(z^)G(\hat z) is close to x∗x^*. Check on test signals that the range of GG contains good approximations.
  • No penalty. With λ=0\lambda = 0 the code can grow without bound where tanh⁡\tanh 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 ∥A∥2\|A\|^2 and with the Lipschitz constant of GG. 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 AA. The theorems use N(0,1/m)N(0, 1/m) entries. With N(0,1)N(0, 1) entries the loss is mm times larger and the step must be mm times smaller.

Implementations

The generator is a given function: the code takes GG and its vector-Jacobian product as arguments and runs lines L1 to L8 around them. The tests build the generator by hand, as G(z)=(tanh⁡z,tanh⁡2z)G(z) = (\tanh z, \tanh 2z), or as a one-layer network tanh⁡(Wz+b)\tanh(Wz + b) 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 z∗=0.5z^* = 0.5, the two exact answers of the non-example, agreement with a fine grid search when k=1k = 1, exact recovery of a signal with n=20n = 20, k=2k = 2 and m=5m = 5 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.

compressed_sensing_generative_models.pyI0RawGitHub
# 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

  1. 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.

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
  • at least three sources
  • a scene preset for the example