Algorithm Search⌘K

Techniquecore

Adjoint model

Also called tangent linear and adjoint models.

The transpose of the tangent linear model, run backward in time, gives the gradient of a cost with respect to the initial state for a small multiple of one model run.

The adjoint model of a forecast model is the transpose of its tangent linear model. The tangent linear model M′(x)M'(x) tells how a small change of the initial state changes the forecast. Its transpose M′(x)⊤M'(x)^\top, run backward in time along a stored forward trajectory, turns the sensitivity of a cost to the forecast into the sensitivity of the cost to the initial state. So one forward run and one backward adjoint run give the full gradient of a scalar cost with respect to all nn initial values, at a cost that is a small multiple of one forward run and does not grow with nn. Finite differences would need n+1n + 1 runs. This is what makes 4D-Var possible for weather models, and it is the same idea as reverse mode automatic differentiation and backpropagation.

In plain words

Suppose we want to know how a forecast error at the end of a day depends on each of a million numbers at the start. Changing each start value in turn and running the model again would take a million runs. The adjoint model does it with about the work of a few runs. It first runs the model forward and keeps the states. Then it starts from the end, where it is easy to say how the error depends on the final state, and steps backward. At each step it asks: if this quantity changes, how does that change what comes later? It passes this sensitivity one step back at a time, and adds the effect of the observations it meets on the way. When it reaches the start, it has the sensitivity to every start value at once.

When it applies

  • The output is a single number, such as a cost or a forecast measure, and the inputs are many: the gradient of a scalar function of nn variables.
  • The function is a composition of steps, xk=Mk(xk−1)x_k = M_k(x_{k-1}), each of which is differentiable, and the code of each step is available, so its tangent linear and adjoint can be written by hand or by a tool.
  • The forward states can be stored, or recomputed from checkpoints, during the backward sweep.
  • The cost is a sum of terms along the trajectory, as in the observation term of a 4D-Var cost.

The template

For xk=Mk(xk−1)x_k = M_k(x_{k-1}), k=1,…,Kk = 1, \ldots, K, and the cost J(x0)=∑k12(Hxk−yk)⊤R−1(Hxk−yk)J(x_0) = \sum_k \tfrac12 (H x_k - y_k)^\top R^{-1}(H x_k - y_k) over the times kk with observations, the gradient is

∇J(x0)=∑kM1′⊤⋯Mk′⊤H⊤R−1(Hxk−yk),Mk′=Mk′(xk−1),\nabla J(x_0) = \sum_k M_1'^\top \cdots M_k'^\top H^\top R^{-1}(H x_k - y_k), \qquad M_k' = M_k'(x_{k-1}),

which a backward recursion evaluates with one product by each Mk′⊤M_k'^\top:

  1. GRADIENT(x_0, obs)
  2. 1run the model forward and store x_0, x_1, ..., x_K
  3. 2lambda <- 0
  4. 3for k <- K down to 0 do
  5. 4if time k has observations then lambda <- lambda + H^T R^-1 (H x_k - y_k)
  6. 5if k > 0 then lambda <- M_k'(x_{k-1})^T lambda ▷ one adjoint step
  7. 6return lambda ▷ = grad J(x_0)

The holes are the model step MkM_k, its adjoint step Mk′⊤M_k'^\top (line L5), and the forcing of the adjoint by the observations (line L4). After line L4 at time kk, λ\lambda is the gradient of the cost terms at times ≥k\ge k with respect to xkx_k. Line L5 moves it to xk−1x_{k-1} by the chain rule. A background term 12(x0−xb)⊤B−1(x0−xb)\tfrac12 (x_0 - x^b)^\top B^{-1}(x_0 - x^b) adds B−1(x0−xb)B^{-1}(x_0 - x^b) at the end.

Writing the adjoint step. The tangent linear code is the derivative of the model code, statement by statement. The adjoint code runs the statements of the tangent linear code in the reverse order and replaces each one by its transpose. For a statement δz=a δu+b δv\delta z = a\,\delta u + b\,\delta v the adjoint is uˉ+=a zˉ\bar u \mathrel{+}= a\,\bar z, vˉ+=b zˉ\bar v \mathrel{+}= b\,\bar z, zˉ=0\bar z = 0. The reference code does this for one Runge-Kutta step of the Lorenz-96 model.

