Skip to content

feat(rust): solve rust models with IDAKLUSolver - #5962

Merged
BradyPlanden merged 24 commits into
mainfrom
stack/07-idaklu-rust-mode
Dec 2, 2026
Merged

BradyPlanden merged 24 commits into
mainfrom
stack/07-idaklu-rust-mode

Conversation

@BradyPlanden

@BradyPlanden BradyPlanden commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Description

IDAKLUSolver solves convert_to_format = "rust" models with the Rust backend in pybammsolvers (#5961); without this PR it converts them to CasADi. set_up lowers the whole model once into a pybamm.rust.CompiledModel. RustModelLowering builds the residual, algebraic block, output variables, termination events and sensitivity parameters on one ExprGraph. It then builds one evaluator per solver with CompiledModel.evaluator() and hands the capsules to idaklu.create_rust_solver_group. options={"num_threads": N} solves input sets in parallel, one solver per thread.

  • CompiledModel:
    • It is a frozen class. It exposes cached views of its tapes (rhs, jacobian, outputs, events, algebraic_residual and algebraic_jacobian), residual and Jacobian evaluation into caller buffers, sparsity patterns and jacobian_stats, and it pickles.
    • Its direct eval_* and assemble_* helpers borrow a Workspace from a ScratchPool, like CompiledFunction. The *_into methods borrow their output buffer through numpy's borrow checker, so a read-only or aliased buffer raises ValueError.
  • Evaluator capsules: CompiledModel.evaluator() returns a new evaluator over the model's tapes, with its own scratch, in a pybamm.rust.evaluator capsule. The solver that claims it owns it (feat(pybammsolvers)!: an IDAKLU backend over the Rust C ABI #5961); a capsule no solver claimed frees its evaluator.
  • Solver sizing: IDAKLU reads every count, the Jacobian's CSC pattern, each state's IDA id, the algebraic block's pattern and which event components read y_dot from the evaluator's FFI table, and works out the band from the pattern. create_rust_solver_group takes only the evaluators, atol, rtol, options and whether to use the algebraic sub-block, and raises ValueError for an atol of another length, evaluators of different models, or a sub-block over only some of the states the mass matrix marks algebraic. The Rust Newton solver reads its block from the table too.
  • Output variables:
    • output_variables solves support calculate_sensitivities, projected in-solver.
    • ExplicitTimeIntegral and DiscreteTimeSum output variables are summed after the solve, as on the CasADi path.
    • OutputAssembly.dense lays out the payload, and raises SolverError when names and lengths disagree.
  • Consistent initialisation: it uses the sub-block Newton iteration when newton_mode="auto" and the model is a standard-form DAE with algebraic states. Initial sensitivities come from fix: consistent IDAKLU sensitivity initial conditions at t0 and breakpoints #5949's initialisation, on Rust as on CasADi.
  • Root method: with a CasADi root method, a rust model's consistent states come from a NonlinearSolver (BaseSolver._root_method_for), which logs a warning; the model stays rust and solver.root_method is unchanged.
  • NonlinearSolver:
    • It has a Rust path: it compiles its own CompiledModel for the algebraic system, lowering the rhs and algebraic equations together when the model has rhs states, and runs the Newton iteration over its own CompiledModel.evaluator().
    • It raises SolverError for compile=True, for sensitivity-extended states, and for size mismatches.
  • BaseSolver: for solvers that integrate through a compiled model, it skips feat(rust): evaluate rust models through compiled evaluators #5960's per-function Rust compilation, leaving the rhs, algebraic and combined evaluators with their Jacobians, JVPs and jacp as None, and does not lower termination or interpolant-extrapolation events. IDAKLU then binds rhs_eval and terminate_events_eval from its lowering, the events viewing the compiled model's own event tapes, and algebraic_eval with jac_algebraic_eval only for a root method that reads them.
  • Every format: solve_batch raises SolverError on a buffer-length mismatch, and a pickled NonlinearSolver drops its set-up model.
  • Docs: rust_idaklu_build.md documents the pybammsolvers side: the evaluator capsules and the ABI version check, how to change the FFI surface, and SUNDIALS troubleshooting.

On the Rust path, IDAKLUSolver raises SolverError for:

  • use_jacobian=False, since KLU needs the Jacobian;
  • sensitivities with respect to an input of width above 1;
  • a TensorField output variable, such as a VectorField;
  • a non-scalar termination event.

Sensitivity names that are not inputs raise SolverError naming the model's inputs. It runs one solver per thread, so a num_solvers different from num_threads is overridden for the solve, which logs a warning, and solver.options keeps the value given. compile=True is ignored on the Rust path, which also logs a warning.

Review on #5732

Type of change

New feature, under ## Features in CHANGELOG.md.

Key checklist

  • No style issues: pre-commit run
  • Unit tests pass (N), as do the integration tests (N)
  • Tests added: 174 Python test functions, with 27 existing tests parametrised over casadi and rust.
    • Integration parity against CasADi:
      • rhs, JVP, the assembled Jacobian with and without cj, and the residual (rtol 1e-9 to 1e-10);
      • solves of SPM and DFN, with events, cubic OCPs, N-D interpolants, inputs, output variables and sensitivities;
      • DFN residual and Jacobian rows, and J(cj) = J(0) − cj·M;
      • algebraic sensitivities at t0 against central finite differences at six currents, for newton_mode "auto" and "full";
      • a CasADi root method on a rust model.
    • Unit tests:
      • parallel input sets, num_solvers, and the capsule claim;
      • each raise condition above;
      • the band and sparsity a rust model takes from its Jacobian, and DAE root methods;
      • output sensitivities, events and pickling;
      • output_variables values and sensitivities against CasADi for the SPM, SPMe and DFN, several parameters and outputs, time integrals and the batch window, with no CasADi function compiled;
      • the Rust Newton solver, and what it and the solver group refuse;
      • unknown sensitivity names, num_solvers and compile handling, and which root methods get algebraic evaluators;
      • the *_into methods' buffer checks;
      • RustModelLowering;
      • CompiledModel's views and argument checks;
      • Jacobian sweep budgets for the pouch and SPMe models;
      • saving and loading a rust solution.
Rust execution engine stack: proposal #5667, showcase #5732

Each PR builds on the one above it.

# PR Adds
0 #5954 Function.create_copy keeps the function's class
0b #5955 CasADi's RegPower and uniform-grid interpolant lookups match evaluate
1 #5956 pybamm-core: expression graph, typed IR, interpreters, forward-mode AD
2 #5957 pybamm-core: CompiledModel, coloured Jacobians, the C ABI
3 #5958 pybamm.rust bindings, built into the pybamm wheel
4 #5959 Symbol.to_rust
5 #5960 convert_to_format = "rust" for ScipySolver, AlgebraicSolver and EIS
6 #5961 pybammsolvers: IDAKLU over the C ABI
7 #5962 IDAKLUSolver on rust models ← this PR
8 #5963 variables and sensitivities read in Rust
9 #5964 pybamm-core: diffsol DAE solver
10 #5965 pybamm.DiffsolSolver
10a #6134 Interpolant over input parameters and expressions
10b #6138 pybamm.rust's own errors, array-likes, threads and Ctrl-C
10c #6135 pybamm.rust.inspection; every tape derived in one place
11 #5966 "rust" as the default convert_to_format

@codecov

codecov Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.17127% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 98.40%. Comparing base (48824c0) to head (d8908f8).

Files with missing lines Patch % Lines
...ackages/pybamm/src/pybamm/solvers/rust_lowering.py 97.34% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5962      +/-   ##
==========================================
+ Coverage   98.37%   98.40%   +0.02%     
==========================================
  Files         363      363              
  Lines       38507    38745     +238     
==========================================
+ Hits        37883    38127     +244     
+ Misses        624      618       -6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-advanced-security

Copy link
Copy Markdown

You are seeing this message because GitHub Code Scanning has recently been set up for this repository, or this pull request contains the workflow file for the Code Scanning tool.

What Enabling Code Scanning Means:

  • The 'Security' tab will display more code scanning analysis results (e.g., for the default branch).
  • Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results.
  • You will be able to see the analysis results for the pull request's branch on this overview once the scans have completed and the checks have passed.

For more information about GitHub Code Scanning, check out the documentation.

@BradyPlanden
BradyPlanden force-pushed the stack/07-idaklu-rust-mode branch from 75103ad to e1a1926 Compare October 28, 2026 11:06
@BradyPlanden
BradyPlanden force-pushed the stack/07-idaklu-rust-mode branch 3 times, most recently from 27666c5 to 1826172 Compare October 29, 2026 08:01
@BradyPlanden
BradyPlanden marked this pull request as ready for review October 29, 2026 08:55
@BradyPlanden
BradyPlanden requested a review from a team as a code owner October 29, 2026 08:55
@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

ProjectPyBaMM
Branchstack/07-idaklu-rust-mode
Testbedbare-metal

⚠️ WARNING: Truncated view!

The full continuous benchmarking report exceeds the maximum length allowed on this platform.

🐰 View full continuous benchmarking report in Bencher

🔗 Link this project to GitHub

@BradyPlanden
BradyPlanden force-pushed the stack/07-idaklu-rust-mode branch from 1826172 to 0198a4f Compare October 29, 2026 17:26
@BradyPlanden
BradyPlanden force-pushed the stack/07-idaklu-rust-mode branch 2 times, most recently from 57bd680 to 58cf088 Compare November 18, 2026 09:39
A `CompiledModel`'s views copied the graph's input registry on first
access. Once another input was registered on the graph, as lowering a
symbol with a new input for `Solution.observe` does, the views refused
the model's `p`, and so did unpickling, since core rebuilt the registry
from the whole restored arena. Views also took the registry's packed
width, so a model widened with `n_inputs=` had views that refused its
own `p`.

Views now take core's registry, which is the one the model compiled
with, and the model's input width; `FunctionMetadata` carries that width
and a view's pickle keeps it. The model pickles how many nodes the graph
held when compiled, and `_rebuild` compiles from that prefix of the
restored graph, which nodes appended since cannot change. The mass
matrix travels as one CSR triple, keeping the pickle tuple within
PyO3's twelve elements.
`x.diff(pybamm.t)`, for CasADi models. Rust models now have them too.

`CompiledModel.events_read_y_dot` says which events read `y_dot`, and each
event's `CompiledFunction` view now reports it in `uses_y_dot`, where views
assumed no observable could read it. The Rust IDAKLU set-up keeps it as
`events_read_yp`, as the CasADi set-up does, and hands it to
`create_rust_solver_group`. After a solve, `_termination_event_values`
evaluates the solve's own event tapes at the state and yp it stopped at,
for the check at the initial conditions and for `closest_event_idx`.

Outputs and the upsampling variable are given no `y_dot`, as on CasADi, and
the lowering now refuses one that reads it with CasADi's error rather than
the compiled model's.

breakpoint with output variables, where the Rust backend's staged outputs
needed flushing.
Annotates each method's arguments and return, and the lowered expressions it
holds, as #5960's review asked of rust_graph_with_inputs. sensitivity_indices
casts the graph's index to int, since it has already refused unknown names.
…ress

`EvaluatorPool.as_ptr` gave C++ an integer address, and the solver group or
Newton solver had to keep the pool alive for as long as it used it.
`CompiledModel.evaluator()` instead returns a new evaluator over the model's
tapes in a `pybamm.rust.evaluator` capsule, which the solver claims and then
owns. A capsule nothing claimed frees its evaluator, and one already claimed
is refused.

`IDAKLUSolver` builds one capsule per solver, and `NonlinearSolver` one for
its Newton solver, which now takes `rust_evaluator`. `EvaluatorPool` is gone,
and the developer guide and crate README describe the capsule handoff and the
frozen-layout rule in place of symbol resolution.
Upsampling and events on time derivatives are part of what solving
Rust models with IDAKLUSolver brings, which this PR's entry announces;
no release has reached the Rust backend for them to change.
…ount

#5961 now refuses an atol or rhs_alg_id whose length is not
number_of_states before Rust sees the model. The test that overcounts
number_of_states lengthens both by one too, so the count still reaches
the Rust model's own check.
A Rust model was lowered several times over. Each integrator compiled
its CompiledModel through its own copy of the recipe, NonlinearSolver
compiled a second one for its Newton step, and process() gave every
symbol it compiled a graph of its own: the initial conditions,
discontinuity times and step state mappers of every solve, and every
part a solver other than IDAKLU read. Two class flags chose the path.

A model now keeps one RustModelLowering, made by RustModelLowering.of
and kept while its input names stay the same; a copy or pickle of the
model drops it. BaseSolver.set_up compiles the model's CompiledModel on
it for every solver: the residual, the algebraic block of a DAE, the
termination events, the df/dp of any sensitivities, the output
variables and the upsampling output a solver's _upsampling_variable
names. The generic rhs_eval, algebraic_eval and rhs_algebraic_eval,
their Jacobians and the termination events are views of it, as
RustEvaluator now takes a view's rows and a prepared Jacobian.
process(), the EIS output Jacobian and NonlinearSolver compile on the
same graph, and NonlinearSolver reuses the model's CompiledModel rather
than compiling its own. A model without states compiles over an empty
mass matrix.

A ScipySolver set-up of an SPM builds one graph rather than six. A DFN
set up for a Newton initialisation compiles one CompiledModel rather
than two, in 2.7 ms rather than 4.4 ms.
…puts

The model's lowering outlives a set-up, and four things went wrong with
that. Each compile left its parts on the lowering, through public step
methods any caller could run out of order, and set-up blanked the
model's evaluators before compiling: a set-up that failed left the
model without them, breaking another solver's next solve. An input the
model does not have, met while lowering, was registered on its graph
for good. IDAKLUSolver passed a model with no states, which now
compiles, to C++ that crashed on it. And EIS compiled its output
function at every solve.

compile_model now lowers every part into locals and keeps the
CompiledModel, output lengths and sensitivity names only once the model
compiles; its steps are private, and set-up binds the model's
evaluators only after it. An input parameter lowered into a model's
graph refuses a name outside its inputs with a SolverError, so a set-up
missing an input, or an observed symbol reading one, leaves the graph
as it was. IDAKLUSolver refuses a model with no states. EIS caches its
output function on the lowering.

process() keeps no Jacobian-vector product for a Rust model, and
refuses y_dot, which only its CompiledModel's termination events read.
Set-up of the CasADi, Python and JAX formats moves, unchanged, into
_set_up_part_evaluators.
…ough of

The guide claimed a failed set-up leaves the model as it was; it keeps
the evaluators of its last set-up, as the initial conditions are set
before the CompiledModel compiles. The Newton tests now make their
lowerings with RustModelLowering.of, as source does.
…onditions a graph of their own

The lowering kept the last compile's output lengths and sensitivity
names for IDAKLU and Diffsol to read back, so two solvers setting up
one model at once could read each other's, and it bound the model's
evaluators itself. Initial conditions compiled on the model's graph,
which grew by one node, carried by every pickle, for each initial
state a sweep tried.

compile_model now keeps only the CompiledModel, for the Newton step to
reuse. BaseSolver._set_up_rust_model compiles it, binds the model's
evaluators as its views, and hands it to the solver's
_prepare_integrator, which IDAKLU and Diffsol implement in place of
_set_up_rust and _prepare_solver; output lengths come from the
CompiledModel's outputs and sensitivity names from the model. Initial
conditions, which change from solve to solve, compile on a graph of
their own. IDAKLU refuses a model without states as it checks the
model, before anything compiles, and a Rust set-up returns before the
CasADi path's preparation.
… last

IDAKLU refused a model with use_jacobian=False only once the model had
compiled and its evaluators were bound to the new CompiledModel. It now
refuses it as it checks the model, before anything compiles, for both
formats; the remaining option helper is _rust_options, and the CasADi
path's unreachable non-CasADi branch is gone. Set-up prepares the
integrator before it binds the model's evaluators, and IDAKLU builds its
set-up before keeping it, so a refused integrator leaves the model as
its last set-up did.

A Rust model's vars_for_processing carries its lowering, which set-up
hands to _set_up_rust_model and swaps for a lowering of their own for
the initial conditions, so process() finds its lowering one way. Its
sensitivity indices come from the lowering's sensitivity_indices, which
refuses an unknown name rather than dropping it. y_dot is checked once,
on the symbol, before it is lowered, so a refused symbol leaves nothing
in the graph; output and event shapes share one helper.
set_up moves the initial-condition block, so comment-slop counts its two
comments as changed lines, and both only name the call beneath them.
IDAKLU's set-up read 15 CompiledModel members in Python and passed 20
arguments to create_rust_solver_group, whose RustFunctions took 15, eight
of them counts the evaluator's FFI table already answers. Each count was
checked three times: in Python, in idaklu.cpp, and in C++ against the
table. The Rust Newton solver took its block split and Jacobian pattern
from Python the same way, with Python shifting the pattern's columns into
the block.

The table now also carries the Jacobian's CSC pattern, each state's IDA
id, the algebraic Jacobian's COO pattern, and which event components read
y_dot, appended within ABI version 2. RustFunctions reads a RustLayout
from its own evaluator and works out the band widths from the pattern, so
create_rust_solver_group takes only the evaluators, atol, rtol, options
and whether to use the algebraic sub-block. It refuses an atol of the
wrong length, evaluators with different counts, and a sub-block that
covers only some of the states the mass matrix marks algebraic. The
Newton solver reads its block from the table and shifts the columns
itself, beside the gather that puts the block at the trailing states.

IDA counts one root per event component, as the flags do, so C++ no
longer refuses a vector event; the lowering still does. The C++ pattern
checks, Python's _csc_bandwidths, and the CompiledModel members that only
fed C++ (has_algebraic, algebraic_jacobian_nnz,
algebraic_jacobian_sparsity_pattern) go, with the tests that faked a
disagreement to reach those checks.
CompiledModel.from_expr took an n_inputs that could make a model wider
than the inputs its graph registered. Nothing but tests used it: set-up
registers every input a solve stacks when it makes the model's graph,
so the lowering only ever passed the default. Widening is why a
function's metadata carried an input width apart from its registry's,
and why a view's pickle kept it.

from_expr drops n_inputs, and a model now takes the packed width of the
inputs its graph had registered when it compiled, read from the same
prefix of the graph _rebuild compiles from, so its pickle no longer
carries the width. A function's input width is its registry's packed
width, so CompiledFunction._rebuild drops input_width.
RustModelLowering.n_inputs and ExprGraph::params lose their last
callers and go.
The Rust Newton path had a file of its own, test_nonlinear_solver_rust.py,
that copied test_nonlinear_solver.py's root finds, inputs, sparse and
dense modes and pivot tolerance for convert_to_format="rust", and an
integration class, TestRustNewton, with more of the same.

test_nonlinear_solver.py now parametrises every test that solves over
convert_to_format, so the Rust path also gets the time-dependent,
caching, pickling, convergence-failure, logging and eSOH checks it
lacked, and the pivot-tolerance test records what reaches each
format's Newton solver. What only the Rust path has, its refusals and
the evaluator it owns, is TestNonlinearSolverRust in the same file.
Two Rust tests the parametrised ones now cover go: a pure-algebraic
parity test and a solver-only pickle round trip.
@BradyPlanden
BradyPlanden force-pushed the stack/07-idaklu-rust-mode branch from 722f0d5 to d13c4a4 Compare December 2, 2026 19:28
@BradyPlanden
BradyPlanden enabled stacked auto-merge December 2, 2026 19:32
martinjrobins
martinjrobins previously approved these changes Dec 2, 2026
…odel case

Seven files compared Rust and CasADi solves, each with its own model and
asserts: an SPM four times over, a DFN, an event, a cubic OCP, an ECM, a
toy model with inputs, and an SPM with inputs plus outputs or
sensitivities. test_rust_model_parity.py already built twelve battery
models to check their compiled expressions against CasADi.

Its case fixture now solves each model with CasADi at tolerances tight
enough for the backends to agree to 1e-5 of each state's scale, plus
1e-8 for states near zero, and TestSolveParity solves it again on Rust:
termination, event time, states and voltage; output variables
evaluated in the solver; and the sensitivities of a case with inputs.
A cubic-OCP SPM joins the cases, and the guard that the DFN reaches
RegPower moves to them. Seven cases end on an event, which a test pins,
and the Thevenin case reads the ECM's N-D interpolants, so
test_rust_idaklu_spm.py, _dfn.py, _parity.py, _inputs.py and
_all_features.py go, with the SPM and DFN parity classes of
test_convert_to_format_rust.py and the decay sensitivity test.

The Marcus-Hush-Chidsey SPM fails on Rust: its algebraic Newton IC
runs on through a NaN state, where CasADi's KLU set-up fails and IDA's
own initialisation takes over. Its solve tests are strict xfails.
The base set-up compiled a Rust model and prepared IDAKLU's integrator
before binding the model's evaluators, the reverse of the CasADi path.
IDAKLUSolver.set_up now builds it after the base set-up, as it does for
CasADi, and the base _prepare_integrator hook is gone. The atol shape
check moves to _check_and_prepare_model_inplace, so a bad tolerance is
refused before anything compiles, in either format.
test_solve_matches_casadi held the Rust and CasADi event times to
rtol=1e-9, tighter than the solve's own rtol of 1e-8. The backends agree
bit for bit on macOS arm64, but on Linux x86-64 their rounding differs
and the SPM drive cycle's maximum-voltage event lands 2e-8 to 5e-8
apart; the CasADi time itself moved 5e-8 between two CI runs.

A 1% change in rtol moves that event by 1.4e-7 of its time, so the
assert takes rtol=1e-6. A wrong event expression or threshold still
moves it far further.
@BradyPlanden
BradyPlanden added this pull request to the merge queue Dec 2, 2026
Merged via the queue into main with commit 6125a5b Dec 2, 2026
71 checks passed
@BradyPlanden
BradyPlanden deleted the stack/07-idaklu-rust-mode branch December 2, 2026 22:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants