from __future__ import annotations
import functools
import math
import time
import numpy as np
import pandas as pd
from mxlpy import (
Model,
Simulator,
adjoint_sensitivities,
fit,
fns,
forward_sensitivities,
)
from mxlpy.integrators.int_native import Native
from mxlpy.runners import KineticRunner
Adjoint gradients¶
Forward sensitivities give the derivative of every simulated value with respect to every parameter. Gradient-based fitting usually needs much less: the gradient of one number, the loss, with respect to all parameters. For a loss \(L\) that depends on the simulation at a few time points, that gradient is a vector-Jacobian product
with the cotangents \(w_i = \partial L / \partial y(t_i)\).
Forward sensitivities compute all of \(S\), integrating \(n\) extra states per parameter. The adjoint method computes the product directly: it integrates an adjoint state \(\lambda\) backwards in time,
That is one forward and one backward solve, however many parameters there are. This is what makes fits with hundreds of parameters practical, e.g. the weights of neural networks in hybrid models.
| cost per gradient | best for | |
|---|---|---|
| finite differences | \(2m\) simulations | models that can't be differentiated |
| forward sensitivities | one solve with \(n(1 + m)\) states | few parameters, residual Jacobians (least squares) |
| adjoint | one forward and one backward solve with \(n\) states | many parameters, loss gradients |
Both products \(\lambda^\top \partial f / \partial x\) and \(\lambda^\top \partial f / \partial \theta\) are generated symbolically in reverse mode, without forming Jacobians. The backward solve interpolates the forward trajectory instead of integrating the model backwards, which would be unstable for stiff models.
A small example¶
The linear chain \(x \to y \to \varnothing\) again, with weights on \(x\), \(y\) and the reaction v1 at four time points.
def get_model() -> Model:
return (
Model()
.add_parameters({"k1": 0.5, "k2": 2.0})
.add_variables({"x": 2.0, "y": 0.0})
.add_reaction(
"v1",
fns.mass_action_1s,
args=["x", "k1"],
stoichiometry={"x": -1, "y": 1},
)
.add_reaction(
"v2",
fns.mass_action_1s,
args=["y", "k2"],
stoichiometry={"y": -1},
)
)
cotangents = pd.DataFrame(
{"x": [1.0, 0.0, -1.0, 2.0], "y": [0.0, 1.0, 1.0, 0.0], "v1": [0.5, 0.5, 0.0, 0.0]},
index=[0.5, 1.0, 2.0, 4.0],
)
res = adjoint_sensitivities.time_course(
get_model(), cotangents, wrt=["k1", "k2", "x"], method="adjoint"
).unwrap_or_err()
res.gradient
k1 -0.021014 k2 -0.250137 x 1.301511 dtype: float64
adjoint_sensitivities.time_course returns an AdjointSensitivities object with
gradient: the derivative ofsum(cotangents * y)with respect to every name inwrt(parameters, and variables for their initial values)simulated: the simulated values at the cotangents' time points and columnsmethod:"discrete_adjoint","continuous_adjoint","forward"or"finite_difference"("adjoint"for steady states)adjoint: the adjoint state \(\lambda(t)\) (only \(\lambda(0)\) for compiled adjoints); \(\lambda(0)\) is the gradient with respect to the initial values
The same product from the forward sensitivities agrees:
sens = forward_sensitivities.time_course(
get_model(), cotangents.index, ["k1", "k2", "x"], outputs=["v1"]
).unwrap_or_err()
pd.Series(
{
k: float(
(sens.derivatives[k].loc[:, cotangents.columns] * cotangents).sum().sum()
)
for k in sens.wrt
}
)
k1 -0.021014 k2 -0.250138 x 1.301511 dtype: float64
Pullbacks: simulate once, differentiate later¶
In a fit the cotangents are the derivative of the loss, which needs the simulation first.
time_course_pullback therefore simulates once and returns a Pullback: its simulated values give the loss, and calling it with the cotangents gives the gradient, without simulating again (as jax.vjp).
A pullback can be called any number of times.
pullback = adjoint_sensitivities.time_course_pullback(
get_model(), [0.5, 1.0, 2.0, 4.0], ["k1", "k2", "x"], columns=["x", "y", "v1"]
).unwrap_or_err()
target = pd.DataFrame({"x": [1.5, 1.0, 0.5, 0.2]}, index=[0.5, 1.0, 2.0, 4.0])
residual = pullback.simulated[["x"]] - target
loss = float((residual**2).sum().sum())
gradient = pullback(2 * residual).unwrap_or_err().gradient
loss, gradient
(0.10928964623799248, k1 -1.453507 k2 0.000000 x 0.540767 dtype: float64)
Discrete and continuous adjoints¶
There are two ways to get the adjoint gradient of an ODE solve:
- The continuous adjoint ("optimise, then discretise") differentiates the ODE and solves the adjoint equations \(\dot\lambda = -J^\top\lambda\) backwards in time.
It works with every integrator, but it is the gradient of the exact solution, which differs from that of the computed solution by \(O(\text{tolerance})\).
MxlPy interpolates the forward trajectory instead of integrating the model backwards (diffrax's
BacksolveAdjoint), which would be unstable for stiff models. - The discrete adjoint ("discretise, then optimise") differentiates the solver's own steps, recorded during the forward solve, like diffrax's
RecursiveCheckpointAdjoint. Its gradient is exactly that of the computed solution (with the step sizes frozen), so it agrees with the loss a line search evaluates. MxlPy runs it for theNativeintegrator, with all of its methods (Radau, LSODA, CVODE BDF and Adams), in compiled code.
method="adjoint" takes the discrete adjoint where possible, "discrete_adjoint" and "continuous_adjoint" force one.
With Native both agree with forward sensitivities to the tolerance:
native = functools.partial(Native, rtol=1e-10, atol=1e-12)
pd.DataFrame(
{
method: adjoint_sensitivities.time_course(
get_model(), cotangents, ["k1", "k2", "x"], method=method, integrator=native
)
.unwrap_or_err()
.gradient
for method in ["discrete_adjoint", "continuous_adjoint", "forward"]
}
)
| discrete_adjoint | continuous_adjoint | forward | |
|---|---|---|---|
| k1 | -0.021014 | -0.021014 | -0.021015 |
| k2 | -0.250137 | -0.250137 | -0.250138 |
| x | 1.301511 | 1.301511 | 1.301511 |
The recording needs memory for every accepted step (about \(4n\) numbers per step for Radau), bounded by Native(max_tape_bytes=...) (default 1 GiB); beyond it "discrete_adjoint" raises TapeTooLarge, and "adjoint" and "auto" use the continuous adjoint.
While recording, the solvers converge their Newton iterations 1000x further than usual, because the gradient is exact for converged iterations.
method="auto" (the default) uses adjoints only where they pay off, see below.
Steady states¶
At a steady state the adjoint of the implicit function theorem needs one linear solve, \(J^\top \mu = w\), for all parameters. Conserved quantities are fixed by the initial values, as for forward sensitivities.
reversible = (
Model()
.add_parameters({"kf": 1.0, "kr": 0.5})
.add_variables({"A": 1.0, "B": 0.0})
.add_reaction(
"vf", fns.mass_action_1s, args=["A", "kf"], stoichiometry={"A": -1, "B": 1}
)
.add_reaction(
"vr", fns.mass_action_1s, args=["B", "kr"], stoichiometry={"A": 1, "B": -1}
)
)
adjoint_sensitivities.steady_state(
reversible, pd.Series({"A": 1.0}), ["kf", "kr", "A"]
).unwrap_or_err().gradient
kf -0.222222 kr 0.444444 A 0.333333 dtype: float64
Protocols¶
protocol_time_course differentiates a protocol simulation, whose steps set parameters.
The adjoint runs backwards through the steps with each step's parameters; \(\lambda\) is continuous at the step ends.
Forward sensitivities don't support protocols, so the alternative is finite differences, and auto uses adjoints from PROTOCOL_ADJOINT_THRESHOLD (3) parameters on.
from mxlpy import make_protocol
with_input = (
get_model()
.add_parameter("u", 0.0)
.add_reaction("vin", fns.constant, args=["u"], stoichiometry={"x": 1})
)
protocol = make_protocol([(1.0, {"u": 0.5}), (1.5, {"u": 2.0}), (2.0, {"u": 0.0})])
adjoint_sensitivities.protocol_time_course(
with_input, protocol, cotangents, ["k1", "k2", "x"]
).unwrap_or_err().gradient
k1 -3.106219 k2 -0.356823 x 1.301511 dtype: float64
Loss gradients in fits¶
Fits get their derivatives from the runner.
With derivatives="adjoint" the gradient of the loss comes from one adjoint solve, with the cotangents \(\partial L / \partial y\) of the chosen loss (standard scaling, replicates, GaussianNll weights and priors included).
The loss itself is then evaluated on the runner's pullback (time_course_pullback), so loss and gradient come from one simulation; with Native the gradient is exactly the loss's.
Residual Jacobians, which least-squares methods need, can't come from adjoints cheaply and still use forward sensitivities.
fit.loss_gradient evaluates the gradient a minimizer sees:
model = get_model()
data = (
Simulator(model)
.simulate_time_course(np.linspace(0, 5, 11))
.get_result()
.unwrap_or_err()
.get_variables()
.loc[:, ["x", "y"]]
)
p = {"k1": 0.6, "k2": 1.7}
pd.DataFrame(
{
derivatives: fit.loss_gradient(
model, data, p, runner=KineticRunner(derivatives=derivatives)
)
for derivatives in ["adjoint", "forward", "finite_difference"]
}
)
| adjoint | forward | finite_difference | |
|---|---|---|---|
| k1 | 1.449345 | 1.449345 | 1.449345 |
| k2 | -0.725772 | -0.725772 | -0.725772 |
fit.time_course(
model,
p0={"k1": 0.3, "k2": 3.0},
data=data,
minimizer=fit.LocalScipyMinimizer(method="L-BFGS-B"),
runner=KineticRunner(derivatives="adjoint"),
).unwrap_or_err().best_pars
{'k1': np.float64(0.4999997593702757), 'k2': np.float64(2.00000035719039)}
When adjoints pay off¶
Forward sensitivities integrate \(n(1 + m)\) states with dense Jacobians of that size, adjoints cost about the same for any number of parameters \(m\).
method="auto" therefore switches to adjoints from adjoint_sensitivities.ADJOINT_THRESHOLD (1000) variables × parameters on, the crossover measured on chains with an added neural-network-like layer.
The Native integrator runs the discrete adjoint in compiled code (all methods, LLVM or wasm backend), and on request the compiled continuous adjoint (Radau, LSODA).
It can't integrate forward sensitivities, so auto always uses adjoints with it.
Models it can't compile fall back to the Python continuous adjoint.
Here is a model with \(n = 6\) states and a layer of 20 tanh units feeding back into every state, 266 parameters in total:
def layer( # noqa: PLR0917
x0: float,
x1: float,
x2: float,
x3: float,
x4: float,
x5: float,
w0: float,
w1: float,
w2: float,
w3: float,
w4: float,
w5: float,
b: float,
) -> float:
return math.tanh(w0 * x0 + w1 * x1 + w2 * x2 + w3 * x3 + w4 * x4 + w5 * x5 + b)
def scaled(h: float, v: float) -> float:
return v * h
def hybrid(n: int, n_hidden: int) -> Model:
rng = np.random.default_rng(0)
xs = [f"x{i}" for i in range(n)]
model = Model().add_variables({x: 1.0 / (i + 1) for i, x in enumerate(xs)})
for i, x in enumerate(xs):
model.add_parameter(f"k{i}", 1.0 / (i + 1))
stoichiometry = {x: -1} | ({xs[i + 1]: 1} if i + 1 < n else {})
model.add_reaction(
f"v{i}", fns.mass_action_1s, args=[x, f"k{i}"], stoichiometry=stoichiometry
)
for j in range(n_hidden):
weights = {f"w{j}_{i}": float(rng.normal(0, 0.3)) for i in range(n)}
model.add_parameters(weights | {f"b{j}": 0.0})
model.add_derived(f"h{j}", layer, args=[*xs, *weights, f"b{j}"])
for k, x in enumerate(xs):
model.add_parameter(f"c{j}_{k}", float(rng.normal(0, 0.05)))
model.add_reaction(
f"r{j}_{k}", scaled, args=[f"h{j}", f"c{j}_{k}"], stoichiometry={x: 1}
)
return model
big = hybrid(6, 20)
wrt = big.get_parameter_names()
w = pd.DataFrame(
np.random.default_rng(1).normal(size=(10, 6)),
index=np.linspace(1, 10, 10),
columns=big.get_variable_names(),
)
len(wrt)
266
native = functools.partial(Native, rtol=1e-8, atol=1e-8)
timings = {}
gradients = {}
for name, kwargs in {
"forward": {"method": "forward"},
"continuous adjoint": {"method": "continuous_adjoint"},
"continuous adjoint, Native": {
"method": "continuous_adjoint",
"integrator": native,
},
"discrete adjoint, Native": {"method": "discrete_adjoint", "integrator": native},
}.items():
adjoint_sensitivities.time_course(big, w, wrt, **kwargs) # generate the code once
start = time.perf_counter()
gradients[name] = (
adjoint_sensitivities.time_course(big, w, wrt, **kwargs)
.unwrap_or_err()
.gradient
)
timings[name] = time.perf_counter() - start
pd.DataFrame(
{
"time (s)": timings,
"relative difference to forward": {
k: float(
np.linalg.norm(g - gradients["forward"])
/ np.linalg.norm(gradients["forward"])
)
for k, g in gradients.items()
},
}
)
| time (s) | relative difference to forward | |
|---|---|---|
| forward | 0.500511 | 0.000000e+00 |
| continuous adjoint | 0.487176 | 1.461697e-07 |
| continuous adjoint, Native | 0.002446 | 1.397437e-07 |
| discrete adjoint, Native | 0.001387 | 1.352541e-07 |
All agree to the integration tolerance.
The forward sensitivities' cost grows with the number of parameters, the adjoints' don't, and the compiled adjoints are about two orders of magnitude faster still.
For a few parameters (here: \(n \cdot m < 1000\)) forward sensitivities are faster, which is why auto keeps them there.
Limitations¶
- Models with events use forward sensitivities (or finite differences); the adjoint methods raise.
- Discrete adjoints need
Native; they freeze the step sizes, so central differences of an adaptive solve (whose steps move with the parameters) differ from them by \(O(\text{tolerance})\). - Fits with a
postprocess_fnuse finite differences of the runner's results. - Models that can't be differentiated symbolically (e.g. neural-network surrogates) fall back to forward sensitivities, and from there to finite differences.