Checks. Two tests catch almost every error (Errico 1997; Kalnay 2003, Appendix B).

  1. Tangent linear test. (M(x+ϵ δx)−M(x−ϵ δx))/(2ϵ)−M′(x)δx(M(x + \epsilon\,\delta x) - M(x - \epsilon\,\delta x))/(2\epsilon) - M'(x)\delta x must fall like ϵ2\epsilon^2.
  2. Dot product test. ⟨M′(x)δx,λ⟩=⟨δx,M′(x)⊤λ⟩\langle M'(x)\delta x, \lambda \rangle = \langle \delta x, M'(x)^\top \lambda \rangle must hold to rounding error for random δx\delta x and λ\lambda. In the reference code it holds to 10−1010^{-10} relative for 20 steps of Lorenz-96 with 40 variables.

Worked example. Take the scalar model xk=xk−12x_k = x_{k-1}^2, K=2K = 2, x0=2x_0 = 2 and one observation y2=15y_2 = 15 at the last time with H=R=1H = R = 1. Then J(x0)=12(x04−15)2J(x_0) = \tfrac12 (x_0^4 - 15)^2 and J′(2)=(16−15)⋅4⋅23=32J'(2) = (16 - 15)\cdot 4 \cdot 2^3 = 32. The adjoint step is multiplication by M′(xk−1)=2xk−1M'(x_{k-1}) = 2x_{k-1}.

kk xkx_k (forward) after line L4 after line L5
2 16 λ=16−15=1\lambda = 16 - 15 = 1 λ=2x1⋅1=8\lambda = 2 x_1 \cdot 1 = 8
1 4 λ=8\lambda = 8 (no observation) λ=2x0⋅8=32\lambda = 2 x_0 \cdot 8 = 32
0 2 λ=32\lambda = 32 (no observation) returned

The result 3232 is J′(2)J'(2).

Cost. One adjoint step costs a small multiple of one forward step, independent of nn (the cheap gradient principle of reverse mode differentiation, Griewank and Walther 2008). For the Lorenz-96 code here, with n=40n = 40 and K=200K = 200 steps, the gradient took about 4 times as long as one forward run, including the forward sweep (a measurement). The memory is the stored trajectory, Θ(nK)\Theta(nK), unless checkpointing trades it for recomputation.

Classic examples

  • 4D-Var. The gradient of the 4D-Var cost with respect to the initial state is exactly the template, and the minimizer calls it once per iteration. Incremental 4D-Var uses the tangent linear model in the inner loop and its adjoint for the gradient.
  • 3D-Var. The gradient needs H⊤H^\top, the adjoint of the observation operator, for example of a radiative transfer model. This is the case K=0K = 0 of the template.
  • Backpropagation. The layers of a neural network are the steps MkM_k, the loss is the cost, and the backward pass is the adjoint sweep.
  • Adjoint sensitivity analysis and the adjoint state method. The gradient of a scalar output of an ODE or PDE model with respect to many parameters or initial values, used in optimal control, shape optimization and seismic imaging.
  • Automatic differentiation. Reverse mode applied to any program gives the adjoint automatically. Tools of this kind now produce many of the adjoint models in use.

Variations

  • Discrete or continuous adjoint. The discrete adjoint is the exact transpose of the code, so its gradient is exact for the discrete cost and passes the dot product test. The continuous adjoint discretizes the adjoint differential equation separately, and its gradient is only an approximation of the gradient of the discrete cost.
  • Checkpointing. Store the state only at some steps and recompute the others during the backward sweep. With logarithmic checkpointing the memory is Θ(nlog⁡K)\Theta(n \log K) for Θ(Klog⁡K)\Theta(K \log K) forward steps (Griewank and Walther 2008).
  • Singular vectors. The leading eigenvectors of M′⊤M′M'^\top M', found with alternate runs of the tangent linear and adjoint models, are the perturbations that grow fastest over a time window, used to start ensemble forecasts (Kalnay 2003, Section 6.3).
  • Sensitivity to observations. The adjoint of the whole assimilation system gives the effect of each observation on a forecast measure.
  • Simplified tangent linear models. Operational systems often use a tangent linear model of a simplified or lower resolution model. Its adjoint must then be the transpose of that simplified model, not of the full one.

