Skip to content

Keep the specialization when rebuilding a SciML function - #1606

Merged
ChrisRackauckas merged 2 commits into
SciML:masterfrom
SebastianM-C:smc/constructorof-keep-specialization
Sep 23, 2026
Merged

ChrisRackauckas merged 2 commits into
SciML:masterfrom
SebastianM-C:smc/constructorof-keep-specialization

Conversation

@SebastianM-C

@SebastianM-C SebastianM-C commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

ConstructionBase.constructorof for the SciML function types rebuilds with DEFAULT_SPECIALIZATION. So any @set f.x = ... / @set prob.f.x = ... (Accessors/Setfield, setproperties) silently changes the specialization: a FullSpecialize function comes back AutoSpecialize, and so does an AutoDespecialize one (e.g. what MTK builds by default).

fn = ODEFunction{true, SciMLBase.FullSpecialize}(f!)
SciMLBase.specialization(@set fn.initialization_data = nothing)  # AutoSpecialize

Since DiffEqBase 7.21.2 type-erases the callbacks of AutoSpecialize problems, this has a real cost. A downstream package stripped initialization_data from its FullSpecialize shooting problems with @set. Its first exact-Hessian (SecondOrder(AutoForwardDiff(), AutoForwardDiff())) calibration then compiled the erased callback path for every Float64/Dual/Dual{Dual} integrator: 282 s instead of 40 s. With this PR alone (no downstream change) it is back to 41 s.

History: the reset dates back to 2022. Callback erasure is simply the first change that made it expensive.

  • add unwrapping specializations for scimlfunctions #230 (August 2022, v1.52.0) added the specialization type parameter. Its first commit kept the specialization in constructorof, but by the time it merged, constructorof rebuilt with a hardcoded FullSpecialize. From then on, every @set on a SciML function returned a FullSpecialize one. Nobody noticed, because most functions were FullSpecialize anyway.
  • Use DEFAULT_SPECIALIZATION for all SciMLFunction constructors #1298 (March 2026, v2.153.0) switched the NonlinearFunction constructors to DEFAULT_SPECIALIZATION (AutoSpecialize), and its sweep changed constructorof along with them. From then on, @set turned FullSpecialize and AutoDespecialize functions into AutoSpecialize ones. That was still free, since AutoSpecialize didn't change anything that mattered for callbacks yet.
  • Despecialize callbacks across solver specialization levels OrdinaryDiffEq.jl#4376 (DiffEqBase 7.21.2, September 2026) type-erases the callbacks of AutoSpecialize problems on Julia ≥ 1.12. That made the reset costly: 40 s → 282 s in the downstream package above.

Change: a single constructorof method that keeps the specialization of the type being rebuilt. The default applies only when the type leaves it unbound (e.g. constructorof(ODEFunction{true})). The field parameters are still narrowed to the new values' types, as before; DiffEqBase relies on that after widen_bounded_type_params, and a test covers it.

