Skip to content

Erase and wrap the callbacks of AutoRespecialize problems (stacked on #4599) - #4604

Draft
SebastianM-C wants to merge 5 commits into
SciML:masterfrom
SebastianM-C:smc/callback-erasure-specialization
Draft

SebastianM-C wants to merge 5 commits into
SciML:masterfrom
SebastianM-C:smc/callback-erasure-specialization

Conversation

@SebastianM-C

Copy link
Copy Markdown
Member

Stacked on #4599. This branch contains #4599's commits; only the last two are new here:

  • Erase the callback types of AutoRespecialize problems (DiffEqBase)
  • Wrap the erased callbacks of AutoRespecialize integrators (OrdinaryDiffEqCore)

Why: SciML/SciMLBase.jl#1606 makes @set on a SciML function keep its specialization. Before it, promote_f's @set f.jac_prototype / jac / tgrad rebuilds reset every problem to AutoSpecialize, so callback erasure (_erases_callback_types) and integrator callback wrapping (_despecialize_callbacks!) applied to any problem with those auxiliary functions, whatever its specialization level. With the specialization kept:

  • ModelingToolkit's default AutoDespecialize problems are unaffected: they are in both lists. Checked for jac = true, sparse = true, tgrad, mass-matrix ODEs and DAEProblem.
  • AutoRespecialize (=== AutoDePSpecialize) is in neither list, so its problems lose the erasure/wrapping they only got through the reset (jac on a ForwardDiff solver, or sparse).
  • FullSpecialize + jac_prototype now keeps typed callbacks. That's intended and not restored here.

Change: add AutoRespecialize to _erases_callback_types and to the _despecialize_callbacks! gate. SciMLBase documents it as extending AutoSpecialize, so its callbacks now follow AutoSpecialize regardless of which auxiliary functions the problem carries. NoSpecialize stays erased but unwrapped, as designed: wrapping measured +0.2 s on the first solve and no gain afterwards.

Compile-time impact on MTK-generated problems (Julia 1.12.5, MTK 11.45.1). Each cell is the median of 5 fresh processes: first solve of model A / first solve of a different model B with the same structure, in the same process. "released" = SciMLBase 3.55.0 + DiffEqBase 7.21.2; "#1606 + #4599" = those two PRs; "+ this" = plus this PR.

MTK problem released #1606 + #4599 + this
default (AutoDespecialize), continuous event, jac, Rodas5P 3.39 / 0.46 s 3.40 / 0.47 s 3.48 / 0.47 s
AutoRespecialize, continuous event, jac, Rodas5P 3.61 / 0.37 s 3.31 / 2.00 s 3.58 / 0.37 s
AutoRespecialize, discrete event, jac, Rodas5P 3.30 / 0.34 s 3.14 / 1.89 s 3.31 / 0.34 s
AutoRespecialize, continuous event, Rodas5P (no jac) 3.11 / 2.21 s 3.10 / 2.21 s 3.45 / 0.36 s
AutoRespecialize, continuous event, Tsit5 1.41 / 1.27 s 1.41 / 1.25 s 1.70 / 0.33 s
AutoRespecialize, continuous event, jac, Tsit5 1.48 / 1.04 s 1.49 / 1.03 s 1.79 / 1.32 s
  • The regression (model B reuse lost with QNDF2, QBDF2, QNDF, FBDF, Rosenbrock23 fail where Rodas4 and Rodas4P have success.  #1606) is restored exactly.
  • Plain AutoRespecialize now gets erasure too: model B is 0.8–1.9 s faster, and the first solve costs about 0.2–0.35 s more (the same cost appears without callbacks).
  • Trade-off: AutoRespecialize + jac + a non-ForwardDiff solver (e.g. Tsit5) costs about +0.3 s per model. On that path promote_f doesn't wrap jac, so the integrator type depends on the model's jac and every model recompiles anyway. Wrapping jac/tgrad on the non-ForwardDiff path would be a separate follow-up.
  • MTK default rows match within noise across all three combos (full tables available).

Numerics: final states match bit for bit across the three combos for all 48 model/setting/solver/specialization cells. DDE/SDE smoke tests give identical values; AutoRespecialize SDE callbacks are now erased, DDEs unchanged.

Tests:

  • DiffEqBase test/high_level_solve.jl: a new block, gated on VERSION >= v"1.12". Erasure follows the concretized specialization for 5 levels, with and without jac_prototype; AutoRespecialize is always erased; FullSpecialize without a prototype stays typed.
  • test/InterfaceII/despecialized_parameters.jl: AutoRespecialize added to the existing loops, plus testsets for callbacks staying erased and wrapped when Rosenbrock23 wraps a jac, and for FullSpecialize staying typed. Without this change: 23 failed / 2 errored.
  • Pass with both released SciMLBase and QNDF2, QBDF2, QNDF, FBDF, Rosenbrock23 fail where Rodas4 and Rodas4P have success.  #1606. Runic clean.

No compat bumps: with only DiffEqBase updated, AutoRespecialize callbacks are erased but not wrapped, like NoSpecialize. Enzyme stays gated off by the existing Julia ≥ 1.12 condition. This change adds new specialization/erasure combinations, not new type paths; it was not tested with Enzyme.

Written by Claude Code on Sebastian's behalf.

🤖 Generated with Claude Code

https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP

SebastianM-C and others added 5 commits September 23, 2026 14:29
`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
`_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
`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
`_erases_callback_types` erased callbacks for `AutoSpecialize`,
`AutoDespecialize` and `NoSpecialize` but not for `AutoRespecialize`, which
extends `AutoSpecialize`. The gap was hidden because SciMLBase's
`constructorof` reset the specialization to the default on every `@set`: an
`AutoRespecialize` problem with a `jac_prototype`, or with a `jac`/`tgrad` on a
ForwardDiff-based solver, came out of `promote_f` as `AutoSpecialize` and had
its callbacks erased, while one without them kept its callbacks typed. With
the specialization kept on `@set` (SciML/SciMLBase.jl#1606) those problems stay
`AutoRespecialize` and lose the erasure, e.g. ModelingToolkit's
`ODEProblem{true, AutoRespecialize}(sys, ...; jac = true)` with events.

Erase the callbacks of every `AutoRespecialize` problem, so its callback
handling no longer depends on which auxiliary functions it carries.
`FullSpecialize` keeps its callbacks typed; `NoSpecialize` was already erased.

Test that the erasure follows the specialization of the concretized function,
with and without a `jac_prototype`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP
`_despecialize_callbacks!` wraps the conditions and affects of the erased
callbacks of `AutoSpecialize` and `AutoDespecialize` integrators so that the
callback machinery compiles once per integrator type. `AutoRespecialize`
extends `AutoSpecialize` and now has its callbacks erased by DiffEqBase, so
wrap them too. Before SciMLBase kept the specialization on `@set`, an
`AutoRespecialize` problem with a `jac_prototype` (or a `jac`/`tgrad` on a
ForwardDiff-based solver) reached the integrator as `AutoSpecialize` and got
this wrapping by accident. `NoSpecialize` still leaves its entries unwrapped,
as it leaves `f`.

Run the existing callback erasure and wrapping testsets for
`AutoRespecialize`, and test that the callbacks stay erased and wrapped when
`promote_f` wraps a Jacobian, and that `FullSpecialize` keeps them typed.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP
# level erases them, `FullSpecialize` keeps them typed. `AutoRespecialize` extends
# `AutoSpecialize` and erases them with or without a `jac_prototype`, whose `@set` in
# `promote_f` rebuilds the function.
@static if VERSION >= v"1.12"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this version dependent?

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it mirrors

VERSION >= v"1.12" || return false

which says that it's related to older Enzyme versions aborting on Vector{Any}

@ChrisRackauckas

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

PR: #4604

Reviewed head: de91b60
Raw SHA-256: aaf16f303730e9e3c8682ec562f779f20c87fd97cf29bd1e1853c6e95be68fb9
Source SHA-256: 6ee17e0f0aa877ad78d995f849e920e1bc95cd539d2680b14800b9879a8bad97
Source: operator-attested-codex-v1 (runner attested by pankgeorg)
Reviewer session: 01a22352-abf0-7da1-9e00-b4e52356c981
Slot: 1
Confidence: unknown
Own risk fixed before author rating/discussion: yes
Redaction: ran (substitutions=0)

Risk assessment

  • Risk: medium-high (MH1)
  • Verdict: CHANGES
  • Reviewed head: de91b60

Review report

VERDICT: CHANGES
PR: #4604
Head: de91b60
Base: 91d6176
Reviewer: codex-cli 0.172.0 / gpt-6.2-sol
Session: 01a22352-abf0-7da1-9e00-b4e52356c981

Risk

medium-high (MH1: the patch changes callback dispatch, cache use, and function promotion on core solve and init paths).

The affected users select AutoRespecialize for callback-based solves, reconcretize wrapped AutoDespecialize problems, or use the ForwardDiff out-of-place wrapper. Callback erasure activates on Julia 1.12 and newer. The changes sit in problem preparation and integrator initialization, downstream of modeling compilation and separate from default solver selection.

Blocking findings

  • P1 · lib/DiffEqBase/src/solve.jl:112. With supported SciMLBase 3.54.0 and the AutoRespecialize preference, init(prob, Tsit5()) now erases and wraps a callback on an explicitly FullSpecialize ODE with jac_prototype=zeros(1,1). Base kept the original typed callback. The @set in promote_f rebuilds the function under the preference, then _erases_callback_types accepts that rebuilt marker. SciMLBase 3.58.0 preserves the explicit marker and callback in the same probe. Preserve specialization through the field rebuilds in both promote_f methods, or raise the SciMLBase floor to the first release verified to preserve it. I recommend preserving the current compatibility range if the rebuild can be localized. Assert both specialization(concrete.f) === FullSpecialize and callback identity after init. The new matrix at lib/DiffEqBase/test/high_level_solve.jl:123 derives the expected erasure from the rebuilt function and passed 15/15 on 3.54.0 despite the marker loss. Derive expectations from the requested specialization.

  • P2 · lib/DiffEqBase/src/solve.jl:1026 and :1190. With SciMLBase 3.58.0, a second direct promote_f on a wrapped AutoDespecialize DAE residual with a matrix Jacobian prototype changes its type in both promotion paths. Base retained the type. Replacing the prototype narrows the metadata fields, then _is_concretized skips the DAE widening step. Keep that widening for DAE functions and assert that two direct promotions return the same function type and evaluate the same residual, with and without ForwardDiff. The public get_concrete_problem and DAE solve probes passed, so the reproduced regression is in the promotion helper.

  • P2 · lib/DiffEqBase/ext/DiffEqBaseMooncakeExt.jl:124. The Mooncake rule calls the changed promote_f path and branches on whether it returns the original function. The supplied Julia 1 AD run was cancelled, and the local cache could not resolve Mooncake. Add a rule-level test with an already wrapped AutoDespecialize function and already packed parameters, asserting identity and tangent propagation, and show the named test passing at the revised head. The local ForwardDiff result covers a different backend. Exact-head AD run

Nonblocking findings

  • lib/DiffEqBase/ext/DiffEqBaseForwardDiffExt.jl:58 fixes the unsupported out-of-place signature probe. It threw UndefVarError on base and DiffEqBase.NoRecompileArgumentError on head. Add that assertion to an active DiffEqBase test file. The root no-recompile include is already commented out at test/runtests.jl:60.
  • lib/OrdinaryDiffEqCore/src/solve.jl:84 trades compilation reuse for warm solve cost in the local continuous-callback benchmark. Distinct closures shared an integrator type on head. Across two run orders, warmed Tsit5 solves took 22–24 µs and allocated 11.8–12.1 kB on base, versus 65–83 µs and 24.3–25.0 kB on head. Terminal values matched. Add a callback-specific benchmark that reports both time to first solve and warmed throughput. The supplied benchmark jobs give conclusions without measurements for this workload. Benchmark job

What I ran

  • git apply --check ../changes.diff from before/, git diff --no-index --check before head, and diff -qr before head. The patch applied cleanly, the whitespace check reported no issues, and the snapshots differed in the six patched files. I parsed ci.json with python3 and traced the relevant groups to their test includes. Exact-head InterfaceII and DiffEqBase Core report success on the Julia 1 lane. InterfaceII · DiffEqBase Core
  • On ARM64 Julia 1.13.4, I instantiated a scratch project from the local cache and ran the three changed test files with julia --startup-file=no --project=.review/<env> -e '… include(…) …'. All passed on head with SciMLBase 3.58.0. The despecialization file passed 64/64. With SciMLBase 3.54.0, the same file had four idempotency failures on base and passed 64/64 on head. On 3.58.0, the direct ODE and SDE promotion probes failed three assertions on base and passed all three on head.
  • I ran the paired scratch probes with julia --startup-file=no --compiled-modules=existing --project=.review/<env> .review/<probe>.jl. These covered specialization and callback identity, raw promotion, solver convergence, ForwardDiff, and the benchmark. The first ODE probe used an absolute bound of 1e-8 that Rosenbrock23 exceeded equally on both snapshots. The refinement check passed 16/16 on each.
  • G1. For (u'=-2u), (u(0)=1), with a jump (a) at (t=0.5), the exact terminal value is (e^{-2}+a e^{-1}). At the tighter tolerance, the maximum terminal errors were (4.11\times10^{-13}) for Tsit5 and (1.67\times10^{-8}) for Rosenbrock23, identical on base and head. Both located the event at 0.5. ForwardDiff gave (0.3678794411737085) for the derivative with respect to the jump, within (2.27\times10^{-12}) of (e^{-1}) on both. The DAE decay error halved from (1.056\times10^{-3}) to (5.283\times10^{-4}) under step refinement. The zero-diffusion EM solve with a discrete jump matched its exact step recurrence within (5.56\times10^{-16}) on both.
  • G3. I initialized two integrators with the same callback closure type and different captured jumps before solving either. Each returned its own analytical endpoint, which would catch reuse of the other integrator’s callback payload. The InterfaceII tests also passed the integrator-type and solver method-instance reuse assertions.
  • julia +lts --startup-file=no --project=.review/<lts-env> -e '… include(…) …' ran the changed DiffEqBase files on Julia 1.10.14. All 64 despecialization assertions passed on head. The high-level file had the same one failure and three errors on both snapshots at lines 94–101. Those existing assertions expect erasure on a Julia version where the implementation disables it. Exact-head LTS Core run

What I did not verify

  • G2. I did not exercise Enzyme through AutoRespecialize callbacks. An exact-head Julia ≥1.12 run of the event Jacobian case with that specialization, checking against its closed-form derivative, would establish the supported behavior. The AD run on the Julia 1 lane was cancelled. AD run
  • I did not exercise GPU-only solves on ARM64. The exact-head root GPU run was cancelled. The patch edits shared CPU-side preparation and callback dispatch and contains no GPU kernel, Reactant, or MPI implementation edits. A CUDA job would need to show an AutoRespecialize solve with callbacks actually running and matching an analytical event time and endpoint. GPU run
  • I did not run DDE or SDDE callback solves or ModelingToolkit-generated problems through the changed specialization. DDE and zero-diffusion SDDE tests with (u'(t)=u(t-1)), constant unit history, (u(0)=0), and a jump of 2 at 0.5 should reach 2.75 at 0.75. A ModelingToolkit test should exercise a generated problem with an explicit specialization, Jacobian prototype, and callback. The supplied downstream success conclusions do not identify those inputs.

Head link: de91b60


🤖 Posted by an AI agent — harness: codex-cli 0.172.0 · model: gpt-6.2-sol
Conversation: local session 01a22352-abf0-7da1-9e00-b4e52356c981 (no session URL)

This branch has not been deployed

No deployments
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