Skip to content

Add AutoDePSpecialize specialization level (de-specialize p via OpaqueParams) - #1107

Merged
ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:add-autodepspecialize
Jul 23, 2026
Merged

ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:add-autodepspecialize

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Note

Draft PR — please ignore until reviewed by @ChrisRackauckas.

Summary

Implements the AutoDePSpecialize specialization level for NonlinearSolve, the analog of SciML/OrdinaryDiffEq.jl#3692 (DiffEqBase). It extends AutoSpecialize by additionally de-specializing the parameter object: for an in-place NonlinearProblem whose p is an isbits non-NullParameters payload, p is packed into a RespecializeParams.OpaqueParams container and the residual's 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).

struct MyParams; a::Float64; b::Float64 end
resid!(res, u, p::MyParams) = (res[1] = u[1]^2 - p.a; res[2] = u[2]^2 - p.b; nothing)
prob = NonlinearProblem(NonlinearFunction{true, AutoDePSpecialize}(resid!), [1.0, 1.0], MyParams(2.0, 3.0))
sol = solve(prob, NewtonRaphson())          # hits the shared wrapped path regardless of MyParams
p_recovered = RespecializeParams.unpack(sol.prob.p, MyParams)

The marker (SciMLBase.AutoDePSpecialize, released in SciMLBase 3.37) and the mechanism (OpaqueVoid, wrap_void_opaque, pack, in RespecializeParams 1.0) are the same shared components DiffEqBase uses — this PR is the second consumer they were built for.

How it works (mirrors the existing AutoSpecialize path)

NonlinearSolve already wraps IIP residuals for AutoSpecialize in lib/NonlinearSolveBase/src/autospecialize.jl (maybe_wrap_nonlinear_f → AutoSpecializeCallable holding a FunctionWrappersWrapper + the original). This PR adds the parallel opaque path:

  • maybe_wrap_f first tries maybe_opaque_wrap: for AutoDePSpecialize + should_opaque_p(p), it packs p and wraps the residual through RespecializeParams.wrap_void_opaque, returning a prob with both f.f (an AutoDePSpecializeCallable{FW}) and p (an OpaqueParams) set. Otherwise it falls back to the existing maybe_wrap_nonlinear_f (which now also plain-wraps AutoDePSpecialize when p isn't opaque-able, e.g. NullParameters).
  • AutoDePSpecializeCallable{FW} parallels AutoSpecializeCallable{FW} — FW is the only type parameter (the OpaqueParams-keyed wrapper), with orig/ptype as type-erased fields, so problems with different parameter struct types share one Julia type (the whole point).
  • The ForwardDiff extension gains a dual-aware wrapfun_iip_opaque (plain + Jacobian-Dual-u signatures, OpaqueParams in the p slot); standardize_forwarddiff_tag already keys off is_fw_wrapped, which the new callable reports true.
  • Fallbacks stay correct: get_raw_f returns an OpaqueVoid (a non-FunctionWrapper callable that still accepts OpaqueParams); maybe_unwrap_prob_for_enzyme fully reverts under Enzyme (raw residual and p unpacked back to the concrete value), since Enzyme can't differentiate through the byte unpack.

Scope (conservative first PR)

Applies only to in-place NonlinearProblem/ImmutableNonlinearProblem, array non-dual state, outside Enzyme AD, with an isbits non-NullParameters p. NonlinearLeastSquaresProblem, OOP, dual-p sensitivity, and Enzyme keep their existing behavior. Follow-ups: NLLS support, an OpaqueRef path for non-isbits params (RespecializeParams already provides it).

Measured

Solve of a 2-var polynomial root with a struct parameter, NewtonRaphson (ForwardDiff Jacobian), BenchmarkTools medians:

median allocs
FullSpecialize 14.9 µs 76
AutoSpecialize 4.14 µs 72
AutoDePSpecialize 4.31 µs 70

AutoDePSpecialize is within ~4% of AutoSpecialize (and fewer allocs). The OpaqueVoid unpack itself is verified zero-allocation.

Changes

  • lib/NonlinearSolveBase/src/autospecialize.jl: should_opaque_p, AutoDePSpecializeCallable, wrapfun_iip_opaque (base), maybe_opaque_wrap; maybe_wrap_nonlinear_f accepts AutoDePSpecialize for the plain-wrap fallback; maybe_unwrap_prob_for_enzyme handles the opaque callable.
  • lib/NonlinearSolveBase/src/solve.jl: maybe_wrap_f tries the opaque path first.
  • lib/NonlinearSolveBase/ext/NonlinearSolveBaseForwardDiffExt.jl: dual-aware wrapfun_iip_opaque.
  • lib/NonlinearSolveBase/src/NonlinearSolveBase.jl: import RespecializeParams.
  • lib/NonlinearSolveBase/Project.toml: RespecializeParams = "1" dep; version 2.37.0 → 2.38.0.
  • lib/NonlinearSolveBase/test/autodepspecialize.jl + runtests entry: opaque-ifies isbits p; AutoSpecialize/FullSpecialize/NullParameters/non-isbits leave p alone or fall back; different struct p types share typeof(prob.f.f); unpack roundtrip; the wrapped call is @inferred.

Test plan

  • New autodepspecialize.jl tests pass (12/12).
  • End-to-end: NewtonRaphson, TrustRegion, NewtonRaphson(AutoFiniteDiff()) on a struct-parameter root problem — converge, match FullSpecialize to 1e-7, sol.prob.p isa OpaqueParams, unpack roundtrip, two struct types share typeof(sol.prob.f.f).
  • Full NonlinearSolveBase suite (running).

🤖 Generated with Claude Code

https://claude.ai/code/session_01UuAbA8hSnrirMrJjFqxwn5

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: Claude Fable 5 <[email protected]>
Co-Authored-By: Chris Rackauckas <[email protected]>
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review July 23, 2026 18:23
@ChrisRackauckas
ChrisRackauckas merged commit 8b85961 into SciML:master Jul 23, 2026
73 of 95 checks passed
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Extended to non-isbits parameters via OpaqueRef (mirrors SciML/OrdinaryDiffEq.jl#4005, the ODE follow-up to the now-merged #3692). should_opaque_p now de-specializes any non-NullParameters, non-already-packed p; maybe_opaque_wrap packs via pack_auto (isbits → OpaqueParams, otherwise → OpaqueRef), and wrapfun_iip_opaque already routes through wrap_void_opaque which picks the container by type, so the wrappers handle OpaqueRef unchanged. Forward-solve latency tool only — reverse-mode AD of p and symbolic indexing read the concrete parameter and are unsupported (reverse-mode is a planned follow-up); recover with unpack(sol.prob.p, typeof(p)). Full NonlinearSolveBase suite green, incl. the AutoDePSpecialize tests now covering OpaqueRef + idempotency.

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]>
ChrisRackauckas added a commit 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]>
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