Algorithm Search⌘K

Techniqueresearch

Bilevel learning of regularizers

Also called bilevel parameter learning.

Learn the parameters of a variational regularizer by minimizing the error of its reconstructions on training data, a bilevel optimization problem.

Bilevel learning chooses the parameters θ\theta of a variational reconstruction method from training pairs (xi,yi)(x_i, y_i), with yi=Axi+eiy_i = Ax_i + e_i. The lower level is the reconstruction itself, and the upper level scores it against the true images:

min⁡θ L(θ)=1N∑i=1N∥xθ(yi)−xi∥2,xθ(y)=arg⁡min⁡x E(x;θ,y)=∥Ax−y∥2+Rθ(x).\min_\theta\ L(\theta) = \frac1N\sum_{i=1}^N\big\|x_\theta(y_i) - x_i\big\|^2, \qquad x_\theta(y) = \arg\min_x\ E(x; \theta, y) = \|Ax - y\|^2 + R_\theta(x).

The parameters can be one regularization weight, weights of several penalties, filters inside the regularizer, or weights of the data terms. Haber and Tenorio (2003) set this up for inverse problems, and Kunisch and Pock (2013) and De los Reyes and Schönlieb (2013) developed it for variational image models. The gradient of LL comes from the implicit function theorem and one adjoint solve per pair.

In plain words

A variational method has knobs, such as how strongly to smooth. Normally a person sets them by hand or by a rule that uses only the measured data. Bilevel learning sets them from examples where the true image is known. For each candidate setting, it runs the reconstruction on the examples and measures how far the results are from the true images. Then it changes the setting in the direction that makes this error smaller. The inner reconstruction is an optimization problem, and the outer search is another one, which is why it is called bilevel.

When it applies

Setting. The lower-level energy E(x;θ,y)E(x; \theta, y) is twice differentiable in xx and differentiable in θ\theta, and has a unique minimizer xθ(y)x_\theta(y) with an invertible Hessian H=∇x2E(xθ;θ,y)H = \nabla_x^2E(x_\theta; \theta, y). The training pairs come from the same source as the data to be reconstructed.

Fact 1 (the gradient, by the implicit function theorem). The minimizer satisfies ∇xE(xθ;θ,y)=0\nabla_xE(x_\theta; \theta, y) = 0. Differentiating in θ\theta gives

H ∂xθ∂θ=− ∂θ∇xE(xθ;θ,y).H\,\frac{\partial x_\theta}{\partial\theta} = -\,\partial_\theta\nabla_xE(x_\theta; \theta, y).

So for the upper loss ℓ(x)=∥x−xi∥2\ell(x) = \|x - x_i\|^2, solve the adjoint system Hp=∇ℓ(xθ)=2(xθ−xi)Hp = \nabla\ell(x_\theta) = 2(x_\theta - x_i), and then

∇θℓ(xθ(yi))=−(∂θ∇xE)Tp.\nabla_\theta\ell\big(x_\theta(y_i)\big) = -\big(\partial_\theta\nabla_xE\big)^Tp.

This is a theorem under the conditions above. Each pair needs one lower-level solve and one linear solve with HH, whatever the number of parameters.

Fact 2 (Tikhonov). For E=∥Ax−y∥2+α∥x∥2E = \|Ax - y\|^2 + \alpha\|x\|^2, the minimizer solves (ATA+αI)xα=ATy(A^TA + \alpha I)x_\alpha = A^Ty, and Fact 1 gives

dxαdα=−(ATA+αI)−1xα.\frac{dx_\alpha}{d\alpha} = -(A^TA + \alpha I)^{-1}x_\alpha.

Both levels are then exact, which makes Tikhonov the test case.

Fact 3 (what is learned). In the scalar model x∼N(0,σx2)x \sim N(0, \sigma_x^2), y=x+ey = x + e with e∼N(0,σ2)e \sim N(0, \sigma^2), the expected upper loss of xα=y/(1+α)x_\alpha = y/(1 + \alpha) is

