Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/skills/code-review/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,12 @@ annotations both have to survive. A **new** overridable field should follow the
same pattern, not invent a second convention. `max_steps` is also `static=True`;
leave it that way.

The `max_steps` **field** has a second sentinel, `"auto"`, resolved in
`__call__` after the `MISSING` check: `len(ts) - 1` for a `diffrax.StepTo`
controller, the scraped `default_max_steps` otherwise. It must stay resolved at
solve time, not at construction, so that `eqx.tree_at` on `stepsize_controller`
picks up the new grid. An explicit integer or `None` must never be rewritten.

## Shape bookkeeping

[interp.py](../../../src/diffraxtra/_src/interp.py) maintains one invariant by
Expand Down
17 changes: 11 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
`DiffEqSolver`, an `equinox.Module` that pre-configures `diffrax.diffeqsolve`
behind a callable object, and `VectorizedDenseInterpolation`, which makes the
`diffrax.DenseInterpolation` produced by a batched solve evaluable at
arbitrarily-shaped arrays of times.
arbitrarily-shaped arrays of times. A small helper, `fixed_steps`, builds a
`diffrax.StepTo` grid for a fixed number of steps.

The design goal is to extend diffrax without diverging from it: follow diffrax's
own API conventions, keep dependencies minimal, and keep every object a PyTree
Expand Down Expand Up @@ -34,7 +35,7 @@ new session needs its group to exist.

## Architecture

The public API is the four names re-exported from
The public API is the five names re-exported from
[src/diffraxtra/\_\_init\_\_.py](src/diffraxtra/__init__.py); everything else
lives under `src/diffraxtra/_src/` and is private. Each public class is an
abstract/`@final` pair of `equinox.Module`s, with `eqx.AbstractVar` fields on
Expand All @@ -45,6 +46,7 @@ the ABC.
| [\_src/diffeq_abc.py](src/diffraxtra/_src/diffeq_abc.py) | `AbstractDiffEqSolver`: the five `AbstractVar` fields, the plum-dispatched `__call__` pair that forwards to `dfx.diffeqsolve`, the `params` signature scrape, and four `from_` overloads |
| [\_src/diffeq.py](src/diffraxtra/_src/diffeq.py) | `DiffEqSolver`: the `@final` concrete module, plus the `default_stepsize_controller` / `default_max_steps` / `default_adjoint` re-exports |
| [\_src/interp.py](src/diffraxtra/_src/interp.py) | `AbstractVectorizedDenseInterpolation` and `VectorizedDenseInterpolation`: the batch-flattening `__init__`, the doubly-vmapped `evaluate`, the `DenseInterpolation` property forwards, and three `from_` overloads |
| [\_src/steps.py](src/diffraxtra/_src/steps.py) | `fixed_steps`: the `optimization_barrier`-wrapped `StepTo` grid and `(t0, t1, StepTo, max_steps)` |
| [conftest.py](conftest.py) | sybil collection and x64 |

