Adjoints¶
Adjoints through time: the backward sweeps of a forward run. A truncated rollout cuts the gradient through the carry before the last \(k\) steps, so reverse mode keeps \(O(k)\) of the history, and for chaotic dynamics it regularises, since the exact adjoint grows like \(e^{\lambda_{\max} T}\). A checkpointed rollout stores every \(k\)-th state on the forward run and recomputes the \(k\) steps between two of them on the backward run: memory \(O(T / k + k)\), minimised near \(k \approx \sqrt{T}\), for about one extra forward pass. Checkpointed and Truncated are the adjoint= options of integrix.march.run, and checkpointed_scan and truncated_scan their function forms for any jax.lax.scan rollout. Forward values never depend on the adjoint. to_diffrax_adjoint resolves pipekit-cycle's adjoint specs, matched structurally, to diffrax adjoints. Adjoints at an optimum (implicit, \(k\)-step) are argminax's.
truncated_scan and to_diffrax_adjoint moved from pipekit-jax at 7d02d8e, whose tests run against them.
The theory is in the Adjoints chapter of the mathematical reference.
adjoint
¶
Adjoints through time: truncated and checkpointed backward sweeps.
Truncated (with its function form truncated_scan) cuts the gradient
through the carry before the last k steps; Checkpointed (with
checkpointed_scan) stores the carry every k steps and recomputes between,
for the exact gradient in O(T/k + k) memory. Both are adjoint options for
integrix.march.run, and scan_for gives the scan of either for a loop of
one's own. to_diffrax_adjoint resolves an
adjoint spec (pipekit-cycle's, matched structurally, or a diffrax adjoint) to
a diffrax adjoint. Adjoints at an optimum (implicit, k-step) are argminax's;
backward sweeps through a forward run are integrix's.
Checkpointed
¶
Bases: Module
The checkpointed adjoint: store every k-th state, recompute between them.
The adjoint option for integrix.march.run: an AbstractStepper's loop
runs as checkpointed_scan, and a diffrax solver gets
diffrax.RecursiveCheckpointAdjoint(checkpoints=⌈N / k⌉), since
diffrax counts checkpoints rather than spacing them.
Attributes:
| Name | Type | Description |
|---|---|---|
every |
int
|
The spacing k ≥ 1 of the stored states; k ≈ √N minimises the memory O(N/k + k). |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
Examples:
Truncated
¶
Bases: Module
The truncated adjoint: gradients flow through the carry of the last k steps.
For an AbstractStepper (a diffrax solve takes Checkpointed or a
diffrax adjoint instead).
The adjoint option for integrix.march.run and the integrix form of
pipekit-cycle's TruncatedAdjoint; truncated_scan is its function
form for any jax.lax.scan rollout. k ≥ T is the exact adjoint.
Attributes:
| Name | Type | Description |
|---|---|---|
k |
int
|
The number of trailing steps whose carry propagates gradients, at least 1. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
Examples:
checkpointed_scan
¶
checkpointed_scan(f: Callable[[Carry, X], tuple[Carry, Y]], init: Carry, xs: X, *, every: int, length: int | None = None) -> tuple[Carry, Y]
jax.lax.scan that stores the carry only every k steps for reverse mode.
The T steps run as ⌊T/k⌋ blocks of k, an outer jax.lax.scan over blocks
whose body is a jax.checkpoint-ed inner scan, then a checkpointed tail
of T mod k steps. Reverse mode keeps the carries at block boundaries and
recomputes each block's interior, so it stores O(T/k + k) states instead
of T. Forward values, and gradients, are those of the plain scan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
Callable[[Carry, X], tuple[Carry, Y]]
|
The scan body |
required |
init
|
Carry
|
The initial carry. |
required |
xs
|
X
|
The stacked per-step inputs, leading axis T, or |
required |
every
|
int
|
The block length k ≥ 1. |
required |
length
|
int | None
|
The number of steps T when |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Carry, Y]
|
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
Examples:
>>> import jax
>>> import jax.numpy as jnp
>>> def step(carry, x):
... new = jnp.sin(carry) + x
... return new, new
>>> xs = jnp.linspace(0.0, 1.0, 10)
>>> _, ys = checkpointed_scan(step, 0.5, xs, every=3)
>>> _, plain = jax.lax.scan(step, 0.5, xs)
>>> bool(jnp.array_equal(ys, plain))
True
Source code in src/integrix/_src/adjoint/_checkpoint.py
to_diffrax_adjoint
¶
Map an adjoint spec onto a diffrax.AbstractAdjoint.
Specs are matched by class name, so pipekit-cycle's and any structurally identical spec are accepted interchangeably:
RecursiveCheckpointAdjoint(checkpoints)→diffrax.RecursiveCheckpointAdjointwith the same checkpoints, the recommended default;DirectAdjoint()→diffrax.DirectAdjoint;BacksolveAdjoint()→diffrax.BacksolveAdjoint. Continuous adjoints diverge for chaotic or stiff dynamics; never a default;ImplicitAdjoint()→diffrax.ImplicitAdjoint, for steady-state solves only (a derivative at a fixed point is argminax's business);TruncatedAdjointraises: truncation belongs to an outer rollout, not to a single solve; useintegrix.adjoint.Truncatedwithintegrix.march.run, ortruncated_scan, at that layer.
A ready-made diffrax.AbstractAdjoint passes through unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
Any
|
A spec from pipekit-cycle's |
required |
Returns:
| Type | Description |
|---|---|
AbstractAdjoint
|
The diffrax adjoint. |
Raises:
| Type | Description |
|---|---|
ValueError
|
For |
Examples:
>>> import diffrax as dfx
>>> class RecursiveCheckpointAdjoint:
... checkpoints = 8
>>> adjoint = to_diffrax_adjoint(RecursiveCheckpointAdjoint())
>>> isinstance(adjoint, dfx.RecursiveCheckpointAdjoint), adjoint.checkpoints
(True, 8)
Source code in src/integrix/_src/adjoint/_diffrax.py
scan_for
¶
The scan that runs a loop under an adjoint.
None gives jax.lax.scan, Checkpointed gives checkpointed_scan with
its every, and Truncated gives truncated_scan with its k. Forward
values are those of jax.lax.scan in every case; only reverse mode differs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
adjoint
|
Any
|
|
required |
Returns:
| Type | Description |
|---|---|
Callable[..., tuple[Any, Any]]
|
A function |
Callable[..., tuple[Any, Any]]
|
is. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
Examples:
>>> import jax
>>> import jax.numpy as jnp
>>> from integrix.adjoint import Checkpointed, Truncated, scan_for
>>> def step(carry, x):
... new = 0.9 * carry + x
... return new, new
>>> xs = jnp.arange(6.0)
>>> _, plain = jax.lax.scan(step, 1.0, xs)
The forward values are the same under each adjoint:
>>> _, ys = scan_for(None)(step, 1.0, xs)
>>> bool(jnp.array_equal(ys, plain))
True
>>> _, ys = scan_for(Checkpointed(every=2))(step, 1.0, xs)
>>> bool(jnp.array_equal(ys, plain))
True
Truncated cuts the gradient through all but the last k steps:
>>> def last(init, adjoint):
... carry, _ = scan_for(adjoint)(step, init, xs)
... return carry
>>> round(float(jax.grad(last)(1.0, None)), 6) # 0.9⁶
0.531441
>>> float(jax.grad(last)(1.0, Truncated(k=2)))
0.0
Source code in src/integrix/_src/adjoint/_scan_for.py
truncated_scan
¶
truncated_scan(f: Callable[[Carry, X], tuple[Carry, Y]], init: Carry, xs: X, *, k: int = 1, length: int | None = None) -> tuple[Carry, Y]
jax.lax.scan with gradients truncated to the trailing k steps.
The carry leaving every step before T − k is wrapped in
jax.lax.stop_gradient, so reverse mode sees only the last k transitions
through the carry. Each step's own output yₜ still receives gradients with
respect to that step's inputs; only the flow through history is cut (the
ROAD-EnKF and truncated-BPTT training regime). k ≥ T is a plain scan.
Forward values are identical to jax.lax.scan's. Memory is not reduced:
the cut is applied inside the scan, so reverse mode still stores every
step's residuals (checkpointed_scan bounds memory).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
Callable[[Carry, X], tuple[Carry, Y]]
|
The scan body |
required |
init
|
Carry
|
The initial carry. |
required |
xs
|
X
|
The stacked per-step inputs, leading axis T, or |
required |
k
|
int
|
The number of trailing steps that propagate gradients through the carry, at least 1. |
1
|
length
|
int | None
|
The number of steps T when |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Carry, Y]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax
>>> import jax.numpy as jnp
>>> def step(carry, x):
... new = 0.9 * carry + x
... return new, new
>>> _, ys = truncated_scan(step, 1.0, jnp.zeros(4), k=2)
>>> _, plain = jax.lax.scan(step, 1.0, jnp.zeros(4))
>>> bool(jnp.array_equal(ys, plain))
True