Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
9582bc2
feat(rust): solve rust models with IDAKLUSolver
BradyPlanden Sep 22, 2026
2fa543b
chore(rust): name CompiledModel's bindings for PyO3 0.30 and the lint…
BradyPlanden Nov 14, 2026
327bdb9
chore(rust): drop a missing_const_for_fn allow nothing trips
BradyPlanden Nov 14, 2026
d8111da
perf(rust): let the core validate build_from_parts' roots
BradyPlanden Nov 16, 2026
2968013
fix(rust): hand the Newton solver its evaluator pool
BradyPlanden Nov 16, 2026
1435e39
feat(rust): upsample rust models in IDAKLUSolver
BradyPlanden Nov 17, 2026
6b80784
fix(rust): keep a compiled model's inputs as compiled
BradyPlanden Nov 20, 2026
07d75b0
feat(rust): IDAKLU events on time derivatives of rust models
BradyPlanden Nov 21, 2026
50bc539
refactor(rust): type RustModelLowering
BradyPlanden Nov 24, 2026
63daaaa
refactor(rust): hand each solver an evaluator capsule, not a pool add…
BradyPlanden Nov 25, 2026
45805ed
chore: fold the Rust IDAKLU parity entries into the feature's
BradyPlanden Nov 26, 2026
9884f8b
test(rust): lengthen the per-state arrays with an overcounted state c…
BradyPlanden Nov 26, 2026
387c857
refactor(rust): lower each model into one graph, compiled once
BradyPlanden Nov 27, 2026
e509bde
fix(rust): compile a model's graph whole or not at all, on its own in…
BradyPlanden Nov 27, 2026
27fc357
docs(rust): say what a failed set-up keeps, and build test models thr…
BradyPlanden Nov 27, 2026
da52d65
refactor(rust): hand each integrator its CompiledModel, and initial c…
BradyPlanden Nov 27, 2026
a94f45a
refactor(rust): check before compiling, and bind a model's evaluators…
BradyPlanden Nov 28, 2026
26e1775
chore: drop two set-up comments that restate the code
BradyPlanden Nov 30, 2026
c4c261e
refactor(rust): IDAKLU sizes itself from the evaluator's own table
BradyPlanden Nov 28, 2026
362683f
refactor(rust): a compiled model takes the inputs its graph registered
BradyPlanden Nov 30, 2026
3cd367c
test: run NonlinearSolver's tests on both formats, in one file
BradyPlanden Nov 30, 2026
d81517e
test: compare Rust and CasADi IDAKLU solves in one test, over every m…
BradyPlanden Nov 30, 2026
dc9b43f
refactor(rust): build IDAKLU's Rust integrator after the base set-up
BradyPlanden Dec 1, 2026
d8908f8
test: hold the parity solve's event time to what the solve fixes
BradyPlanden Dec 2, 2026
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
1 change: 1 addition & 0 deletions changelog.d/5962.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`IDAKLUSolver` solves `convert_to_format = "rust"` models through a Rust `CompiledModel`, one evaluator per thread, so `num_threads` parallelises input sets. `output_variables` support sensitivities and time integrals, and `NonlinearSolver` compiles its own model.
110 changes: 104 additions & 6 deletions docs/source/developer/rust_idaklu_build.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,50 @@
# Building the Rust Backend

This guide covers building the Rust compute core and its Python bindings for
development. Everything lives in this repository's `uv` workspace; there are
no side-by-side clones or environment variables to configure.
This guide covers building the Rust compute core, its Python bindings, and the
Rust-capable IDAKLU solver for development. Everything lives in this
repository's `uv` workspace; there are no side-by-side clones or environment
variables to configure.

## Components

| Component | Location | Build tool | Output |
|-----------|----------|------------|--------|
| `pybamm-core` | `packages/pybamm-rust/pybamm-core` | Cargo | Rust library (rlib) |
| `pybamm-python` | `packages/pybamm-rust/pybamm-python` | maturin (via `uv sync`) | `pybamm.rust._core` extension module |
| pybammsolvers | `packages/pybammsolvers` | scikit-build-core / CMake | `idaklu` extension module |

**How the pieces connect:**

- `pybamm-python` implements `pybamm.rust`, which provides the Python API over
the Rust code in `pybamm-core`, which compiles expressions into evaluable
functions and sparse Jacobians.
- `pybamm.rust` also lowers a discretised model to a `CompiledModel` for the
IDAKLU solver.
- pybammsolvers does **not** link against the Rust core (the package
dependency only flows the other way). Instead, `CompiledModel.evaluator()`
hands IDAKLU each evaluator in a Python capsule named
`pybamm.rust.evaluator`. The capsule holds the evaluator and a pointer to the
function table of the build that made it, and IDAKLU calls only through that
table. Nothing is resolved by symbol name, so `pybamm.rust._core` exports no
FFI symbols.
- IDAKLU claims each capsule by renaming it `pybamm.rust.evaluator.claimed`,
and then owns the evaluator: each solver frees its own, and a claimed
evaluator cannot be handed to a second solver.
- The contract's source of truth is `FfiTable` and `EvaluatorHandle` in
`packages/pybamm-rust/pybamm-core/src/ffi.rs`. The C++ consumer mirrors them
in
`packages/pybammsolvers/src/pybammsolvers/idaklu_source/Expressions/Rust/pybamm_rust_ffi.h`,
and the `test_ffi_abi_contract` drift test compares the two field by field.
- The table leads with its ABI version and its size. IDAKLU refuses an
evaluator of another version, or one whose table is shorter than the one it
reads, before calling anything.
- IDAKLU sizes every buffer Rust reads or writes from the evaluator's own
table: its counts, Jacobian pattern, state ids, algebraic block and which
events read `yp`. Python hands `create_rust_solver_group` the evaluators,
tolerances, options and whether to use the algebraic sub-block for the
initial conditions. IDAKLU checks what it cannot read from the table, such
as `atol`'s length and a sub-block that covers every algebraic state,
raising `ValueError` on a mismatch.

