Repository navigation
DiffEqBase: AutoDePSpecialize — de-specialize p via OpaqueParams, opt-in + precompiled - #3692
Conversation
|
I'm fairly skeptical of this being a good idea. |
|
I wonder if this could be an option to |
|
We have specialization options, so we can just make this a specialization option. |
605d2b1 to
77e27a2
Compare
|
Updated per follow-up instructions: the opaque-p transform is no longer applied by default under AutoSpecialize — it is now the opt-in Process notes for this revision:
|
|
Follow-up on the pre-existing |
|
CI triage after the QA/downstream fixes (commit e2c4dc8): Resolved by the fixes: the QA Registration-gated (self-heal once DiffEqBase 7.7.0 + OrdinaryDiffEqCore 4.8.0 are registered): Pre-existing master breakage (all reproduced locally on unmodified master with current registry versions; investigation agents dispatched, separate fix PRs):
At this point every red lane is either registration-gated or reproduces on unmodified master; nothing further is actionable from this branch. |
|
The red
Once those merge, a rebase/rerun should turn these lanes green. |
|
Per review direction, moved the |
A new AbstractSpecialization marker that extends AutoSpecialize by also de-specializing the parameter object: solver paths with an opaque-parameter strategy (e.g. RespecializeParams.OpaqueParams in DiffEqBase's promote_f) pack isbits p into a fixed-type container and wrap callables with the container type in the p slot, making the concretized problem type — and the solver compilation — independent of the user's parameter struct type. One precompiled solve is then shared across all isbits parameter types, while the user's f still receives p at its original concrete type via a type-stable, allocation-free unpack. SciMLBase only defines the marker (public, documented, allowed in the SpecializationLevel preference); the wrapping itself is solver-owned so any function family can implement it — the immediate consumers are DiffEqBase (SciML/OrdinaryDiffEq.jl#3692) and, prospectively, NonlinearSolve.jl. Co-authored-by: ChrisRackauckas-Claude <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
|
Also moved the |
|
Pushed the maximal-sharing refactor so NonlinearSolve.jl can reuse the entire AutoDePSpecialize machinery (it deps SciMLBase but not DiffEqBase). Final split:
Verified against dev SciMLBase 3.37 + RespecializeParams 0.1.4: |
|
Both dependency gates are now cleared — pushed the compat bump:
The PR's environment now resolves against the registry. Verified locally: full stack resolves with RespecializeParams 1.0.0 + compat "1", and an AutoDePSpecialize Rodas5P solve + unpack roundtrip is green. Re-triggering CI with the bump. |
7bbba46 to
3095120
Compare
|
Rebased onto current master and force-pushed. CI wasn't running because the PR had gone DIRTY (merge-conflicted) as master advanced ~32 commits — GitHub can't build the merge ref for a conflicted PR, so no workflows triggered on the compat-bump push. Now MERGEABLE and CI is running (79 checks queued/in-progress). Details of the rebase:
Re-verified against current master + registered SciMLBase 3.37.0 + RespecializeParams 1.0.0 in a clean env: full sublib precompile (workloads run real solves) is clean, DiffEqBase opaque_p_test 13/13, and end-to-end across Tsit5/Vern7/Vern9/Rosenbrock23/Rodas5P/FBDF/CompositeAlgorithm green including interpolation, unpack roundtrip, and zero-alloc. |
3095120 to
0ae31f9
Compare
|
Added inference/allocation regression tests for the AutoDePSpecialize path (good question raised in review — the paths do infer well, but the DiffEqBase suite wasn't locking it in). Measured (Julia 1.12, current branch + registered SciMLBase 3.37 / RespecializeParams 1.0):
Coverage before/after: RespecializeParams already |
0ae31f9 to
ed0dcac
Compare
|
Fixed the broad CI failure. The first full CI run failed across all main lanes with Fix: define Re-verified against the exact registry versions CI uses (SciMLBase 3.37.0 + RespecializeParams 1.0.0, not dev'd): DiffEqBase |
ed0dcac to
b48d588
Compare
|
Master advanced again (Rosenbrock → 2.5.0) and re-conflicted the branch, so CI hadn't re-run on the should_opaque_p fix. Rebased onto current master (Rosenbrock bumped to 2.5.1 above master's 2.5.0; my workload survived the source auto-merge), force-pushed. PR is MERGEABLE again and CI is running on the fixed commit (b48d588). Verified before push: no conflict markers, should_opaque_p is defined locally (0 refs to SciMLBase.should_opaque_p). |
New opt-in specialization level that extends AutoSpecialize by de-specializing the parameter object: an isbits non-NullParameters p is packed into a RespecializeParams.OpaqueParams container and the FunctionWrappersWrapper signature carries the container type in the p slot instead of typeof(p), so the concretized problem type — and the whole solve compilation — is independent of the user's parameter struct type. One precompiled solve is shared across all isbits parameter types; the user's f still receives p at its concrete type via a type-stable, allocation-free unpack. Shared, reusable split (so NonlinearSolve.jl can adopt the same level; it deps SciMLBase but not DiffEqBase): - SciMLBase (3.37): AutoDePSpecialize marker + should_opaque_p policy. - RespecializeParams (1): OpaqueParams/OpaqueRef/OpaqueVoid, pack_auto, opaque_container_type/opaque_signature, and the wrap_void_opaque installer. - DiffEqBase here: promote_f returns (f, p) and routes the AutoDePSpecialize path through SciMLBase.should_opaque_p + RespecializeParams.wrap_void_opaque; the FD ext builds the 4-variant dual wrapper. sol.prob.p stays the opaque container (dense/lazy interpolation re-invokes the wrapped RHS with it). Precompilation: PrecompileAutoDePSpecialize workload in the flagship solver sublibs (Tsit5/Rosenbrock/Default default-on; Verner/SDIRK/BDF/SSPRK/LowStorage default-off). Measured fresh-process TTFX for a never-seen parameter struct drops ~12.1s to ~0.43s for DefaultODEAlgorithm; runtime within ~2% of AutoSpecialize. Co-Authored-By: Claude Fable 5 <[email protected]> Co-Authored-By: Chris Rackauckas <[email protected]>
b48d588 to
0a6bd1a
Compare
|
CI triage after the should_opaque_p fix — the cascade cleared: main Mine, just fixed:
Pre-existing, not this PR (verified by untouched sublibs failing identically):
Rebased onto current master (3 new commits, no conflicts; all my version bumps still above master) and force-pushed with the docs fix. Will confirm the docs lane goes green on the next run. |
|
Documentation lane is green now — the docs cross-ref fix worked. Final CI triage is conclusive: every remaining red is pre-existing / repo-wide; none is attributable to this PR. Green (everything genuinely this PR's):
Pre-existing (verified by untouched sublibs failing identically):
So functionally the PR is as-green-as-the-repo-allows. Ready for review whenever, @ChrisRackauckas. (Master is very active, so the branch may need periodic rebases to stay un-conflicted; happy to keep it current.) |
Implements the NonlinearSolve analog of the DiffEqBase AutoDePSpecialize path (SciML/OrdinaryDiffEq.jl#3692). For an in-place NonlinearProblem whose p is an isbits non-NullParameters payload, packs p into a RespecializeParams.OpaqueParams container and wraps the residual so its FunctionWrappersWrapper signature carries OpaqueParams in the parameter slot (via RespecializeParams.OpaqueVoid). The concretized problem type — and the solver compilation — becomes independent of the user's parameter struct type, so one precompiled solve is shared across all such types, while the residual still runs fully specialized on p (recovered by a type-stable, allocation-free unpack). The marker (SciMLBase.AutoDePSpecialize, 3.37) and mechanism (OpaqueVoid, wrap_void_opaque, pack, in RespecializeParams 1.0) are the same shared components DiffEqBase uses; this is the second consumer they were built for. Mirrors the existing AutoSpecialize path in autospecialize.jl: maybe_wrap_f tries maybe_opaque_wrap first (pack p + wrap f), else falls back to maybe_wrap_nonlinear_f (now also plain-wraps AutoDePSpecialize when p is not opaque-able). AutoDePSpecializeCallable{FW} parallels AutoSpecializeCallable{FW} — FW is the only type parameter so different parameter struct types share one Julia type. The ForwardDiff extension gains a dual-aware wrapfun_iip_opaque. Fallbacks: get_raw_f returns an OpaqueVoid; maybe_unwrap_prob_for_enzyme fully reverts (raw residual + concrete p) under Enzyme. Scoped to in-place NonlinearProblem/ImmutableNonlinearProblem, array non-dual state, outside Enzyme AD. NLLS, OOP, dual-p sensitivity, and Enzyme keep existing behavior. RespecializeParams = 1 dep; version 2.37.0 -> 2.38.0. Verified: full NonlinearSolveBase suite green (incl. 12 new tests); end-to-end NewtonRaphson/TrustRegion/AutoFiniteDiff on a struct-parameter root problem match FullSpecialize, sol.prob.p isa OpaqueParams, unpack roundtrips, struct types share typeof(prob.f.f); runtime within ~4% of AutoSpecialize. Co-authored-by: ChrisRackauckas-Claude <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
…4005) * AutoDePSpecialize: de-specialize non-isbits parameters via OpaqueRef Follow-up to #3692 (which shipped AutoDePSpecialize for isbits parameters). Extends the opaque-p path to non-isbits parameters: should_opaque_p now accepts any non-NullParameters, non-already-packed p, and pack_auto/opaque_container_type route isbits payloads into OpaqueParams (byte copy) and everything else into RespecializeParams.OpaqueRef (by reference). The FD ext substitutes opaque_container_type(P) rather than hardcoding OpaqueParams, and an idempotency guard prevents re-wrapping an already-opaque problem (no nested OpaqueVoid). This extends the shared-compilation TTFX benefit to problems whose parameter type is a non-isbits struct (e.g. a param struct holding arrays). It remains a forward-solve latency tool: de-specializing makes sol.prob.p an opaque container, so reverse-mode AD of p (SciMLSensitivity) and symbolic parameter indexing (getp/setp/observed) — which read the concrete parameter — are not supported. Reverse-mode support (unwrap the RHS + unpack p in the adjoint, as AutoSpecialize already does for its function wrapper) is a planned follow-up. Recover the payload with RespecializeParams.unpack(sol.prob.p, typeof(p)). DiffEqBase 7.8.0 -> 7.9.0. Verified: GROUP=Core green (Opaque-p Hook 25/25 incl. OpaqueRef + idempotency + inference; ForwardDiff Dual Detection); full-stack non-isbits solves match FullSpecialize across Tsit5/Rodas5P/FBDF. Co-Authored-By: Claude Fable 5 <[email protected]> Co-Authored-By: Chris Rackauckas <[email protected]> * Precompile the OpaqueRef (non-isbits) AutoDePSpecialize path The AutoDePSpecialize precompile workload only exercised an isbits `p` (the `lorenz_p_params` NamedTuple), so only the `OpaqueParams` container was precompiled. A non-isbits `p` routes through `OpaqueRef`, a distinct wrapper signature that nothing precompiled — so it compiled on first use and saw no TTFX benefit (measured: first Tsit5 solve 2.40s, same as FullSpecialize's 2.13s). Add a non-isbits variant (`lorenz_pref` with a `Vector` `p`) to the shared setup and to each algorithm's `@compile_workload`. Like the isbits case, one precompiled `OpaqueRef` solve is shared across all non-isbits parameter types, since the wrapped signature carries `OpaqueRef` rather than `typeof(p)`. After this the non-isbits first solve drops to 0.37s, matching the isbits AutoDePSpecialize path. Patch-bumps the touched precompile-carrying sublibraries. Co-Authored-By: Chris Rackauckas <[email protected]> * Decline the opaque path for symbolic-system (MTK) problems The non-isbits path packs any non-isbits `p` into an OpaqueRef, which swept in `MTKParameters`. A ModelingToolkit problem opting into AutoDePSpecialize then errored at solve time in `promote_u0_p(::OpaqueRef)` (MTK's initialization pipeline needs a concrete parameter object), and even had it solved, `getp`/observed/symbolic indexing read the concrete `p` and would break. Guard both `promote_f` opaque branches with `!SciMLBase.has_sys(f)`: a function carrying a symbolic system falls back to the normal specialization. This is a pure no-op for such problems anyway — `MTKParameters` is non-isbits and already type-uniform, so there is no shared-compilation win to be had. Verified end-to-end with a real MTK ODEProblem (solve + `sol[x]` + `getp` all succeed) and a `SymbolCache`-backed regression test; plain non-isbits/isbits problems still de-specialize as before. Co-Authored-By: Chris Rackauckas <[email protected]> * Precompile the no-algorithm solve(prob) entry for AutoDePSpecialize The Default workload only swept `solve(prob, solver)`, so it covered `solve(prob, DefaultODEAlgorithm())` but not the no-algorithm `solve(prob)` entry, which runs default algorithm *selection* — a separate code path, and the one most user code and MTK tutorials actually write. The opaque-p precompilation therefore never reached it. Measured on an AutoDePSpecialize problem with an isbits struct `p`: solve(prob, DefaultODEAlgorithm()) 0.42s (already precompiled) solve(prob) before this change 11.25s solve(prob) after this change 0.45s FullSpecialize is 13.3s on the same no-alg path, so this is a ~30x first-solve win on the most common entry point rather than the ~1.2x it was getting before. Co-Authored-By: Chris Rackauckas <[email protected]> --------- Co-authored-by: ChrisRackauckas-Claude <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
Note
Draft PR — please ignore until reviewed by @ChrisRackauckas.
Note
Both upstream dependencies are now registered — the environment resolves against the registry (the AutoDePSpecialize machinery is deliberately split so NonlinearSolve.jl can reuse all of it — it deps SciMLBase but not DiffEqBase):
AutoDePSpecializemarker and theshould_opaque_ppolicy.[compat] SciMLBase = "3.37".OpaqueParams/OpaqueRefcontainers, theOpaqueVoidcallback wrapper,pack_auto/opaque_container_type/opaque_signature, and thewrap_void_opaqueinstaller (FunctionWrappersWrappers is a hard dep there).[compat] RespecializeParams = "1".Summary
Implements the ODE-stack support for
AutoDePSpecialize, an opt-in specialization level (owned by SciMLBase, per @ChrisRackauckas's direction so NonlinearSolve.jl can adopt the same level for its residual wrappers) that extendsAutoSpecializeby additionally de-specializing the parameter object: anisbitsnon-NullParameterspis packed into aRespecializeParams.OpaqueParamscontainer and theFunctionWrappersWrappersignature carriesOpaqueParamsin thepslot instead oftypeof(p). The concretized problem type — and therefore the entire integrator/solve compilation — becomes independent of the user's parameter struct type, so one precompiled solve is shared across all isbits parameter types. Inside the user'sf,pis recovered at its original concrete type via a single type-stable, allocation-free unpack (unsafe_load), so the RHS itself stays fully specialized.This supersedes the earlier revision of this PR which applied the opaque-
ptransform by default underAutoSpecialize. It is now strictly opt-in:AutoSpecializebehavior is fully restored to stock (ppasses through untouched). The marker is defined and documented in SciMLBase (#1458); DiffEqBase imports it from SciMLBase and re-exports it, and OrdinaryDiffEqCore / OrdinaryDiffEq import it from SciMLBase (the owner) and re-export sousing OrdinaryDiffEq; ODEProblem{true, AutoDePSpecialize}(...)works unqualified.The eight solver sublibraries with specialization workloads gain a
PrecompileAutoDePSpecializepreference-gated workload entry. Because the wrapped signature isp-type-independent, this single workload gives full precompile coverage for any isbitsp. It defaults to true for Tsit5, Rosenbrock, and Default (the flagship solvers) and false for Verner/SDIRK/BDF/SSPRK/LowStorageRK (see precompile costs below).Is it a good TTFX option? (measured)
Fresh process,
using OrdinaryDiffEq, first solve of a Lorenz system with a never-before-seen parameter struct type (Julia 1.12.4, this branch, medians of 3):AutoSpecialize(default)FullSpecializeAutoDePSpecializeTsit5()Rodas5P()DefaultODEAlgorithm()First
sol(t)interpolation call: 0.23–0.50 s under Auto/Full → < 0.1 ms underAutoDePSpecialize.Marginal cost of each additional distinct
(f, typeof(p))in the same session (the sharing effect itself, independent of pkgimages):AutoSpecializeFullSpecializeAutoDePSpecializeTsit5()Rodas5P()So yes: for the "many problems, many parameter-struct types" workflow (parameter sweeps over differently-typed configs, package tests, teaching, MTK-free scripting) it is easily the best TTFX option available, and unlike
PrecompileAutoSpecialize=truethe precompile investment is paid once for all parameter types instead of only coveringVector{Float64}/NullParameters.Precompile-time cost of the workload (per-lib pkgimage build delta, measured off→on): Tsit5 +3.0 s, Rosenbrock +5.2 s, Default +10.3 s (defaults on); BDF +3.1 s, SDIRK +14.3 s, Verner +34.2 s (defaults off — flip with the
PrecompileAutoDePSpecializepreference). Happy to flip any of the defaults per review.How does it affect runtime? (measured)
Lorenz,
tspan = (0, 100), BenchmarkTools medians:FullSpecializeAutoSpecializeAutoDePSpecializeTsit5()Rodas5P()Raw RHS-call cost: direct 5.1 ns,
AutoSpecializewrapper 19.8 ns,OpaqueVoidwrapper 24.9 ns. I.e. the unpack adds ~5 ns per RHS call on top of the function-wrapper indirection thatAutoSpecializealready pays; on this 3-ODE Lorenz that shows up as ~2% vsAutoSpecialize(and ~10–20% vsFullSpecialize, same asAutoSpecializeitself). For anything but tiny systems the difference vanishes. The wrapped inner call is verified@allocated == 0.Same runtime trade as
AutoSpecialize, same advice as the existing docs: useFullSpecializefor long-running production solves of tiny systems;AutoDePSpecializeis the TTFX-optimal choice otherwise.What changed
lib/DiffEqBase/src/opaque_void.jl— now just thewrapfun_iip_opaquestub (FD-ext methods) plus a header comment. All the reusable glue moved out: theAutoDePSpecializemarker +should_opaque_ppolicy → SciMLBase (Update README.md #1458); theOpaqueVoidwrapper, container selection (pack_auto/opaque_container_type), signature surgery (opaque_signature), and thewrap_void_opaqueinstaller → RespecializeParams (Extra FSAL after internals modification by continuous events #23). The file shrank by ~55 lines —promote_fnow callsSciMLBase.should_opaque_pandRespecializeParams.wrap_void_opaque(ff, P, (natural_sig,))/pack_auto.lib/DiffEqBase/src/solve.jl—promote_freturns(f, p); the opaque branch triggers only forspecialize === AutoDePSpecialize(falls back to plainAutoSpecializewrapping for non-isbitsp/NullParameters). TheVal{false}(non-FD) path builds its single-signature wrapper directly so the wrapper type does not depend on whether ForwardDiff is loaded — this is required for the Tsit5 pkgimage to be reused under the full OrdinaryDiffEq (see commit message for the 2.5 s → 0.35 s effect).lib/DiffEqBase/ext/DiffEqBaseForwardDiffExt.jl— 4-variant (plain / Jac-Dual / t-Dual / both)wrapfun_iip_opaquefor the stiff/FD path.lib/OrdinaryDiffEqCore/src/precompilation_setup.jl—lorenz_p+lorenz_p_params(NamedTuple) workload helpers; AutoDePSpecialize problem construction.PrecompileAutoDePSpecializeworkload blocks (defaults per above).docs/src/api/diffeqbase.mdpoints its@docsentry atSciMLBase.AutoDePSpecialize.SciMLBase = "3.37"compat floor in DiffEqBase / OrdinaryDiffEqCore / OrdinaryDiffEq;RespecializeParams = "1"dep in DiffEqBase.lib/DiffEqBase/test/opaque_p_test.jlreworked for the opt-in level: opaque-ifies isbitspunderAutoDePSpecialize;AutoSpecialize/FullSpecializepasspthrough untouched;NullParameters/non-isbits fall back; different isbitsptypes sharetypeof(prob.f)/typeof(prob.p); unpack roundtrip.Behavioral notes
sol.prob.punderAutoDePSpecializeis theOpaqueParamscontainer and deliberately stays that way: dense/lazy interpolation (e.g. Verner) re-invokes the wrapped RHS withsol.prob.p, so restoring the user'spintosol.probbreakssol(t)with "No matching function wrapper" (this is why the earlier "restore user-facing prob" commit is gone — it was caught by the Verner precompile workload). Recover the original withRespecializeParams.unpack(sol.prob.p, MyParams); this is documented in the docstring. Since the level is opt-in, downstream code that introspectssol.prob.psimply shouldn't opt in.p(e.g.Vector{Float64}) underAutoDePSpecializegracefully degrades to exactlyAutoSpecializebehavior.Test plan
GROUP=Core Pkg.test()onlib/DiffEqBasegreen (includes the 13 opaque-p tests).FullSpecializebaseline to 1e-6 acrossTsit5,Vern7,Vern9(lazy interp),Rosenbrock23,Rodas5P,FBDF,DefaultODEAlgorithm, includingsol(t)interpolation, unpack roundtrip, and@allocated == 0on the wrapped inner call.solve, so a workload failure is a precompile failure — this is what caught the Verner issue).Follow-ups (out of scope)
using OrdinaryDiffEqvs ~0.1–0.2 ms when only the solver sublib is loaded. Worth an independent invalidation hunt.OpaqueRefpath for non-isbits payloads; DAE/DDE/SDEpromote_fequivalents; a payload-type-free accessor for recoveringp(via the storedobjectidtypeid).CI triage (first full run, 2026-07-17)
Compared against the last merged PR (#3921) as baseline:
ExplicitImportsfailures on the modified sublibs — the workloads' qualified access toOrdinaryDiffEqCore.lorenz_p/lorenz_p_paramsneeded the same ignore-list treatment as the existinglorenz/lorenz_oop; (b)lib/DiffEqBase [Downstream]/[Downstream2]— the downstream test env pulled DiffEqBase from the registry (≤ 7.6.2) while the dev'd OrdinaryDiffEqCore requires 7.7, now fixed by addingDiffEqBase = {path = "../.."}to its[sources].benchmark (1)/benchmark (lts)build the PR's top-level package against the registry (no path sources), andOrdinaryDiffEqCore = "4.8"is unreleased. These go green once DiffEqBase 7.7.0 / OrdinaryDiffEqCore 4.8.0 are registered. The floor cannot be loosened: OrdinaryDiffEq 7.2.0 importsAutoDePSpecializefrom OrdinaryDiffEqCore 4.8.julia ltstest-group failures (InterfaceI, Integrators_I, Regression_I/II, AlgConvergence_I/III) come from the test env resolving RootedTrees 2.6.2 (predatesRungeKuttaMethod) on Julia 1.10, killing DiffEqDevTools precompile. Registry drift, not this PR — investigation + fix running separately.DiffEqDevTools [QA](Aqua persistent-tasks / undocumented names in DevTools' own API) is the same drift class.downgrade-sublibrariesset (identical failing list on Fix reinit! crash on null-u0 integrators (uType Nothing) #3921), and GPU jobs.