E(xα−x)2=α2σx2+σ2(1+α)2,\mathbb{E}(x_\alpha - x)^2 = \frac{\alpha^2\sigma_x^2 + \sigma^2}{(1 + \alpha)^2},

which is smallest at α=σ2/σx2\alpha = \sigma^2/\sigma_x^2, with the value σ2σx2/(σx2+σ2)\sigma^2\sigma_x^2/(\sigma_x^2 + \sigma^2), the posterior variance. So with many pairs, bilevel learning recovers the weight of the Bayes estimator for a linear Gaussian problem. With few pairs, it fits those pairs.

Use bilevel learning when there are training pairs and the regularizer has few, meaningful parameters, so that the learned method stays a variational method that can be analyzed. If the regularizer is nonsmooth, such as total variation, smooth it first or use a nonsmooth analysis; Kunisch and Pock and De los Reyes and Schönlieb treat such cases.

The template

  1. BILEVEL-LEARN(pairs (x_i, y_i), LOWER, α_0, η, K)
  2. 1α ← α_0
  3. 2for k = 1 to K
  4. 3g ← 0
  5. 4for each pair (x_i, y_i), i = 1 to N
  6. 5x ← LOWER(α, y_i) ▷ hole: the lower-level solver, a given function
  7. 6g ← g + (2/N) ⟨dx/dα, x - x_i⟩ ▷ adjoint solve, Fact 1
  8. 7α ← max(α - η g, 0) ▷ projected gradient step
  9. 8return α

The holes are the lower-level energy and its solver, the parameters, the upper loss and the outer optimizer. The template learns one weight α≥0\alpha \geq 0 by projected gradient descent; for many parameters, α\alpha becomes a vector and the outer optimizer is often a quasi-Newton method. Each outer step costs NN lower-level solves and NN adjoint solves. If the lower level is solved only approximately, the gradient is approximate too, and the outer method needs a solve accuracy that grows as it converges.

The lower-level solver and the product ⟨dx/dα,v⟩\langle dx/d\alpha, v\rangle are given functions: the code takes them as arguments and runs lines L1 to L8 around them. The tests build them by hand, for Tikhonov in closed form by Fact 2 or as y/(1+α)y/(1 + \alpha) for a scalar problem, and draw the training pairs from fixed seeds; no network is trained. They check the hand example below, that the projection keeps α\alpha at 0 when the data asks for less than no smoothing, the adjoint gradient against finite differences, that the learned weight matches a grid search on a seeded problem, and Fact 3 on 2000 seeded pairs.

Classic examples

One pair by hand. Let A=1A = 1, x1=1x_1 = 1 and y1=1.2y_1 = 1.2. Then xα=1.2/(1+α)x_\alpha = 1.2/(1 + \alpha) and L(α)=(xα−1)2L(\alpha) = (x_\alpha - 1)^2. At α=1\alpha = 1: xα=0.6x_\alpha = 0.6, L=0.16L = 0.16, dx/dα=−0.6/2=−0.3dx/d\alpha = -0.6/2 = -0.3 by Fact 2, and dL/dα=2(−0.4)(−0.3)=0.24dL/d\alpha = 2(-0.4)(-0.3) = 0.24. The minimizer is α=0.2\alpha = 0.2, where xα=1x_\alpha = 1 and L=0L = 0; projected gradient descent with η=0.5\eta = 0.5 reaches it from α=1\alpha = 1. With y1=0.8y_1 = 0.8 instead, every α≥0\alpha \geq 0 shrinks the estimate further from 1, so the learned weight is α=0\alpha = 0, with L=0.04L = 0.04.

Many scalar pairs. Draw 2000 pairs with σx=1\sigma_x = 1 and σ=0.5\sigma = 0.5 (seed 6). Fact 3 predicts α=0.25\alpha = 0.25 and a loss of 0.2 for infinitely many pairs. The learned weight is 0.2677, which equals the exact minimizer ∑yi2/∑xiyi−1\sum y_i^2/\sum x_iy_i - 1 for this sample. The difference from 0.25 is sampling error, a measurement for this seed.

