Repository navigation
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
Open
BradyPlanden wants to merge 12 commits into
BradyPlanden wants to merge 12 commits into
Conversation
BradyPlanden
force-pushed
the
stack/10b-graph-inspection
branch
from
November 30, 2026 10:24
e62e4a0 to
90b4254
Compare
This was referenced Nov 30, 2026
|
|
||
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
BradyPlanden
force-pushed
the
stack/10b-graph-inspection
branch
from
November 30, 2026 11:54
90b4254 to
e6753ae
Compare
4 tasks done
BradyPlanden
changed the base branch from
stack/10a-input-interpolant
to
stack/10b-rust-bindings
November 30, 2026 11:54
BradyPlanden
marked this pull request as ready for review
November 30, 2026 12:00
Contributor
|
| Project | PyBaMM |
| Branch | stack/10b-graph-inspection |
| 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/10b-graph-inspection
branch
2 times, most recently
from
December 2, 2026 09:22
26f6959 to
f7d5fa6
Compare
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
force-pushed
the
stack/10b-graph-inspection
branch
from
December 4, 2026 10:47
f7d5fa6 to
a52b8c7
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
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.viewshows 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_viewsnames 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:Evidence
solve_pathscounters and the trajectory hashes match bitwise.eval_trajectoryandeval_trajectory_hermiterun 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
pre-commit runcargo test --all-features, clippy over every feature combination, MSRV 1.89Rust 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.DiffsolSolverInterpolantover input parameters and expressionspybamm.rust's own errors, array-likes, threads and Ctrl-Cpybamm.rust.inspection; every tape derived in one place ← this PR"rust"as the defaultconvert_to_format