Skip to content

Keep the unwrapped adjoint problem out of AutoDespecialize - #1324

Merged
ChrisRackauckas merged 2 commits into
SciML:masterfrom
SebastianM-C:smc/unwrapped-problem-specialization
Sep 27, 2026
Merged

ChrisRackauckas merged 2 commits into
SciML:masterfrom
SebastianM-C:smc/unwrapped-problem-specialization

Conversation

@SebastianM-C

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

Copy link
Copy Markdown
Member

_unwrap_despecialized_problem builds the problem that the adjoint path (_solve_adjoint) and the Enzyme path (maybe_unwrap_prob_for_enzyme) use: raw residual, raw callbacks, concrete p. It kept the original specialization, so an AutoDespecialize problem stayed AutoDespecialize. When the sensitivity code concretizes that problem again, _despecialize_parameters sees a problem that is AutoDespecialize and not wrapped, and wraps p back into DespecializedParameters.

Why this didn't show before: the ChainRules solve_up rrule starts with @set prob.f.f = get_raw_f(prob.f.f), and SciMLBase's constructorof reset every rebuilt function to AutoSpecialize. The problem reaching _unwrap_despecialized_problem was therefore never AutoDespecialize on this path. SciML/SciMLBase.jl#1606 makes @set keep the specialization, which exposes this.

