Repository navigation
feat(rust): evaluate rust models through compiled evaluators - #5960
Merged
Merged
Conversation
This was referenced Oct 22, 2026
This was referenced Oct 22, 2026
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #5960 +/- ##
==========================================
- Coverage 98.37% 98.36% -0.02%
==========================================
Files 360 362 +2
Lines 38052 38160 +108
==========================================
+ Hits 37433 37535 +102
- Misses 619 625 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
BradyPlanden
force-pushed
the
stack/05-rust-generic-evaluators
branch
from
October 28, 2026 09:55
db04e34 to
45bbd36
Compare
BradyPlanden
force-pushed
the
stack/05-rust-generic-evaluators
branch
2 times, most recently
from
October 28, 2026 15:28
67e6c0a to
3e4986e
Compare
BradyPlanden
force-pushed
the
stack/05-rust-generic-evaluators
branch
from
October 29, 2026 08:01
3e4986e to
b408f4d
Compare
BradyPlanden
marked this pull request as ready for review
October 29, 2026 08:55
Contributor
|
| Project | PyBaMM |
| Branch | stack/05-rust-generic-evaluators |
| Testbed | bare-metal |
🐰 View full continuous benchmarking report in Bencher
⚠️ WARNING: Truncated view!The full continuous benchmarking report exceeds the maximum length allowed on this platform.
BradyPlanden
force-pushed
the
stack/05-rust-generic-evaluators
branch
from
October 29, 2026 17:26
b408f4d to
d158fdb
Compare
BradyPlanden
force-pushed
the
stack/05-rust-generic-evaluators
branch
from
November 17, 2026 11:24
d158fdb to
b6dcf91
Compare
BradyPlanden
force-pushed
the
stack/05-rust-generic-evaluators
branch
2 times, most recently
from
November 19, 2026 13:30
294503a to
99e7905
Compare
3 tasks done
martinjrobins
requested changes
Nov 23, 2026
martinjrobins
left a comment
Contributor
There was a problem hiding this comment.
thanks @BradyPlanden, looks great. most of the comments below are pre-existing bugs or notes for the future
BradyPlanden
force-pushed
the
stack/05-rust-generic-evaluators
branch
from
November 24, 2026 11:24
3cc29df to
4f75b78
Compare
BradyPlanden
force-pushed
the
stack/05-rust-generic-evaluators
branch
2 times, most recently
from
November 24, 2026 14:04
f0d8c4a to
98df1e1
Compare
"rust" is a valid convert_to_format; BaseSolver.process builds RustEvaluators; ScipySolver, AlgebraicSolver and EIS run on them.
#6056 lets a solver take events on the state derivatives: `process` gives the CasADi functions `y_dot` as a fourth input when `use_state_derivatives` is set, and otherwise refuses an expression reading `y_dot` as it converts. The Rust branch ignored the flag, so an event on `x.diff(pybamm.t)` compiled for a solver that never supplies `y_dot` and failed only when evaluated. It now raises the same `ValueError` as the CasADi conversion when the compiled function reads `y_dot` and the flag is unset, and a "func" `RustEvaluator` passes a fourth argument on as `y_dot`, as the CasADi function takes it.
…uested Output variables always ask `process` for a stacked jacp, so `BaseSolver(output_variables=[...])` refused a rust model even with no sensitivities requested. CasADi reads the flag only when sensitivities are on, and the Rust branch now does the same.
The Rust vector-input check ran after the loop that disables observability for each missing input. Observability cannot be re-enabled, so a refused call left the model unobservable even once a later solve supplied every input. The check now runs before that loop.
Replaces the per-format branch with the idiom the algebraic, scipy and IDAKLU solvers use: `stack_inputs` for a stacked-input format, the dict otherwise. The new test solves with two inputs, in both orders, on both backends, and checks the impedances agree.
Converting a StateVector without `y`, or a StateVectorDot without `y_dot`, raised ValueError on CasADi, and the Rust branch copied it to match. Both backends now raise pybamm.ModelError, as StateVectorDot.diff already does for a second time derivative. BREAKING CHANGE: code catching ValueError from these conversions, including solution.observe of a time derivative, must catch pybamm.ModelError.
Annotates `input_names` as an iterable of names and the return as an `ExprGraph`, and documents both.
BradyPlanden
force-pushed
the
stack/05-rust-generic-evaluators
branch
from
November 25, 2026 10:36
98df1e1 to
ef18ee7
Compare
martinjrobins
approved these changes
Nov 25, 2026
martinjrobins
left a comment
Contributor
There was a problem hiding this comment.
all good, happy to merge
This was referenced Nov 30, 2026
This was referenced Dec 1, 2026
Closed
BradyPlanden
added a commit
that referenced
this pull request
Dec 2, 2026
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.
GHzytp
pushed a commit
to GHzytp/PyBaMM
that referenced
this pull request
Dec 3, 2026
* feat(rust): solve rust models with IDAKLUSolver CompiledModel/EvaluatorPool bindings, RustModelLowering, the IDAKLU rust set-up and the Rust-backed NonlinearSolver. * chore(rust): name CompiledModel's bindings for PyO3 0.30 and the lint table `CompiledModel._rebuild` keeps its Python name through `#[pyo3(name = ...)]`, as PyO3 0.30 trips `used_underscore_items` on an underscored Rust name. `sparsity_pattern` and `csc_sparsity_pattern` cannot fail, so they return their arrays directly now that the workspace no longer allows `unnecessary_wraps`. * chore(rust): drop a missing_const_for_fn allow nothing trips Clippy no longer suggests `const` for the `nnz` getter, so the allow suppressed nothing. * perf(rust): let the core validate build_from_parts' roots `CompiledModel::new` and `set_observables` validate every root they lower, so the binding's own pass walked each root twice. * fix(rust): hand the Newton solver its evaluator pool Pass the pool itself to `StandaloneNewtonSolver`, which now owns it, and drop `_NonlinearSolverSetup`'s keepalive slot. A test that built two solvers from one evaluator address now gives each its own pool, as the pool's hand-out-once rule requires. * feat(rust): upsample rust models in IDAKLUSolver `upsampling_tolerance` now reaches `convert_to_format = "rust"` models, which raised a `SolverError` instead. The variable choice that `_upsampling_fcn` made for CasADi, by name, scale and whether it is an algebraic state, moves into `_upsampling_variable`, which both backends call. The Rust path lowers that variable into the `CompiledModel`'s upsampling output, so IDAKLU places the same points for either backend, and a test holds a model's `t_additive` to the CasADi one. `CompiledModel.from_expr` takes an `upsampling_expr`, `upsampling_len` and an `upsampling` view expose it, and pickling keeps its root. `test_scale` checks the function each backend compiled, and main's newer IDAKLU tests (upsampling, non-finite residuals, sensitivity error control and the iterative linear solver) run on both formats. The Rust check that `solve` pre-empts for vector-width sensitivities is reached through `set_up`. * fix(rust): keep a compiled model's inputs as compiled 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. * feat(rust): IDAKLU events on time derivatives of rust models `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. * refactor(rust): type RustModelLowering Annotates each method's arguments and return, and the lowered expressions it holds, as pybamm-team#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. * refactor(rust): hand each solver an evaluator capsule, not a pool address `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. * chore: fold the Rust IDAKLU parity entries into the feature's 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. * test(rust): lengthen the per-state arrays with an overcounted state count pybamm-team#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. * refactor(rust): lower each model into one graph, compiled once 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. * fix(rust): compile a model's graph whole or not at all, on its own inputs 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. * docs(rust): say what a failed set-up keeps, and build test models through 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. * refactor(rust): hand each integrator its CompiledModel, and initial conditions 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. * refactor(rust): check before compiling, and bind a model's evaluators 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. * chore: drop two set-up comments that restate the code 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. * refactor(rust): IDAKLU sizes itself from the evaluator's own table 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. * refactor(rust): a compiled model takes the inputs its graph registered 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. * test: run NonlinearSolver's tests on both formats, in one file 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. * test: compare Rust and CasADi IDAKLU solves in one test, over every model 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. * refactor(rust): build IDAKLU's Rust integrator after the base set-up 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: hold the parity solve's event time to what the solve fixes 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Makes
"rust"a validconvert_to_format. A rust model's rhs, algebraic, Jacobian, event and initial-condition functions are compiled to Rust and evaluated byScipySolver,AlgebraicSolverand EIS. The default stays"casadi".BaseSolver.processcompiles each function into aCompiledFunctionon its ownExprGraph. Inputs are registered in stacking order at their widths (rust_graph_with_inputs).RustEvaluatorwraps the compiled function with CasADi's(t, y, inputs)calling convention. It has four roles: the value, the Jacobian (a scipy CSC built on first use), a Jacobian-vector product, andjacp, with one column per sensitivity parameter.stack_inputsgainsconvert_to_format="casadi", and returns a flat numpy array for rust models. Every caller passes the model's format (EIS, inside its rust branch, passes"rust"), and a one-argument call behaves as in v26.10.0.Moduloperiods are evaluated through the model's own compiled functions, with the inputs stacked in its format, as its residual is.pybamm.SolverErrornaming the input. So does a vector-width input that only a variable reads and that has no value, which before raised a bareValueErrorfrom Rust.IDAKLUSolver,CasadiSolverandCasadiAlgebraicSolverconvert rust models to CasADi, with a warning; feat(rust): solve rust models with IDAKLUSolver #5962 adds IDAKLU's Rust path.ScipySolverevent wrapper returnsnp.asarray(...).item(), and EIS calls.sparse()only on CasADi Jacobians, so a python or jax model's Jacobian goes tocsc_matrixas it is.validate_rust_sensitivity_widthsis added in this PR, and feat(rust): solve rust models with IDAKLUSolver #5962 calls it.Not supported in this PR:
return_jacp_stackedraisesSolverError, before anything is lowered or compiled.NonlinearSolver, still builds its residual with CasADi, so no DAE solver keeps a rust model until feat(rust): solve rust models with IDAKLUSolver #5962.ScipySolversensitivities raiseNotImplementedError, as onmain.Type of change
New feature, under
## FeaturesinCHANGELOG.md.Key checklist
pre-commit runRustEvaluatorrole against CasADi on a toy DAE (rtol 1e-12, atol 1e-14), including events, initial conditions and a rectangular Jacobian.stack_inputsfor rust models, and called with one argument;SolverErrorat widths 1 and 3, and for a missing vector input;return_jacp_stackedrejected before lowering;TestDenseMatrixToRust) and theconftest_rustfixtures from feat(rust): lower expression trees with Symbol.to_rust #5959, withrust_backendadded here;AlgebraicSolveron rust against casadi (rtol 1e-8);"rust"round-trips through serialisation.Rust execution engine stack: proposal #5667, showcase #5732
Each PR is one commit on the one above it.
Function.create_copykeeps the function's classRegPowerand uniform-grid interpolant lookups matchevaluatepybamm-core: expression graph, typed IR, interpreters, forward-mode ADpybamm-core:CompiledModel, coloured Jacobians, the C ABIpybamm.rustbindings, built into thepybammwheelSymbol.to_rustconvert_to_format = "rust"forScipySolver,AlgebraicSolverand EIS ← this PRpybammsolvers: IDAKLU over the C ABIIDAKLUSolveron rust modelspybamm-core: diffsol DAE solverpybamm.DiffsolSolver"rust"as the defaultconvert_to_format