Related PRs. These came out of tracking this down. In merge order:

  1. Don't re-despecialize an already concretized AutoDespecialize function OrdinaryDiffEq.jl#4599: makes DiffEqBase promote_f idempotent for concretized AutoDespecialize functions. Needed before this PR (details below).
  2. Keep the unwrapped adjoint problem out of AutoDespecialize NonlinearSolve.jl#1324: keeps the unwrapped adjoint problem out of AutoDespecialize. Needed before this PR (details below).
  3. This PR.
  4. Erase and wrap the callbacks of AutoRespecialize problems (stacked on #4599) OrdinaryDiffEq.jl#4604, stacked on 1: erases and wraps the callbacks of AutoRespecialize problems. Those problems only got that through the reset; without it they lose model-to-model reuse once this PR lands (MTK, jac + Rodas5P: second model's first solve 0.37 s → 1.85 s on Julia 1.13.0). It can merge any time after 1.

Depends on a DiffEqBase fix. With the specialization kept, the downstream DiffEqBase test despecialized_p_test.jl ("AutoDespecialize uses the dynamic parameter barrier") fails: promote_f is not idempotent for an already concretized AutoDespecialize function.

  • It widens the bounded type parameters, then skips the wrapping step that would narrow them back.
  • Today this is masked because the first concretization's @sets reset the problem to AutoSpecialize, so the second pass never takes the despecialize branch.
  • The companion DiffEqBase change, Don't re-despecialize an already concretized AutoDespecialize function OrdinaryDiffEq.jl#4599, skips re-despecializing an already wrapped function. With it, despecialized_p_test.jl passes with both this branch and released SciMLBase 3.55.0.
  • So the DiffEqBase change should be released first. Until then, the OrdinaryDiffEq/Core downstream job here is expected to fail on that one test.

Also depends on a NonlinearSolveBase fix. SciMLSensitivity Core8 "Mooncake through init" (desauty_dae_mwe.jl:163) fails with this PR.

  • NonlinearSolveBase's ChainRules solve_up rule strips the residual wrapper with @set prob.f.f = .... The old reset made that problem AutoSpecialize.
  • Now it stays AutoDespecialize, so when the adjoint concretizes the unwrapped problem again, p is wrapped back into DespecializedParameters. The parameter tangent gains an extra params field, and Mooncake rejects it.
  • Keep the unwrapped adjoint problem out of AutoDespecialize NonlinearSolve.jl#1324 builds the unwrapped problem as AutoSpecialize explicitly. With it, that test passes with this branch and with released SciMLBase alike. It should be released first as well; until then Core8 is expected to fail on that test here.

Other CI failures here are unrelated. They also fail on master, at the same test locations with the same messages:

  • SymbolicIndexingInterface lts/1 (SCCNonlinearProblem has no field u0) and QA (Base.Callable non-public access).
  • SciMLSensitivity Core1/6/7 (complex/Tracker adjoints, a Mooncake segfault, _vecjacobian(::SVector)).
  • Core8 "Enzyme through init" (desauty_dae_mwe.jl:123, EnzymeNoTypeError). This is Core8's other failure; unlike "Mooncake through init" above, it also fails on master and with released SciMLBase.
  • Catalyst (test/extensions/Project.toml: Permission denied on the runner).

Also fixed here, since this PR exposes it: _remake_odeproblem rewrapped an out-of-place FunctionWrapperSpecialize function with the in-place argument tuple (u, u, p, t) instead of (u, p, t). So the remade function threw "No matching function wrapper". Previously the specialization reset kept get_concrete_problem out of that branch; with the specialization kept, solve goes through it. A new downstream test (test/downstream/function_wrapper_remake.jl) fails on 3.55.0 and passes with the fix.

Local verification (Julia 1.12.5; the tests were re-run on 1.12.7 and 1.13.0 with the same results): test/problem_building_test.jl passes, detect_ambiguities reports nothing for constructorof, and the Core group passes (including Remake).

Written by Claude Code on Sebastian's behalf.

🤖 Generated with Claude Code

https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP

`ConstructionBase.constructorof` for SciML functions always rebuilt with
`DEFAULT_SPECIALIZATION`, so `@set f.x = ...` (or `@set prob.f.x = ...`)
turned a `FullSpecialize` function into an `AutoSpecialize` one, and an
`AutoDespecialize` one (e.g. MTK's default) into `AutoSpecialize` as well.
With DiffEqBase's callback type erasure for `AutoSpecialize` problems, the
silent change made a downstream package's first calibration compile ~8x longer.

Keep the specialization of the type being rebuilt; the default applies only
when the type leaves it unbound (e.g. `constructorof(ODEFunction{true})`). The
field parameters are still narrowed to the new values' types, which DiffEqBase
relies on after `widen_bounded_type_params`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP
@SebastianM-C
SebastianM-C force-pushed the smc/constructorof-keep-specialization branch from dbda0c1 to 5adcd4a Compare September 23, 2026 11:29
@SebastianM-C SebastianM-C changed the title Keep the specialization and field parameters when rebuilding a SciML function Keep the specialization when rebuilding a SciML function Sep 23, 2026
…)` in remake

`_remake_odeproblem` rewrapped an out-of-place `FunctionWrapperSpecialize`
function with the in-place argument tuple `(u, u, p, t)`, so calling the
remade function (or solving the remade problem) failed with "No matching
function wrapper". The problem constructor and the BVP remake already use
`(u, p, t)`.

Previously `get_concrete_problem` rarely reached this branch, because the
`@set`s in DiffEqBase's `promote_f` reset the specialization to
`AutoSpecialize`; with the specialization kept, `solve` goes through it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review September 23, 2026 21:36
@ChrisRackauckas
ChrisRackauckas merged commit b7076b5 into SciML:master Sep 23, 2026
64 of 73 checks passed
@SebastianM-C
SebastianM-C deleted the smc/constructorof-keep-specialization branch September 23, 2026 21:38
ChrisRackauckas referenced this pull request Sep 26, 2026
Agent-Harness: Claude Code
Agent-Model: claude-opus-5-5[1m]
Agent-Session: local Claude Code session 3cd6500a-1f81-46b5-ac0b-c466e15b6a53 on Chris's Mac (session ID, no URL)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
ChrisRackauckas pushed a commit to SciML/OrdinaryDiffEq.jl that referenced this pull request Sep 27, 2026
#4599)

* Don't re-despecialize an already concretized AutoDespecialize function

`promote_f` widens the bounded type parameters of an `AutoDespecialize`
function (`_despecialize_auxiliary_functions`) and relies on the `@set`s of
the wrapping step to narrow them back. For a function that is already wrapped
the wrapping step is skipped, so concretizing a concretized problem returned
the widened type (`initialization_data::Union{Nothing, OverrideInitData}`).

This was masked because SciMLBase's `constructorof` reset the specialization
to the default on every `@set`, so a concretized problem was no longer
`AutoDespecialize`. Once the specialization survives (SciML/SciMLBase.jl#1606),
`despecialized_p_test.jl` catches it. Skip the auxiliary despecialization for
an `f` whose RHS is already wrapped; this works with either SciMLBase.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP

* Handle functions without an `f` field and SDEs in `_is_concretized`

`_is_concretized` read `f.f`, which `DynamicalODEFunction` (`f1`/`f2`) does not
have, so every `AutoDespecialize` `DynamicalODEProblem` threw a `FieldError`
when concretized. It also excluded `SDEFunction` outright, so an SDE wrapped by
the non-ForwardDiff path was despecialized again on a second concretization,
re-widening its `ID` parameter. Treat a function without an `f` field as not
wrapped, and an `SDEFunction` as wrapped when both drift and diffusion are,
matching the skip condition of the wrapping step.

Add an idempotency testset covering a plain `AutoDespecialize` ODE (no
jac/tgrad, which the existing test relies on), an SDE on the non-ForwardDiff
path and a `DynamicalODEProblem`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP

* Qualify `NoRecompileArgumentError` in the ForwardDiff extension

`wrapfun_oop` threw `NoRecompileArgumentError(IT)` unqualified, but the error
type lives in DiffEqBase, so the unsupported-signature path raised an
`UndefVarError` instead of the intended error.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP

* Test the unsupported-signature error of the ForwardDiff extension

An out-of-place `FunctionWrapperSpecialize` problem with argument types that
have no precompiled wrapper signature must raise `NoRecompileArgumentError`.
Before the previous commit it raised an `UndefVarError`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Check the idempotency of `promote_f` without `remake`

SciMLBase 3.56.1 (SciML/SciMLBase.jl#1616) makes `remake` keep the narrowed
metadata types when a concretized `AutoDespecialize` function is replaced by a
re-widened one. That hides a non-idempotent `promote_f` from the problem-level
checks, so these now pass without the fix. Also compare the output of the
`promote_f` call of `get_concrete_problem` on an already concretized problem
directly, for the plain ODE and the SDE cases.

The `DynamicalODEFunction` case is left at the problem level: there
`promote_f` widens `ID` on every pass and `remake` narrows it back, so its
output never matches the concretized function.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.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