Skip to content

Don't re-despecialize an already concretized AutoDespecialize function - #4599

Merged
ChrisRackauckas merged 5 commits into
SciML:masterfrom
SebastianM-C:smc/despecialize-idempotent
Sep 27, 2026
Merged

ChrisRackauckas merged 5 commits into
SciML:masterfrom
SebastianM-C:smc/despecialize-idempotent

Conversation

@SebastianM-C

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

Copy link
Copy Markdown
Member

promote_f is not idempotent for an already concretized AutoDespecialize function:

  • For AutoDespecialize, _despecialize_auxiliary_functions runs SciMLBase.widen_bounded_type_params, which boxes the bounded type parameters (initialization_data, nlstep_data).
  • Only the @sets of the wrapping step narrow them back.
  • For a function whose RHS is already a FunctionWrappersWrapper, the wrapping step is skipped. So concretizing a concretized problem returns a different, widened function type.

This has been masked by SciMLBase: its ConstructionBase.constructorof resets the specialization to DEFAULT_SPECIALIZATION on every @set. After the first concretization the problem is no longer AutoDespecialize (it is AutoSpecialize while carrying DespecializedParameters), so the second pass never takes the despecialize branch.

SciML/SciMLBase.jl#1606 makes constructorof keep the specialization. With it, test/despecialized_p_test.jl ("AutoDespecialize uses the dynamic parameter barrier") fails on typeof(remade) === typeof(first_prob).

Change: skip the auxiliary despecialization for an f whose RHS is already wrapped (_is_concretized), in both promote_f methods.

