Repository navigation
feat(rust): interpolant tables over input parameters and expressions - #6134
Open
BradyPlanden wants to merge 12 commits into
Open
BradyPlanden wants to merge 12 commits into
BradyPlanden wants to merge 12 commits into
Conversation
This was referenced Nov 30, 2026
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## stack/10-diffsol-solver #6134 +/- ##
========================================================
Coverage 98.41% 98.42%
========================================================
Files 364 364
Lines 39223 39303 +80
========================================================
+ Hits 38601 38683 +82
+ Misses 622 620 -2 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
BradyPlanden
force-pushed
the
stack/10a-input-interpolant
branch
from
November 30, 2026 11:54
37619c5 to
27c1b4a
Compare
4 tasks done
BradyPlanden
marked this pull request as ready for review
November 30, 2026 12:00
Contributor
|
| Project | PyBaMM |
| Branch | stack/10a-input-interpolant |
| 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/10a-input-interpolant
branch
from
November 30, 2026 15:40
27c1b4a to
c3e7bd1
Compare
BradyPlanden
force-pushed
the
stack/10a-input-interpolant
branch
from
December 2, 2026 09:22
c3e7bd1 to
03b1a3a
Compare
…f/dp seeding `active_branch` computes the selector's window in closed form instead of scanning every branch. The batched `Dispatch` marks each lane's branch in one pass, out of line from the interpreter loop, so it costs its lanes plus the blocks they select rather than branches squared times lanes. `unit_param_columns` zeroes its seed buffers once per assembly and clears only the seeds each walk set, so `df/dp` no longer costs the square of the parameter count.
`InputInterpolant1DLinear` reads its ordinates from the packed inputs in place, sharing the knot search and blend of the fixed-table interpolant so the two agree bit for bit. Its slope node serves state derivatives and a tangent node reads the ordinates' parameter seeds, so forward, batched and reverse mode each give one sensitivity column per ordinate. `AdjointTape::assemble_row` takes the inputs, since reverse mode reads the ordinates there. `ExprGraph.interpolant_1d_linear_inputs(x_data, values, child)` builds it from scalar input parameters registered one after another.
PyBaMM registers inputs in sorted-name order, so a table's knot inputs are rarely registered in knot order: breakpoint-named knots such as "R0 at T 1000 [Ohm]" sort before "R0 at T 25 [Ohm]". The table now holds each knot's registration index and packed offset, so any scalar input parameters, in any order, can be its ordinates. The extra indirection costs about 1 ns per lookup: 5-10% on the node's evaluation, which stays at the fixed-table floor.
`flatten_inputs` converts the values in one call when they share a shape, as all-scalar inputs do, and concatenates them only otherwise; `stack_inputs` reuses it. `validate_rust_input_widths` sizes a Python scalar without `np.size`. On an ECM with 2048 scalar knot inputs, a solve takes 2.3 ms instead of 5.7 ms.
`y` may be a sequence of scalar symbols, such as input parameters to fit. They are the interpolant's children after the interpolated one, so parameter processing, identity and serialisation carry them; values that all process to constants make an ordinary fixed table. The Rust backend lowers it through `interpolant_1d_linear_inputs`, and CasADi through `interpn_linear` over the values. Python evaluation interpolates the evaluated values. Symbolic differentiation, DiffSL export and Python source export refuse it, as they cannot represent it.
Python evaluation of an Interpolant with symbolic y evaluated every value child, so a solve whose extrapolation check reads a 512-knot fitted table spent 0.7 ms evaluating input parameters it never used. It now evaluates only the values `interp1d` reads at each point, covering both its extrapolating path and the `np.interp` path it takes otherwise, and the result is unchanged bit for bit.
Each knot of an `InputInterpolant1DLinear` reads an `Ordinate`: an input parameter, or a constant that carries no parameter seed. Tables that fix some knots and fit the rest keep the in-place read, and the binding takes constant nodes beside scalar input parameters.
`ExprInterpolant1DLinear` reads its ordinates from a child vector, so a table's values may be any scalar expressions: slopes summed from fitted parameters, transformed or scaled inputs, or state-dependent values. Its tangent is the slope times the argument's tangent plus the same table read over the values' tangent; reverse mode sends each element's blend weights to the two values beside it. `const_entries` unions every value's seeds into each element, as the node is not element-wise. The scalar, adjoint and batched kernels run out of line, keeping the interpreters' loops as they were. `ExprGraph.interpolant_1d_linear` takes numbers, or one scalar `Expr` per knot: input parameters and constants keep the in-place read, and any other values build the new node. `interpolant_1d_linear_inputs` is folded into it, so `pybamm.Interpolant` with symbolic `y` lowers to Rust whatever its values are, as it does to CasADi.
`Symbol.pre_order(unique=True)` yields each node object once, in the order of its first occurrence: symbols are immutable, so a repeated object's subtree has already been yielded. Discretisation shares equal subtrees, so a tree walk repeats each shared one per use; for a table whose values are running sums, the walk grows with the square of its knots. `check_for_time_derivatives` raises on the first offending node, which the unique walk meets first too. The flux boundary condition check only asks whether each flux is some divergence's child, which a repeat cannot change; a test finds a flux whose divergence an equation uses twice. In `_set_up_events` a repeat adds an event already deduplicated by name and expression, a constant switch time that `np.unique` drops, or a period whose stops and restarts change nothing a second time. A test sets up one model both ways and gets the same events, segments and solution, bit for bit. A 512-knot ECM table in the slopes formulation first solves in 0.22 s, not 1.2 s; DFN and SPMe are unchanged.
`ParamRegistry::from_arena` reserved `index_extent() - 1` for every input interpolant, which underflowed for a table of constants, so unpickling one failed. It now reserves only for ordinates read from the inputs, and refuses an ordinate whose slot disagrees with its parameter's, or with another ordinate's at an index none is registered at, as `ParamSlotConflict`. `ExprGraph.interpolant_1d_linear` builds the fixed table when every value is a constant, and validates expression values before it allocates their `Concat`, so a refused call leaves the graph unchanged. `pybamm.Interpolant` raises `ShapeError` and `NotImplementedError` for its symbolic-`y` checks, and its docstring notes that, like a linear table of fixed values, it cannot be differentiated symbolically.
_to_rust returns before reaching the tables when y is None, but Pyrefly cannot carry that narrowing into the method, so coerce y as the 2D and 3D tables already do.
BradyPlanden
force-pushed
the
stack/10a-input-interpolant
branch
from
December 4, 2026 10:47
03b1a3a to
eafe297
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
pybamm.Interpolanttakes one scalar symbol per value for 1D linear tables, so a table's values can be input parameters to fit, constants, or any expression. The Rust backend lowers it with a sensitivity per value; CasADi lowers it throughinterpn_linear.NotImplementedError, as they cannot represent the table.Evidence
ytable matches the fixed table of its values in Python, CasADi and Rust.CompiledModel's rhs Jacobian anddf/dpover an input table, match central differences; fitted-value sensitivities match CasADi's.Merge Danger
Door: two-way. Blast radius: models with symbolic
y; numeric tables lower as before.Type of change
New feature and optimizations:
6134.feature.md,6134.optimization.md,6134.optimization.1.md.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 expressions ← this PRpybamm.rust's own errors, array-likes, threads and Ctrl-Cpybamm.rust.inspection; every tape derived in one place"rust"as the defaultconvert_to_format