A seeded matrix problem. A Gaussian 5×45 \times 4 matrix, four training pairs and noise of standard deviation 0.5 (seed 5). Projected gradient descent from α=1\alpha = 1 with η=0.5\eta = 0.5 lowers the loss from 0.340 to 0.255 and stops at α=0.36527\alpha = 0.36527, which matches a grid search with spacing 10−310^{-3}.

Image models. Kunisch and Pock learn the weights of filter-based regularizers for denoising, and De los Reyes and Schönlieb learn the weights of the data terms for mixed noise. Their results on test images are measurements.

Variations

  • Many parameters. Learn filters and penalty functions inside the regularizer, as in Kunisch and Pock. Fact 1 still needs only one adjoint solve per pair.
  • Unrolled lower level. Replace the exact minimizer by KK steps of a solver and backpropagate through them. This is algorithm unrolling, and the learned parameters may then depend on KK.
  • Learning the data term. Learn the weights of several noise models, as De los Reyes and Schönlieb do.
  • Without true images. Replace the upper loss by an unbiased estimate of the error, such as the Stein unbiased risk estimate, or by cross-validation on the data.

Pitfalls

  • Nonsmooth lower levels. With total variation or an ℓ1\ell_1 penalty, xθx_\theta is not differentiable everywhere and Fact 1 does not apply as written. Smooth the penalty, or use a nonsmooth calculus.
  • Inexact lower-level solves. An inaccurate xθx_\theta gives an inaccurate gradient. Check the gradient against finite differences on a small case.
  • Nonconvex upper level. L(θ)L(\theta) is not convex in general, so the outer method can stop at a local minimizer.
  • Overfitting. With few pairs and many parameters, the learned method fits the training images. Keep test pairs apart.
  • Positivity. Weights such as α\alpha must stay nonnegative. Project, or learn log⁡α\log\alpha instead.

Code

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.

bilevel_learning_of_regularizers.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bilevel-learning-of-regularizers/. The authors are listed in prov/VE2JDY.jsonl.
"""Bilevel learning of a regularization weight.

Upper level: L(alpha) = (1/N) sum_i ||x_alpha(y_i) - x_i||^2 over training
pairs (x_i, y_i). Lower level: x_alpha(y) minimizes the variational energy
with weight alpha. The lower-level solver and the derivative of its solution
in alpha are given functions. For Tikhonov regularization both are exact.
Matrices are lists of rows; vectors are lists of floats.
"""


def bilevel_learn(pairs, lower, lower_vjp, alpha0, step, iters):
    """Projected gradient descent on alpha >= 0. Return (alpha, losses).

    lower(alpha, y) returns x_alpha(y).
    lower_vjp(alpha, y, x, v) returns <dx_alpha(y)/dalpha, v> for x = x_alpha(y).
    Each step calls lower and lower_vjp once per pair.
    """
    n_pairs = len(pairs)
    alpha = alpha0  # @line L1
    losses = []
    for _ in range(iters):  # @line L2
        g, loss = 0.0, 0.0  # @line L3
        for x_true, y in pairs:  # @line L4
            x = lower(alpha, y)  # @line L5
            r = [p - q for p, q in zip(x, x_true)]
            loss += sum(v * v for v in r) / n_pairs
            g += 2.0 * lower_vjp(alpha, y, x, r) / n_pairs  # @line L6
        losses.append(loss)
        alpha = max(alpha - step * g, 0.0)  # @line L7
    return alpha, losses  # @line L8


