Skip to content

Add adtype passthrough to OptimizationFunction/OptimizationProblem constructors - #5110

Merged
ChrisRackauckas merged 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:devin/optfn-adtype
Sep 12, 2026
Merged

ChrisRackauckas merged 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:devin/optfn-adtype

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Summary

SciMLBase.OptimizationFunction{iip}(sys::System, ...) hardcoded ad = SciMLBase.NoAD(), so there was no way to select an AD backend when building an OptimizationProblem from a System — users always had to rely on whatever the solver picked. Optimization.jl's instantiate_function dispatches on f.adtype, so this is the knob that selects solver-side AD.

This PR plumbs an adtype keyword through the MTKBase constructors:

  • OptimizationFunction(sys, AutoForwardDiff()) — positional, matching the SciMLBase.OptimizationFunction(f, adtype) signature — and OptimizationFunction{iip}(sys; adtype = AutoEnzyme()) both set f.adtype.
  • OptimizationProblem(sys, op; adtype = AutoForwardDiff()) forwards it through process_SciMLProblem to the OptimizationFunction constructor, the same way grad/hess/cons_j/cons_h already flow through.
  • The default remains SciMLBase.NoAD(), so existing behavior is unchanged. adtype (runtime AD selection) is independent of grad/hess/cons_j/cons_h (symbolic derivative generation); both can be combined.
  • expression = Val{true} codegen path works as well: the adtype object is embedded in the generated let block (ad = AutoForwardDiff()), verified below.

To keep the type annotation on adtype a public spelling (SciMLBase.AbstractADType is not public in SciMLBase and would fail the ExplicitImports QA check), ADTypes is promoted from a test-only [extras] entry to a real dependency of ModelingToolkitBase. It is a zero-dependency stub package that is already unconditionally loaded via SciMLBase, and it already had a [compat] bound (1.14.0), so this adds no effective weight.

Motivated by SciML/NeuralPDE.jl#1161 (NeuralPDE needs to control the AD backend used for its optimization problems).

Test plan

New @testset "adtype passthrough" in lib/ModelingToolkitBase/test/optimization/optimizationsystem.jl covers:

  • OptimizationFunction(sys, AutoForwardDiff()) → f.adtype isa AutoForwardDiff
  • OptimizationFunction{true}(sys; adtype = AutoEnzyme()) → f.adtype isa AutoEnzyme
  • OptimizationFunction(sys, AutoForwardDiff(); grad = true, hess = true) → adtype stored and symbolic grad/hess still generated
  • Default remains NoAD() for both OptimizationFunction and OptimizationProblem
  • OptimizationProblem(sys, op; adtype = AutoForwardDiff()) → prob.f.adtype isa AutoForwardDiff
  • End-to-end solve: solve(prob, Optim.BFGS()) on the Rosenbrock-like system using the selected ForwardDiff backend (ForwardDiff and ADTypes added to the optimization test env)

Run (cd lib/ModelingToolkitBase/test/optimization && julia --project=. optimizationsystem.jl, Julia 1.12.4):

Test Summary:        | Pass  Total  Time
`adtype` passthrough |    9      9  4.8s

Full optimizationsystem.jl file: all testsets pass (exit code 0; the pre-existing @test_broken in "time dependent var" is unchanged).

Additionally verified locally:

  • expression = Val{true}: eval(OptimizationFunction{true}(sys; expression = Val{true}, adtype = AutoForwardDiff())).adtype isa AutoForwardDiff → true
  • ExplicitImports QA checks run directly (check_all_qualified_accesses_are_public, check_no_implicit_imports, check_no_stale_explicit_imports, check_all_explicit_imports_are_public): zero ADTypes-related violations — SciMLBase.AbstractADType would have been flagged, ADTypes.AbstractADType is not.
  • Runic formatting applied (Runic.main --inplace on all changed files); typos clean.

Not run locally: the full qa/aqua.jl file (JET) and the docs build — the change touches docstrings only via the existing function_docstring/problem_docstring machinery, which was exercised by precompiling the package, but CI should confirm.

