Skip to content

feat(rust): sparsity, coloured Jacobians, compiled models and the C ABI - #5957

Merged
BradyPlanden merged 21 commits into
mainfrom
stack/02-rust-core-model-ffi
Nov 19, 2026
Merged

BradyPlanden merged 21 commits into
mainfrom
stack/02-rust-core-model-ffi

Conversation

@BradyPlanden

@BradyPlanden BradyPlanden commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Description

Builds the model layer of pybamm-core on the compiler from #5956. A CompiledModel holds a DAE M 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.

  • Sparsity: detect_sparsity_per_output reads each output's Jacobian pattern from the graph without evaluating it. The pattern is conservative: an entry it leaves out is zero for every y.
  • Jacobian assembly:
    • Columns are coloured with DSATUR.
    • Entries that classify_constant_entries proves 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.
    • LanePlan sweeps the colours 8 or 4 lanes at a time, from a cost model fitted on an Apple M4, within a 32 MiB scratch budget.
    • Rows too dense to colour well are filled one reverse-mode pass per row (AdjointTape). That split is kept only when it lowers the colour count.
  • CompiledModel, Workspace and ModelEvaluator:
    • A CompiledModel is built once, from CompiledModelOptions { sensitivities, algebraic }. Once its output variables and events are set, it is shared read-only.
    • Each caller holds its own Workspace. ModelEvaluator pairs an Arc<CompiledModel> with one Workspace, and it is what the C ABI receives as user_data.
    • The mass matrix is classified as the identity, a diagonal selector or general.
    • The rhs is compiled without simplify, as a fold that shifts a value by one ulp stalls IDA's Newton iteration.
  • Output variables and events: each set is fused into one tape, with output sensitivities projected as dg/dp + dg/dy·S.
  • Snapshots: DagSnapshot, behind the serialize feature, is the bincode form of a graph. The benches and the golden and bit-exactness tests read it.
  • C ABI (ffi.rs):
    • 21 extern "C" entry points. The count queries return a count or a negative status; every other entry point returns SUCCESS (0) or a negative status: ERROR_NULL_POINTER, ERROR_PANIC, ERROR_INVALID_PARAM, ERROR_INVALID_OUTPUT, ERROR_NO_SENS, ERROR_NO_OUTPUTS, ERROR_NO_ALG or ERROR_NO_EVENTS.
    • Each checks user_data and every required buffer for null, and catches a panic, rebuilding the workspace after one.
    • Buffer sizes, and exclusive use of the evaluator for the call, are the caller's contract. The algebraic block's sizes have their own count queries, pybamm_rust_n_algebraic and pybamm_rust_alg_jac_nnz.
    • pybamm_rust_abi_version() returns RUST_ABI_VERSION, which is 1.
  • pybammsolvers consumer headers:
    • pybamm_rust_ffi.h resolves the symbols at runtime: dlsym(RTLD_DEFAULT), or GetProcAddress over the loaded modules on Windows. It checks the version first, and throws on any failed status.
    • RustFunctions.hpp adapts a model to IDAKLU's Expression interface. Its algebraic and Newton adapters check n_alg, n_rhs + n_alg and the Jacobian pattern and nnz against those queries, and throw std::invalid_argument before Rust writes through a buffer.
    • Both land here, uncompiled, so that the drift test can read both sides of the ABI; feat(pybammsolvers)!: an IDAKLU backend over the Rust C ABI #5961 compiles them.
  • ABI drift test:
    • test_ffi_abi_contract parses ffi.rs and both headers, and checks that:
      • the versions match;
      • each bound symbol's signature and name match its export;
      • every export is bound and called;
      • every call checks its status;
      • the status codes agree.
    • EXPECTED_ABI_HASH pins the exported signatures, so a change to them fails until the hash is updated. The version numbers are only checked against each other.
    • The rust_tests CI job also runs when only packages/pybammsolvers changes, since the test reads its headers.
  • Primitive values: 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:

  • Sensitivities:
    • Only width-1 inputs are supported; a vector-width input gives SensParamVector.
    • df/dp is assembled from a dense pattern.
  • Algebraic block: it must be square, strictly ascending and made only of algebraic states.
  • Workspaces: a workspace from another model panics, which the C ABI returns as ERROR_PANIC.
  • Lanes: the lane widths are 8 and 4, with costs tuned on one machine.
  • Linux loading: the extension must be loaded with RTLD_GLOBAL for the symbols to resolve, which pybamm.rust does in feat(rust)!: ship pybamm.rust in the pybamm wheel #5958.

Review on #5732

Type of change

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

Key checklist

  • No style issues: pre-commit run, including cargo fmt and cargo clippy
  • Rust tests pass (478 with --all-features, 1 ignored: the golden-fixture regenerator)
  • MSRV check passes: cargo +1.89 check --locked --all-targets --all-features
  • Tests added: 274 Rust tests.
    • Unit tests:
      • colouring and Jacobian assembly recover every entry;
      • sparsity and constant-entry classification;
      • row extraction;
      • mass matrices and the algebraic block;
      • sensitivities;
      • reverse mode;
      • every C ABI entry point with a null user_data and each null buffer, a panic, null inputs, negative indices and overflowing counts, and the count queries, the algebraic block's included;
      • a dirtied workspace is never trusted.
    • Integration tests:
      • forward and reverse mode against finite differences;
      • sparsity and constant-entry soundness proptests over graphs with inputs, powers, min/max, signed zeros, sparse products, conditionals on literal, input or state-dependent selectors, linear interpolants, reductions, step functions and time, probed at varying t, y and inputs;
      • the reverse pass skips inactive branch blocks;
      • dense-row splits match the unsplit build and central finite differences;
      • SPM, SPMe and DFN sparsity goldens;
      • residuals bitwise reproducible;
      • reverse-mode partials take the primitives' reference values;
      • the five ABI contract checks.
    • Benches: four criterion benches cover compilation, evaluation, sparsity detection and Jacobian assembly.
Rust execution engine stack: proposal #5667, showcase #5732

Each PR is one commit 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 ← this PR
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
11 #5966 "rust" as the default convert_to_format

@codecov

codecov Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.31%. Comparing base (79eb089) to head (5638feb).
⚠️ Report is 1 commits behind head on main.

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.
📢 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/02-rust-core-model-ffi branch from 6a8acfa to a32f8b6 Compare October 28, 2026 09:55
@BradyPlanden
BradyPlanden force-pushed the stack/02-rust-core-model-ffi branch 3 times, most recently from b3e6fed to 5f19006 Compare October 29, 2026 08:01
@BradyPlanden
BradyPlanden marked this pull request as ready for review October 29, 2026 08:55
@BradyPlanden
BradyPlanden requested a review from a team as a code owner October 29, 2026 08:55
@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

ProjectPyBaMM
Branchstack/02-rust-core-model-ffi
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

@BradyPlanden
BradyPlanden force-pushed the stack/02-rust-core-model-ffi branch from 5f19006 to 377f61d Compare October 29, 2026 17:26

@martinjrobins martinjrobins left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 martinjrobins left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @BradyPlanden, a few more queries/changes to add to yesterdays review:

@BradyPlanden
BradyPlanden requested a review from a team as a code owner November 6, 2026 12:09
@BradyPlanden
BradyPlanden force-pushed the stack/02-rust-core-model-ffi branch from 377f61d to f41ef26 Compare November 17, 2026 11:24
`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
BradyPlanden force-pushed the stack/02-rust-core-model-ffi branch from f39387a to aeaa3cc Compare November 19, 2026 14:26

@martinjrobins martinjrobins left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@martinjrobins martinjrobins left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

happy to merge 👍

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