Skip to content

AutoDePSpecialize: de-specialize non-isbits parameters via OpaqueRef - #4005

Merged
ChrisRackauckas merged 4 commits into
SciML:masterfrom
ChrisRackauckas-Claude:autodepspecialize-nonisbits
Jul 25, 2026
Merged

ChrisRackauckas merged 4 commits into
SciML:masterfrom
ChrisRackauckas-Claude:autodepspecialize-nonisbits

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Note

Draft PR — please ignore until reviewed by @ChrisRackauckas.

Follow-up to #3692 (which shipped AutoDePSpecialize for isbits parameters, now on master). This extends the opaque-p path to non-isbits parameters.

What changed

should_opaque_p now de-specializes any p except NullParameters and already-packed containers (previously isbits-only). RespecializeParams.pack_auto/opaque_container_type route the payload: isbits → OpaqueParams (byte copy, as before), everything else → OpaqueRef (by reference). The ForwardDiff extension substitutes opaque_container_type(P) instead of hardcoding OpaqueParams, and an idempotency guard stops a re-concretized opaque problem from being re-wrapped (no nested OpaqueVoid).

The RespecializeParams machinery (OpaqueRef, OpaqueVoid's OpaqueRef methods, pack_auto) already existed — this just stops gating it out. DiffEqBase 7.8.0 → 7.9.0.

Value + scope

Extends the shared-compilation TTFX benefit to problems whose parameter type is a non-isbits struct (e.g. a parameter struct holding arrays — different model types then share one precompiled solve).

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. Recover the payload explicitly with RespecializeParams.unpack(sol.prob.p, typeof(p)).
  • Reverse-mode support is a planned follow-up: the adjoint would unwrap the RHS (via unwrapped_f, extended to see through OpaqueVoid) and unpack p, the same way it already unwraps the plain AutoSpecialize function wrapper. (Prototyped; it's a multi-path SciMLSensitivity change, so it's separated out.)
  • Forward-mode AD of p is unaffected — the existing isdualtype(u0) guard skips the opaque path whenever p carries duals.

Verified

  • GROUP=Core green: Opaque-p Hook 25/25 (adds OpaqueRef + idempotency + inference cases), ForwardDiff Dual Detection unchanged.
  • Full-stack non-isbits solves match FullSpecialize across Tsit5/Rodas5P/FBDF (sol.prob.p isa OpaqueRef, unpack roundtrips, different non-isbits types share typeof(prob.f)).

🤖 Generated with Claude Code

https://claude.ai/code/session_01UuAbA8hSnrirMrJjFqxwn5

Follow-up to SciML#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]>
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]>
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Added precompilation of the non-isbits (OpaqueRef) path — without it the forward-solve speedup this PR enables was not actually being realized on first use.

The existing AutoDePSpecialize @compile_workload only exercised an isbits p (the lorenz_p_params NamedTuple → OpaqueParams). A non-isbits p routes through the distinct OpaqueRef wrapper signature, which nothing precompiled, so it compiled fresh on first solve. Added a lorenz_pref (Vector p) variant to the shared setup and each algorithm workload; one precompiled OpaqueRef solve is shared across all non-isbits parameter types.

Measured (fresh process, first Tsit5 solve of a never-seen parameter struct):

case before after
isbits p, FullSpecialize 2.17s —
isbits p, AutoDePSpecialize 0.39s 0.40s
non-isbits p, FullSpecialize 2.13s 2.16s
non-isbits p, AutoDePSpecialize 2.40s 0.37s

So the non-isbits path now gets the same ~5.8× first-solve TTFX win as the isbits path. Patch-bumped the touched precompile-carrying sublibraries.

ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/NonlinearSolve.jl that referenced this pull request Jul 23, 2026
SciML#1107 merged AutoDePSpecialize with an isbits-only policy
(`should_opaque_p(p) = isbits(p) && !NullParameters`), so a non-isbits `p`
was left concrete and got no de-specialization. Relax the policy to
de-specialize any non-`NullParameters`, non-already-packed `p`, and pack
via `pack_auto` so isbits payloads go to `OpaqueParams` (byte copy) and
non-isbits payloads to `OpaqueRef` (by reference). Mirrors the ODE
DiffEqBase path (SciML/OrdinaryDiffEq.jl#4005).

This is what makes the non-isbits problem in the precompile workloads
actually take the opaque path. Reverse-mode AD of `p` and symbolic
parameter indexing remain unsupported under the opaque path (forward-solve
latency tool); recover the payload with
`RespecializeParams.unpack(sol.prob.p, typeof(p))`.

Minor-bumps NonlinearSolveBase (extends the opt-in AutoDePSpecialize feature).

Co-Authored-By: Chris Rackauckas <[email protected]>
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]>
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Added an MTK-safety guard, because the non-isbits path had a real footgun here.

