Skip to content

DiffEqBase: AutoDePSpecialize — de-specialize p via OpaqueParams, opt-in + precompiled - #3692

Merged
ChrisRackauckas merged 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:despecialize-p-via-opaque-params
Jul 23, 2026
Merged

ChrisRackauckas merged 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:despecialize-p-via-opaque-params

Conversation

@ChrisRackauckas-Claude

@ChrisRackauckas-Claude ChrisRackauckas-Claude commented May 27, 2026 •

Copy link
Copy Markdown
Member

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):

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 extends AutoSpecialize by additionally de-specializing the parameter object: an isbits non-NullParameters p is packed into a RespecializeParams.OpaqueParams container and the FunctionWrappersWrapper signature carries OpaqueParams in the p slot instead of typeof(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's f, p is recovered at its original concrete type via a single type-stable, allocation-free unpack (unsafe_load), so the RHS itself stays fully specialized.

struct MyParams; σ::Float64; ρ::Float64; β::Float64 end
prob = ODEProblem{true, AutoDePSpecialize}(lorenz!, u0, tspan, MyParams(10.0, 28.0, 8/3))
sol = solve(prob, Tsit5())   # hits the precompiled path regardless of MyParams

This supersedes the earlier revision of this PR which applied the opaque-p transform by default under AutoSpecialize. It is now strictly opt-in: AutoSpecialize behavior is fully restored to stock (p passes 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 so using OrdinaryDiffEq; ODEProblem{true, AutoDePSpecialize}(...) works unqualified.

The eight solver sublibraries with specialization workloads gain a PrecompileAutoDePSpecialize preference-gated workload entry. Because the wrapped signature is p-type-independent, this single workload gives full precompile coverage for any isbits p. 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):

First solve AutoSpecialize (default) FullSpecialize AutoDePSpecialize
Tsit5() 2.67 s 2.70 s 0.36 s (7.5×)
Rodas5P() 5.12 s 6.37 s 0.42 s (12×)
DefaultODEAlgorithm() 12.1 s 8.34 s 0.43 s (28×)

First sol(t) interpolation call: 0.23–0.50 s under Auto/Full → < 0.1 ms under AutoDePSpecialize.

Marginal cost of each additional distinct (f, typeof(p)) in the same session (the sharing effect itself, independent of pkgimages):

Next new p-type AutoSpecialize FullSpecialize AutoDePSpecialize
Tsit5() ~2.1 s ~1.9 s ~0.2–0.33 s
Rodas5P() ~4.6 s ~5.0 s ~0.23–0.33 s

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=true the precompile investment is paid once for all parameter types instead of only covering Vector{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 PrecompileAutoDePSpecialize preference). Happy to flip any of the defaults per review.

How does it affect runtime? (measured)

Lorenz, tspan = (0, 100), BenchmarkTools medians:

solve FullSpecialize AutoSpecialize AutoDePSpecialize
Tsit5() 0.751 ms 0.907 ms 0.924 ms
Rodas5P() 6.82 ms 7.22 ms 7.26 ms

Raw RHS-call cost: direct 5.1 ns, AutoSpecialize wrapper 19.8 ns, OpaqueVoid wrapper 24.9 ns. I.e. the unpack adds ~5 ns per RHS call on top of the function-wrapper indirection that AutoSpecialize already pays; on this 3-ODE Lorenz that shows up as ~2% vs AutoSpecialize (and ~10–20% vs FullSpecialize, same as AutoSpecialize itself). 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: use FullSpecialize for long-running production solves of tiny systems; AutoDePSpecialize is the TTFX-optimal choice otherwise.

What changed

  • lib/DiffEqBase/src/opaque_void.jl — now just the wrapfun_iip_opaque stub (FD-ext methods) plus a header comment. All the reusable glue moved out: the AutoDePSpecialize marker + should_opaque_p policy → SciMLBase (Update README.md #1458); the OpaqueVoid wrapper, container selection (pack_auto/opaque_container_type), signature surgery (opaque_signature), and the wrap_void_opaque installer → RespecializeParams (Extra FSAL after internals modification by continuous events #23). The file shrank by ~55 lines — promote_f now calls SciMLBase.should_opaque_p and RespecializeParams.wrap_void_opaque(ff, P, (natural_sig,)) / pack_auto.
  • lib/DiffEqBase/src/solve.jl — promote_f returns (f, p); the opaque branch triggers only for specialize === AutoDePSpecialize (falls back to plain AutoSpecialize wrapping for non-isbits p / NullParameters). The Val{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_opaque for the stiff/FD path.
  • lib/OrdinaryDiffEqCore/src/precompilation_setup.jl — lorenz_p + lorenz_p_params (NamedTuple) workload helpers; AutoDePSpecialize problem construction.
  • 8 solver sublibs — PrecompileAutoDePSpecialize workload blocks (defaults per above).
  • Re-export chain — marker imported from SciMLBase (owner) in DiffEqBase, OrdinaryDiffEqCore, and OrdinaryDiffEq; each re-exports so it is available unqualified. docs/src/api/diffeqbase.md points its @docs entry at SciMLBase.AutoDePSpecialize.
  • Versions / compat — DiffEqBase 7.7.0, OrdinaryDiffEqCore 4.8.0, patch bumps for the 8 sublibs, OrdinaryDiffEq 7.2.0; SciMLBase = "3.37" compat floor in DiffEqBase / OrdinaryDiffEqCore / OrdinaryDiffEq; RespecializeParams = "1" dep in DiffEqBase.
  • Tests — lib/DiffEqBase/test/opaque_p_test.jl reworked for the opt-in level: opaque-ifies isbits p under AutoDePSpecialize; AutoSpecialize/FullSpecialize pass p through untouched; NullParameters/non-isbits fall back; different isbits p types share typeof(prob.f)/typeof(prob.p); unpack roundtrip.

Behavioral notes

  • sol.prob.p under AutoDePSpecialize is the OpaqueParams container and deliberately stays that way: dense/lazy interpolation (e.g. Verner) re-invokes the wrapped RHS with sol.prob.p, so restoring the user's p into sol.prob breaks sol(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 with RespecializeParams.unpack(sol.prob.p, MyParams); this is documented in the docstring. Since the level is opt-in, downstream code that introspects sol.prob.p simply shouldn't opt in.
  • Non-isbits p (e.g. Vector{Float64}) under AutoDePSpecialize gracefully degrades to exactly AutoSpecialize behavior.

Test plan

  • GROUP=Core Pkg.test() on lib/DiffEqBase green (includes the 13 opaque-p tests).
  • End-to-end vs FullSpecialize baseline to 1e-6 across Tsit5, Vern7, Vern9 (lazy interp), Rosenbrock23, Rodas5P, FBDF, DefaultODEAlgorithm, including sol(t) interpolation, unpack roundtrip, and @allocated == 0 on the wrapped inner call.
  • Full local rebuild of all sublibs with the workloads enabled (PrecompileTools workloads run the real solve, so a workload failure is a precompile failure — this is what caught the Verner issue).
  • CI: Tests.yml / Downstream.yml / FormatCheck.yml (Runic applied locally).

Follow-ups (out of scope)

  • Pre-existing cross-sublib invalidation: even fully-covered stock workload paths pay a few hundred ms under using OrdinaryDiffEq vs ~0.1–0.2 ms when only the solver sublib is loaded. Worth an independent invalidation hunt.
  • OpaqueRef path for non-isbits payloads; DAE/DDE/SDE promote_f equivalents; a payload-type-free accessor for recovering p (via the stored objectid typeid).

CI triage (first full run, 2026-07-17)

Compared against the last merged PR (#3921) as baseline:

  • Fixed in this PR after the first run: (a) QA ExplicitImports failures on the modified sublibs — the workloads' qualified access to OrdinaryDiffEqCore.lorenz_p/lorenz_p_params needed the same ignore-list treatment as the existing lorenz/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 adding DiffEqBase = {path = "../.."} to its [sources].
  • Expected-red until the release lands: benchmark (1)/benchmark (lts) build the PR's top-level package against the registry (no path sources), and OrdinaryDiffEqCore = "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 imports AutoDePSpecialize from OrdinaryDiffEqCore 4.8.
  • Pre-existing master breakage, reproduced on unmodified master locally: all julia lts test-group failures (InterfaceI, Integrators_I, Regression_I/II, AlgConvergence_I/III) come from the test env resolving RootedTrees 2.6.2 (predates RungeKuttaMethod) 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.
  • Pre-existing on baseline too: the wide QA failure set (Stochastic*, DelayDiffEq, etc.), downgrade-sublibraries set (identical failing list on Fix reinit! crash on null-u0 integrators (uType Nothing) #3921), and GPU jobs.

@oscardssmith

Copy link
Copy Markdown
Member

I'm fairly skeptical of this being a good idea.

@MasonProtter

Copy link
Copy Markdown
Contributor

I wonder if this could be an option to ODEFunction so that it's less invasive? I.e. you provide T to ODEFunction, and then provide a wrapper for your params?

@ChrisRackauckas

Copy link
Copy Markdown
Member

We have specialization options, so we can just make this a specialization option.

@ChrisRackauckas-Claude
ChrisRackauckas-Claude force-pushed the despecialize-p-via-opaque-params branch from 605d2b1 to 77e27a2 Compare July 17, 2026 14:03
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Updated per follow-up instructions: the opaque-p transform is no longer applied by default under AutoSpecialize — it is now the opt-in AutoDePSpecialize level, wired into the precompilation workloads (PrecompileAutoDePSpecialize, default on for Tsit5/Rosenbrock/Default). PR body rewritten with measured TTFX and runtime numbers.

Process notes for this revision:

  • Rebased onto current master (was ~30 commits behind; one trivial Project.toml compat conflict).
  • The old "restore sol.prob to the user-facing prob" commit was dropped, not carried: the Verner precompile workload caught that lazy interpolation calls the wrapped RHS with sol.prob.p, so restoring the user's p into sol.prob breaks sol(t) with "No matching function wrapper". sol.prob.p deliberately stays the OpaqueParams container (documented).
  • New standalone fix: the FD-ext 3-arg wrapfun_iip_opaque fallback made the non-FD wrapper type depend on whether ForwardDiff was loaded, which silently defeated Tsit5 pkgimage reuse under full OrdinaryDiffEq (2.5 s → 0.35 s TTFX once fixed).
  • Local verification: DiffEqBase GROUP=Core green ×3 runs; end-to-end vs FullSpecialize baseline across Tsit5/Vern7/Vern9/Rosenbrock23/Rodas5P/FBDF/Default incl. interpolation, unpack roundtrip, and zero-alloc inner call; full sublib rebuild with workloads on.

@ChrisRackauckas-Claude ChrisRackauckas-Claude changed the title DiffEqBase: de-specialize p via OpaqueVoid in AutoSpecialize DiffEqBase: AutoDePSpecialize — de-specialize p via OpaqueParams, opt-in + precompiled Jul 17, 2026
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Follow-up on the pre-existing julia lts failures: root-caused to the DataStructures v0.19.6 release (2026-07-17) widening its OrderedCollections compat to allow OC 2, which makes Latexify (requires OC 1) unresolvable, which silently drops RootedTrees to v2.6.2 (2021, predates RungeKuttaMethod), breaking DiffEqDevTools precompile in the root test envs. Fix PR: #3941 (floors DiffEqDevTools' RootedTrees compat at 2.8). The lts lanes here stay red until that merges (and, for the root groups on 1.10, until DiffEqDevTools 3.1.3 is registered, since <1.11 ignores [sources] for root groups). Unrelated to this PR's changes — reproduced on unmodified master.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

CI triage after the QA/downstream fixes (commit e2c4dc8):

Resolved by the fixes: the QA ExplicitImports failures on Tsit5/Verner/SSPRK/LowStorageRK are green now.

Registration-gated (self-heal once DiffEqBase 7.7.0 + OrdinaryDiffEqCore 4.8.0 are registered): benchmark (1)/benchmark (lts) and the OrdinaryDiffEqDefault [QA] Aqua persistent-tasks check — all three build a fresh env from the registry with no path sources, and OrdinaryDiffEqCore = "4.8" doesn't exist there yet.

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.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

The red lib/DiffEqBase [Downstream] / [Downstream2] lanes here are pre-existing master failures unrelated to this PR (both reproduce locally on unmodified master with current registry versions). Fixes:

Once those merge, a rebase/rerun should turn these lanes green.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Per review direction, moved the AutoDePSpecialize marker type out of DiffEqBase and into SciMLBase so NonlinearSolve.jl (and any other function family) can implement the same specialization level for its own residual wrappers. SciMLBase PR: SciML/SciMLBase.jl#1458 (adds the type, @public, docstring + docs entry, SpecializationLevel preference allowlist entry, tests). This branch now imports it from SciMLBase (owner) in DiffEqBase / OrdinaryDiffEqCore / OrdinaryDiffEq and re-exports; SciMLBase = "3.37" compat floor added. 3692 is now additionally gated on SciMLBase 3.37.0 registering. Verified locally against a dev'd SciMLBase 3.37: DiffEqBase GROUP=Core green (13/13 opaque + rest), end-to-end across all seven solver configs green.

ChrisRackauckas added a commit to SciML/SciMLBase.jl that referenced this pull request Jul 22, 2026
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]>
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Also moved the OpaqueVoid callback wrapper (the unpack-at-f-boundary callable) out of DiffEqBase and into RespecializeParams — SciML/RespecializeParams.jl#23 — since it's a reusable primitive (the "recover the concrete type inside f without allocation" half of that package's purpose) that NonlinearSolve.jl can share rather than re-defining. DiffEqBase now builds its FunctionWrappersWrapper around RespecializeParams.OpaqueVoid; compat floor RespecializeParams = "0.1.3". So this PR's dependency chain is now: SciMLBase 3.37 (#1458, the AutoDePSpecialize marker) + RespecializeParams 0.1.3 (#23, OpaqueParams + OpaqueVoid). Verified locally against both dev'd: DiffEqBase GROUP=Core green (13/13 opaque + ForwardDiff Dual Detection), end-to-end across all seven solver configs green.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Pushed the maximal-sharing refactor so NonlinearSolve.jl can reuse the entire AutoDePSpecialize machinery (it deps SciMLBase but not DiffEqBase). Final split:

  • SciMLBase Update README.md #1458: AutoDePSpecialize marker + should_opaque_p(p) policy (isbits & !NullParameters).
  • RespecializeParams Extra FSAL after internals modification by continuous events #23 (v0.1.4): the whole mechanism — OpaqueParams/OpaqueRef/OpaqueVoid, pack_auto/opaque_container_type/opaque_signature, and the wrap_void_opaque installer (FunctionWrappersWrappers extension). A solver's opaque wrapping is now one call: wrap_void_opaque(f, typeof(p), (natural_sig,)).
  • Here: only genuinely ODE-specific code remains — the promote_f ODEFunction tgrad/jac/sparsity threading and the FD-ext 4-variant dual-signature builder. opaque_void.jl shrank from ~73 to ~24 lines (just the wrapfun_iip_opaque stub).

Verified against dev SciMLBase 3.37 + RespecializeParams 0.1.4: GROUP=Core green (Opaque-p Hook 13/13, ForwardDiff Dual Detection), end-to-end across all seven solver configs green. Compat floor RespecializeParams = "0.1.4".

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

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.

@ChrisRackauckas-Claude
ChrisRackauckas-Claude force-pushed the despecialize-p-via-opaque-params branch from 7bbba46 to 3095120 Compare July 23, 2026 09:00
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

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:

  • Collapsed the iterative agent commits into one clean commit (full history was noisy; the PR description carries the detail).
  • Conflicts were compat-only in two sublib Project.tomls (master bumped SciMLOperators/MuladdMacro while I bumped OrdinaryDiffEqCore) — took both.
  • Master's release-prep had already taken OrdinaryDiffEqCore 4.8.0 / Rosenbrock 2.4.2 / BDF 2.3.2, colliding with my target versions, so bumped those above master: Core 4.9.0, Rosenbrock 2.4.3, BDF 2.3.3.

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.

@ChrisRackauckas-Claude
ChrisRackauckas-Claude force-pushed the despecialize-p-via-opaque-params branch from 3095120 to 0ae31f9 Compare July 23, 2026 09:11
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

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):

  • The hot path (OpaqueVoid unpack → forward) is fully inferred; @inferred OK, returns Nothing.
  • The wrapped-f call is inference-identical to the existing AutoSpecialize Void wrapper — both erase to Nothing via FunctionWrappersWrapper, both @inferred OK.
  • pack_auto infers to concrete OpaqueParams for isbits payloads (isbits(p) constant-folds on a concrete type — no Union).
  • get_concrete_problem yields the same count of concrete return types for AutoDePSpecialize as for AutoSpecialize — the level adds no instability over the existing design.
  • Steady-state inner loop: 74 allocs / 10.5 µs vs AutoSpecialize's 72 / 10.3 µs — a stable loop (an unstable one would allocate wildly), matching AutoSpecialize.

Coverage before/after: RespecializeParams already @inferred-tests the primitives (unpack/unsafe_unpack) + zero-alloc on OpaqueVoid. What was missing was a DiffEqBase-level guard. Added a testset to opaque_p_test.jl asserting: the wrapped-f call is @allocated == 0 (function-barriered) and @inferred; unsafe_unpack and pack_auto infer to the concrete types; and get_concrete_problem's inference shape matches AutoSpecialize. 21/21 pass locally. Amended into the commit + force-pushed.

@ChrisRackauckas-Claude
ChrisRackauckas-Claude force-pushed the despecialize-p-via-opaque-params branch from 0ae31f9 to ed0dcac Compare July 23, 2026 10:34
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Fixed the broad CI failure. The first full CI run failed across all main lanes with UndefVarError: should_opaque_p not defined in SciMLBase. Root cause: the released SciMLBase 3.37.0 ships AutoDePSpecialize but not should_opaque_p — that predicate never landed on SciMLBase master (SciML/SciMLBase.jl#1458 merged with the marker but not the policy commit). My local verification had passed only because it used a dev'd SciMLBase that still had should_opaque_p, masking the gap.

Fix: define should_opaque_p locally in DiffEqBase (it's a trivial one-liner: isbits(p) && !(p isa NullParameters)) rather than depend on an unreleased SciMLBase symbol. The valuable sharing (OpaqueVoid + wrap_void_opaque + containers, via RespecializeParams 1.0.0) is unaffected. If NonlinearSolve later wants to share the policy too, it can be promoted to SciMLBase in a follow-up and DiffEqBase switched over.

Re-verified against the exact registry versions CI uses (SciMLBase 3.37.0 + RespecializeParams 1.0.0, not dev'd): DiffEqBase GROUP=Core green (Opaque-p Hook 21/21 incl. the new inference/alloc guards), full solver-stack precompile clean, end-to-end across all seven configs green. This time the verification env pins the registered artifacts, so it actually reproduces CI's resolution.

@ChrisRackauckas-Claude
ChrisRackauckas-Claude force-pushed the despecialize-p-via-opaque-params branch from ed0dcac to b48d588 Compare July 23, 2026 11:51
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

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]>
@ChrisRackauckas-Claude
ChrisRackauckas-Claude force-pushed the despecialize-p-via-opaque-params branch from b48d588 to 0a6bd1a Compare July 23, 2026 13:10
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

CI triage after the should_opaque_p fix — the cascade cleared: main tests / lanes went from all-red to 43 pass / 1 fail, successes 23 → 173. Remaining reds are either pre-existing repo-wide or one more of mine, now fixed:

Mine, just fixed:

  • Documentation build (:cross_references error). My @docs SciMLBase.AutoDePSpecialize block in docs/src/api/diffeqbase.md pulled the SciMLBase-owned docstring into OrdinaryDiffEq's doc build, dragging its [AutoSpecialize](@ref) cross-ref which only resolves in SciMLBase's own docs. Since AutoDePSpecialize is documented at its owner (SciMLBase), I replaced the @docs block with a prose description + external link — no re-rendering, no dangling @ref.

Pre-existing, not this PR (verified by untouched sublibs failing identically):

  • tests / QA + all [QA] lanes: SciMLTesting's "public API is rendered in docs" / "No unapproved public reexports" checks flag the whole SciMLBase reexport surface (hundreds of names) — fails identically on OrdinaryDiffEqLinear [QA] which this PR never touches. My own ExplicitImports fix passes (6/6).
  • downgrade-sublibraries: fails on every sublib including untouched ones (GlobalDiffEq/Feagin/AMF/Multirate) — repo-wide minimum-version resolution issue.
  • DiffEqBase [Downstream] (build_J_W / VectorContinuousCallback — Fix build_J_W cache init for structured jac_prototypes #3942/Migrate community callback test off removed VectorContinuousCallback 4-arg form #3943) and ModelingToolkit downstream — pre-existing.
  • GPU lanes (need hardware); benchmark (needs this PR's own sublibs registered, i.e. merge).

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.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

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):

  • Main tests / lanes (InterfaceI–V, Integrators, Regression, AD): passing.
  • Documentation: passing.
  • DiffEqBase Core (opaque-p + the new inference/alloc guards): passing.
  • ExplicitImports on the touched sublibs (my lorenz_p ignore): passing 6/6.

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.)

@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review July 23, 2026 18:19
@ChrisRackauckas
ChrisRackauckas merged commit 37f2e04 into SciML:master Jul 23, 2026
19 of 22 checks passed
ChrisRackauckas added a commit to SciML/NonlinearSolve.jl that referenced this pull request Jul 23, 2026
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]>
ChrisRackauckas added a commit that referenced this pull request Jul 25, 2026
…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]>
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.

4 participants