Repository navigation
feat(rust): pybamm.DiffsolSolver, integrating rust models with diffsol - #5965
Open
BradyPlanden wants to merge 33 commits into
Open
BradyPlanden wants to merge 33 commits into
BradyPlanden wants to merge 33 commits into
Conversation
2 of 4 tasks
This was referenced Oct 22, 2026
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## stack/09-rust-core-diffsol #5965 +/- ##
============================================================
Coverage 98.42% 98.43%
============================================================
Files 363 364 +1
Lines 39022 39262 +240
============================================================
+ Hits 38409 38646 +237
- Misses 613 616 +3 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
This was referenced Oct 22, 2026
BradyPlanden
force-pushed
the
stack/10-diffsol-solver
branch
from
October 28, 2026 09:55
d3bb4ff to
856f633
Compare
BradyPlanden
force-pushed
the
stack/10-diffsol-solver
branch
2 times, most recently
from
October 28, 2026 14:11
76e3077 to
283bed6
Compare
BradyPlanden
force-pushed
the
stack/10-diffsol-solver
branch
2 times, most recently
from
October 29, 2026 08:01
37788fe to
b9bb622
Compare
BradyPlanden
marked this pull request as ready for review
October 29, 2026 08:56
Contributor
|
| Project | PyBaMM |
| Branch | stack/10-diffsol-solver |
| 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/10-diffsol-solver
branch
from
October 29, 2026 17:26
b9bb622 to
519f514
Compare
BradyPlanden
force-pushed
the
stack/10-diffsol-solver
branch
from
November 17, 2026 11:24
519f514 to
4ec163f
Compare
pybamm-core no longer retries a sensitivity solve with the sensitivities out of error control, so a failure under it is a `SolverError` carrying diffsol's own message, as IDAKLUSolver raises. `SolverStatistics.sens_error_control_relaxed` goes, with the warning DiffsolSolver logged on a relaxed solve, the binding's `SensRetryFailed` mapping and the stub's property. Statistics add field by field again, as no field is a flag. An unmeetable `sens_atol_factor` now fails the DFN solve, and the pulse-train gradients must all hold error control.
`DiffsolSolver`'s defaults mirror pybamm-core's again. It gains `max_number_timesteps`, 100,000 steps between consecutive breakpoints, and `max_nonlinear_solver_failures` falls to diffsol's 10, now counted per step. `min_timestep` follows diffsol to machine epsilon, and the options stub lists the new key. A budget of zero is the one sure to fail the pulse train now that failures are counted per step, so the budget test uses it, and its companion only needs the workload to spend a failure at all.
DiffsolSolver always put the forward sensitivities in the local error test, where IDAKLUSolver leaves them out unless its `sensitivity_error_control` option asks. A solve that switched between the two changed cost and could fail where IDAKLU did not. `sensitivity_error_control` is now a DiffsolSolver option of the same name and default, passed to `PreparedSolver` as a keyword, and `sens_atol_factor` is documented as acting only under it. The options docstring also says `min_timestep` defaults to machine epsilon. Tests of gradient accuracy against tight references opt in, and the spatial parity test turns it on in both solvers so they compare alike.
IDAKLUSolver takes `model.atol` over its own `atol` when a model sets one, and DiffsolSolver ignored it. It now reads it the same way, and the per-state atol tests check both solvers.
BaseSolver keeps only each window's first and last sample for a solver that interpolates, and experiments read the flag from the solver, but DiffsolSolver's constructor did not take it. It does now, and the plain-solve and experiment tests run on both solvers.
…-only DiffsolSolver orders `on_failure`, `output_variables` and its own arguments differently from IDAKLUSolver, so a positional call written for one would silently mean something else to the other. Every argument after `rtol` and `atol` is now keyword-only.
An expression the Rust backend cannot lower raises NotImplementedError advising `model.convert_to_format = 'casadi'`, which DiffsolSolver undoes by converting every model to Rust. Its set-up now adds that it solves Rust models only and that IDAKLUSolver takes this one.
`solve` said it lands on every `t_stop`, and the binding that each must be in `t_eval`; one that is not is integrated through. `y_event` is the state at a root, or at the end of an outputs solve, not at every end. `default_solver_options` still named the failure budget as the change from diffsol's defaults, where it is now the step budget.
DiffsolSolver defaulted to rtol 1e-6 where IDAKLUSolver, and PyBaMM's other solvers, take 1e-4, so switching solvers changed accuracy and cost together. `PreparedSolver` takes the same default. At 1e-4 the voltage on the output grid stays within 3e-5 to 6e-5 V of a 1e-9 reference on SPM, SPMe, DFN, thermal DFN and the pulse train, as IDAKLU's does, and within 7e-5 V on DFN at 3C, where IDAKLU's is 2.5e-3 V. Solves take 0.7 to 1.4 times IDAKLU's time, bar thermal DFN at 4.2. Tests that check an accuracy finer than 1e-4 delivers now set their own tolerances, and the initial-condition comparisons match the root solve's.
The comment put later knots' derivatives ~1e-6 off the analytic one; at the test's rtol of 1e-10 they are 1e-11 to 4e-9 off.
With sensitivity error control off, the steps follow the states alone, so a jump in ds/dt the state never sees is resolved only where PyBaMM places a breakpoint, as it does at each time discontinuity it finds. Both solvers now have to resolve such a jump at `t > 0.5` to 1e-6 without error control, and DiffsolSolver's docstring says where the uncontrolled mode relies on that breakpoint.
`SolveRequest::with_interrupt` takes an `Interrupt`, which a solve polls before each integration step and once before it starts. A solve that reads it as set returns `CoreError::Interrupted`, so in a batch every set still running stops too. An `AtomicBool` is an `Interrupt`, and a solve with none, or with one never set, takes the same steps as before. The Python bindings pass no interrupt yet.
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.
DiffsolSolver lowered and compiled the model itself, after BaseSolver.set_up. It now prepares its integrator over the CompiledModel set-up compiles on the model's graph. That CompiledModel holds a DAE's algebraic block, which diffsol never reads: it adds 0.23 ms to a DFN's 1.2 ms compile, and lets the Newton step of a calc_ic=False solve reuse the model rather than compile its own. An event reading y_dot is refused as the model lowers, with the ModelError of every solver whose events take no state derivatives, rather than by PreparedSolver.
Native observation compiled its leaves on the graph of the CompiledModel a solver had bound to the model's ObserverCache, each leaf lowering afresh. A model no solver bound, as ScipySolver left every model, or a hand-built Solution read through CasADi, as did a VectorField. The _observes_via_compiled_model flag chose which solvers bound. Every Rust model's variables, VectorField components among them, now compile on its RustModelLowering, sharing its memo of lowered symbols, and a leaf reads as many states as its segment stores. ObserverCache keeps only CasADi leaves, and the flag goes. Setting the model up again keeps its leaves; a copy compiles its own. Reading five variables of a ScipySolver SPM solution takes 6 ms rather than 10 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.
…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.
Diffsol kept the CompiledModel and its output assembly before making its PreparedSolver, so an invalid tolerance or option left them from a set-up that failed. It now keeps them once the PreparedSolver is made.
sens_atol kept the algebraic states at the state atol, on the claim that tightening them fails DAE sensitivity solves. Applied to every state, Chen2020 DFN sensitivity solves, with constant and stepped currents, succeed at factors down to 1e-4 and rtol 1e-4 and 1e-6, with the same sensitivities. The exemption only left the algebraic sensitivities, the potentials a voltage gradient reads, looser than the factor asked for. IDAS likewise applies its sensitivity tolerances to every state.
Above 4096 output columns a solve stopped storing yp, so off-grid reads fell from cubic to linear without saying so. The reason given, that a dense grid's chord is already at the integration error floor, depends on the model's timescales against the span, not on the column count, and IDAKLU has no such cap. hermite_interpolation=False remains the way to save the memory.
A single solve could factorise its sparse LU on num_threads workers of a shared pool, documented as worthwhile from about 50k states. Timed on Chen2020 DFNs of 962, 8262 and 50652 states and an SPM, 2, 4 and 8 threads were never faster than one, and on the 50652-state DFN 4 and 8 threads were 12% and 24% slower. IDAKLU's num_threads only solves input sets in parallel, so DiffsolSolver's now does the same. SolveRequest loses lu_threads, PreparedSolver.solve loses num_threads, and the solve loses the lu_par it carried through Run, Recorder and its LU helpers. Every LU still runs at an explicit serial Par, since a host may disable faer's global parallelism.
A stored yp's algebraic slope at a segment start needs dF/dt when a constraint reads t: without it, z = 1000t(1+1000t) stores dz/dt(0) = 0 rather than 1000, and reads inside the first output interval are 6-55% off. PreparedSolver compiled dF/dt from a graph the binding re-read and simplified a second time. CompiledModel now compiles it from the graph it already simplified, when the model has algebraic states and reads t, so with_time_derivative and the binding's graph round trip go. The tests that only checked the slope's value now also read inside the first interval: the time-driven constraint, the algebraic model, whose reads had all landed in later intervals, and a Chen2020 DFN after each current step, which stays under 4 mV and reaches 54.5 mV without the consistent algebraic slope.
…onfig PreparedSolver took rtol and atol, then five builders, two of them fallible and one building the g_v layout as a side effect, so its settings were validated in four places. PreparedSolver::new now takes a SolverConfig with every setting, which SolverConfig::new fills with defaults beside rtol and atol, validates it once, and builds what the config implies. The binding fills the config from its arguments; the Python API is unchanged. Outputs are bit-identical on every solve_paths case.
…ch them Core's solve_batch takes a slice of InputSets, which can't disagree on how many sets there are; only the binding's row arrays can. The check moves into the binding, raising the same InvalidInputError text, and core drops check_batch_widths, CoreError::BatchWidths and BatchSensWidth. `solver::batch` becomes private, as solve_batch is a PreparedSolver method. A Python test replaces the core one.
_stack_y0_sens repeated its only caller's sensitivity guard, _solve_one's y0S default was never used, and _use_default_root_method is one boolean.
- The single-set num_threads test compared one call with itself; only its pool check could fail, so it keeps that alone. - The dense-grid test's read sat below its tolerance on a chord as well as a cubic; the flags carry the change. It now reads 4097 columns over one span, without a stop at every column. - A first-interval read superseded by the analytic ones goes, and the stepped-current voltage check uses assert_allclose. - ed2422fe2 (a failed set-up keeps the last good one) and 50bbe35eb (other inputs reuse one lowering per set of names) gain the tests that fail without them.
Codecov found DiffsolSolver's patch short of the project's coverage: no unit test solved several input sets at once with sensitivities, so the batch's dy0/dp seeds were never stacked, and no test sent the binding a request it refuses. A sweep with sensitivities is now solved at four threads and serially, with an initial state fixed and one set by the input, and must match bit for bit and analytically. A non-finite t_eval is refused as a SolverError.
The base set-up no longer prepares a solver's integrator, so DiffsolSolver's _prepare_integrator went uncalled and every solve failed for want of one. DiffsolSolver.set_up now builds it after the base set-up, as IDAKLUSolver does, and checks atol in _check_and_prepare_model_inplace, so a bad tolerance is refused before anything compiles.
BradyPlanden
force-pushed
the
stack/10-diffsol-solver
branch
from
December 4, 2026 10:47
d5f2cc3 to
49b07a1
Compare
This branch has not been deployed
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
Adds
pybamm.DiffsolSolver, which integrates a rust model entirely in Rust through the solver from #5964, with no CasADi or SUNDIALS on the path. It releases the GIL while it integrates.set_upswitches the model toconvert_to_format = "rust", lowers it withRustModelLowering(#5962), and reads its solutions natively (#5963).rtol(default 1e-4) andatolas a scalar or per state, with a model's ownatoltaking precedence, as forIDAKLUSolver.calc_ic=True: diffsol finds consistent initial conditions. WithFalse, they are root-solved first withroot_method, which defaults toNonlinearSolverfor DAEs.hermite_interpolation=True,store_first_last,sensitivity_error_control=Falseandsens_atol_factor=1.0, keyword-only like every argument after the tolerances.options: a dict of diffsol's 16OdeSolverOptions, with pybamm-core's defaults (max_number_timestepsis 100,000 between breakpoints), plusnum_threads.Nonewhere only the growth and shrink bounds take it), and an invalidnum_threadsorsens_atol_factorraiseSolverErrornaming the option. NumPy scalars are accepted.on_failuretakes only"error", the default;"warn"and"ignore"raiseSolverError, since diffsol returns no partial solution.t_evalis the discontinuity map, as forIDAKLUSolver. Output times aret_eval ∪ t_interpplus the discontinuity times, and each discontinuity segment gets only thet_interppoints inside it.t_interp, they also include 100 uniform points over the span, chosen from the times passed in, before discontinuities are merged. A bare[t0, tf]therefore gives 100 points plus the discontinuity times, and a coarset_evalsuch as[0, 1800, 3600]still has a grid fine enough for Hermite reads. Passt_interp=t_evalfor output at exactlyt_eval, as forIDAKLUSolver.t_interpkeeps exactlyt_evalwhen that has three or more points, which drive-cycle experiment steps rely on.num_threads > 1solves several input sets concurrently withsolve_batch, and a single set solves serially, as withIDAKLUSolver. Withnum_threads = 1, the sets run one after another.forkduring a build cannot deadlock the child.yp, as forIDAKLUSolver, andhermite_interpolation=Falsedropsyp.ypis never stored foroutput_variables, or above 4096 output points.sensitivity_error_control=True, as forIDAKLUSolver. Under it,sens_atol_factorscales the sensitivity floor.output_variablessolve keeps the states and state sensitivities at both ends, sofirst_state,last_stateand a continued step have them. Like IDAKLU's, it lists its sensitivity names with zero-row state sensitivities, sostep()'s restart checks find them.pybamm.rust.PreparedSolver,SolveOutcome,SolverStatisticsanddefault_solver_options, with stubs.SolveOutcome.event_indexnames the event that ended a solve, and solutions setclosest_event_idxfrom it.pybamm-core,check_batch_widthswith itsBatchWidthsandBatchSensWidtherrors, andTermination::as_flag,event_timeandevent_index, which these bindings use. AlsoSolveRequest::with_interrupt, which stops a solve between steps withCoreError::Interrupted; the bindings pass none yet.pybamm.SolverStatisticsgains diffsol's counters, includingproblem_setup_time_secs. Unpickling one saved by 26.10 fills the new fields with their defaults, so it still adds to a new one.IDAKLUSolverthroughBaseSolver: theatolcheck,_internal_initialisation, and the event-violation guard.OutputAssembly.stack_parameter_blocksstacks sensitivity blocks, andhatch_build.pybuildspybamm.rustwith thediffsolfeature.api/solvers/diffsol_solver.rst.Errors and limits:
SolverErrorwith the binding's message. Sensitivity names that are not inputs raiseSolverErrorfrom the lowering.SolverErrornaming the input set.SolverErrorat set-up, since diffsol's root function gets none.NotImplementedErrorthat points atIDAKLUSolver.TensorFieldoutput variables, raiseSolverError, as on IDAKLU's Rust path.nprocis ignored.Review on #5732
rayon_pool.rs: the thread pools are inpybamm-python/src/rayon_pool.rs.Type of change
New feature, under
## FeaturesinCHANGELOG.md.Key checklist
pre-commit run--all-features, 1 ignored)t_eval;output_variablessolves;SolverErrorfor unknown keys, wrong types, out-of-range values, invalid tolerances, unknown sensitivity parameters andon_failure;closest_event_idxfor state and output solves;num_threads: serial equals batch (Hypothesis), result order, shared and evicted pools, a forked child (forked from a fresh interpreter, so the test process never forks), failures named per set;atoland time discontinuities.IDAKLUSolverat rtol 1e-5 and atol 1e-8:sens_atol_factorandsensitivity_error_control;dy0/dpseeding;t_eval: within 2e-6 V on diffsol's own grid, and 1.2 mV (Hermite) or 19 mV (linear) at worst in between;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 modelspybamm-core: diffsol DAE solverpybamm.DiffsolSolver← this PRInterpolantover 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