Repository navigation
feat(rust): sparsity, coloured Jacobians, compiled models and the C ABI - #5957
Merged
Merged
Conversation
This was referenced Oct 22, 2026
This was referenced Oct 22, 2026
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #5957 +/- ##
==========================================
- Coverage 98.31% 98.31% -0.01%
==========================================
Files 354 354
Lines 36955 36955
==========================================
- Hits 36334 36333 -1
- Misses 621 622 +1 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
4 tasks done
BradyPlanden
force-pushed
the
stack/02-rust-core-model-ffi
branch
from
October 28, 2026 09:55
6a8acfa to
a32f8b6
Compare
BradyPlanden
force-pushed
the
stack/02-rust-core-model-ffi
branch
3 times, most recently
from
October 29, 2026 08:01
b3e6fed to
5f19006
Compare
BradyPlanden
marked this pull request as ready for review
October 29, 2026 08:55
Contributor
|
| Project | PyBaMM |
| Branch | stack/02-rust-core-model-ffi |
| 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/02-rust-core-model-ffi
branch
from
October 29, 2026 17:26
5f19006 to
377f61d
Compare
martinjrobins
requested changes
Nov 4, 2026
martinjrobins
left a comment
Contributor
There was a problem hiding this comment.
I'm only 1/2 way through this one, but I've been getting github bugs and flakyness all day so I'm going to submit this now and continue later on
martinjrobins
requested changes
Nov 5, 2026
martinjrobins
left a comment
Contributor
There was a problem hiding this comment.
Thanks @BradyPlanden, a few more queries/changes to add to yesterdays review:
BradyPlanden
force-pushed
the
stack/02-rust-core-model-ffi
branch
from
November 17, 2026 11:24
377f61d to
f41ef26
Compare
`CompiledModel::new` compiled the residual from the unsimplified rhs but differentiated it into a simplified tangent, and the algebraic block was the reverse: a simplified residual with the Jacobian of the raw graph. Where `simplify` changes a value (`x - x` at `x = inf`, say) the residual and its Jacobian then disagreed. Both now simplify first, and the residual, Jacobian and `df/dp` derive from the simplified graph. The unsimplified compile guarded against an older integer-power lowering that moved bits; `simplify` now lowers only powers it takes exactly, and `test_residual_bit_exactness` confirms the simplified residual is bit-identical to the raw one on SPM, SPMe and DFN.
Assembly reads a sweep only at swept entries, so a row with none, split to reverse mode or wholly constant, need not be computed in each colour walk. `mask_rows` now zeroes every `Concat` leaf whose rows are all unswept and keeps the rest, where `mask_scalar_rows` masked only width-1 split rows and gave up on everything if one row could not be masked. Nothing to zero leaves the root, and the tape, as it was.
The cap abandoned any element with more than 64 seed coefficients, so a wide linear row was always swept and set the colouring bound. It bounded nothing that sparsity detection does not already store: an element's coefficients are a subset of its dependencies. Without it a dense linear `A @ y` folds to constants. At n = 2048 it compiles in 4.0 s rather than 5.4 s and sweeps no colours rather than 2048; peak memory rises from 550 MB to 680 MB. The SPM, SPMe and DFN Jacobians are unchanged, and they compile about 5% slower (DFN 640 us to 675 us) from carrying wide intermediate coefficient sets.
Output sensitivities project through `dH/dy` and `dH/dp`, but events only locate roots, so with sensitivities on only outputs are differentiated. diffsol differentiates its root function only to apply a reset, which pybamm never sets. On the DFN with one sensitivity parameter, compiling ten events takes 330 us rather than 565 us.
Sensitivity columns ran one scalar tangent sweep each. The batched sweep now also loads parameter seeds, so a `dp` tape walks 4 or 8 unit seeds at once by its `LanePlan`, each column bitwise what a scalar sweep gives. `df/dp` and the outputs' `dH/dp` share `unit_param_columns`, and a `dp` Jacobian batches its colours as a `dy` one does. A tape seeding both states and parameters stays scalar, since one seed array serves every load. On a 200-state model with 8 parameters, `df/dp` takes 7.4 us rather than 13.8 us. `SensIdx` lost its last use and is removed.
… graph `ObservableSet::compile` compiled each output and event as given, but differentiated it into simplified `dH/dy` and `dH/dp` tapes: the mismatch the rhs had. At `y0 - y0` with `y0 = inf` an output read NaN while its tangent read zero. A family's roots are now copied into one graph under a `Concat` and simplified together, and the per-item, fused and tangent tapes all compile from it. `simplify_family` carries each root through every pass as a further root, so a root survives where zero propagation folds the `Concat` away. `set_observables` takes `&Arena`, since it no longer allocates in the caller's arena. Simplifying the family together, not each root alone, keeps the cost to one pass: the outputs-and-events compile bench rises 35-47% (DFN 1.41 ms to 1.85 ms, model compile included) rather than 2-3.5x. The DFN fixture's observable tapes come out about 9% shorter.
`compile_algebraic_block` took the rhs arena and the spec, then built a `DagRef` from them on its first line. `CompiledModel::new` now builds it and passes the residual and its variable indices.
The module docs said every sparse product goes through `rows`, but `row_dot` and `matvec` read a row's span directly. Both still sum a row in its stored order.
Every production `unsafe` block in `ffi.rs` already carries its `SAFETY:` argument; the test module, whose tests own the pointers they pass, opts out as a whole. The ABI contract test parses into `BTreeMap`s, so a failing run names the same symbol first every time.
Criterion 0.8 deprecates its `black_box` for `std::hint::black_box`, so the benches take it from std. `autobenches = false` stops cargo from building `benches/helpers.rs`, a module the benches share, as a bench target of its own.
`assert_eq!` on `f64` passes `0.0 == -0.0`, so the tests that hold a batched Jacobian, action or algebraic block to its scalar or whole-tape twin now compare `to_bits()` through a shared `test_support::bits`. `classify_mass_matrix` matches its 0 and 1 entries with float literal patterns, and the split-assembly proptest keeps `==` under an `expect`, as exact agreement is its claim. The other `float_cmp` allows covered `assert_eq!` or a comparison against zero, which clippy never flags.
…for bit The test allowed the two a relative 1e-12, yet every slot matches to the bit. On this fixture both builds run the same tape: its entries are all nonlinear, so the full build folds no constants, and its band leaves no dense row to split.
`validate` takes every root a caller lowers together, so a subgraph they share is checked once, with one width table, rather than once per root.
…nicking `CompiledModel::new` and `set_observables` lowered caller graphs without `validate`, so, for one, a non-constant `MatMul` left operand panicked in `TypedIr::from_dag`. Both now validate every root they lower, in one walk, and return `CoreError::Graph`.
`matmul_row` and `union_seeds` re-merged their whole accumulator once per column, so one dense row of width n cost O(n^2): 5.3 s to compile at n = 80k. A seed-indexed accumulator folds each seed's contributions in the same column order with the same `mul_acc`, so values stay bit-identical, in O(n): 18 ms at n = 80k. A `dense_row` compile bench guards the scaling.
The `pow` doc and the `real_model_eval` bench still said the residual compiles unsimplified, which stopped being true once `CompiledModel::new` simplified the rhs. The bench now times the simplified tape the solvers run, which moves its baseline.
IDAKLU's upsampling (#5998) adds output times inside each step until linear interpolation of one scalar output, u(t, y; p), resolves it. A Rust model had no way to supply u, so `upsampling_tolerance` could not reach it. `ObservableKind::Upsampling` is a third observable family, compiled like events without tangent tapes, since it only places output times. The C ABI gains `pybamm_rust_upsampling_len` and `pybamm_rust_upsampling_eval`, which returns `ERROR_NO_UPSAMPLING` on a model without one. `RustFunctions` sets the ExpressionSet's `upsampling_fcn` only when the model has a scalar upsampling output, so IDAKLU's upsampling stays off otherwise. The ABI is unreleased, so `RUST_ABI_VERSION` stays 1; the drift test's export hash is updated.
BradyPlanden
force-pushed
the
stack/02-rust-core-model-ffi
branch
from
November 19, 2026 14:26
f39387a to
aeaa3cc
Compare
martinjrobins
requested changes
Nov 19, 2026
martinjrobins
left a comment
Contributor
There was a problem hiding this comment.
sorry, one last thing I noticed:
`CompiledModel::new` simplified the rhs, then `compile_algebraic_block` simplified the algebraic residual again on its own. The residual is a subtree of the rhs: on DFN it reaches 364 of the rhs's 404 nodes, so the second pass redid most of the first. Both now go through `simplify_family` in one pass, and the block compiles from its member of that graph. The residual's state extent is checked up front beside the rhs's, before anything is simplified. On DFN, `CompiledModel::new` with an algebraic block drops from ~955 µs to ~913 µs, and every tape is bit-identical to before.
This was referenced Nov 30, 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
Builds the model layer of
pybamm-coreon the compiler from #5956. ACompiledModelholds a DAEM y' = f(t, y; p)with its Jacobian, sensitivities, output variables and events, and a C ABI lets pybammsolvers' IDAKLU evaluate it. Nothing in Python changes.detect_sparsity_per_outputreads each output's Jacobian pattern from the graph without evaluating it. The pattern is conservative: an entry it leaves out is zero for everyy.classify_constant_entriesproves independent of(t, y, y', p)are written from a table instead of swept. On the pinned fixtures, SPM has 116 such entries and needs 0 colours, the SPMe 116 and 3, and the DFN 2316 and 9.LanePlansweeps the colours 8 or 4 lanes at a time, from a cost model fitted on an Apple M4, within a 32 MiB scratch budget.AdjointTape). That split is kept only when it lowers the colour count.CompiledModel,WorkspaceandModelEvaluator:CompiledModelis built once, fromCompiledModelOptions { sensitivities, algebraic }. Once its output variables and events are set, it is shared read-only.Workspace.ModelEvaluatorpairs anArc<CompiledModel>with oneWorkspace, and it is what the C ABI receives asuser_data.simplify, as a fold that shifts a value by one ulp stalls IDA's Newton iteration.dg/dp + dg/dy·S.DagSnapshot, behind theserializefeature, is the bincode form of a graph. The benches and the golden and bit-exactness tests read it.ffi.rs):extern "C"entry points. The count queries return a count or a negative status; every other entry point returnsSUCCESS(0) or a negative status:ERROR_NULL_POINTER,ERROR_PANIC,ERROR_INVALID_PARAM,ERROR_INVALID_OUTPUT,ERROR_NO_SENS,ERROR_NO_OUTPUTS,ERROR_NO_ALGorERROR_NO_EVENTS.user_dataand every required buffer for null, and catches a panic, rebuilding the workspace after one.pybamm_rust_n_algebraicandpybamm_rust_alg_jac_nnz.pybamm_rust_abi_version()returnsRUST_ABI_VERSION, which is 1.pybamm_rust_ffi.hresolves the symbols at runtime:dlsym(RTLD_DEFAULT), orGetProcAddressover the loaded modules on Windows. It checks the version first, and throws on any failed status.RustFunctions.hppadapts a model to IDAKLU'sExpressioninterface. Its algebraic and Newton adapters checkn_alg,n_rhs + n_algand the Jacobian pattern and nnz against those queries, and throwstd::invalid_argumentbefore Rust writes through a buffer.test_ffi_abi_contractparsesffi.rsand both headers, and checks that:EXPECTED_ABI_HASHpins the exported signatures, so a change to them fails until the hash is updated. The version numbers are only checked against each other.rust_testsCI job also runs when onlypackages/pybammsolverschanges, since the test reads its headers.test_primitive_values(feat(rust): expression graph, typed IR, evaluator and forward-mode AD #5956) gains reverse mode: the adjoint partials take the same reference values as the interpreters.Known limits:
SensParamVector.df/dpis assembled from a dense pattern.ERROR_PANIC.RTLD_GLOBALfor the symbols to resolve, whichpybamm.rustdoes in feat(rust)!: ship pybamm.rust in the pybamm wheel #5958.Review on #5732
CompiledModelholds no scratch. Each caller'sWorkspaceis separate, andModelEvaluatorpairs the two. The bindings' pools in feat(rust)!: ship pybamm.rust in the pybamm wheel #5958 and feat(rust): solve rust models with IDAKLUSolver #5962 follow the same split.Type of change
New feature, under
## FeaturesinCHANGELOG.md.Key checklist
pre-commit run, includingcargo fmtandcargo clippy--all-features, 1 ignored: the golden-fixture regenerator)cargo +1.89 check --locked --all-targets --all-featuresuser_dataand each null buffer, a panic, null inputs, negative indices and overflowing counts, and the count queries, the algebraic block's included;t,yand inputs;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 ABI ← this PRpybamm.rustbindings, built into thepybammwheelSymbol.to_rustconvert_to_format = "rust"forScipySolver,AlgebraicSolverand EISpybammsolvers: IDAKLU over the C ABIIDAKLUSolveron rust modelspybamm-core: diffsol DAE solverpybamm.DiffsolSolver"rust"as the defaultconvert_to_format