Pitfalls

  • Wrong order in the backward sweep. In the template the observation term at time kk is added (line L4) before λ\lambda is moved to time k−1k - 1 (line L5). Swapping the two lines attaches each observation to the wrong time.
  • Not the exact transpose. A small slip, such as a wrong index in one statement, gives a gradient that is wrong but plausible, and the minimizer then stalls or converges to a wrong point. Always run the dot product test, step by step and for the full window.
  • Linearizing about the wrong state. The adjoint step at time kk must use the forward state xk−1x_{k-1} that the forward run produced, including the intermediate stages of the time step. Using the state at the end of the step, or a state from another run, gives the wrong Jacobian.
  • Switches and thresholds. Physical parameterizations with if statements, such as the onset of convection, are not differentiable at the threshold. The tangent linear model can then be a poor approximation of finite differences, even if the adjoint is the exact transpose of the code.
  • Long windows in a chaotic model. The tangent linear model describes small perturbations only for a limited time: in Lorenz-96 small errors double in about 0.42 time units. Over long windows the cost has many local minima, and the gradient from the adjoint, although exact, is of little use for a global search.

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.

adjoint_model.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adjoint-model/. The authors are listed in prov/D36VQ5.jsonl.

"""Tangent linear and adjoint models of Lorenz-96 with RK4 steps.

The forward model is x_{k+1} = M(x_k), one classical Runge-Kutta step of
dx_j/dt = (x_{j+1} - x_{j-2}) x_{j-1} - x_j + F with cyclic indices.

* tlm_step(x, dx) returns M'(x) dx, the tangent linear model.
* adj_step(x, lam) returns M'(x)^T lam, the adjoint model, written by
  reversing the statements of tlm_step line by line.
* gradient(...) returns the gradient of the 4D-Var cost with respect to the
  initial state by one forward sweep and one backward adjoint sweep.
"""


def tendency(x, F):
    """Return the Lorenz-96 tendency f(x)."""
    n = len(x)
    return [(x[(j + 1) % n] - x[j - 2]) * x[j - 1] - x[j] + F for j in range(n)]


def tlm_tendency(x, dx):
    """Return f'(x) dx."""
    n = len(x)
    return [
        (dx[(j + 1) % n] - dx[j - 2]) * x[j - 1] + (x[(j + 1) % n] - x[j - 2]) * dx[j - 1] - dx[j]
        for j in range(n)
    ]


def adj_tendency(x, lam):
    """Return f'(x)^T lam, the transpose of tlm_tendency, statement by statement."""
    n = len(x)
    out = [-v for v in lam]
    for j in range(n):
        out[(j + 1) % n] += lam[j] * x[j - 1]
        out[j - 2] -= lam[j] * x[j - 1]
        out[j - 1] += lam[j] * (x[(j + 1) % n] - x[j - 2])
    return out


def _axpy(a, x, y):
    return [a * u + v for u, v in zip(x, y)]


def step(x, F, h):
    """Return M(x), one RK4 step of length h."""
    k1 = tendency(x, F)
    k2 = tendency(_axpy(h / 2, k1, x), F)
    k3 = tendency(_axpy(h / 2, k2, x), F)
    k4 = tendency(_axpy(h, k3, x), F)
    return [a + h / 6 * (b + 2 * c + 2 * d + e) for a, b, c, d, e in zip(x, k1, k2, k3, k4)]


def _stages(x, F, h):
    k1 = tendency(x, F)
    z2 = _axpy(h / 2, k1, x)
    k2 = tendency(z2, F)
    z3 = _axpy(h / 2, k2, x)
    k3 = tendency(z3, F)
    z4 = _axpy(h, k3, x)
    return x, z2, z3, z4


def tlm_step(x, dx, F, h):
    """Return M'(x) dx: the derivative of one RK4 step in the direction dx."""
    z1, z2, z3, z4 = _stages(x, F, h)
    dk1 = tlm_tendency(z1, dx)
    dk2 = tlm_tendency(z2, _axpy(h / 2, dk1, dx))
    dk3 = tlm_tendency(z3, _axpy(h / 2, dk2, dx))
    dk4 = tlm_tendency(z4, _axpy(h, dk3, dx))
    return [a + h / 6 * (b + 2 * c + 2 * d + e) for a, b, c, d, e in zip(dx, dk1, dk2, dk3, dk4)]


