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 tells how a small change of the initial state changes the forecast. Its transpose , 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 initial values, at a cost that is a small multiple of one forward run and does not grow with . Finite differences would need 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 variables.
- The function is a composition of steps, , 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 , , and the cost over the times with observations, the gradient is
which a backward recursion evaluates with one product by each :
GRADIENT(x_0, obs)- 1
run the model forward and store x_0, x_1, ..., x_K - 2
lambda <- 0 - 3
for k <- K down to 0 do - 4
if time k has observations then lambda <- lambda + H^T R^-1 (H x_k - y_k) - 5
if k > 0 then lambda <- M_k'(x_{k-1})^T lambda ▷ one adjoint step - 6
return lambda ▷ = grad J(x_0)
The holes are the model step , its adjoint step (line L5), and the forcing of the adjoint by the observations (line L4). After line L4 at time , is the gradient of the cost terms at times with respect to . Line L5 moves it to by the chain rule. A background term adds 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 the adjoint is , , . 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).
- Tangent linear test. must fall like .
- Dot product test. must hold to rounding error for random and . In the reference code it holds to relative for 20 steps of Lorenz-96 with 40 variables.
Worked example. Take the scalar model , , and one observation at the last time with . Then and . The adjoint step is multiplication by .
| (forward) | after line L4 | after line L5 | |
|---|---|---|---|
| 2 | 16 | ||
| 1 | 4 | (no observation) | |
| 0 | 2 | (no observation) | returned |
The result is .
Cost. One adjoint step costs a small multiple of one forward step, independent of (the cheap gradient principle of reverse mode differentiation, Griewank and Walther 2008). For the Lorenz-96 code here, with and 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, , 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 , the adjoint of the observation operator, for example of a radiative transfer model. This is the case of the template.
- Backpropagation. The layers of a neural network are the steps , 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 for forward steps (Griewank and Walther 2008).
- Singular vectors. The leading eigenvectors of , 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 is added (line L4) before is moved to time (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 must use the forward state 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
ifstatements, 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.
# 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
- For the scalar model and observations of every with , write the adjoint recursion and check that it gives .
- Write the tangent linear and adjoint statements of , and check the dot product test by hand at , for and .
- Show that the dot product test with random vectors detects an error in a single entry of with probability 1.
References
- 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
- 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
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag D36VQ5 Edit this page History Report an error Markdown