Skip to content

feat(rust): inspect the graph a model compiles to, and derive every tape in one place - #6135

Open
BradyPlanden wants to merge 12 commits into
stack/10b-rust-bindingsfrom
stack/10b-graph-inspection
Open

BradyPlanden wants to merge 12 commits into
stack/10b-rust-bindingsfrom
stack/10b-graph-inspection

Conversation

@BradyPlanden

@BradyPlanden BradyPlanden commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Description

See what the Rust backend compiles, and derive it in one place. Two halves; review commit by commit, or by file group:

Inspection (5 commits; new inspect.rs, dag_view.rs, pybamm/rust/inspection/)

  • ExprGraph.view shows the graph a model's roots reach at one stage (as built, simplified, or differentiated with respect to the states or inputs), each node's value at a point, and the tape the stage lowers to.
  • pybamm.rust.inspection.model_views names the nodes behind each equation, state, interpolant and variable of the graph the solver compiled. Views render with Graphviz, or side by side in Google's Model Explorer (optional dependency).

Refactors (5 commits; new derivation.rs, tangent_sweep.rs, trajectory.rs). Each compile site derived its own tapes, and the sites disagreed; now one place does each job:

derivation      validate -> simplify once -> copy, differentiate, simplify -> lower
tangent_sweep   one walk of a tangent tape over seed directions
CompiledModel   built whole: outputs, events, upsampling are options; every refusal before compiling
Jacobians       derived through the same funnel from roots that carry their width and reads
trajectory      one tape evaluated along points or Hermite knots

Evidence

  • Every tape of the SPM, SPMe and DFN fixtures is unchanged, instruction for instruction; the solve_paths counters and the trajectory hashes match bitwise.
  • A test checks each inspection stage's tape against the one a compiled model runs.
  • New property tests: trajectories against point-by-point evaluation, bitwise; JVPs against finite differences.
  • From Python on a DFN, eval_trajectory and eval_trajectory_hermite run 20-33% faster.

Merge Danger

Door: two-way. Blast radius: every rust model's compile path, pinned by the unchanged tapes. When CompiledModel::new's input is wrong in more than one way, a different error may win.

Type of change

New feature: 6135.feature.md. The refactors are internal.

Key checklist

  • No style issues: pre-commit run
  • Unit tests pass (7517), as do the integration tests (812)
  • Rust: cargo test --all-features, clippy over every feature combination, MSRV 1.89
  • Tests added: inspection stages and views; property tests for trajectories, JVPs and tangent sweeps
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
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 ← this PR
11 #5966 "rust" as the default convert_to_format


if TYPE_CHECKING:
from pybamm.rust import DagView, Expr, ExprGraph
from pybamm.rust.inspection.tape import TapeView
if TYPE_CHECKING:
from matplotlib.axes import Axes

from pybamm.rust.inspection.graph import GraphNode, GraphView
if TYPE_CHECKING:
from matplotlib.axes import Axes

from pybamm.rust.inspection.graph import GraphNode, GraphView
@codecov

codecov Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.44%. Comparing base (ed735a2) to head (f7d5fa6).

Additional details and impacted files
@@                     Coverage Diff                     @@
##           stack/10b-rust-bindings    #6135      +/-   ##
===========================================================
+ Coverage                    98.41%   98.44%   +0.02%     
===========================================================
  Files                          364      369       +5     
  Lines                        39311    39835     +524     
===========================================================
+ Hits                         38688    39215     +527     
+ Misses                         623      620       -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 removed this pull request from stack #6136 November 30, 2026 11:52
@BradyPlanden
BradyPlanden deleted the stack/10b-graph-inspection branch November 30, 2026 11:52
@BradyPlanden
BradyPlanden restored the stack/10b-graph-inspection branch November 30, 2026 11:53
@BradyPlanden BradyPlanden reopened this Nov 30, 2026
@BradyPlanden
BradyPlanden force-pushed the stack/10b-graph-inspection branch from 90b4254 to e6753ae Compare November 30, 2026 11:54
@BradyPlanden
BradyPlanden changed the base branch from stack/10a-input-interpolant to stack/10b-rust-bindings November 30, 2026 11:54
@BradyPlanden
BradyPlanden added this pull request to stack #6139 November 30, 2026 11:54
@BradyPlanden
BradyPlanden marked this pull request as ready for review November 30, 2026 12:00
@BradyPlanden
BradyPlanden requested a review from a team as a code owner November 30, 2026 12:00
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