## Prerequisites

Expand All @@ -38,12 +67,14 @@ git submodule update --init --recursive
uv sync --extra all --group dev
```

Verify the extension imports:
Verify the two halves see each other:

```bash
uv run python -c "
from pybamm.rust import ExprGraph
print('Rust bindings:', ExprGraph)
from pybamm.rust import CompiledModel
from pybammsolvers import idaklu
print('Rust bindings:', CompiledModel)
print('Rust FFI available:', hasattr(idaklu, 'create_rust_solver_group'))
"
```

Expand All @@ -52,11 +83,54 @@ print('Rust bindings:', ExprGraph)
`uv`'s cache keys cover the Rust sources, so `uv sync --extra all --group dev`
or `uv run` rebuilds `pybamm.rust._core` whenever a `.rs` file changes.

pybammsolvers' cache key is only its `pyproject.toml`. After changing any of
its C++ sources — including `pybamm_rust_ffi.h` — force a rebuild:

```bash
uv cache clean pybammsolvers
uv sync --extra all --group dev --reinstall-package pybammsolvers
```

## Changing the FFI surface

The drift test parses both sides of the boundary, so the workflow is
mechanical:

1. Edit `FfiTable` and `FFI_TABLE` in `ffi.rs` and `PybammRustFfi` in
`pybamm_rust_ffi.h` together. The drift test fails on any field the two
tables do not share, in order and type, on an `FFI_TABLE` entry wired to
another entry's function, and on an entry idaklu never calls.
2. Run `cargo test -p pybamm-core --test test_ffi_abi_contract` from
`packages/pybamm-rust/`. The test holds the layout the current ABI version
froze:
- **Appending** table entries passes it unchanged. A pybammsolvers built
against the shorter table reads only the entries it knows, so it keeps
working with the newer core.
- **Any other change** (an entry's signature or meaning, removing or
reordering entries, or the handle's layout) fails it. Bump
`RUST_ABI_VERSION` and `PYBAMM_RUST_ABI_VERSION` together; the test then
prints the new layout to freeze in its place.
3. Rebuild both extensions (previous section). A pybammsolvers built for
another ABI version refuses the evaluator, naming both versions, rather
than corrupting an evaluation.

## Running tests

```bash
# Rust unit + contract tests
cd packages/pybamm-rust && cargo test --workspace

# Battery models' expressions and IDAKLU solves on Rust against CasADi (from the repo root)
uv run --group dev pytest packages/pybamm/tests/integration/test_rust_model_parity.py
```

## Checking the ABI version

`idaklu.rust_abi_version` is the version a pybammsolvers build reads; it must
equal `RUST_ABI_VERSION` in the `ffi.rs` that built `pybamm.rust._core`:

```bash
uv run python -c "from pybammsolvers import idaklu; print(idaklu.rust_abi_version)"
```

## Running benchmarks
Expand All @@ -68,8 +142,32 @@ cd packages/pybamm-rust && cargo bench -p pybamm-core --all-features

## Troubleshooting

### Segfaults in SUNDIALS callbacks

Crashes during `solve()` (especially in residual/Jacobian callbacks) usually
indicate a **SuiteSparse version mismatch**: the `.idaklu/` build directory
holds a stale build while the submodules (or a Homebrew install picked up via
`@rpath`) moved on. Rebuild the native dependencies from the current
submodules:

```bash
cd packages/pybammsolvers
rm -rf .idaklu
uv run python install_KLU_Sundials.py
cd ../.. && uv sync --extra all --group dev --reinstall-package pybammsolvers
```

Do **not** point the build at Homebrew's suite-sparse; version mismatches
between it and the local SUNDIALS build cause runtime crashes.

### `pybamm.rust._core` import fails

```bash
uv sync --extra all --group dev --reinstall-package pybamm
```

### Rust ABI version errors

pybammsolvers and `pybamm.rust._core` were built for different ABI versions,
or the core's table is older than the one pybammsolvers reads. Rebuild both
extensions from the same tree (see "Rebuilding after changes").
14 changes: 13 additions & 1 deletion packages/pybamm-rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@ differentiate, lower and evaluate. The crate-level doc walks through them, links
module, and explains how the Jacobian is assembled (see
[Finding your way around](#finding-your-way-around)).

## Who consumes it

- **IDAKLU**, through the C ABI in `ffi.rs`. `pybammsolvers` cannot link against this
crate, because PyBaMM depends on `pybammsolvers` and not the reverse. So each evaluator
reaches IDAKLU in a Python capsule that also carries the function table of the build
that made it, and IDAKLU calls only through that table. Nothing is resolved by symbol
name, so IDAKLU loads standalone. The table leads with an ABI version, which IDAKLU
must match, and its size: within a version entries are only appended, so a newer core
still works with an older IDAKLU. Bumping the Rust version means bumping the C++ one
in the same change.

## Building

Build through the workspace, not `cargo` or `maturin` directly:
Expand Down Expand Up @@ -53,7 +64,8 @@ uv run --group dev pytest -m unit packages/pybamm/tests # python side, from r

Rust and Python tests cover different things. The Rust suite owns the compiler and
interpreter, including property tests that check AD against finite differences and the
split primal/tangent tape against a monolithic one. The Python suite owns the bindings.
split primal/tangent tape against a monolithic one. The Python suite owns parity: the
same model solved through Rust and through CasADi must agree.

## Benchmarking

Expand Down
Loading
Loading