`__call__` is **two** methods: a `@dispatch`ed positional one on the class, and
Expand Down Expand Up @@ -106,7 +108,9 @@ is an example run by [sybil](https://sybil.readthedocs.io) from
"not passed" (use the field) stays distinguishable from an explicit `None`
(unbounded / no event). Never "simplify" either default to `None`. `max_steps`
is additionally `static=True`, so each distinct value is a separate
compilation.
compilation. The `max_steps` field defaults to `"auto"`, resolved at solve
time to `len(ts) - 1` for a `diffrax.StepTo` controller and to the scraped
`default_max_steps` otherwise.
- **`__call__` is `eqx.filter_jit`-wrapped, twice.** `throw`,
`vectorize_interpolation` and `max_steps` are static; a structurally different
`solver` / `stepsize_controller` / `adjoint` retraces. Both dispatch overloads
Expand All @@ -127,7 +131,7 @@ is an example run by [sybil](https://sybil.readthedocs.io) from
- **`jax` and `numpy` are imported in `src/` but not declared** in
`[project.dependencies]` (which lists `diffrax`, `equinox`, `jaxtyping`,
`plum-dispatch`, `typing_extensions`). They arrive transitively.
- **CI runs `--resolution lowest`**, so new code must work on `diffrax>=0.6`,
- **CI runs `--resolution lowest`**, so new code must work on `diffrax>=0.6.2`,
not just the newest release. Because that lowers _transitive_ deps too, a
dependency that only publishes an old sdist can break the job during install,
before a single test runs — hence the transitive lower bounds in
Expand All @@ -149,8 +153,9 @@ is an example run by [sybil](https://sybil.readthedocs.io) from

## Dependencies

`diffrax>=0.6`, `equinox>=0.11.5`, `jaxtyping>=0.2.35`, `plum-dispatch>=2.5.7`,
`typing_extensions>=4.12.2`; Python >=3.11. Minimum supported versions follow
`diffrax>=0.6.2`, `equinox>=0.11.10`, `jaxtyping>=0.2.35`,
`plum-dispatch>=2.5.7`, `typing_extensions>=4.12.2`; Python >=3.11. Minimum
supported versions follow
[SPEC 0](https://scientific-python.org/specs/spec-0000/).

## Further Reading
Expand Down
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,24 @@ DiffEqSolver(...solver=Dopri5(...)...
For a full enumeration of the ways to construct a `DiffEqSolver` object, see
`diffraxtra.DiffEqSolver.from_`.

### `fixed_steps`

`fixed_steps(t0, dt, n_steps)` returns the `t0`, `t1`, `diffrax.StepTo`
controller and `max_steps` for `n_steps` fixed steps of size `dt`. `t0` and `dt`
can be traced, and a negative `dt` runs backward. A `DiffEqSolver` with a
`StepTo` controller sets `max_steps` to the number of steps on the grid by
itself, so you can drop the fourth value.

```pycon
>>> from diffraxtra import fixed_steps
>>> t0, t1, stepto, max_steps = fixed_steps(0.0, 0.1, 30)
>>> solver = DiffEqSolver(dfx.Tsit5(), stepsize_controller=stepto)
>>> soln = solver(term, t0, t1, None, 1.0)
>>> soln.ys.round(3)
Array([0.05], dtype=float64)

```

### `VectorizedDenseInterpolation`

Vectorized wrapper around a `diffrax.DenseInterpolation`
Expand Down
7 changes: 4 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
]
dynamic = ["version"]
dependencies = [
"diffrax>=0.6",
"equinox>=0.11.5",
"diffrax>=0.6.2",
"equinox>=0.11.10",
"jaxtyping>=0.2.35",
"plum-dispatch>=2.5.7",
"typing_extensions>=4.12.2",
Expand Down Expand Up @@ -143,6 +143,8 @@ filterwarnings = [
"ignore:jax.core.pp_eqn_rules is deprecated:DeprecationWarning",
# Equinox 0.11.5 & Jax 0.4.35
"ignore:jax.interpreters.batching.NotMapped is deprecated:DeprecationWarning",
# Equinox 0.11.10 & Jax 0.4.38
"ignore:jax\\.core\\.\\w+ is deprecated:DeprecationWarning",
]
log_cli_level = "INFO"
testpaths = ["README.md", "src/", "skills/", "tests/"]
Expand Down Expand Up @@ -218,7 +220,6 @@ constraint-dependencies = [
"pillow>=10.3.0",
# Jax
"scipy>=1.14",
"jax>0.4.34",
# Misc
"opt-einsum>=3.3.0",
# Transitive dependencies for --resolution lowest
Expand Down
58 changes: 47 additions & 11 deletions skills/diffraxtra/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ description:
when a batched `diffrax.diffeqsolve` result needs `.evaluate`, when the output
of a batched solve has an unexpected shape, when `vectorize_interpolation` or
`apply_to_solution` appears, when a per-call `max_steps` or `event` override
is needed, when `max_steps=None` conflicts with a `diffrax.SaveAt`, or when a
`DiffEqSolver` recompiles on every call.
is needed, when `max_steps=None` conflicts with a `diffrax.SaveAt`, when a
`DiffEqSolver` recompiles on every call, or when running a fixed number of
`diffrax.StepTo` steps with `fixed_steps`.
---

# Using diffraxtra Effectively

`diffraxtra` is two extras for [diffrax](https://docs.kidger.site/diffrax/), and
nothing else:
a small helper:

- **`DiffEqSolver`** — an `equinox.Module` holding a `solver`,
`stepsize_controller`, `adjoint`, `event` and `max_steps`, callable with the
Expand All @@ -23,12 +24,14 @@ nothing else:
- **`VectorizedDenseInterpolation`** — a wrapper around
`diffrax.DenseInterpolation` that evaluates a **batched** solution at an
**arbitrarily-shaped** array of times, without you writing the `jax.vmap`.
- **`fixed_steps(t0, dt, n_steps)`** — the `(t0, t1, StepTo, max_steps)` for
`n_steps` fixed steps of size `dt`, with `t0` and `dt` allowed to be traced.

Each comes as an `Abstract*`/`@final` pair of `equinox.Module`s, and each has a
`plum`-dispatched `from_` constructor. That is the whole library.
Each class comes as an `Abstract*`/`@final` pair of `equinox.Module`s, and each
has a `plum`-dispatched `from_` constructor.

Checked against diffraxtra 1.5.3, diffrax 0.7.0, equinox 0.13.0, plum-dispatch
2.5.7, jax 0.7.1, Python >=3.11. The supported floor is `diffrax>=0.6`.
2.5.7, jax 0.7.1, Python >=3.11. The supported floor is `diffrax>=0.6.2`.

## Quick start

Expand Down Expand Up @@ -179,8 +182,13 @@ genuinely three-way — omitting the argument is **not** the same as passing
`None`. The parameter defaults to `dataclasses.MISSING`, and only that sentinel
means "use the field".

The `max_steps` field defaults to `"auto"`, which is resolved at solve time.
With a `diffrax.StepTo` controller it is `len(ts) - 1`, the exact number of
steps on the grid. With any other controller it is diffrax's default, 4096. An
integer or `None`, on the field or in the call, is used as is.

```python
assert DiffEqSolver(dfx.Dopri5()).max_steps == 4096 # diffrax's default, scraped
assert DiffEqSolver(dfx.Dopri5()).max_steps == "auto"
assert DiffEqSolver(dfx.Dopri5()).event is None

solver(term, t0=0.0, t1=3.0, dt0=0.1, y0=1.0, saveat=t1_only) # use the field
Expand Down Expand Up @@ -219,6 +227,33 @@ solver(
That is exactly why the per-call override exists — configure a solver once with
a bounded `max_steps`, and drop the bound only for the calls that can take it.

## Fixed steps

`fixed_steps(t0, dt, n_steps)` builds the grid `t0 + dt * arange(n_steps + 1)`
behind `jax.lax.optimization_barrier` and returns `(t0, t1, StepTo, max_steps)`.
The barrier stops XLA's simplifier from rewriting `t1` and the grid separately
with different roundings, and `StepTo` rejects a `t1` that is one rounding off
`ts[-1]`. `t0` and `dt` can be traced, and a negative `dt` runs backward. With
`DiffEqSolver` the fourth value isn't needed, because `"auto"` reads it off the
`StepTo`. With `RecursiveCheckpointAdjoint` the exact bound matters: it sets how
many checkpoints the backward pass stores.

```python
from diffraxtra import fixed_steps


@jax.jit
def final_y(t0, dt):
t0, t1, stepto, _ = fixed_steps(t0, dt, 100)
fixed = DiffEqSolver(dfx.Heun(), stepsize_controller=stepto)
return fixed(dfx.ODETerm(lambda t, y, args: t), t0, t1, None, 1.0).ys[-1]


assert jnp.allclose(final_y(1.0, 0.01), 2.5) # 1 + (2**2 - 1**2) / 2
assert jnp.allclose(final_y(2.0, -0.01), -0.5) # backward: 1 + (1**2 - 2**2) / 2
assert jnp.allclose(jax.grad(final_y, argnums=1)(1.0, 0.01), 200.0) # n_steps * t1
```

## What is static, and what retraces

`AbstractDiffEqSolver.__call__` is wrapped in `eqx.filter_jit`, so the whole
Expand Down Expand Up @@ -339,7 +374,8 @@ compile-time constant everywhere it is used.
## Version notes

diffraxtra reads `diffrax.diffeqsolve`'s defaults out of its signature at import
time, so `max_steps=4096`, the default `adjoint`, and the default
`stepsize_controller` are diffrax's values, and change when diffrax changes.
`diffrax>=0.6` is the supported floor and is tested in CI; minimum supported
versions follow [SPEC 0](https://scientific-python.org/specs/spec-0000/).
time, so the 4096 that `max_steps="auto"` falls back to, the default `adjoint`,
and the default `stepsize_controller` are diffrax's values, and change when
diffrax changes. `diffrax>=0.6.2` is the supported floor and is tested in CI;
minimum supported versions follow
[SPEC 0](https://scientific-python.org/specs/spec-0000/).
2 changes: 2 additions & 0 deletions src/diffraxtra/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
"DiffEqSolver",
"AbstractVectorizedDenseInterpolation",
"VectorizedDenseInterpolation",
"fixed_steps",
]

from ._src import (
AbstractDiffEqSolver,
AbstractVectorizedDenseInterpolation,
DiffEqSolver,
VectorizedDenseInterpolation,
fixed_steps,
)
from ._version import ( # noqa: F401
version as __version__,
Expand Down
6 changes: 5 additions & 1 deletion src/diffraxtra/_src/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"""Extras for `diffrax`. Private API."""

__all__ = [ # pylint: disable=R0801
# pylint: disable=duplicate-code

__all__ = [
"AbstractDiffEqSolver",
"DiffEqSolver",
"AbstractVectorizedDenseInterpolation",
"VectorizedDenseInterpolation",
"fixed_steps",
]

from .diffeq import DiffEqSolver
Expand All @@ -13,3 +16,4 @@
AbstractVectorizedDenseInterpolation,
VectorizedDenseInterpolation,
)
from .steps import fixed_steps
50 changes: 46 additions & 4 deletions src/diffraxtra/_src/diffeq.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,14 @@
]

from dataclasses import KW_ONLY
from typing import Any, final
from typing import Any, Literal, final

import diffrax as dfx
import equinox as eqx

from .diffeq_abc import AbstractDiffEqSolver, params
from .diffeq_abc import AbstractDiffEqSolver, default_max_steps, params

default_stepsize_controller = params["stepsize_controller"].default
default_max_steps = params["max_steps"].default
default_adjoint = params["adjoint"].default


Expand Down Expand Up @@ -99,6 +98,47 @@ class DiffEqSolver(AbstractDiffEqSolver): # pylint: disable=R0903,W0223
Array([[0.90483742, 0.81872516],
[0.74080871, 0.67031456]], dtype=float64)

With a `diffrax.StepTo` controller, ``max_steps`` defaults to the number of
steps on the grid, ``len(ts) - 1``. Saving every step shows the bound,
because diffrax pads the saved steps out to ``max_steps``.

>>> grid = jnp.linspace(0, 1, 11)
>>> stepto = DiffEqSolver(dfx.Euler(), stepsize_controller=dfx.StepTo(grid))
>>> every_step = dfx.SaveAt(steps=True)
>>> stepto(term, t0=0, t1=1, y0=1, saveat=every_step).ys.shape
(10,)

A ``max_steps`` given to the solver or to the call is used as is.

>>> stepto(term, t0=0, t1=1, y0=1, saveat=every_step, max_steps=20).ys.shape
(20,)
>>> stepto30 = DiffEqSolver(dfx.Euler(), stepsize_controller=dfx.StepTo(grid),
... max_steps=30)
>>> stepto30(term, t0=0, t1=1, y0=1, saveat=every_step).ys.shape
(30,)

Passing ``max_steps="auto"`` to the call asks for the grid's step count
even when the solver holds an integer.

>>> stepto30(term, t0=0, t1=1, y0=1, saveat=every_step, max_steps="auto").ys.shape
(10,)

``max_steps=None`` stays unbounded, so diffrax rejects it when saving
every step.

>>> stepto(term, t0=0, t1=1, y0=1, saveat=every_step, max_steps=None)
Traceback (most recent call last):
...
ValueError: `max_steps=None` is incompatible with saving at `steps=...

Other controllers use diffrax's default.

>>> solver(term, t0=0, t1=3, dt0=0.1, y0=1, saveat=every_step).ys.shape
(4096,)

`diffraxtra.fixed_steps` builds a `diffrax.StepTo` grid from ``t0``,
``dt`` and a number of steps.

"""

#: The solver for the differential equation.
Expand All @@ -121,6 +161,8 @@ class DiffEqSolver(AbstractDiffEqSolver): # pylint: disable=R0903,W0223
event: dfx.Event | None = None

#: The maximum number of steps to take before quitting.
#: The default, ``"auto"``, means ``len(ts) - 1`` with a `diffrax.StepTo`
#: controller, and `diffrax.diffeqsolve`'s default otherwise.
#: Some `diffrax.SaveAt` options can be incompatible with `max_steps=None`,
#: so you can override the `max_steps` argument when calling `DiffEqSolver`
max_steps: int | None = eqx.field(default=default_max_steps, static=True)
max_steps: int | None | Literal["auto"] = eqx.field(default="auto", static=True)
Loading
Loading