ProjectPyBaMM
Branchstack/10b-graph-inspection
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 reopened this Nov 30, 2026
@BradyPlanden
BradyPlanden force-pushed the stack/10b-graph-inspection branch 2 times, most recently from 26f6959 to f7d5fa6 Compare December 2, 2026 09:22
ExprGraph.view returns a DagView of the expression graph its roots
reach at one stage of compilation: as built, simplified, or
differentiated with respect to the states or the input parameters, each
root differentiated as the Jacobian sweep does. A view lists its nodes
children first, evaluates every node at one point, and summarises the
tape its first root compiles to: each instruction's operation, the
buffer windows it reads and writes, the earlier instructions it reads
from, and the node it lowers. The IR builder records that last link as
it emits; when privatising conditionals renumbers the graph, the link
is left out. A test checks each stage's tape against the one a compiled
model runs.

pybamm.rust.inspection builds on it for a discretised model. model_views
names the nodes that compute each equation, state, interpolant and
variable, and groups the rest under the named node that alone reaches
them. A GraphView renders with Graphviz, a TapeView lists its tape or
plots the buffer over the run, and show_model_explorer opens any of
them side by side in Google's Model Explorer, an optional dependency.
model_views lowered a model into a graph of its own, with the inputs in
the order the model registers them. It now views the model's
RustModelLowering, with the inputs sorted as a solve stacks them, so
the view of a solved model is of the graph its solver compiled.
…idual

model_views attached a Rust lowering to any model it viewed, a CasADi
model included, and took the residual from the lowering's step-by-step
build. It now views a Rust model's own lowering, and lowers another
model into one it leaves off the model. It lowers the residual as any
other symbol.
A variable that is a constant, such as an SPM's zero discharge energy,
lowers to a node other expressions share, so once a solve had lowered
those, inspection named the shared node after the variable. Constant
variables now name no node.
Each compile site wrote out the stage order itself (validate, simplify,
differentiate, simplify again, lower), and the sites disagreed:
CompiledFunction skipped the copy before differentiating, inspection
differentiated inside the simplified graph, and the property tests
compiled tangents no model builds.

A new derivation module validates a set of roots, simplifies them
together once, and owns the one copy, differentiate and simplify step.
CompiledModel, ObservableSet, JacobianData, CompiledFunction and
inspect::stage all go through it, so a tape only comes from a validated
graph and inspection derives what the solver compiles. Every tape of
the SPM, SPMe and DFN fixtures is unchanged, instruction for
instruction.

The split-eval and lane-batch property tests now check the tangent a
model compiles as well as the unsimplified one. The constant-entry and
finite-difference tests and the real-model eval bench use the model's
derivation, and simplify_pipeline is now test-only.
Four places wrote out their own walk of a tangent tape over many seed
directions: Jacobian colour assembly, matrix-free Jacobian actions, the
observables' sensitivity projection, and the unit parameter columns the
model and observables shared. Each picked its lanes, transposed seeds,
handled surplus lanes and fell back to scalar itself, and each kept a
LanePlan beside its tape and sized its own lane scratch.

A new tangent_sweep module holds a tape, its lane plan and the states
it loads, and walks any set of unit seeds or dense state directions,
handing each tangent back to the caller; it also runs the one-direction
actions. It reads whether a tape seeds states or parameters from the
tape's own loads, so no caller can pass the wrong one. Lane buffers grow
to fit each walk, and an owner's sweeps share them. tangent_batch is now
the private K-lane kernel, so the 8-or-4-lanes panic is internal.

Batched Jacobian actions now refuse a subset or parameter build up
front; nothing called them on one. They transpose only the states the
tape loads, and scalar colour assembly zeroes its seed once per call
rather than once per colour. No value changes, and Jacobian assembly
time on the SPMe and DFN fixtures is unchanged.

The lane-batch property test now goes through the sweep, walking unit
seeds and dense directions under plans that switch width part-way
through a call, on lane buffers earlier walks left dirty.
CompiledModel was documented immutable but built by mutation: its one
production caller ran set_observables three times straight after new.
Because set_observables also took roots from any arena, it re-validated
them, re-checked the input width, cross-checked each parameter's packed
slot against the model's and widened the dp extent, and a workspace made
before a call was silently sized for the old sets. Inside new, too, the
sensitivity, df/dt and algebraic artifacts were filled into a
half-built model, and the sensitivity, algebraic and row-count checks
ran only after the Jacobian had compiled.

