Repository navigation
feat(rust): solve rust models with IDAKLUSolver - #5962
Merged
Merged
Conversation
This was referenced Oct 22, 2026
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
2 of 3 tasks
BradyPlanden
force-pushed
the
stack/07-idaklu-rust-mode
branch
from
October 28, 2026 09:55
560fd32 to
75103ad
Compare
|
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:
For more information about GitHub Code Scanning, check out the documentation. |
BradyPlanden
force-pushed
the
stack/07-idaklu-rust-mode
branch
from
October 28, 2026 11:06
75103ad to
e1a1926
Compare
BradyPlanden
force-pushed
the
stack/07-idaklu-rust-mode
branch
3 times, most recently
from
October 29, 2026 08:01
27666c5 to
1826172
Compare
BradyPlanden
marked this pull request as ready for review
October 29, 2026 08:55
Contributor
|
| Project | PyBaMM |
| Branch | stack/07-idaklu-rust-mode |
| 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/07-idaklu-rust-mode
branch
from
October 29, 2026 17:26
1826172 to
0198a4f
Compare
BradyPlanden
force-pushed
the
stack/07-idaklu-rust-mode
branch
2 times, most recently
from
November 18, 2026 09:39
57bd680 to
58cf088
Compare
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
force-pushed
the
stack/07-idaklu-rust-mode
branch
from
December 2, 2026 19:28
722f0d5 to
d13c4a4
Compare
BradyPlanden
enabled stacked auto-merge
December 2, 2026 19:32
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
force-pushed
the
stack/07-idaklu-rust-mode
branch
from
December 2, 2026 21:29
d13c4a4 to
d8908f8
Compare
martinjrobins
approved these changes
Dec 2, 2026
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
IDAKLUSolversolvesconvert_to_format = "rust"models with the Rust backend in pybammsolvers (#5961); without this PR it converts them to CasADi.set_uplowers the whole model once into apybamm.rust.CompiledModel.RustModelLoweringbuilds the residual, algebraic block, output variables, termination events and sensitivity parameters on oneExprGraph. It then builds one evaluator per solver withCompiledModel.evaluator()and hands the capsules toidaklu.create_rust_solver_group.options={"num_threads": N}solves input sets in parallel, one solver per thread.CompiledModel:rhs,jacobian,outputs,events,algebraic_residualandalgebraic_jacobian), residual and Jacobian evaluation into caller buffers, sparsity patterns andjacobian_stats, and it pickles.eval_*andassemble_*helpers borrow aWorkspacefrom aScratchPool, likeCompiledFunction. The*_intomethods borrow their output buffer through numpy's borrow checker, so a read-only or aliased buffer raisesValueError.CompiledModel.evaluator()returns a new evaluator over the model's tapes, with its own scratch, in apybamm.rust.evaluatorcapsule. 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.y_dotfrom the evaluator's FFI table, and works out the band from the pattern.create_rust_solver_grouptakes only the evaluators,atol,rtol, options and whether to use the algebraic sub-block, and raisesValueErrorfor anatolof 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_variablessolves supportcalculate_sensitivities, projected in-solver.ExplicitTimeIntegralandDiscreteTimeSumoutput variables are summed after the solve, as on the CasADi path.OutputAssembly.denselays out the payload, and raisesSolverErrorwhen names and lengths disagree.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.NonlinearSolver(BaseSolver._root_method_for), which logs a warning; the model stays rust andsolver.root_methodis unchanged.NonlinearSolver:CompiledModelfor the algebraic system, lowering the rhs and algebraic equations together when the model has rhs states, and runs the Newton iteration over its ownCompiledModel.evaluator().SolverErrorforcompile=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 andjacpasNone, and does not lower termination or interpolant-extrapolation events. IDAKLU then bindsrhs_evalandterminate_events_evalfrom its lowering, the events viewing the compiled model's own event tapes, andalgebraic_evalwithjac_algebraic_evalonly for a root method that reads them.solve_batchraisesSolverErroron a buffer-length mismatch, and a pickledNonlinearSolverdrops its set-up model.rust_idaklu_build.mddocuments the pybammsolvers side: the evaluator capsules and the ABI version check, how to change the FFI surface, and SUNDIALS troubleshooting.On the Rust path,
IDAKLUSolverraisesSolverErrorfor:use_jacobian=False, since KLU needs the Jacobian;TensorFieldoutput variable, such as aVectorField;Sensitivity names that are not inputs raise
SolverErrornaming the model's inputs. It runs one solver per thread, so anum_solversdifferent fromnum_threadsis overridden for the solve, which logs a warning, andsolver.optionskeeps the value given.compile=Trueis ignored on the Rust path, which also logs a warning.Review on #5732
ModelEvaluator, and IDAKLU indexes its solvers by OpenMP thread, so each thread already has its own scratch.Workspaceis sized for itsCompiledModel.Vec<Mutex<ModelEvaluator>>: there is no pool any more: each solver claims and owns its ownModelEvaluator, handed over in a capsule (feat(pybammsolvers)!: an IDAKLU backend over the Rust C ABI #5961). The capsule's construction and destructor are the bindings' onlyunsafe.CompiledJacobianbut one scratch onCompiledModel:CompiledModelpools its workspaces in aScratchPool, likeCompiledFunctionandCompiledJacobian.model.rscomment is gone.Type of change
New feature, under
## FeaturesinCHANGELOG.md.Key checklist
pre-commit runcj, and the residual (rtol 1e-9 to 1e-10);J(cj) = J(0) − cj·M;t0against central finite differences at six currents, fornewton_mode"auto"and"full";num_solvers, and the capsule claim;output_variablesvalues 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;num_solversandcompilehandling, and which root methods get algebraic evaluators;*_intomethods' buffer checks;RustModelLowering;CompiledModel's views and argument checks;Rust execution engine stack: proposal #5667, showcase #5732
Each PR builds 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 EISpybammsolvers: IDAKLU over the C ABIIDAKLUSolveron rust models ← this PRpybamm-core: diffsol DAE solverpybamm.DiffsolSolverInterpolantover input parameters and expressionspybamm.rust's own errors, array-likes, threads and Ctrl-Cpybamm.rust.inspection; every tape derived in one place"rust"as the defaultconvert_to_format