def adj_step(x, lam, F, h):
    """Return M'(x)^T lam: the statements of tlm_step in reverse order, each transposed."""
    z1, z2, z3, z4 = _stages(x, F, h)
    a_dx = list(lam)
    a_dk1 = [h / 6 * v for v in lam]
    a_dk2 = [h / 3 * v for v in lam]
    a_dk3 = [h / 3 * v for v in lam]
    a_dk4 = [h / 6 * v for v in lam]
    a_in4 = adj_tendency(z4, a_dk4)  # dk4 = f'(z4)(dx + h dk3)
    a_dx = _axpy(1.0, a_in4, a_dx)
    a_dk3 = _axpy(h, a_in4, a_dk3)
    a_in3 = adj_tendency(z3, a_dk3)  # dk3 = f'(z3)(dx + h/2 dk2)
    a_dx = _axpy(1.0, a_in3, a_dx)
    a_dk2 = _axpy(h / 2, a_in3, a_dk2)
    a_in2 = adj_tendency(z2, a_dk2)  # dk2 = f'(z2)(dx + h/2 dk1)
    a_dx = _axpy(1.0, a_in2, a_dx)
    a_dk1 = _axpy(h / 2, a_in2, a_dk1)
    return _axpy(1.0, adj_tendency(z1, a_dk1), a_dx)  # dk1 = f'(z1) dx


def forward(x0, F, h, K):
    """Return the trajectory [x_0, ..., x_K]."""
    path = [list(x0)]
    for _ in range(K):
        path.append(step(path[-1], F, h))
    return path


def cost(x0, F, h, K, obs, idx, r):
    """Return J(x_0) = 1/2 sum over k in obs of |x_k[idx] - obs[k]|^2 / r."""
    path = forward(x0, F, h, K)
    total = 0.0
    for k, y in obs.items():
        total += sum((path[k][i] - yi) ** 2 for i, yi in zip(idx, y)) / (2 * r)
    return total


def gradient(x0, F, h, K, obs, idx, r):
    """Return grad J(x_0) by one forward sweep and one backward adjoint sweep.

    obs maps a step k (0 <= k <= K) to the observed values of the variables
    idx at x_k; the observation errors have variance r.
    """
    path = forward(x0, F, h, K)  # @line L1
    lam = [0.0] * len(x0)  # @line L2
    for k in range(K, -1, -1):  # @line L3
        if k in obs:  # @line L4
            for i, yi in zip(idx, obs[k]):
                lam[i] += (path[k][i] - yi) / r
        if k > 0:  # @line L5
            lam = adj_step(path[k - 1], lam, F, h)
    return lam  # @line L6
test_adjoint_model.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adjoint-model/. The authors are listed in prov/D36VQ5.jsonl.

import random

from adjoint_model import (
    adj_step,
    adj_tendency,
    cost,
    forward,
    gradient,
    step,
    tendency,
    tlm_step,
    tlm_tendency,
)

F, H = 8.0, 0.05


def dot(a, b):
    return sum(u * v for u, v in zip(a, b))


def attractor_state(n, seed):
    rng = random.Random(seed)
    x = [F + rng.uniform(-1, 1) for _ in range(n)]
    for _ in range(200):
        x = step(x, F, H)
    return x


def test_dot_product_test_tendency():
    rng = random.Random(31)
    for _ in range(200):
        n = rng.randint(4, 20)
        x = [rng.uniform(-10, 10) for _ in range(n)]
        dx = [rng.uniform(-1, 1) for _ in range(n)]
        lam = [rng.uniform(-1, 1) for _ in range(n)]
        a, b = dot(tlm_tendency(x, dx), lam), dot(dx, adj_tendency(x, lam))
        assert abs(a - b) <= 1e-12 * (1 + abs(a))


def test_dot_product_test_step_and_trajectory():
    rng = random.Random(32)
    n, K = 40, 20
    x0 = attractor_state(n, 1)
    path = forward(x0, F, H, K)
    for _ in range(5):
        dx = [rng.gauss(0, 1) for _ in range(n)]
        lam = [rng.gauss(0, 1) for _ in range(n)]
        # one step
        a, b = dot(tlm_step(x0, dx, F, H), lam), dot(dx, adj_step(x0, lam, F, H))
        assert abs(a - b) <= 1e-12 * (1 + abs(a))
        # K steps: <M_K ... M_1 dx, lam> = <dx, M_1^T ... M_K^T lam>
        u = list(dx)
        for k in range(K):
            u = tlm_step(path[k], u, F, H)
        v = list(lam)
        for k in range(K - 1, -1, -1):
            v = adj_step(path[k], v, F, H)
        a, b = dot(u, lam), dot(dx, v)
        assert abs(a - b) <= 1e-10 * (1 + abs(a))