Outputs, events and the upsampling output are now options of new, and
new refuses every bad input before anything compiles. All roots are
validated in one walk that also returns each root's width, so the rhs
length and the algebraic block's squareness are checked against the
graph rather than the lowered tape. The model is then compiled and
assembled in one struct literal. Each observable family still compiles
through its own ObservableSet, so no tape changes, and the solve_paths
counters are identical.

When an input is wrong in more than one way, which error wins can
differ: observable errors now come before mass-matrix and spec errors,
and the state extent reported spans the rhs and every observable.

set_observables, the ObservableParamSlot error, the param_extent field,
verify_widths and has_sensitivities go, as do two tests of cross-arena
paths no caller has reached since one-graph fixed inputs when the graph
is made. A new test pins that every refusal runs no simplify pipeline.
A validated, simplified root forgot its width and what it read, so
JacobianData took a bare graph with a row and state count, built its
own tangent from raw closures and re-checked the width; CompiledModel,
ObservableSet and CompiledFunction each scanned the graph for its read
extents again, under a "scan before simplifying" rule kept in a comment.

Roots now carry their width and what they read as built, measured in
one pass over each copied family. JacobianData::new_wrt_* take a
Simplified root and a column count, and derive the state, parameter and
state-subset tangents through derivation, which also debug-checks once
that simplifying kept every root's width. The Jacobian checks the
root's reads against its state count once and builds its pattern with
no further scan. build_outputs, the model's state-extent checks and
CompiledFunction take widths and reads from the roots, and the views of
a compiled model no longer rescan what CompiledModel::new already
refused.

DiffTarget folds into Wrt { States, Params }; the derivative in time is
Simplified::time_derivative_tape, and tangent_wrt is the one public
differentiation entry in place of tangent_wrt_states and _params.

An event still reads y_dot only if its tape does, as before, and a new
test pins it: a solve refuses an event that reads y_dot. Tapes are
unchanged, instruction for instruction. Tests and benches now build
their Jacobians from simplified roots, so the dense_block build bench
no longer compares with older baselines; the pinned SPM, SPMe and DFN
Jacobian counts hold.
Three owners each wrote out evaluating a tape at many points.
CompiledFunction's eval_trajectory and eval_trajectory_hermite picked
lanes, tiled the points, rebuilt Hermite states and transposed the
lane-minor roots inline; its jvp and jvp_trajectory summed the states
and inputs tangent walks, each tape with its own scratch pool.
ObservableSet::eval_batch ran however many points it was handed as one
batch, with a scalar fallback per tape, and the solver staged a fixed
128 columns per batch whatever the tape's scratch.

A new trajectory module owns it. TrajectoryTape wraps a primal tape
proven batchable when made: CompiledExpr records at compile time
whether anything on its tape, branch blocks included, refuses a lane
walk, so no walk fails part-way and the fallback goes. It picks lanes
from the tape's scratch, walks Points or states rebuilt from
HermiteKnots, and writes point-major output. Jvp sums the two tangent
tapes at one point or along Points from one shared scratch. The PyO3
adapter keeps coercion, checks and GIL release, the solver stages one
walk of the outputs tape per batch, and the C ABI passes its buffers
through. The refusal scan matches every instruction exhaustively, so a
new instruction has to be classified as the kernel classifies it.

A tape whose only y_dot read sits in a branch no point takes is now
refused, where the kernel would have run it. No caller reaches that:
CompiledFunction refuses a y_dot-reading function before any
trajectory, and CompiledModel refuses outputs that read y_dot. The knot
checks move into HermiteKnots::new with the same messages, and the
Python interface and stubs are unchanged.

Every value is bitwise unchanged: the solve_paths counters and the
hashes of each case's trajectories match, as do the Python trajectory
results. In an interleaved A/B against the parent, the solve_paths
outputs paths, the C ABI output batch at 1 to 1000 points and the
batch kernel are within noise. From Python on a DFN, eval_trajectory
and eval_trajectory_hermite run 20-33% faster and the JVPs are
unchanged.

New property tests check a trajectory against one point at a time,
bitwise, and a JVP along one against finite differences.
Codecov found inspection's patch short of the project's coverage. New
tests pin GraphView.kind_counts, TapeView.op_counts and summary, with
and without a tangent section; label an input no variable names; fold
a zero derivative into its parent as zeros; refuse to render without
Graphviz; give a node without values no summary; name nothing on a tape
without its graph; and draw no window for an empty write. The test
that inspection reads the graph the solver compiled now solves a Rust
model: on the CasADi default it had no graph to compare.
@BradyPlanden
BradyPlanden force-pushed the stack/10b-graph-inspection branch from f7d5fa6 to a52b8c7 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