MTKParameters is non-isbits, so the OpaqueRef path swept it in. A ModelingToolkit problem opting into AutoDePSpecialize then errored at solve — not just symbolic indexing, the solve itself:

promote_u0_p(u0::Vector{Float64}, p::OpaqueRef, t0::Float64)   # no method
  in _late_binding_update_u0_p_impl   (MTK initialization)

Fix: guard both promote_f opaque branches with !SciMLBase.has_sys(f). A function carrying a symbolic system falls back to the normal specialization — a pure no-op for MTK anyway (its params are non-isbits and already type-uniform, so no shared-compilation win exists).

Verified with a real MTK ODEProblem after the guard:

before guard after guard
prob.p after opt-in OpaqueRef MTKParameters (declined)
solve errors Success
sol[x] — ✓
getp(sys, k)(sol) — ✓ 2.0
sol(0.5; idxs=x) — ✓

Plain non-isbits/isbits problems (no sys) still de-specialize exactly as before. Regression test uses a SymbolCache sys to reproduce has_sys without pulling in ModelingToolkit; DiffEqBase opaque-p suite now 30/30.

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]>
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Found and fixed a further precompilation gap, this time on the default solver — and it was the biggest one.

The workload only swept solve(prob, solver), which covers solve(prob, DefaultODEAlgorithm()) but not the no-algorithm solve(prob) entry. That entry runs default algorithm selection, a separate code path — and it is the one most user code and MTK tutorials actually write. So the opaque-p precompilation never reached it.

Measured (fresh process, isbits struct p, 3-state problem):

entry point FullSpecialize AutoDePSpecialize before AutoDePSpecialize after
solve(prob, DefaultODEAlgorithm()) 7.90s 0.42s 0.42s
solve(prob) (no algorithm) 13.29s 11.25s 0.45s

So the most common entry point went from a ~1.2× win to ~30×. Worth noting the polyalgorithm payoff is far larger than for a single method (Tsit5: 2.17s → 0.37s), since a uniform p slot shares compilation across every solver the polyalgorithm instantiates — more methods, more shared work.

Fix keeps the AutoDePSpecialize problems in their own list so they drive both the solve(prob, solver) sweep and a solve(prob) pass. Verified by precompiling (the workload solve runs during precompilation, so a clean build confirms it) and timing fresh-process first solves.

@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review July 25, 2026 02:57
@ChrisRackauckas
ChrisRackauckas merged commit 5d640b8 into SciML:master Jul 25, 2026
224 of 285 checks passed
ChrisRackauckas added a commit to SciML/NonlinearSolve.jl that referenced this pull request Jul 25, 2026
…1110)

* Precompile the AutoDePSpecialize opaque-p path

#1107 added the AutoDePSpecialize specialization level but no workload
exercised it, so the opaque-p solve compiled on first use and struct/array
parameters saw no TTFX benefit. Add an AutoDePSpecialize problem (isbits
`p` -> OpaqueParams, non-isbits `p` -> OpaqueRef) to the FirstOrder,
QuasiNewton, and SpectralMethods `@compile_workload`s. Each container is a
single wrapped-residual signature shared across all parameter types of its
kind, so one precompiled solve per container serves first solves with any
struct/array parameter.

Measured (fresh process, first NewtonRaphson solve of a never-seen
non-isbits parameter struct): FullSpecialize 3.02s, AutoDePSpecialize
0.88s after this change (vs 3.1s before, when the opaque path was not
precompiled). Broyden and DFSane first solves likewise drop to ~1s.

Patch-bumps the three touched sublibraries.

Co-Authored-By: Chris Rackauckas <[email protected]>

* Add the non-isbits (OpaqueRef) AutoDePSpecialize path

