Skip to content

feat(rust): pybamm.DiffsolSolver, integrating rust models with diffsol - #5965

Open
BradyPlanden wants to merge 33 commits into
stack/09-rust-core-diffsolfrom
stack/10-diffsol-solver
Open

BradyPlanden wants to merge 33 commits into
stack/09-rust-core-diffsolfrom
stack/10-diffsol-solver

Conversation

@BradyPlanden

@BradyPlanden BradyPlanden commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

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_up switches the model to convert_to_format = "rust", lowers it with RustModelLowering (#5962), and reads its solutions natively (#5963).

  • Options:
    • rtol (default 1e-4) and atol as a scalar or per state, with a model's own atol taking precedence, as for IDAKLUSolver.
    • calc_ic=True: diffsol finds consistent initial conditions. With False, they are root-solved first with root_method, which defaults to NonlinearSolver for DAEs.
    • hermite_interpolation=True, store_first_last, sensitivity_error_control=False and sens_atol_factor=1.0, keyword-only like every argument after the tolerances.
    • options: a dict of diffsol's 16 OdeSolverOptions, with pybamm-core's defaults (max_number_timesteps is 100,000 between breakpoints), plus num_threads.
    • Unknown keys, an option of the wrong type (a count that is not a non-negative integer, a real that is not a number, None where only the growth and shrink bounds take it), and an invalid num_threads or sens_atol_factor raise SolverError naming the option. NumPy scalars are accepted.
    • on_failure takes only "error", the default; "warn" and "ignore" raise SolverError, since diffsol returns no partial solution.
  • Times: t_eval is the discontinuity map, as for IDAKLUSolver. Output times are t_eval ∪ t_interp plus the discontinuity times, and each discontinuity segment gets only the t_interp points inside it.
    • Without 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 coarse t_eval such as [0, 1800, 3600] still has a grid fine enough for Hermite reads. Pass t_interp=t_eval for output at exactly t_eval, as for IDAKLUSolver.
    • An explicit empty t_interp keeps exactly t_eval when that has three or more points, which drive-cycle experiment steps rely on.
  • Threads:
    • num_threads > 1 solves several input sets concurrently with solve_batch, and a single set solves serially, as with IDAKLUSolver. With num_threads = 1, the sets run one after another.
    • Rayon pools are shared process-wide by thread count. The cache keeps the 4 most recently used, and builds a pool outside its lock, so a fork during a build cannot deadlock the child.
  • Hermite reads:
    • Off-grid reads interpolate with cubic Hermite from the stored yp, as for IDAKLUSolver, and hermite_interpolation=False drops yp.
    • yp is never stored for output_variables, or above 4096 output points.
  • Sensitivities:
    • Forward sensitivities of states, output variables, events and time integrals are computed along with the states, outside error control unless sensitivity_error_control=True, as for IDAKLUSolver. Under it, sens_atol_factor scales the sensitivity floor.
    • An output_variables solve keeps the states and state sensitivities at both ends, so first_state, last_state and a continued step have them. Like IDAKLU's, it lists its sensitivity names with zero-row state sensitivities, so step()'s restart checks find them.
  • Bindings:
    • pybamm.rust.PreparedSolver, SolveOutcome, SolverStatistics and default_solver_options, with stubs. SolveOutcome.event_index names the event that ended a solve, and solutions set closest_event_idx from it.
    • In pybamm-core, check_batch_widths with its BatchWidths and BatchSensWidth errors, and Termination::as_flag, event_time and event_index, which these bindings use. Also SolveRequest::with_interrupt, which stops a solve between steps with CoreError::Interrupted; the bindings pass none yet.
    • pybamm.SolverStatistics gains diffsol's counters, including problem_setup_time_secs. Unpickling one saved by 26.10 fills the new fields with their defaults, so it still adds to a new one.
    • A pickled solver drops its native handles and rebuilds them on the next solve.
  • Shared with IDAKLUSolver through BaseSolver: the atol check, _internal_initialisation, and the event-violation guard.
  • Other: OutputAssembly.stack_parameter_blocks stacks sensitivity blocks, and hatch_build.py builds pybamm.rust with the diffsol feature.
  • Docs: the API page api/solvers/diffsol_solver.rst.

Errors and limits:

  • An invalid tolerance or option, or a request the compiled model cannot serve, such as sensitivities it was compiled without, raises SolverError with the binding's message. Sensitivity names that are not inputs raise SolverError from the lowering.
  • An integration failure, or a panic inside diffsol, raises SolverError naming the input set.
  • A model whose events read time derivatives raises SolverError at set-up, since diffsol's root function gets none.
  • An expression the Rust backend cannot lower raises NotImplementedError that points at IDAKLUSolver.
  • Sensitivities with respect to an input of width above 1, and TensorField output variables, raise SolverError, as on IDAKLU's Rust path.
  • nproc is ignored.

Review on #5732

Type of change

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

Key checklist

  • No style issues: pre-commit run
  • Rust tests pass (643 with --all-features, 1 ignored)
  • Unit tests pass (N), as do the integration tests (N)
  • Tests added: 185 Python test functions, and 7 Rust tests: the pool cache's eviction, a racing build and the unheld lock, the batch-width check, and an interrupt stopping a solve and a batch, or, unset, changing nothing.
    • Solver:
      • output grids, including the default grid with discontinuities and a coarse t_eval;
      • Hermite reads against the analytic derivative, and the 4096-point limit;
      • first and last states with sensitivities in output_variables solves;
      • failures, initial conditions and event violations;
      • pickling;
      • option defaults equal to Rust's, and SolverError for unknown keys, wrong types, out-of-range values, invalid tolerances, unknown sensitivity parameters and on_failure;
      • a statistics object pickled by 26.10, and closest_event_idx for 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;
      • per-state atol and time discontinuities.
    • Sensitivity parity with a CasADi IDAKLUSolver at rtol 1e-5 and atol 1e-8:
      • states, output variables, subsets, time integrals and events;
      • finite differences;
      • sens_atol_factor and sensitivity_error_control;
      • dy0/dp seeding;
      • the DFN under error control at the default floor;
      • stepped experiments.
    • Output variables: layouts, the batch window, experiment stitching and seeded restarts.
    • Batched inputs.
    • GIL release: a worker thread keeps running during a solve.
    • Integration:
      • SPM, DFN, cubic OCP, ECM, a two-step experiment and a pulsed DFN against IDAKLU (rtol 1e-4 to 1e-5);
      • a stepped-current SPM against IDAKLU, with and without Hermite, on a bare and a coarse t_eval: within 2e-6 V on diffsol's own grid, and 1.2 mV (Hermite) or 19 mV (linear) at worst in between;
      • a pulse train;
      • native initial conditions against a root solve, including a 3D model.
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
8 #5963 variables and sensitivities read in Rust
9 #5964 pybamm-core: diffsol DAE solver
10 #5965 pybamm.DiffsolSolver ← this PR
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 98.85057% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 98.43%. Comparing base (f3637a0) to head (49b07a1).

Files with missing lines Patch % Lines
...ckages/pybamm/src/pybamm/solvers/diffsol_solver.py 98.61% 3 Missing ⚠️
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.
📢 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.

@BradyPlanden
BradyPlanden force-pushed the stack/10-diffsol-solver branch 2 times, most recently from 76e3077 to 283bed6 Compare October 28, 2026 14:11
@BradyPlanden
BradyPlanden force-pushed the stack/10-diffsol-solver branch 2 times, most recently from 37788fe to b9bb622 Compare October 29, 2026 08:01
@BradyPlanden
BradyPlanden marked this pull request as ready for review October 29, 2026 08:56
@BradyPlanden
BradyPlanden requested a review from a team as a code owner October 29, 2026 08:56
@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

ProjectPyBaMM
Branchstack/10-diffsol-solver
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/10-diffsol-solver branch from b9bb622 to 519f514 Compare October 29, 2026 17:26
@BradyPlanden
BradyPlanden force-pushed the stack/10-diffsol-solver branch from 519f514 to 4ec163f Compare November 17, 2026 11:24
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
BradyPlanden force-pushed the stack/10-diffsol-solver branch from d5f2cc3 to 49b07a1 Compare December 4, 2026 10:47

This branch has not been deployed

No deployments
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.

2 participants