def solve(m, b):
    """Solve m x = b by Gaussian elimination with partial pivoting."""
    n = len(b)
    a = [list(row) + [bi] for row, bi in zip(m, b)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(a[r][c]))
        a[c], a[p] = a[p], a[c]
        for r in range(c + 1, n):
            f = a[r][c] / a[c][c]
            for k in range(c, n + 1):
                a[r][k] -= f * a[c][k]
    x = [0.0] * n
    for r in range(n - 1, -1, -1):
        x[r] = (a[r][n] - sum(a[r][k] * x[k] for k in range(r + 1, n))) / a[r][r]
    return x


def rmatvec(a, y):
    return [sum(a[r][j] * y[r] for r in range(len(a))) for j in range(len(a[0]))]


def tikhonov(a):
    """Return (lower, lower_vjp) for x_alpha = argmin ||Ax - y||^2 + alpha ||x||^2.

    x_alpha solves (A^T A + alpha I) x = A^T y. Differentiating in alpha gives
    (A^T A + alpha I) dx/dalpha = -x_alpha, so <dx/dalpha, v> = -<p, x_alpha>
    with the adjoint solve (A^T A + alpha I) p = v.
    """
    n = len(a[0])
    ata = [[sum(a[r][i] * a[r][j] for r in range(len(a))) for j in range(n)]
           for i in range(n)]

    def system(alpha):
        return [[ata[i][j] + (alpha if i == j else 0.0) for j in range(n)]
                for i in range(n)]

    def lower(alpha, y):
        return solve(system(alpha), rmatvec(a, y))

    def lower_vjp(alpha, y, x, v):
        p = solve(system(alpha), v)
        return -sum(pi * xi for pi, xi in zip(p, x))

    return lower, lower_vjp


def upper_loss(pairs, lower, alpha):
    """L(alpha), the mean squared reconstruction error on the pairs."""
    total = 0.0
    for x_true, y in pairs:
        x = lower(alpha, y)
        total += sum((p - q) ** 2 for p, q in zip(x, x_true))
    return total / len(pairs)
test_bilevel_learning_of_regularizers.py 83 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bilevel-learning-of-regularizers/. The authors are listed in prov/VE2JDY.jsonl.

import random

from bilevel_learning_of_regularizers import bilevel_learn, tikhonov, upper_loss


def seeded_pairs(seed, m=5, n=4, count=4, noise=0.5):
    rng = random.Random(seed)
    a = [[rng.gauss(0.0, 1.0) for _ in range(n)] for _ in range(m)]
    pairs = []
    for _ in range(count):
        x = [rng.gauss(0.0, 1.0) for _ in range(n)]
        y = [sum(a[r][j] * x[j] for j in range(n)) + rng.gauss(0.0, noise)
             for r in range(m)]
        pairs.append((x, y))
    return a, pairs


def upper_gradient(pairs, lower, lower_vjp, alpha):
    g = 0.0
    for x_true, y in pairs:
        x = lower(alpha, y)
        g += 2.0 * lower_vjp(alpha, y, x, [p - q for p, q in zip(x, x_true)])
    return g / len(pairs)


def test_hand_example():
    lower, vjp = tikhonov([[1.0]])
    pairs = [([1.0], [1.2])]
    assert abs(lower(1.0, [1.2])[0] - 0.6) < 1e-15
    assert abs(upper_loss(pairs, lower, 1.0) - 0.16) < 1e-15
    assert abs(upper_gradient(pairs, lower, vjp, 1.0) - 0.24) < 1e-15
    alpha, losses = bilevel_learn(pairs, lower, vjp, 1.0, 0.5, 60)
    assert abs(alpha - 0.2) < 1e-10 and losses[-1] < 1e-18


def test_projection_keeps_alpha_nonnegative():
    lower, vjp = tikhonov([[1.0]])
    alpha, losses = bilevel_learn([([1.0], [0.8])], lower, vjp, 1.0, 0.5, 60)
    assert alpha == 0.0 and abs(losses[-1] - 0.04) < 1e-12