Symptom (with SciML/SciMLBase.jl#1606): SciMLSensitivity Core8, desauty_dae_mwe.jl:163 "Mooncake through init" (use_scc = true). The parameter tangent coming out of the steady-state backpass gains an extra params::MTKParameters field next to tunable/initials/..., and NonlinearSolveBaseMooncakeExt._accum_cr_tangent! throws ArgumentError: The fdata type Mooncake.FData{...} ... and tangent type @NamedTuple{params::MTKParameters, tunable, ...}.

Change: _unwrap_despecialized_problem builds the unwrapped function as FullSpecialize. _map_parameter_callbacks takes an optional specialization argument for this. When the problem is concretized again, FullSpecialize keeps both p and the residual as they are: AutoDespecialize would wrap p back into DespecializedParameters, and AutoSpecialize (what this path got through the reset before) would wrap the residual in an AutoSpecializeCallable for in-place array-state problems.

Tests: a new testset in test/autodespecialize.jl checks that the unwrapped problem keeps the concrete p, the raw residual and raw callbacks after get_concrete_problem, for a struct p and a Vector{Float64} p. The p and Jacobian checks fail on master, the residual check fails with AutoSpecialize, and all pass with this change; the rest of the file passes in all three. NonlinearSolveBase Core passes locally (Julia 1.12.7, 535 assertions).

Verification (Julia 1.13.0, local, CI's versions: MTK 11.45.1, Mooncake 0.5.60, SCCNonlinearSolve 1.15.3, SciMLSensitivity 7.119.11):

No compat bump is needed: the change is correct with both released SciMLBase and SciML/SciMLBase.jl#1606.

Related: SciML/SciMLBase.jl#1606 exposed other places that relied on the reset:

I also checked NonlinearSolveBase's other @set f.f = get_raw_f(...) sites (Jacobian cache, bounds transform, Enzyme unwrap, autodiff). They are local transforms inside __init; none of them goes through get_concrete_problem again, so the kept specialization doesn't change them.

Written by Claude Code on Sebastian's behalf.

🤖 Generated with Claude Code

https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP

`_unwrap_despecialized_problem` kept the original specialization, so an
`AutoDespecialize` problem stayed `AutoDespecialize` with concrete parameters.
When the sensitivity code concretized it again, `_despecialize_parameters`
wrapped `p` back into `DespecializedParameters`, and the parameter tangent
gained an extra `params` field (Mooncake through SCC initialization fails).

This used to be hidden because `@set prob.f.f = ...` in the ChainRules rule
reset the specialization to `AutoSpecialize`; SciMLBase#1606 keeps it. Build
the unwrapped function as `AutoSpecialize`, which is what this path had before.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JNAfKDURNdkubVjmftigPP
Comment on lines +104 to +106
# Not `AutoDespecialize`: the unwrapped problem carries the concrete parameters, and
# `_despecialize_parameters` must not wrap them again when the sensitivity code
# concretizes it a second time.

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.

Is this the right branch?

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.

so the fix should live in SciMLSensitivity rather than using the specialization as a marker?

This worked before the specialization fix because the @set prob.f.f = get_raw_f(…) at the top of the rrule which resets the specialization level to AutoSpecialize which had the net effect of leaving p alone, but now, after the fix (SciML/SciMLBase.jl#1606) it would get re-wrapped.

# `_despecialize_parameters` must not wrap them again when the sensitivity code
# concretizes it a second time.
f = _map_parameter_callbacks(
_unwrap_parameter_callback, prob.f, residual, SciMLBase.AutoSpecialize

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.

Seems weird to hardcode this?

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.

that mirrors the old behavior from before the SciMLBase fix, which was leading to AutoSpecialize, should this use FullSpecialize instead?

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.

Went with FullSpecialize in 5760526. AutoSpecialize kept p concrete, but on re-concretization maybe_wrap_nonlinear_f still wraps the residual in an AutoSpecializeCallable for any in-place array-state problem. The extended test checks that f.f stays raw and fails under AutoSpecialize. The SciMLSensitivity question in the other thread is still open.

posted by Claude claude-opus-5-5[1m] on behalf of Sebastian

@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 785825a).

The patch builds the internal unwrapped adjoint/Enzyme problem with AutoSpecialize so subsequent concretization preserves concrete parameters and raw parameter callbacks. The regression is confirmed and all failing CI checks match master, but the unchanged draft still has an unresolved discussion with you about the specialization policy and which package should own the fix, so it is not ready for an unconditional merge recommendation.

Risk assessment

  • Risk: low
  • Blast radius: AutoDespecialize nonlinear problems entering adjoint or Enzyme paths; the internal helper changes, with no new public API or dependencies.
  • Evidence: Read the full diff, description, all four inline comments and four review records, and the three related PR descriptions. No maintainer other than Chris is reviewing; the other replies are the author's. Head remains 785825a160ab68bfd549d5da0085d13034777fc0, still draft, with no update after the author's September 23 design questions. Local Julia 1.12.7 / SciMLBase 3.56.0: the new test fails on base c76316a with 3 passed, 2 failed (parameters and Jacobian are rewrapped), and passes on head with 5/5. The entire autodespecialize.jl file passes 37/37, and the full NonlinearSolveBase Core group passes 528 assertions across 22 testsets, ending Testing NonlinearSolveBase tests passed. Runic reports no differences in either changed file. All four failed head CI checks have matching failures on recent master runs, detailed below.
  • Merge: needs changes (resolve the draft's open design discussion and confirm the final implementation is ready; no demonstrated new test regression).

Findings

  1. lib/NonlinearSolveBase/src/autospecialize.jl:108 — Unresolved design/readiness issue, not an observed correctness regression. Chris asks whether this is the right branch and questions hardcoding the specialization. The author's last replies ask whether to use FullSpecialize and whether the fix instead belongs in SciMLSensitivity; neither question has a subsequent resolution or revision, and the PR remains a draft. Resolve the intended policy and ownership with Chris, update the implementation/tests if that decision changes them, and mark the finalized PR ready. The distinction is concrete: my vector-parameter probe shows that reconcretization keeps p::Vector{Float64} but wraps the residual again as AutoSpecializeCallable; this patch prevents parameter rewrapping, rather than guaranteeing an entirely unwrapped residual after reconcretization. That probe did not demonstrate a failure.

Validation details

Commands run from the scratch directory:

julia +1.12 --project=env-base -e 'using NonlinearSolveBase, SciMLBase; include("wt-head/lib/NonlinearSolveBase/test/autodespecialize.jl")'
julia +1.12 --project=env-head -e 'using NonlinearSolveBase, SciMLBase; include("wt-head/lib/NonlinearSolveBase/test/autodespecialize.jl")'
GROUP=Core julia +1.12 --compiled-modules=existing --project=env-head -e 'using Pkg; Pkg.test("NonlinearSolveBase"; julia_args=["--compiled-modules=existing"])'
julia +1.12 --project=@runic -m Runic --check --diff wt-head/lib/NonlinearSolveBase/src/autospecialize.jl wt-head/lib/NonlinearSolveBase/test/autodespecialize.jl

The first Core attempt stopped before tests because Pkg resolved the sibling SciMLJacobianOperators source to a missing scratch path. After supplying a scratch-local symlink to the head's sibling package, the same test command passed. No tracked source files were changed. The author's end-to-end Mooncake/MTK gradient and finite-difference comparison were not independently rerun; local evidence covers the structural regression and the full Core group. The diff adds no skipped/weakened assertions, dependency, new dependency-internal access, or new public name; no SemVer-major or new-public-API documentation requirement was identified.

Failed head check Comparison with master
sublibraries / lib/NonlinearSolveBase [QA] / Julia 1 / Tests - QA (Julia 1) Same failures in master run 35798794342, commit ce7518c: non-public import of implicit_sensitivity_solve, and unrendered public names nlls_solve_adjoint_dp / solve_call; both report 18 passed, 1 failed, 1 errored.
sublibraries / lib/NonlinearSolveFirstOrder / Julia 1 / Tests - Core (Julia 1) Same Enzyme ThunkCallError signatures in rootfind_tests__item8.jl:30 on master run 35840823032, commit 4b5a616; both report 1113 passed, 21 errored.
sublibraries / lib/NonlinearSolveFirstOrder [QA] / Julia 1 / Tests - QA (Julia 1) Same non-public RobustTrustRegionLinsolve import on master run 35840823032; both report 19 passed, 1 errored.
downgrade-sublibraries / test (lib/NonlinearSolveFirstOrder) Same Enzyme ccall argument-5 SVector{2, Float64} versus Vector{Float64} TypeError on master run 36094728481, commit 29af7e6; both report 1512 passed, 28 errored.

Head NonlinearSolveBase Core checks, root Adjoint checks, documentation, Runic and Typos are green. Recent master Sublibrary CI runs that only performed change detection were not treated as evidence that these individual checks passed.

AI-generated review — harness: Codex CLI 0.156.1 (Mac); model: gpt-6-astra. Conversation: local session ID 01a0dda0-9655-7a00-b18c-7b0223c8587c (no published conversation URL available). GitHub was read-only.

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)

The unwrapped problem carries raw callables and concrete parameters for the
adjoint and Enzyme paths. `AutoSpecialize` kept the parameters concrete when
the sensitivity code concretizes the problem again, but `maybe_wrap_nonlinear_f`
still wrapped the residual in an `AutoSpecializeCallable`. `FullSpecialize`
opts out of both wrappings.

The regression test now also covers `Vector{Float64}` parameters and checks
that the residual stays raw after re-concretization; that check fails with
`AutoSpecialize`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@SebastianM-C
SebastianM-C marked this pull request as ready for review September 26, 2026 19:50
@ChrisRackauckas
ChrisRackauckas merged commit 60b76b6 into SciML:master Sep 27, 2026
96 of 100 checks passed
Proektsoft-EOOD added a commit to Proektsoft-EOOD/NonlinearSolve.jl that referenced this pull request Sep 27, 2026
@SebastianM-C
SebastianM-C deleted the smc/unwrapped-problem-specialization branch September 27, 2026 12:41
ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/NonlinearSolve.jl that referenced this pull request Sep 27, 2026
Pick up SciML#1324 AutoDespecialize adjoint unwrap fix so Adjoint CI matches master.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Cursor Agent <[email protected]>
Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe
Agent-Model: auto
Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/NonlinearSolve.jl/jobs/1197-cursor/log.txt on amdci2.julia.csail.mit.edu
ChrisRackauckas referenced this pull request Sep 29, 2026
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