Repository navigation
Add AutoDePSpecialize specialization level (de-specialize p via OpaqueParams) - #1107
Conversation
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]>
|
Extended to non-isbits parameters via OpaqueRef (mirrors SciML/OrdinaryDiffEq.jl#4005, the ODE follow-up to the now-merged #3692). |
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]>
…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]>
Note
Draft PR — please ignore until reviewed by @ChrisRackauckas.
Summary
Implements the
AutoDePSpecializespecialization level for NonlinearSolve, the analog of SciML/OrdinaryDiffEq.jl#3692 (DiffEqBase). It extendsAutoSpecializeby additionally de-specializing the parameter object: for an in-placeNonlinearProblemwhosepis anisbitsnon-NullParameterspayload,pis packed into aRespecializeParams.OpaqueParamscontainer and the residual'sFunctionWrappersWrappersignature carriesOpaqueParamsin the parameter slot (viaRespecializeParams.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 onp(recovered by a type-stable, allocation-free unpack).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
AutoSpecializeinlib/NonlinearSolveBase/src/autospecialize.jl(maybe_wrap_nonlinear_f→AutoSpecializeCallableholding aFunctionWrappersWrapper+ the original). This PR adds the parallel opaque path:maybe_wrap_ffirst triesmaybe_opaque_wrap: forAutoDePSpecialize+should_opaque_p(p), it packspand wraps the residual throughRespecializeParams.wrap_void_opaque, returning a prob with bothf.f(anAutoDePSpecializeCallable{FW}) andp(anOpaqueParams) set. Otherwise it falls back to the existingmaybe_wrap_nonlinear_f(which now also plain-wrapsAutoDePSpecializewhenpisn't opaque-able, e.g.NullParameters).AutoDePSpecializeCallable{FW}parallelsAutoSpecializeCallable{FW}—FWis the only type parameter (theOpaqueParams-keyed wrapper), withorig/ptypeas type-erased fields, so problems with different parameter struct types share one Julia type (the whole point).wrapfun_iip_opaque(plain + Jacobian-Dual-usignatures,OpaqueParamsin thepslot);standardize_forwarddiff_tagalready keys offis_fw_wrapped, which the new callable reportstrue.get_raw_freturns anOpaqueVoid(a non-FunctionWrappercallable that still acceptsOpaqueParams);maybe_unwrap_prob_for_enzymefully reverts under Enzyme (raw residual andpunpacked 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 anisbitsnon-NullParametersp.NonlinearLeastSquaresProblem, OOP, dual-psensitivity, and Enzyme keep their existing behavior. Follow-ups: NLLS support, anOpaqueRefpath for non-isbitsparams (RespecializeParams already provides it).Measured
Solve of a 2-var polynomial root with a struct parameter,
NewtonRaphson(ForwardDiff Jacobian), BenchmarkTools medians:FullSpecializeAutoSpecializeAutoDePSpecializeAutoDePSpecialize is within ~4% of
AutoSpecialize(and fewer allocs). TheOpaqueVoidunpack 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_facceptsAutoDePSpecializefor the plain-wrap fallback;maybe_unwrap_prob_for_enzymehandles the opaque callable.lib/NonlinearSolveBase/src/solve.jl:maybe_wrap_ftries the opaque path first.lib/NonlinearSolveBase/ext/NonlinearSolveBaseForwardDiffExt.jl: dual-awarewrapfun_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 isbitsp;AutoSpecialize/FullSpecialize/NullParameters/non-isbits leavepalone or fall back; different structptypes sharetypeof(prob.f.f); unpack roundtrip; the wrapped call is@inferred.Test plan
autodepspecialize.jltests pass (12/12).NewtonRaphson,TrustRegion,NewtonRaphson(AutoFiniteDiff())on a struct-parameter root problem — converge, matchFullSpecializeto 1e-7,sol.prob.p isa OpaqueParams, unpack roundtrip, two struct types sharetypeof(sol.prob.f.f).NonlinearSolveBasesuite (running).🤖 Generated with Claude Code
https://claude.ai/code/session_01UuAbA8hSnrirMrJjFqxwn5