Follow-ups found by a broader audit (a concretize-twice matrix over ODE/SDE/DAE/DDE/SDDE/Discrete/Split/Dynamical/RODE × specialization levels × {SciMLBase 3.55.0, #1606} × {DiffEqBase 7.21.2, this branch}):

  • _is_concretized now handles functions without an f field. The first version threw a FieldError for every AutoDespecialize DynamicalODEProblem/SecondOrderODEProblem.
  • It also treats an SDEFunction as wrapped when both drift and diffusion are. SDEs on the non-ForwardDiff path (e.g. EM) were not idempotent before this PR either: the ID parameter got re-widened.
  • New testset "concretizing a concretized problem is idempotent": a plain AutoDespecialize ODE (the existing test has jac/tgrad, whose @sets hid this), an SDE on the non-ForwardDiff path, and a DynamicalODEProblem.
  • Separate commit: qualify NoRecompileArgumentError in DiffEqBaseForwardDiffExt. The unsupported-signature path raised an UndefVarError instead of the intended error.

With these, despecialized_p_test.jl passes completely with both SciMLBase versions, the matrix shows no non-idempotent case, and 14 related DiffEqBase test files give identical results across the combos.

Verified locally (Julia 1.12.5): despecialized_p_test.jl passes completely with this change, with both released SciMLBase 3.55.0 and SciML/SciMLBase.jl#1606. It works with either SciMLBase version, so it can be released before #1606. The existing test already covers the case once #1606 is in.

CI notes: the failing jobs are all unrelated to this change:

  • The DiffEqBase and OrdinaryDiffEqDifferentiation downgrade jobs, and SciMLSensitivity Core1, fail on master as well.
  • DiffEqBase Core (lts) fails high_level_solve.jl:94–101, the same lines as master's DiffEqBase downgrade job: those tests expect callback erasure, which is gated to Julia ≥ 1.12.
  • GlobalDiffEq Core, OrdinaryDiffEqBDF QA and OrdinaryDiffEqDifferentiation Core also fail on other current PRs.
  • SciMLSensitivity Core3 hit a segfault inside LLVM's loop-unroll pass while Enzyme was compiling the gradient in Core3/default_alg_diff.jl:21. That test uses a plain AutoSpecialize problem, for which the new guard (despecialize && !_is_concretized(f)) is never evaluated, so the code that ran is identical to master's; master's Core3 passes. It looks like an intermittent compiler crash; a re-run should confirm it.

Written by Claude Code on Sebastian's behalf.

🤖 Generated with Claude Code Opus 5.5 (1M context)

https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP

`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
SebastianM-C and others added 2 commits September 23, 2026 15:12
`_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
Comment on lines +922 to +928
# Whether `promote_f` already wrapped `f` on an earlier concretization. The auxiliary
# despecialization widens the bounded type parameters, which only the `@set`s of the
# wrapping step narrow back, and that step is skipped for a wrapped `f`. So an `f` that
# is already wrapped must not be despecialized again, or concretizing a concretized
# problem would change its type.
# Functions without an `f` field (e.g. `DynamicalODEFunction`, which stores `f1`/`f2`)
# are never wrapped here.

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.

That seems wrong?

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.

with SciML/SciMLBase.jl#1606

using DiffEqBase, SciMLBase
using DiffEqBase: promote_f, _despecialize_auxiliary_functions
const AD = SciMLBase.AutoDespecialize
rhs!(du, u, p, t) = (du[1] = -p.rate * u[1]; nothing)
u0, p, t = [1.0], (; rate = 0.5), 0.0
initT(f) = fieldtype(typeof(f), :initialization_data)

f0 = ODEFunction{true, AD}(rhs!)
initT(f0)                                    # Nothing
initT(_despecialize_auxiliary_functions(f0)) # Union{Nothing, OverrideInitData}

f1, p1 = promote_f(f0, Val(AD), u0, p, t, Val(false))
initT(f1)  # Nothing: unwrapped_f rebuilds from typeof(field), narrowing it back
# Second call before this PR: it widens again, then the wrap step returns early
# because f1.f isa FunctionWrappersWrapper, so nothing narrows it back.
initT(_despecialize_auxiliary_functions(f1))  # Union{Nothing, OverrideInitData}
f2, _ = promote_f(f1, Val(AD), u0, p1, t, Val(false))  # with this PR
typeof(f2) === typeof(f1)  # true

(code by Claude Opus 5.5)

is the problem that wrapping undoes the widening? on the ODE/SDE wrap path an AutoDespecialize ends up with a concrete initialization_data type, which seems unwanted. is that what you are referring to?

@ChrisRackauckas

Copy link
Copy Markdown
Member

🤖 Automated review from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris. It is posted so that you can act on it. Chris or a maintainer may disagree.

Verdict: changes needed before merge (reviewed at 0d1cfda).

This makes repeated AutoDespecialize concretization preserve its type and fixes the ForwardDiff extension's unsupported-signature exception. The main regression tests and local Core suite pass, but the separate exception fix needs a committed regression test and the unmatched SciMLSensitivity Core3 failure needs resolution before merge.

Risk assessment

  • Risk: medium
  • Blast radius: AutoDespecialize ODE/SDE/DAE function promotion and unsupported out-of-place FunctionWrapperSpecialize signatures with ForwardDiff loaded; downstream AD remains incompletely validated.
  • Evidence: Read the complete three-file diff, description, all comments/reviews, and the linked SciMLBase prerequisite. No maintainer other than Chris is reviewing; Chris asked “That seems wrong?” on the new guard, and the author asked whether narrowing initialization metadata was the concern. The PR is open, not draft, and its head remains 0d1cfda. Head checks: 264 successful, 9 failed, 1 skipped. Detailed comparisons and local output follow.
  • Merge: needs changes (commit the exception regression test; resolve or establish the Core3 failure as unrelated).

Local verification, Julia 1.12.7:

  • GROUP=Core julia +1.12 --project=envs/head-master -e 'using Pkg; Pkg.test("DiffEqBase"; allow_reresolve=false)': Testing DiffEqBase tests passed; Despecialized-p Hook 64/64. This environment uses head DiffEqBase and SciMLBase 83b4fc38.
  • With SciMLBase b7076b57 (the prerequisite change), ran the head's complete despecialized_p_test.jl against base 91d6176 and head: base fails the existing type-identity assertion at line 128 (14 pass, 1 fail); head passes all 64 assertions. Extracted the new testset unchanged to review-newtests.jl: base gives 10 pass / 4 fail; head's complete-file run gives 14/14 for that testset.
  • With newer SciMLBase 83b4fc38, all 64 assertions pass on BOTH base and head: SciMLBase's subsequent remake guard masks the original regression. The prerequisite-version run above establishes failing-before/passing-after evidence.
  • review-error.jl, using the public ODEProblem constructor with ForwardDiff loaded: base throws UndefVarError(:NoRecompileArgumentError, ..., DiffEqBaseForwardDiffExt) and fails the assertion; head throws DiffEqBase.NoRecompileArgumentError and passes.
  • julia +1.12 --project=@runic -m Runic --check on all three changed Julia files exited 0. Head CI formatting, spelling and documentation checks also pass.
  • Probed a DAE with initialization data and jac_prototype: repeated concretization retained initialization_data::Any on base and head for both promotion paths. No timing, convergence or speedup claim was independently established.

CI comparison (read failed job logs; default branch comparison is master 4e8d61f unless stated):

Head failing check Default-branch evidence / classification
SciMLSensitivity.jl/Core1/1 / Downstream Tests - Core1 Same Mooncake Any constructor error, ComplexF64 ForwardDiff error and eventual signal 11 on master. Baseline failure.
SciMLSensitivity.jl/Core3/1 / Downstream Tests - Core3 Head signal 11 in LLVM LoopUnrollPass at Core3/default_alg_diff.jl:21; same check succeeds on master 4e8d61f and base 91d6176. Unresolved, not demonstrated to be a PR regression or a baseline failure.
downgrade-sublibraries / test (lib/DiffEqBase) Same high_level_solve.jl:94–101 callback assertions/absent callback field on master. Baseline failure.
downgrade-sublibraries / test (lib/OrdinaryDiffEqDifferentiation) Same missing diag(::ScalarOperator) method on master. Baseline failure.
sublibrary-ci / lib/DiffEqBase / Julia lts / Tests - Core (Julia lts) Same callback failure as master's DiffEqBase downgrade job. This exact Core/lts job was not scheduled in the recent master runs inspected, so an exact-check baseline comparison is unavailable; likely the existing Julia-version gating issue, not proven by an exact-check rerun.
sublibrary-ci / lib/GlobalDiffEq / Julia 1 / Tests - Core (Julia 1) Same unsupported-callback exception at companion_tests.jl:49 on master. Baseline failure.
sublibrary-ci / lib/OrdinaryDiffEqBDF [QA] / Julia 1 / Tests - QA (Julia 1) Same JET runtime dispatch in _despecialize_callback, reported by qa/jet.jl:48, on master. Baseline failure.
sublibrary-ci / lib/OrdinaryDiffEqDifferentiation / Julia 1 / Tests - Core (Julia 1) Same missing diag(::ScalarOperator) method on master. Baseline failure.
sublibrary-ci / lib/OrdinaryDiffEqNonlinearSolve / Julia 1 / Tests - Core (Julia 1) Same Trapezoid diagonal-mass-matrix restriction at mass_matrix_tests.jl:106 on master. Baseline failure.

No new dependency or public name, no test deletion/skipping/tolerance relaxation, and no new cross-package production internal-API access appears in the diff. These are intended bug corrections rather than a new public API requiring a major bump. The full downstream AD suite and Julia lts were not run locally.

Findings

  1. P2 — lib/DiffEqBase/ext/DiffEqBaseForwardDiffExt.jl:58: the independent exception fix has no regression test. None of the added tests loads ForwardDiff or exercises wrapfun_oop's unsupported-signature branch. Add this to a test that loads the extension; I ran it and observed failure on base and success on head:
    using DiffEqBase, SciMLBase, ForwardDiff, Test
    @test_throws DiffEqBase.NoRecompileArgumentError ODEProblem{false, SciMLBase.FunctionWrapperSpecialize}(
        (u, p, t) -> u, Float32[1], (0f0, 1f0), nothing
    )
  2. P2 — head CI, SciMLSensitivity.jl/Core3/1 / Downstream Tests - Core3: the compiler crash is still unverified. The claim that it is intermittent is plausible but is not a successful rerun or a matching default-branch failure. Rerun this job; if it recurs, compare a reproducer with identical dependencies on base and head and resolve or document the independent compiler issue. I did not trigger a rerun because this review is read-only.

Produced by an AI agent: Codex CLI (Mac), version unavailable; model gpt-6-astra. Conversation: local session ID 01a0dd91-049a-7aa2-acdf-09df47dabd8b (no conversation URL provided). No GitHub writes were performed.

Push a fix and the PR is reviewed again automatically at the new head.


🤖 Posted by an AI agent — harness: Claude Code · model: claude-opus-5-5[1m] (fleet master); review by Codex CLI (Mac) / gpt-6-astra
Conversation: local Claude Code session 3cd6500a-1f81-46b5-ac0b-c466e15b6a53 on Chris's Mac (session ID, no URL)

SebastianM-C and others added 2 commits September 26, 2026 22:53
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]>
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]>
@SebastianM-C