def test_tangent_linear_against_finite_differences():
    rng = random.Random(33)
    n = 40
    x = attractor_state(n, 2)
    dx = [rng.gauss(0, 1) for _ in range(n)]
    tl = tlm_step(x, dx, F, H)
    errs = []
    for eps in (1e-2, 1e-3):
        xp = step([a + eps * b for a, b in zip(x, dx)], F, H)
        xm = step([a - eps * b for a, b in zip(x, dx)], F, H)
        fd = [(p - m) / (2 * eps) for p, m in zip(xp, xm)]
        errs.append(max(abs(a - b) for a, b in zip(fd, tl)))
    # central differences: the error falls like eps^2
    assert errs[1] < 2e-4
    assert 50 < errs[0] / errs[1] < 200


def make_problem(n, K, seed):
    rng = random.Random(seed)
    xt = attractor_state(n, seed)
    truth = forward(xt, F, H, K)
    idx = list(range(0, n, 2))
    obs = {k: [truth[k][i] + rng.gauss(0, 1) for i in idx] for k in range(0, K + 1, 2)}
    x0 = [v + rng.gauss(0, 0.5) for v in xt]
    return x0, obs, idx


def test_gradient_against_forward_mode_columns():
    # Reference: the gradient from n tangent linear runs, one per unit vector.
    n, K, r = 12, 10, 1.0
    x0, obs, idx = make_problem(n, K, 3)
    g = gradient(x0, F, H, K, obs, idx, r)
    path = forward(x0, F, H, K)
    for j in range(n):
        u = [1.0 if i == j else 0.0 for i in range(n)]
        gj = 0.0
        for k in range(K + 1):
            if k in obs:
                gj += sum(u[i] * (path[k][i] - yi) / r for i, yi in zip(idx, obs[k]))
            if k < K:
                u = tlm_step(path[k], u, F, H)
        assert abs(gj - g[j]) <= 1e-10 * (1 + abs(gj))


def test_gradient_against_finite_differences():
    n, K, r = 40, 20, 1.0
    x0, obs, idx = make_problem(n, K, 4)
    g = gradient(x0, F, H, K, obs, idx, r)
    eps = 1e-5
    for j in (0, 7, 13, 39):
        xp, xm = list(x0), list(x0)
        xp[j] += eps
        xm[j] -= eps
        fd = (cost(xp, F, H, K, obs, idx, r) - cost(xm, F, H, K, obs, idx, r)) / (2 * eps)
        assert abs(fd - g[j]) < 1e-5 * (1 + abs(g[j]))


def test_tendency_is_lorenz96():
    x = [1.0, 2.0, 3.0, 4.0, 5.0]
    f = tendency(x, 8.0)
    # j = 0: (x1 - x3) x4 - x0 + F = (2 - 4) 5 - 1 + 8
    assert f[0] == -3.0
    assert tendency([8.0] * 6, 8.0) == [0.0] * 6

Exercises

  1. For the scalar model xk=axk−1x_k = a x_{k-1} and observations y1,…,yKy_1, \ldots, y_K of every xkx_k with R=1R = 1, write the adjoint recursion and check that it gives ∇J=∑kak(akx0−yk)\nabla J = \sum_k a^k(a^k x_0 - y_k).
  2. Write the tangent linear and adjoint statements of z=u vz = u\,v, and check the dot product test by hand at u=2u = 2, v=3v = 3 for (δu,δv)=(1,1)(\delta u, \delta v) = (1, 1) and zˉ=1\bar z = 1.
  3. Show that the dot product test with random vectors detects an error in a single entry of M′⊤M'^\top with probability 1.

References

  1. F.-X. Le Dimet and O. Talagrand, Variational algorithms for analysis and assimilation of meteorological observations, theoretical aspects, Tellus A 38(2) (1986) 97-110, the adjoint equations for the gradient of a cost over a time window
  2. O. Talagrand and P. Courtier, Variational assimilation of meteorological observations with the adjoint vorticity equation. I, Theory, Quarterly Journal of the Royal Meteorological Society 113(478) (1987) 1311-1328, the adjoint of a discrete model and its use in variational assimilation
  3. R. M. Errico, What is an adjoint model?, Bulletin of the American Meteorological Society 78(11) (1997) 2577-2591, the tangent linear model, the adjoint model, and their tests
  4. Eugenia Kalnay, Atmospheric Modeling, Data Assimilation and Predictability, Cambridge University Press, 2003, Section 6.3 (tangent linear model, adjoint model, singular vectors) and Appendix B (coding and checking the tangent linear and the adjoint models)
  5. A. Griewank and A. Walther, Evaluating Derivatives, Principles and Techniques of Algorithmic Differentiation, second edition, SIAM, 2008, the reverse mode, its cost bound, and checkpointing

Where this leads

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)
WritingW3 standard
  • five exercises