Repository navigation
feat(rust): observe rust-model solutions natively - #5963
BradyPlanden wants to merge 10 commits into
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #5963 +/- ##
==========================================
+ Coverage 98.40% 98.42% +0.01%
==========================================
Files 363 363
Lines 38745 39009 +264
==========================================
+ Hits 38127 38394 +267
+ Misses 618 615 -3 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
73c029c to
879f508
Compare
26c1029 to
63e4b86
Compare
b77ac50 to
52b69b1
Compare
|
| Project | PyBaMM |
| Branch | stack/08-native-observation |
| Testbed | bare-metal |
⚠️ WARNING: Truncated view!The full continuous benchmarking report exceeds the maximum length allowed on this platform.
🚨 2 Alerts
🐰 View full continuous benchmarking report in Bencher52b69b1 to
b55c69e
Compare
b55c69e to
b6a75a5
Compare
c133038 to
6ef71f2
Compare
5699aaa to
0fc2584
Compare
A second reader in build_variable: a model bound with ObserverCache.bind_rust_model reads each segment through native tapes kept on its ObserverCache, with shared-tape variable sets and native sensitivities.
#6056 makes `x.diff(pybamm.t)` work through functions and observables, and pins that observing one raises `ModelError("Must provide a 'y_dot'...")`: observation gives a leaf no state derivatives. A native leaf compiled the derivative regardless and failed only when read, with another message. The native leaf and the native set now refuse a tape reading `y_dot` as they compile, with the error `process` raises, so `Solution.observe` and `Solution.update` fail the same way for either format.
`_sweep_sensitivities` built each parameter's direction as a C-order `(n_states, n_t)` transpose of `dy_dp`, a strided copy that Rust then gathered again into the column-major layout it reads. Gathering the column first and reshaping gives an F-contiguous array, which Rust borrows. Reading the sensitivities of a Rust DFN over 10,000 points, with three parameters, drops from 242 ms to 15 ms for "Voltage [V]", and from 1.58 s to 87 ms for six variables. At the 138 points the solver steps to, it drops from 0.56 ms to 0.19 ms.
Reading Rust solutions natively is how IDAKLUSolver serves Rust models, which no release reaches yet, so it takes no entry. What every backend sees is `Solution.update([...])` now storing a list all or nothing, so the entry records that.
Native observation compiled its leaves on the graph of the CompiledModel a solver had bound to the model's ObserverCache, each leaf lowering afresh. A model no solver bound, as ScipySolver left every model, or a hand-built Solution read through CasADi, as did a VectorField. The _observes_via_compiled_model flag chose which solvers bound. Every Rust model's variables, VectorField components among them, now compile on its RustModelLowering, sharing its memo of lowered symbols, and a leaf reads as many states as its segment stores. ObserverCache keeps only CasADi leaves, and the flag goes. Setting the model up again keeps its leaves; a copy compiles its own. Reading five variables of a ScipySolver SPM solution takes 6 ms rather than 10 ms.
Native leaves were cached on the model's lowering by variable name, and the lowering now outlives a set-up, so a variable given a new expression went on reading the old one. A Solution whose inputs held the model's names in another order replaced the model's lowering, though leaves take their inputs by name, and each such read rebuilt the graph and every leaf. Leaves, shared tapes, time integrals and post-sum tapes are cached by the expression they compile as well as the name. A segment reads through the model's lowering whenever it has the segment's input names, in whatever order. VariableObserver.with_leaves is abstract.
…l's graph A Solution whose inputs were not the model's replaced the model's lowering, dropping its CompiledModel and every compiled variable. It now reads through a lowering of its own, and the model's is used only for its own inputs, in any order, or made when the model has none.
A Solution whose inputs were not the model's made a new lowering for every read and every segment, so each read recompiled every variable. That lowering is now cached on the model's, by the set of input names.
- The single-set num_threads test compared one call with itself; only its pool check could fail, so it keeps that alone. - The dense-grid test's read sat below its tolerance on a chord as well as a cubic; the flags carry the change. It now reads 4097 columns over one span, without a stop at every column. - A first-interval read superseded by the analytic ones goes, and the stepped-current voltage check uses assert_allclose. - ed2422fe2 (a failed set-up keeps the last good one) and 50bbe35eb (other inputs reuse one lowering per set of names) gain the tests that fail without them.
…all matching Codecov found native observation's patch short of the project's coverage. The Solution vector-field test now runs on both formats, so a Rust model's components are read natively, through NativeObserver's with_leaves and the lowering a hand-built Solution's model makes on first read. A hand-built three-segment solution, its middle segment a single knot, is read natively and through CasADi at query times in one segment and in all three. A table test covers when a shared tape reuses a held call.
0fc2584 to
4cb7407
Compare
martinjrobins
left a comment
There was a problem hiding this comment.
looks great, thanks @BradyPlanden , just minor stuff below
| check_variable_in_solve(solution, name, var_pybamm) | ||
| if isinstance(var_pybamm, pybamm.VectorField): | ||
| leaves[i] = [ | ||
| segment.leaf(f"{name}[{k}]", component)[0] |
There was a problem hiding this comment.
I guess time_integral is not supported for VectorFields (totally understandable), but would be better to raise a not supported error rather than silently dropping time_integral
| ) | ||
|
|
||
|
|
||
| def native_sensitivities( |
There was a problem hiding this comment.
this is a private function? so _native_sensitivities
| return dpost_dy @ integral_sensitivities + dpost_dp | ||
|
|
||
|
|
||
| def chain_rule_sensitivities( |
There was a problem hiding this comment.
is this public or private? I wasn't sure since you use it in the tests, if private then needs to be _chain_rule_sensivitiies, if public then needs typing
| solves, which store no states; ``None`` when states are real. | ||
| """ | ||
|
|
||
| def __init__(self, leaves, placeholder_states=None, post_sum_leaf=None) -> None: |
| class SharedOutputLeaf: | ||
| """One variable's rows of a :class:`SharedOutputs` tape, used as its own tape.""" | ||
|
|
||
| def __init__(self, shared, name) -> None: |
| reads are safe: each caller gets the result of its own arguments. | ||
| """ | ||
|
|
||
| def __init__(self, function) -> None: |
Description
Reads variables, and their sensitivities, from a rust-model
IDAKLUSolversolution in Rust.set_upbinds theCompiledModelto the model'sObserverCache(refactor: read solution variables through per-model observer caches #5786).build_variablethen evaluates each variable on a tape compiled into the model's retained graph: one Rust call per segment, cubic-Hermite between time points when the solution stores derivatives.Besides
CompiledModel.graph, a getter it adds to the bindings with its stub, this PR is Python only; the other Rust methods it calls (n_states,ExprGraph.from_expr) are from #5962.ObserverCache:bind_rust_model,native_leaf(a variable's tape, compiled once per model),native_set(several variables on one tape, sharing subexpressions) andpost_sum_leaf.set_updrops the native leaves.observation.pysays.NativeObserver: evaluates raw values (eval_trajectory), Hermite values (eval_trajectory_hermite) and sensitivities. Time integrals add their post-sum sensitivities throughnative_postfix_sensitivities. On anoutput_variablessolve, a variable that is not an output reads its values and sensitivities from the placeholder states, as on the CasADi path.Solution.update([...]):SharedOutputstape and sweeps its sensitivities once per parameter, and each variable reads its rows through aSharedOutputLeaf. A segment with no time points gives empty rows.output_variablessolve) nothing is stored. Before, on CasADi and rust alike, the names before the failing one were rebuilt and kept.update("name")with one string is unchanged.QuickPlotandSolution.get_data_dictbuild all their variables this way.ProcessedVariableTimeIntegral.sum_over_timeis public, andcheck_discrete_timesis a method, for the native path.When native reading applies:
IDAKLUSolver.VectorFieldvariables.VectorFieldvariables are read one by one, not on a shared tape.calculate_sensitivitiesraisesValueError, as onmain.ModelErroras it compiles, the error CasADi'sprocessraises (feat: IDAKLU termination events on time derivatives #6056).On the CasADi path, values are unchanged.
Solution.updatededuplicates its names and stores all or nothing, andQuickPlotandget_data_dictbuild every variable up front.Review on #5732
observation.pykeeps the observer naming from refactor: read solution variables through per-model observer caches #5786 onmain(ObserverCache,VariableObserver), and the class under review is not in this stack.backend[key]is:SharedOutputsholds one result for as many reads as it has leaves, which its docstring states. Each call keeps its own result and a lock guards the held one, so threads reading different solutions while the GIL is released get their own rows.Type of change
New feature, under
## FeaturesinCHANGELOG.md.Key checklist
pre-commit runt_interp;output_variablessolve;updatestoring nothing when one name fails.Rust 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"rust"as the defaultconvert_to_format