Copy link
Copy Markdown
Member Author

Re the automated review at 0d1cfda. Pushed f0b200d and 8759db1, which only add tests:

1. Regression test for the exception fix (f0b200d): the suggested @test_throws DiffEqBase.NoRecompileArgumentError case is added to forwarddiff_dual_detection.jl, which loads ForwardDiff and is part of the Core group.

2. SciMLSensitivity Core3: the push reruns it. The same signal 11 in LLVM's LoopUnrollPass at Core3/default_alg_diff.jl:21 also appeared on SciML/SciMLBase.jl#1616's CI (job), which does not contain this change. So it looks independent of this PR.

Also (8759db1): as the review notes, with SciMLBase ≥ 3.56.1 (#1616) the problem-level idempotency checks pass without the fix, because remake restores the narrowed types. The idempotency testset now also compares the output of get_concrete_problem's promote_f call on an already concretized problem directly, with no remake involved, for the plain ODE and the SDE cases.

Verified locally with Julia 1.12.7 and SciMLBase 29308523 (3.56.1), running despecialized_p_test.jl and forwarddiff_dual_detection.jl:

  • this branch: 423 passed, 0 failed (9 broken, all pre-existing)
  • PR base 91d6176 with the new test files: 4 failures, exactly the new assertions: 2× promote_f ODE (with and without ForwardDiff), 1× promote_f SDE, and the NoRecompileArgumentError test (on the base it raises UndefVarError)

Runic --check passes on both files. I did not rerun the whole Core group locally; only test files changed.

Written by Claude Code (claude-opus-5-5[1m]) on behalf of Sebastian.

@ChrisRackauckas
ChrisRackauckas merged commit 3178b19 into SciML:master Sep 27, 2026
270 of 279 checks passed
ChrisRackauckas referenced this pull request Sep 29, 2026
* Bump DiffEqBase to 7.21.3

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Agent-Harness: Devin CLI 3000.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqBDF to 2.4.12

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Agent-Harness: Devin CLI 3000.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqSDIRK to 2.9.7

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Agent-Harness: Devin CLI 3000.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqRosenbrock to 2.7.5

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Agent-Harness: Devin CLI 3000.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqLowOrderRK to 2.2.6

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Agent-Harness: Devin CLI 3000.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqTsit5 to 2.1.5

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Agent-Harness: Devin CLI 3000.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqVerner to 2.4.2

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Agent-Harness: Devin CLI 3000.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqSymplecticRK to 2.2.3

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Agent-Harness: Devin CLI 3000.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
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