Repository navigation
Despecialize callbacks across solver specialization levels - #4376
Merged
ChrisRackauckas merged 6 commits intoSep 17, 2026
Merged
ChrisRackauckas merged 6 commits into
ChrisRackauckas merged 6 commits into
Conversation
ChrisRackauckas-Claude
force-pushed
the
autospecialize-callback-wrappers
branch
2 times, most recently
from
September 11, 2026 02:37
8f0bea3 to
98205cc
Compare
Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Chris Rackauckas <[email protected]>
Two problems surfaced once the branch was rebased onto current master. Custom initialize/finalize hooks treat `affect!` as an object, not a function: DiffEqCallbacks' `saving_initialize` reads and mutates `cb.affect!.saveat_cache`, and `initialize_manifold_projection` dispatches on `::ManifoldProjection`. A FunctionWrapper supports neither, so only wrap callbacks whose hooks are the SciMLBase defaults. The condition wrappers pinned every argument slot to one observed concrete type, but callers disagree: `get_condition` passes a view of `callback_cache.tmp_condition` while `find_discontinuity` passes a plain vector, and the state slot varies between `u`, `uprev`, the tmp cache, a view, and a scalar. FunctionWrapper converts each argument rather than re-dispatching, so pin only the integrator slot and leave the rest `Any`. Type erasure still keeps the callback type constant, which is what holds the integrator and `solve!` method instances fixed. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011zATW7VHYDA8rNUr5JR73e
`get_concrete_problem` and `merge_problem_kwargs` now give every AutoSpecialize, AutoDespecialize, and NoSpecialize problem a type-erased `callback`, including one built without any callback, so that adding a callback does not change the solver type. Two DiffEqBase testsets asserted the previous contract: `high_level_solve.jl` dispatched `__solve` on the original problem type and required `get_concrete_problem` to return it identically, and `problem_kwargs_merging.jl` compared the merged kwargs and the surviving callback by identity. Both now assert the new contract directly rather than around it, and each keeps a FullSpecialize case pinning the old strict-identity behavior, so the gate deciding which specialization levels erase stays covered both ways. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011zATW7VHYDA8rNUr5JR73e
ChrisRackauckas-Claude
force-pushed
the
autospecialize-callback-wrappers
branch
from
September 13, 2026 00:10
98205cc to
d00d0ca
Compare
…e erased paths precompilable
Callback wrapping now uses the tool SciMLBase already uses for `f`:
`FunctionWrappersWrapper` with the signatures the integrator actually passes
and a cached typed fallback for the rest, plus `SciMLBase.Void` for affects.
This replaces hand-rolled closures over `FunctionWrapper` whose argument
slots had to be widened to `Any` because `get_condition`, `find_discontinuity`
and the `idxs` variants disagree on the state and output types. Wrapping now
applies to `AutoDespecialize` as well as `AutoSpecialize`, mirroring
`promote_f`; `NoSpecialize` keeps callbacks as plain `Any` entries as it
keeps `f`. Callbacks are rebuilt with `@reset` instead of positional
constructors, and the wrapped set is built fresh and assigned to the
options rather than mutating the erased vectors in place, which also removes
the per-solve copy in `_erase_callback_types`.
The erased vectors cost a 5x cold start with no callbacks at all: loops over
`Vector{Any}` get their bodies inferred with abstract types where the tuple
loops were statically empty, and two abstract edges left in the precompiled
`solve!` were invalidated by extensions the umbrella loads. `value(::Any)`
came from the residual returned by a dynamic `find_callback_time`;
`nextfloat(::Any)` came from `disco_probs` keeping an abstract element type
when no callback uses discontinuity detection. Type-erased callbacks are now
called through `Base.inferencebarrier` with the event time and residual
converted on the callee side, and `disco_probs` gets its concrete problem
type up front, since the zero function is always behind the same
`FunctionWrapper`.
DelayDiffEq's `calck` default compared against `CallbackSet()` by identity,
which an erased empty set never satisfies; it now uses `isempty`.
Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_011zATW7VHYDA8rNUr5JR73e
…ilable
CI on the previous revision surfaced six consequences of storing callbacks
type-erased, all present since the first version of this branch:
`_ode_init` and DelayDiffEq defaulted `calck` by comparing the callback
against `CallbackSet()`, which an erased empty set is never `===` to, so
every despecialized solve did dense-output work per step (FBDF allocated
48 bytes per step; the low-storage integrators grew past their storage
ratios). Both now use `isempty`.
Whether a vector callback is present is not known from an erased set's
type, so `callback_cache` inferred as `Union{Nothing, CallbackCache}` and
`init` was no longer `@inferred`. For erased sets the integrator's cache
field is now typed as that union up front, with the cache type inferred
rather than built, so the integrator type is fixed and a callback-free
solve still constructs no cache.
`get_concrete_problem` erased before the u0/p/tspan promotions, and the
ForwardDiff extension's `promote_tspan` decides on `prob.kwargs[:callback]`
at run time for an erased set, which cost inference under a gradient. It
now erases last.
The discontinuity problems kept an abstract element type when no callback
used discontinuity detection, leaving abstract call edges into the
bracketing solver that `nextfloat(::Dual)` invalidated; their type is now
inferred up front and does not depend on `p`, since the zero function
reads its state from its own struct. That state is loaded through a typed
helper rather than dynamic `setproperty!` on the untyped `FunctionWrapper`
payload, which Enzyme's forward mode could not compile.
`RODEProblem` and `BVProblem` cannot be rebuilt through
`ConstructionBase.setproperties`, which erasure needs, so erasure is limited
to the ODE, SDE, DAE, DDE and SDDE families and those two keep their
callbacks as given.
ExplicitImports flagged `SciMLBase.INITIALIZE_DEFAULT`/`FINALIZE_DEFAULT`
and `Base.inferencebarrier` as non-public; the default hooks are now read
off a callback built with none given, and the dynamic calls use
`Base.invokelatest`.
Enzyme's forward mode is exercised through continuous callbacks on the LTS
(test/AD gates Enzyme off on 1.11+), and it aborts LLVM verification on the
erased vector's dynamic dispatch instead of throwing the catchable error it
throws without erasure, taking down the whole test process. Callback
type-erasure is therefore restricted to Julia >= 1.12, where it has been
validated; older versions keep callbacks concretely typed, exactly as before.
The discontinuity index write goes through the same typed helper as the rest
of the zero-function state. On Julia < 1.12, where callbacks are not
erased, loading that state through a typed setter instead of a dynamic
`setproperty!` on the FunctionWrapper payload also lets Enzyme's forward mode
differentiate through a `ContinuousCallback`, which previously threw
`EnzymeNoDerivativeError`; the test/AD case becomes `@test` there and stays
`@test_broken` on 1.12+, where the erased path is not yet Enzyme-differentiable.
Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_011zATW7VHYDA8rNUr5JR73e
ChrisRackauckas
marked this pull request as ready for review
September 17, 2026 06:43
ChrisRackauckas
added a commit
that referenced
this pull request
Sep 17, 2026
Ships the callback despecialization across solver specialization levels (#4376): a CallbackSet-of-vectors initialize! path that avoids specializing on callback types. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.273 Agent-Model: claude-opus-5[1m] Agent-Session: 6a01e420-3436-4518-83cc-6cd853283cfb (local transcript; this harness publishes no conversation URL)
ChrisRackauckas
added a commit
that referenced
this pull request
Sep 17, 2026
Ships the callback despecialization across solver specialization levels (#4376): a CallbackSet-of-vectors initialize! path that avoids specializing on callback types. Agent-Harness: Claude Code 2.1.273 Agent-Model: claude-opus-5[1m] Agent-Session: 6a01e420-3436-4518-83cc-6cd853283cfb (local transcript; this harness publishes no conversation URL) Co-authored-by: Claude <[email protected]>
ChrisRackauckas
added a commit
that referenced
this pull request
Sep 17, 2026
Ships the callback despecialization (#4376, using the existing Base.isempty(::CallbackSet)) and symbolic-index resolution in the ODE/DDE integrator interpolants (#4469). Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.273 Agent-Model: claude-opus-5[1m] Agent-Session: 6a01e420-3436-4518-83cc-6cd853283cfb (local transcript; this harness publishes no conversation URL)
ChrisRackauckas
added a commit
that referenced
this pull request
Sep 17, 2026
Ships the callback despecialization (#4376, using the existing Base.isempty(::CallbackSet)) and symbolic-index resolution in the ODE/DDE integrator interpolants (#4469). Agent-Harness: Claude Code 2.1.273 Agent-Model: claude-opus-5[1m] Agent-Session: 6a01e420-3436-4518-83cc-6cd853283cfb (local transcript; this harness publishes no conversation URL) Co-authored-by: Claude <[email protected]>
This was referenced Sep 20, 2026
6 tasks done
ChrisRackauckas
added a commit
that referenced
this pull request
Sep 22, 2026
* Require the DiffEqBase release that erases callback types The despecialized callback paths call `DiffEqBase.find_first_continuous_callback(integrator, ::AbstractVector)` and `DiffEqBase.apply_discrete_callback!(integrator, ::AbstractVector)`, both added alongside them in #4376 and first released in DiffEqBase 7.21.2. The monorepo sources DiffEqBase from `lib/DiffEqBase`, so CI never resolves the floor: with 7.19-7.21.1 the callback is never erased and callback despecialization silently does nothing. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Agent-Harness: Claude Code 2.1.278 Agent-Model: claude-opus-5[1m] Agent-Session: https://claude.ai/code/session_01Wt79fZeNaZxiwQ3LagMYXH Claude-Session: https://claude.ai/code/session_01Wt79fZeNaZxiwQ3LagMYXH * Release OrdinaryDiffEqCore 4.18.0 Version bump only; no code changes in this commit. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Agent-Harness: Claude Code 2.1.278 Agent-Model: claude-opus-5[1m] Agent-Session: https://claude.ai/code/session_01Wt79fZeNaZxiwQ3LagMYXH Claude-Session: https://claude.ai/code/session_01Wt79fZeNaZxiwQ3LagMYXH --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
ChrisRackauckas
added a commit
that referenced
this pull request
Sep 23, 2026
The saveat-at-event tests took the event time from a `save_everystep = false` solve and reused it as `saveat` in solves with a different integrator type. Since #4376 the former can run pkgimage code while the latter is JIT-compiled, and `@muladd` may fuse differently in code compiled for different CPU targets, so the located root moved by a few ULPs and the exact-equality checks failed. The event time is now found with a scalar `saveat` solve that shares the integrator type. The AutoTsit5-vs-Tsit5 TerminateSteadyState check compared two different compiled algorithms bitwise; it now requires the same step count and agreement to rtol = 1e-5 per step (observed drift up to 7e-7, solver reltol 1e-3). Fixes #4589 Agent-Harness: Claude Code Agent-Model: claude-opus-5-5[1m] Agent-Session: https://claude.ai/code/session_012H1cxx1FFbAEP7nkpdapJc Claude-Session: https://claude.ai/code/session_012H1cxx1FFbAEP7nkpdapJc Co-authored-by: ChrisRackauckas-Claude <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This was referenced Oct 2, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed and why
Store solver callback sets behind type-erased vectors for
AutoSpecialize,AutoDespecializeandNoSpecialize, and route their execution through vector code paths, so that a new callback closure type no longer compiles a new solver. ForAutoSpecializeandAutoDespecializethe callbacks' condition and affect functions are additionally wrapped once the concrete integrator type is known, so the callback machinery itself (find_callback_time,apply_discrete_callback!, …) compiles once per integrator type too. This is the callback counterpart of whatDiffEqBase.promote_fdoes tofat the same levels, and it sits in the same place (get_concrete_problem).Builds on the vector-backed
CallbackSetfrom SciML/SciMLBase.jl#1541; the compat prerequisite #4374 is merged. Ignore this PR until reviewed by @ChrisRackauckas.Does it reuse compilation? Measured.
Compile time charged to
solve(prob, Tsit5(); callback = cb)for each new callback closure type (six distinct closure types per fresh Julia process; mean over types 2–6;Base.cumulative_compile_time_ns).firstis the first callback ever seen in the process;rtis the solve time of a 2-state oscillator over(0, 500)with an often-firing callback, once compiled.(seconds of compile per new closure type;
firstseconds;rtmilliseconds for ~500–580 accepted steps)solve!,perform_step!andhandle_callbacks!get no new method instances.FullSpecializeis unchanged.Vector{Any}container, ~2× on this deliberately callback-dominated microbenchmark. That is inherent to erasure, the same tradefmakes throughFunctionWrappersWrapper, and a small fraction on a realistic right-hand side.What the re-analysis found, and what this revision changes
A 5× cold-start regression with no callbacks at all, on the default level (not in the earlier PR body):
Cold compile time of
solve(prob, Tsit5())with no callback, seconds:With
using OrdinaryDiffEqTsit5alone the cold solve was 0.37 s, so the precompiledsolve!was there;using OrdinaryDiffEqinvalidated it.SnoopCompile.@snoop_invalidationsfound two chains with one cause — a loop overVector{Any}gets its body inferred with abstract types where the tuple loop was statically empty or concrete — each broken by an extension the umbrella loads:value(::ForwardDiff.Dual)←value(::Any)←find_first_continuous_callback(…, ::Vector{Any})←handle_callbacks!←loopfooter!←solve!— the residual came backAnyfrom the dynamicfind_callback_time.nextfloat(::ForwardDiff.Dual)←BracketingNonlinearSolve.__solve←solve(::IntervalNonlinearProblem)←find_discontinuity←loopheader!←solve!— with no discontinuity callbacksdisco_probsstayedVector{IntervalNonlinearProblem}; master never compiled that loop body because the tuple was empty.Fixed: type-erased callbacks are called through
Base.inferencebarrier, with the event time and residual converted on the callee side, anddisco_probsgets its concrete problem type up front (the zero function is always behind the sameFunctionWrapper, so the type does not depend on any callback). After the fix the umbrella cold solve is 0.39 s (0.36 s withOrdinaryDiffEqTsit5alone — parity) and the snoop finds no tree reachingsolve!orloopheader!.Design changes in the same revision:
FunctionWrapperthat, after the rebase fixes, hadAnyargument slots becauseget_condition,find_discontinuityand theidxsvariants pass different state/output types. SciMLBase's tool for exactly that isFunctionWrappersWrapper— listed signatures plus a cached typed fallback — and it now wraps callbacks with the signatures the integrator actually passes, usingSciMLBase.Voidfor affects.AutoSpecialize-only;promote_fwrapsfforAutoDespecializetoo, and callbacks now follow the same rule.NoSpecializekeeps callbacks as plainAnyentries, as it keepsf.@resetinstead of 17-positional-argument constructors.integrator.opts; the erased vectors are no longer mutated in place, which removes the per-solve copy in_erase_callback_types.calckdefault compared againstCallbackSet()by identity, which an erased empty set never satisfies; it now usesisempty.Where things belong. The vector loops next to the tuple splats are the pattern SciMLBase#1541 established for
save_discretes!& co., so their DiffEqBase counterparts belong where they are. Nothing here wants to move to MTK (its callbacks keep the default hooks when a system has no initialize affects, so they get wrapped like any other). The one thing that would belong in SciMLBase is doing the erasure in the problem constructors, so the type a user sees is the type the solver sees — that would also remove theget_concrete_problemidentity/prepare_algsurprise found on the last rebase — but it is a separate, larger change.CI failures from the first push of this revision, and how each is resolved
The first CI run of this revision was red across many jobs. Every failure fell into one of these classes; all are fixed here, verified locally (Julia 1.12 unless noted). The two pre-existing/unrelated ones are called out.
OrdinaryDiffEqBDFCoreFBDF perform_step! non-allocating(48 bytes);SSPRK/LowStorageRKCore + downgrade storage-ratio5 <= 4calckdefaulted viacallback !== CallbackSet(), never===for an erased empty set, so every despecialized solve did dense-output work per step!isempty(callback)(and the same in DelayDiffEq);step!back to 0 bytesRegression_II@inferred initreturns a 2-memberUnion;SDIRK/RosenbrockCore DAE@inferred solveunder nested ForwardDiffcallback_cache(NothingvsCallbackCache), and the discontinuity problem kept an abstract element typedisco_probsgets its concrete type viapromote_op, independent ofpOrdinaryDiffEqCore [QA]ExplicitImports non-publicINITIALIZE_DEFAULT/FINALIZE_DEFAULT/inferencebarrierBase.invokelatestfor the erased dynamic callsDiffEqDevTools/GlobalDiffEqCore (BVProblemprecompile) andStochasticDiffEq [Interface1](RODEProblem)@set prob.kwargsrebuilds throughConstructionBase.setproperties, whichRODEProblem/BVProblemhave no usable constructor fortests / Downstream,DiffEqBase [Downstream]unit-type errors (zero(::Type{<:Quantity}),NoDims)zeros(needszero(T)) and the disco prototype built[zero(tType), one(tType)]zero(T); the disco type is inferred, not constructedtests / AD (julia lts)Enzyme forward throughContinuousCallbackaborts LLVM verification (signal 6, kills the group)@test_brokenbecomes@testthere and stays@test_brokenon 1.12+StochasticDiffEq* [QA]JETConfigError: target_defined_modulesModelingToolkit.jl/SciMLSensitivity.jldownstreamFailing before / passing after
On clean upstream master with only the compiler regression test applied:
The regression counts
solve!method instances before and after solving otherwise identical problems with distinct callback closure types. It passes on this branch (see below), together with new tests thatAutoDespecializewraps,NoSpecializedoes not, custom-hook callbacks are stored as given, and the problem's own callback set stays unwrapped.Verification
Validated at merge-base d63b9c8 (master has since moved 36 commits; none touch these paths). Every group below run as
GROUP=<name> julia --startup-file=no --project -e 'using Pkg; Pkg.test()', exit 0, zero failures.Julia 1.12:
InterfaceI,InterfaceII,InterfaceIII,Integrators_I,Integrators_II,Regression_II,QA,DiffEqBase_Core,DiffEqBase_QA,OrdinaryDiffEqCore_QA,DelayDiffEq_Integrators,OrdinaryDiffEqSDIRK_Core,OrdinaryDiffEqBDF_Core,OrdinaryDiffEqSSPRK_Core,OrdinaryDiffEqLowStorageRK_Core,StochasticDiffEq_Interface1,Downstream,DiffEqBase_Downstream,DiffEqDevTools.AD: green on both Julia 1.10 (Autodiff Events 12 pass / 2 broken) and Julia 1.13 (5 pass / 1 broken). Julia 1.13 (CI's "1") also green forRegression_II,OrdinaryDiffEqSDIRK_Core,OrdinaryDiffEqBDF_Core,OrdinaryDiffEqCore_QA.Compile reuse (fresh process, seconds of compile charged per new callback closure type, mean of types 2-6):
FBDF
step!allocates 0 bytes; coldsolvewith no callback compiles in ~0.38 s (parity with master's 0.22 s class, vs the 1.27 s regression of the previous revision);@snoop_invalidations using OrdinaryDiffEqfinds no invalidation tree reachingsolve!orloopheader!.Diff: 12 files, +802/-74; source-only 370 added lines, 35 comments (9.5%). No public names added.
Not verified
GPU, downstream, and allowed-to-fail
julia prejobs were not run locally. Documentation was not built: no public API is added and no docs or docstrings are touched. The benchmark ran on a loaded machine (load ≈70, concurrently with the test groups); the 6–10× compile ratios are far outside that noise, the ±20% runtime differences between the PR as pushed and this revision are not.Reviewer notes
callbackkwarg afterget_concrete_problem) is unchanged from the previous revision and still reaches beyond the two DiffEqBase testsets that cover it.FunctionWrappersWrappersbecomes a direct test dependency of the root package (it was already a dependency of OrdinaryDiffEqCore and DiffEqBase)._condition_return_typeusesBase.promote_opon the user's condition; anything inference cannot pin down is boxed rather than coerced totypeof(t)as the earlier revision did.Links
🤖 Generated with Claude Code
https://claude.ai/code/session_011zATW7VHYDA8rNUr5JR73e