def test_adjoint_gradient_matches_finite_differences():
    a, pairs = seeded_pairs(5)
    lower, vjp = tikhonov(a)
    h = 1e-6
    for alpha in (0.05, 0.4, 2.0):
        fd = (upper_loss(pairs, lower, alpha + h) - upper_loss(pairs, lower, alpha - h)) / (2 * h)
        assert abs(fd - upper_gradient(pairs, lower, vjp, alpha)) < 1e-8


def test_learned_weight_matches_a_grid_search():
    a, pairs = seeded_pairs(5)
    lower, vjp = tikhonov(a)
    alpha, losses = bilevel_learn(pairs, lower, vjp, 1.0, 0.5, 300)
    assert all(l2 <= l1 + 1e-15 for l1, l2 in zip(losses, losses[1:]))
    assert abs(upper_gradient(pairs, lower, vjp, alpha)) < 1e-9
    best = min((upper_loss(pairs, lower, k / 1000), k / 1000) for k in range(0, 2001))
    assert abs(alpha - best[1]) < 1e-3 and upper_loss(pairs, lower, alpha) <= best[0] + 1e-15
    assert abs(alpha - 0.36527) < 1e-5


def test_many_scalar_pairs_give_the_noise_to_signal_ratio():
    rng = random.Random(6)
    pairs = []
    for _ in range(2000):
        x = rng.gauss(0.0, 1.0)
        pairs.append(([x], [x + rng.gauss(0.0, 0.5)]))

    def lower(alpha, y):  # Tikhonov with A = 1, written by hand
        return [y[0] / (1.0 + alpha)]

    def vjp(alpha, y, x, v):
        return -x[0] * v[0] / (1.0 + alpha)

    alpha, _ = bilevel_learn(pairs, lower, vjp, 1.0, 1.0, 100)
    sxy = sum(x[0] * y[0] for x, y in pairs)
    syy = sum(y[0] * y[0] for _, y in pairs)
    assert abs(alpha - (syy / sxy - 1.0)) < 1e-9  # the exact minimizer
    assert abs(alpha - 0.25) < 0.05  # sigma^2 / sigma_x^2 for large N
    assert abs(lower(0.3, [0.7])[0] - tikhonov([[1.0]])[0](0.3, [0.7])[0]) < 1e-15

Exercises

  1. Derive Fact 1 from the implicit function theorem, and Fact 2 from Fact 1.
  2. Verify the hand example, and show that α=y1/x1−1\alpha = y_1/x_1 - 1 is the minimizer when y1>x1>0y_1 > x_1 > 0.
  3. Prove Fact 3 and compare the minimum with the posterior variance of xx given yy.
  4. For the lower level ∥Ax−y∥2+α∥Dx∥2\|Ax - y\|^2 + \alpha\|Dx\|^2 with a matrix DD, find dxα/dαdx_\alpha/d\alpha and write the adjoint gradient.
  5. For a vector of weights αj\alpha_j on the penalties ∥Djx∥2\|D_jx\|^2, show that one adjoint solve per pair gives the gradient in all αj\alpha_j.

References

  1. Eldad Haber and Luis Tenorio, Learning regularization functionals, a supervised training approach, Inverse Problems 19(3), 2003, pages 611 to 626 (learning the regularization functional from training models by minimizing the reconstruction error)
  2. Karl Kunisch and Thomas Pock, A bilevel optimization approach for parameter learning in variational models, SIAM Journal on Imaging Sciences 6(2), 2013, pages 938 to 983 (the bilevel problem for learning the weights of variational denoising models, and its solution by gradient methods)
  3. Juan Carlos De los Reyes and Carola-Bibiane Schönlieb, Image denoising, learning the noise model via nonsmooth PDE-constrained optimization, Inverse Problems and Imaging 7(4), 2013, pages 1183 to 1214 (learning the weights of the data terms for mixed noise by a bilevel problem)
  4. Simon Arridge, Peter Maass, Ozan Öktem and Carola-Bibiane Schönlieb, Solving inverse problems using data-driven models, Acta Numerica 28, 2019, the section on learning the regularizer by bilevel optimization

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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
  • three classic examples