Skip to content

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 every is not a positive integer.

Examples:

>>> Checkpointed(every=100).every
100

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 k is not a positive integer.

Examples:

>>> Truncated(k=5).k
5

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 (carry, x) -> (carry, y).

required
init Carry

The initial carry.

required
xs X

The stacked per-step inputs, leading axis T, or None with length.

required
every int

The block length k ≥ 1.

required
length int | None

The number of steps T when xs has no leaves.

None

Returns:

Type Description
tuple[Carry, Y]

(final_carry, ys), exactly as jax.lax.scan returns them.

Raises:

Type Description
ValidationError

If every is not a positive integer, a leaf of xs has no leading axis, the leaves or length disagree, or there are no stacked inputs and no length.

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
def checkpointed_scan[Carry, X, Y](
    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.

    Args:
        f: The scan body ``(carry, x) -> (carry, y)``.
        init: The initial carry.
        xs: The stacked per-step inputs, leading axis T, or ``None`` with
            ``length``.
        every: The block length k ≥ 1.
        length: The number of steps T when ``xs`` has no leaves.

    Returns:
        ``(final_carry, ys)``, exactly as `jax.lax.scan` returns them.

    Raises:
        ValidationError: If ``every`` is not a positive integer, a leaf of
            ``xs`` has no leading axis, the leaves or ``length`` disagree, or
            there are no stacked inputs and no ``length``.

    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
    """
    block = positive_count(every, "every")
    steps = scan_length(xs, length, "checkpointed_scan")
    if steps == 0:
        # nothing to checkpoint: the empty scan, with its empty outputs
        return jax.lax.scan(f, init, xs, length=0)
    n_blocks, remainder = divmod(steps, block)
    head = n_blocks * block

    @jax.checkpoint
    def run_block(carry: Carry, block_xs: Any) -> tuple[Carry, Y]:
        return jax.lax.scan(f, carry, block_xs, length=block)

    @jax.checkpoint
    def run_tail(carry: Carry, tail_xs: Any) -> tuple[Carry, Y]:
        return jax.lax.scan(f, carry, tail_xs, length=remainder)

    carry = init
    pieces = []
    if n_blocks:
        # (T, …) → (blocks, k, …) for the head of whole blocks
        blocked = jax.tree.map(
            lambda x: einx.id("(blocks k) ... -> blocks k ...", x[:head], k=block),
            xs,
        )
        carry, blocked_ys = jax.lax.scan(run_block, carry, blocked, length=n_blocks)
        # (blocks, k, …) → (blocks · k, …)
        pieces.append(
            jax.tree.map(
                lambda y: einx.id("blocks k ... -> (blocks k) ...", y), blocked_ys
            )
        )
    if remainder:
        tail = jax.tree.map(lambda x: x[head:], xs)
        carry, tail_ys = run_tail(carry, tail)
        pieces.append(tail_ys)
    if len(pieces) == 1:
        return carry, pieces[0]
    ys = jax.tree.map(lambda a, b: jnp.concatenate([a, b]), *pieces)
    return carry, ys

to_diffrax_adjoint

to_diffrax_adjoint(spec: Any) -> AbstractAdjoint

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.RecursiveCheckpointAdjoint with 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);
  • TruncatedAdjoint raises: truncation belongs to an outer rollout, not to a single solve; use integrix.adjoint.Truncated with integrix.march.run, or truncated_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 adjoints, any structurally identical object, or a diffrax adjoint.

required

Returns:

Type Description
AbstractAdjoint

The diffrax adjoint.

Raises:

Type Description
ValueError

For TruncatedAdjoint or an unrecognised spec (a ValidationError, which is a ValueError).

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
def to_diffrax_adjoint(spec: Any) -> dfx.AbstractAdjoint:
    """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.RecursiveCheckpointAdjoint` with 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);
    - ``TruncatedAdjoint`` raises: truncation belongs to an outer rollout,
      not to a single solve; use `integrix.adjoint.Truncated` with
      `integrix.march.run`, or `truncated_scan`, at that layer.

    A ready-made `diffrax.AbstractAdjoint` passes through unchanged.

    Args:
        spec: A spec from pipekit-cycle's ``adjoints``, any structurally
            identical object, or a diffrax adjoint.

    Returns:
        The diffrax adjoint.

    Raises:
        ValueError: For ``TruncatedAdjoint`` or an unrecognised spec (a
            `ValidationError`, which is a `ValueError`).

    Examples:
        >>> import diffrax as dfx
        >>> class RecursiveCheckpointAdjoint:
        ...     checkpoints = 8
        >>> adjoint = to_diffrax_adjoint(RecursiveCheckpointAdjoint())
        >>> isinstance(adjoint, dfx.RecursiveCheckpointAdjoint), adjoint.checkpoints
        (True, 8)
    """
    if isinstance(spec, dfx.AbstractAdjoint):
        return spec
    name = type(spec).__name__
    if name == "RecursiveCheckpointAdjoint":
        return dfx.RecursiveCheckpointAdjoint(
            checkpoints=getattr(spec, "checkpoints", None)
        )
    if name == "DirectAdjoint":
        return dfx.DirectAdjoint()
    if name == "BacksolveAdjoint":
        return dfx.BacksolveAdjoint()
    if name == "ImplicitAdjoint":
        return dfx.ImplicitAdjoint()
    if name in ("TruncatedAdjoint", "Truncated"):
        raise ValidationError(
            "TruncatedAdjoint applies to an outer rollout (assimilation cycle "
            "or solver iteration), not to a single ODE/SDE solve — use "
            "integrix.adjoint.Truncated with an AbstractStepper in "
            "integrix.march.run, or integrix.adjoint.truncated_scan, at that "
            "layer."
        )
    raise ValidationError(f"Unrecognised adjoint spec: {spec!r}")

scan_for

scan_for(adjoint: Any) -> Callable[..., tuple[Any, Any]]

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

Checkpointed, Truncated, or None for plain reverse mode, which stores every carry. Anything else is refused.

required

Returns:

Type Description
Callable[..., tuple[Any, Any]]

A function scan(f, init, xs) -> (carry, ys), called as jax.lax.scan

Callable[..., tuple[Any, Any]]

is.

Raises:

Type Description
ValidationError

If adjoint is anything else, such as a diffrax adjoint (which to_diffrax_adjoint maps for a diffrax solve) or the class Truncated in place of an instance.

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
def scan_for(adjoint: Any) -> Callable[..., tuple[Any, Any]]:
    """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.

    Args:
        adjoint: `Checkpointed`, `Truncated`, or ``None`` for plain reverse mode,
            which stores every carry. Anything else is refused.

    Returns:
        A function ``scan(f, init, xs) -> (carry, ys)``, called as `jax.lax.scan`
        is.

    Raises:
        ValidationError: If ``adjoint`` is anything else, such as a diffrax
            adjoint (which `to_diffrax_adjoint` maps for a diffrax solve) or the
            class `Truncated` in place of an instance.

    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
    """
    if adjoint is None:
        return jax.lax.scan
    if isinstance(adjoint, Checkpointed):
        every = adjoint.every

        def checkpointed(f: Any, init: Any, xs: Any) -> tuple[Any, Any]:
            return checkpointed_scan(f, init, xs, every=every)

        return checkpointed
    if isinstance(adjoint, Truncated):
        k = adjoint.k

        def truncated(f: Any, init: Any, xs: Any) -> tuple[Any, Any]:
            return truncated_scan(f, init, xs, k=k)

        return truncated
    name = adjoint.__name__ if isinstance(adjoint, type) else type(adjoint).__name__
    raise ValidationError(
        f"'adjoint' of a scan must be None, Checkpointed or Truncated (an "
        f"instance), got {name}; a diffrax adjoint applies to a diffrax solve, "
        f"through integrix.adjoint.to_diffrax_adjoint"
    )

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 (carry, x) -> (carry, y).

required
init Carry

The initial carry.

required
xs X

The stacked per-step inputs, leading axis T, or None with length.

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 xs has no leaves.

None

Returns:

Type Description
tuple[Carry, Y]

(final_carry, ys), exactly as jax.lax.scan returns them.

Raises:

Type Description
ValueError

If k is not an integer of at least 1, a leaf of xs has no leading axis, the leaves or length disagree, or there are no stacked inputs and no length (a ValidationError, which is a ValueError).

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
Source code in src/integrix/_src/adjoint/_truncated.py
def truncated_scan[Carry, X, Y](
    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).

    Args:
        f: The scan body ``(carry, x) -> (carry, y)``.
        init: The initial carry.
        xs: The stacked per-step inputs, leading axis T, or ``None`` with
            ``length``.
        k: The number of trailing steps that propagate gradients through the
            carry, at least 1.
        length: The number of steps T when ``xs`` has no leaves.

    Returns:
        ``(final_carry, ys)``, exactly as `jax.lax.scan` returns them.

    Raises:
        ValueError: If ``k`` is not an integer of at least 1, a leaf of ``xs``
            has no leading axis, the leaves or ``length`` disagree, or there
            are no stacked inputs and no ``length`` (a `ValidationError`,
            which is a `ValueError`).

    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
    """
    if isinstance(k, bool) or not isinstance(k, int) or k < 1:
        raise ValidationError(f"truncated_scan needs k >= 1; got k={k!r}.")
    steps = scan_length(xs, length, "truncated_scan")
    cutoff = steps - k

    def body(carry: Carry, indexed: tuple[Any, X]) -> tuple[Carry, Y]:
        i, x = indexed
        new_carry, y = f(carry, x)
        # jnp.where keeps the graph differentiable in the trailing window and
        # routes earlier steps through stop_gradient.
        cut = i < cutoff
        new_carry = jax.tree.map(
            lambda c: jnp.where(cut, jax.lax.stop_gradient(c), c), new_carry
        )
        return new_carry, y

    return jax.lax.scan(body, init, (jnp.arange(steps), xs), length=steps)