🤖 Generated with Devin (harness: Devin CLI 3000.10.21, model: SWE-2 High, session: local Devin CLI session — no shareable URL)

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Fixed the CI failure: [targets] test in lib/ModelingToolkitBase/Project.toml still named ADTypes, but Pkg.test requires test-target entries to resolve through [extras]/[weakdeps] — moving ADTypes to [deps] left a dangling target entry, so every sublibrary/downgrade job failed at test-env resolution before any tests ran:

ERROR: `ADTypes` declared as a `test` dependency, but no such entry in `extras` or `weakdeps`

ADTypes is a real dep now so it's already available to the test env — dropped it from the test target (same pattern as e.g. ForwardDiff, which is in both [deps] and [extras] and so resolves either way).

Verified locally on Julia 1.12.4: Pkg.test() previously errored during test-env resolution with the message above; after the fix it resolves, precompiles, and completes (Testing ModelingToolkitBase tests passed).

Fix by an AI agent (Devin CLI 3000.10.21, model: SWE-2 High; local session, no shareable URL).

ChrisRackauckas and others added 2 commits September 12, 2026 01:02
`OptimizationFunction{iip}(sys, ...)` hardcoded `ad = SciMLBase.NoAD()`,
so there was no way to select an AD backend when building an optimization
problem from a `System`. Add an `adtype` keyword (default `NoAD()`) to the
`OptimizationFunction` constructors, a positional `OptimizationFunction{iip}
(sys, adtype)` method matching the SciMLBase signature, and let `adtype`
flow through `OptimizationProblem(sys, op; adtype = ...)` to the function
constructor like `grad`/`hess`. `Optimization.jl`'s `instantiate_function`
dispatches on `f.adtype`, so this selects solver-side AD while `grad`/`hess`
keep controlling symbolic derivative generation independently.

Promotes ADTypes from a test-only extra to a real dependency of
ModelingToolkitBase (it is already unconditionally loaded via SciMLBase and
has no dependencies of its own) so the `adtype` annotation can use the
public `ADTypes.AbstractADType` spelling.

Motivated by SciML/NeuralPDE.jl#1161

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.10.21
Agent-Model: SWE-2 High
Agent-Session: local Devin CLI session (no shareable URL)
`Pkg.test` requires `[targets] test` entries to resolve through
`[extras]`/`[weakdeps]`; since ADTypes moved to `[deps]` it must not
remain in the test target, or test-env resolution fails before any
tests run.

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.10.21
Agent-Model: SWE-2 High
Agent-Session: local Devin CLI session (no shareable URL)
@ChrisRackauckas

Copy link
Copy Markdown
Member

Rebased onto master (3d9e44b). The branch was conflicting because master gained a weights kwarg on the same two OptimizationFunction constructors this PR touches, and separately released ModelingToolkitBase 1.69.3 then 1.70.0.

Two files conflicted. Both were resolved by keeping both features rather than choosing between them, so the approved behaviour of this PR is unchanged and master's weights support is preserved:

  • src/problems/optimizationproblem.jl
    • the inner constructor now takes weights = nothing and adtype::ADTypes.AbstractADType = SciMLBase.NoAD(), and the outer one forwards both;
    • the function docstring keeps extra_kwargs = WEIGHTS_KWARGS and adds :adtype to the symbol list, which resolves through the :adtype => ADTYPE_KWARGS entry this PR added;
    • the problem docstring concatenates them: extra_kwargs = WEIGHTS_KWARGS * ADTYPE_PROBLEM_KWARGS.
  • test/optimization/optimizationsystem.jl — the Multi-cost \weights`and ``adtype` passthrough `` testsets landed at the same offset; both are kept as sibling testsets.

lib/ModelingToolkitBase/Project.toml auto-merged and keeps master's version = "1.70.0"; the release bump was not clobbered.

Verification performed locally: all three touched Julia files parse (Meta.parseall, no :error nodes), and Runic reports no formatting changes needed (--check, exit 0). I did not run the test suite locally; CI on this push is the first execution of the merged weights + adtype code paths together.

Since the approval predates this rebase, the combined-kwarg resolution is worth a second look before merge.

🤖 Posted by an AI agent — harness: Claude Code, model: claude-opus-5[1m]
https://claude.ai/code/session_014FEzNTLFutCmTEAZ3zBg5R

@ChrisRackauckas
ChrisRackauckas merged commit f54dc8f into SciML:master Sep 12, 2026
99 of 110 checks passed
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.

3 participants