#1107 merged AutoDePSpecialize with an isbits-only policy
(`should_opaque_p(p) = isbits(p) && !NullParameters`), so a non-isbits `p`
was left concrete and got no de-specialization. Relax the policy to
de-specialize any non-`NullParameters`, non-already-packed `p`, and pack
via `pack_auto` so isbits payloads go to `OpaqueParams` (byte copy) and
non-isbits payloads to `OpaqueRef` (by reference). Mirrors the ODE
DiffEqBase path (SciML/OrdinaryDiffEq.jl#4005).

This is what makes the non-isbits problem in the precompile workloads
actually take the opaque path. Reverse-mode AD of `p` and symbolic
parameter indexing remain unsupported under the opaque path (forward-solve
latency tool); recover the payload with
`RespecializeParams.unpack(sol.prob.p, typeof(p))`.

Minor-bumps NonlinearSolveBase (extends the opt-in AutoDePSpecialize feature).

Co-Authored-By: Chris Rackauckas <[email protected]>

* Decline the opaque path for symbolic-system (MTK) problems

Mirror of the DiffEqBase guard: the non-isbits path packs any non-isbits
`p` (including MTKParameters) into an OpaqueRef, which breaks MTK's
initialization pipeline and symbolic parameter indexing. Guard
`maybe_opaque_wrap` with `!SciMLBase.has_sys(prob.f)` so a NonlinearProblem
carrying a symbolic system falls back to the normal specialization — a
no-op for such problems, which gain nothing from de-specialization. Adds a
`SymbolCache`-backed regression test.

Co-Authored-By: Chris Rackauckas <[email protected]>

* Precompile the polyalgorithm and no-kwarg solve entries for AutoDePSpecialize

Two gaps, both on the paths users actually hit:

1. The AutoDePSpecialize problems were only added to the FirstOrder,
   QuasiNewton and SpectralMethods workloads, which sweep individual
   algorithms. The polyalgorithm / no-algorithm sweep lives in the main
   NonlinearSolve workload, so `solve(prob)` (default algorithm selection
   via FastShortcutNonlinearPolyalg) never saw an opaque-p problem.

2. The workload's default sweep passes `abstol`/`verbose`, and the keyword
   NamedTuple's type participates in the specialization — so precompiling
   `solve(prob; kwargs...)` does not cover the bare `solve(prob)` that most
   user code writes.

Add the opaque-p problems (isbits -> OpaqueParams, non-isbits -> OpaqueRef)
to the main workload, and give them their own bare no-kwarg `solve(prob)`
sweep.

Measured (fresh process, non-isbits struct `p`, `solve(prob)` no algorithm):

  FullSpecialize                        5.04s
  AutoDePSpecialize, before             3.11s
  AutoDePSpecialize, + polyalg probs    1.69s
  AutoDePSpecialize, + bare sweep       0.61s

That matches the single-algorithm figure (0.72s), i.e. the polyalgorithm
path now gets the same first-solve win. Verified: NonlinearSolveBase
AutoDePSpecialize suite 23/23; polyalg/NewtonRaphson/Broyden/DFSane all
converge on a non-isbits opaque-p problem.

Co-Authored-By: Chris Rackauckas <[email protected]>

---------

Co-authored-by: ChrisRackauckas-Claude <[email protected]>
ChrisRackauckas added a commit that referenced this pull request Jul 30, 2026
… workloads (#4080)

#4005 added a non-isbits precompile workload built on
OrdinaryDiffEqCore.lorenz_pref / lorenz_pref_params, and referenced it from
eight sublibraries' @compile_workload blocks without raising their
OrdinaryDiffEqCore floors. It bumped Core to 4.10.1, but 4.10.1 was never
registered — the next registered Core after 4.10.0 is 4.11.0 — so the first
released Core containing the symbols is 4.11.0.

Tsit5 2.1.1, Verner 2.2.1, SSPRK 2.2.1 and Rosenbrock 2.6.1 are all registered
declaring OrdinaryDiffEqCore = "4.10", so any environment holding Core at 4.10.0
resolves a combination that fails to precompile with

  UndefVarError: `lorenz_pref` not defined in `OrdinaryDiffEqCore`

Reproduced locally with OrdinaryDiffEqTsit5 2.1.1 + OrdinaryDiffEqCore 4.10.0;
the same pair with Core 4.11.0 precompiles and solves.

Audited every sublibrary's qualified OrdinaryDiffEqCore accesses and explicit
import lists against the registered Core trees for 4.0.0 - 4.11.0. Exactly
these eight are affected. BDF and SDIRK were additionally below the floor for
AutoDePSpecialize / lorenz_p / lorenz_p_params (first released in 4.8.1) under
their "4.8" bound; that is subsumed by 4.11. No other sublibrary references a
Core name absent at its declared floor.

Metadata-only; the source in this repo is already correct.

Fixes #4079



Claude-Session: https://claude.ai/code/session_017ZqxphdTA1MydR1WXye9Jc

Co-authored-by: ChrisRackauckas-Claude <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[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.

2 participants