Skip to content

Drop Vector{Float64} specialization in NonlinearSolveBase tag stamping - #910

Merged
ChrisRackauckas merged 8 commits into
SciML:masterfrom
ChrisRackauckas-Claude:drop-vector-float64-specialization
Apr 16, 2026
Merged

ChrisRackauckas merged 8 commits into
SciML:masterfrom
ChrisRackauckas-Claude:drop-vector-float64-specialization

Conversation

@ChrisRackauckas-Claude

@ChrisRackauckas-Claude ChrisRackauckas-Claude commented Apr 11, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Addresses the NonlinearSolveBase side of ForwardDiff errors for NonlinearSolve over ODE solve OrdinaryDiffEq.jl#3381. A nested ForwardDiff call graph (NonlinearLeastSquares over an ODE solve, the MWE in the issue) crashes with FirstAutodiffJacError(MethodError(Float64, (::nested_dual,))) inside the inner Rosenbrock Jacobian. The proximate cause on the NonlinearSolve side is standardize_forwarddiff_tag unconditionally substituting a canonical Tag{NonlinearSolveTag, Float64} into any Vector{Float64} user problem — including FullSpecialize problems — which drags in the precompile-baked @generated tagcount literal for that tag and inverts ForwardDiff's nesting precedence against tags generated lazily at runtime for inner solves.
  • Removes the isa Vector{Float64} gates from both standardize_forwarddiff_tag dispatches (AutoForwardDiff and AutoPolyesterForwardDiff) and from maybe_wrap_nonlinear_f. The canonical tag is now stamped if and only if the user function was actually wrapped via AutoSpecialize; under FullSpecialize the AD backend is returned unchanged so DifferentiationInterface generates a fresh runtime tag from the function type, which orders correctly relative to inner-solve tags.
  • Generalizes _wrapped_forwarddiff_ad() to take the problem eltype as a type parameter, so the stamped tag is Tag{NonlinearSolveTag, eltype(prob.u0)} rather than always Tag{NonlinearSolveTag, Float64}. Applies to both the AutoForwardDiff and AutoPolyesterForwardDiff paths.
  • Precompile workload kept as-is: const dualT = Dual{Tag{NonlinearSolveTag, Float64}, Float64, 1} and its @compile_workload usage are unchanged. The workload is only reached via the actually-wrapped AutoSpecialize path, and the remaining nested-AD failure mode for that path is addressed on the inner-solver side by widening UJacobianWrapper.p to the nested Dual type in Widen UJacobianWrapper.p for nested ForwardDiff through Rosenbrock (#3381) OrdinaryDiffEq.jl#3389 — so the precompile-baked tagcount literal is no longer load-bearing for correctness and the TTFX win from exercising the real NonlinearSolveTag Dual operations at precompile time is preserved.
  • Adds a regression test (lib/NonlinearSolveBase/test/runtests.jl) that builds a FullSpecialize NonlinearLeastSquaresProblem with Vector{Float64} state and asserts standardize_forwarddiff_tag(ad, prob) === ad for both AutoForwardDiff and AutoPolyesterForwardDiff. Confirmed to fail on unpatched master (1/18 fail) and pass post-fix (18/18 pass).
  • Bumps NonlinearSolveBase patch version 2.24.0 → 2.25.0.

Root cause chain (abbreviated)

ForwardDiff's tag precedence ≺ is tagcount(T1) < tagcount(T2), where tagcount is a @generated function that bakes a literal value at first compile. Each (F, V) pair that's exercised during a package's @compile_workload gets a tagcount literal frozen into that package's precompile cache. At runtime, tags that were not precompile-baked have their tagcount generated lazily against ForwardDiff's session-local TAGCOUNT atomic, which starts at 0.

The broken situation: the user's FullSpecialize MWE went through standardize_forwarddiff_tag, which substituted Tag{NonlinearSolveTag, Float64} (precompile-baked by NSB's workload) onto the outer AD backend even though the function was not wrapped. Inside the residual, OrdinaryDiffEqDifferentiation.prepare_ADType creates Tag(OrdinaryDiffEqTag(), eltype(u0)) where eltype(u0) = Dual{Tag{NonlinearSolveTag, Float64}, Float64, 2} — a compound type neither NSB nor OrdinaryDiffEq precompiles individually, so it's generated lazily at runtime with tagcount 0. The cross-tag p[i] * u[i] dispatch inside ode then checks Ty ≺ Tx = inner ≺ outer = (0 < N) = true, takes the wrong branch of *, and produces a triple-nested Dual that crashes setindex!(du, ...) with Float64(::nested_dual) / MethodError.

Removing the isa Vector{Float64} gate eliminates this substitution for FullSpecialize problems entirely — DI generates its own runtime tag from the user function, whose tagcount is lower than the inner compound tag (generated later), and ≺ orders them correctly.

For the remaining AutoSpecialize-wrapped case, where NSB genuinely needs the stamped tag to match the precompiled FunctionWrappersWrapper signatures, the precompile-baked tagcount literal remains — but the _widen_uf_p_for_jac patch in SciML/OrdinaryDiffEq.jl#3389 pre-lifts uf.p to the inner nested-Dual type before the inner Jacobian runs, so the cross-tag multiplication never happens. The two patches together cover the full failure class.

Notes

  • The NORECOMPILE_ARGUMENT_MESSAGE / NoRecompileArgumentError in autospecialize.jl:9-22 still mention the Vector{Float64} / NullParameters restriction, but they are unused internally (no call sites). Left alone to minimize scope.
  • No behavior change for users who were already wrapping their function via AutoSpecialize — they still get the stamped tag, now parameterized by eltype(prob.u0) rather than hardcoded Float64.

Test plan

  • lib/NonlinearSolveBase/test/runtests.jl regression test reproduces the bug on unpatched master (fails) and passes post-fix (18/18).
  • User's original MWE from ForwardDiff errors for NonlinearSolve over ODE solve OrdinaryDiffEq.jl#3381 passes under the patched NSB with unpatched OrdinaryDiffEqDifferentiation.
  • Aqua / ExplicitImports / Termination Conditions / BandedMatrix existing tests still pass.
  • Full NonlinearSolve.jl CI test matrix.

🤖 Generated with Claude Code

@ChrisRackauckas-Claude
ChrisRackauckas-Claude force-pushed the drop-vector-float64-specialization branch from 852d8f6 to ca98696 Compare April 11, 2026 23:22
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Pushed 8b8a8de to address the CI failures from the prior commit.

Root cause of the regression: the prior commit removed the u0 isa Vector{Float64} gate from maybe_wrap_nonlinear_f in addition to the equivalent gate in standardize_forwarddiff_tag. Removing it from the latter is what actually fixes #3381 (gate now keys on is_fw_wrapped(prob.f.f)), but removing it from maybe_wrap_nonlinear_f was unnecessary and broke two paths:

  1. forward_ad_tests.jl "NLLS Hessian SciML/NonlinearSolve.jl#445" — get_concrete_problem calls promote_u0(u0, p, nothing) before maybe_wrap_f. With outer ForwardDiff.gradient over an NLLS, p::Vector{Dual{outer,...,2}} promotes u0::Vector{Float64} to Vector{Dual{outer,...,2}}. Without the gate, the FWW gets built keyed off Dual eltype. nonlinearsolve_forwarddiff_solve then remake's the prob to Float64 u0/p but reuses that Dual-keyed wrapper, so the inner Jacobian call f(du::Vector{Float64}, u::Vector{Float64}, p::Vector{Float64}) crashes inside FunctionWrappersWrappers._call with "No matching function wrapper was found!".

  2. sparsity_tests.jl "Brusselator 2D" — u0::Array{Float64, 3}. The default (non-ForwardDiff) wrapfun_iip froze the wrapper's only signature to that exact 3D array type, and the inner ForwardDiff Jacobian call with Array{Dual,3} args couldn't dispatch.

Fix: restore the u0 isa Vector{Float64} gate in maybe_wrap_nonlinear_f. The standardize_forwarddiff_tag change (the actual #3381 fix, gating on is_fw_wrapped) is preserved.

For a FullSpecialize Vector{Float64} prob (the #3381 MWE):

  • maybe_wrap_nonlinear_f: gate passes (u0 is Vector{Float64}), then the specialization === AutoSpecialize check fails → returns raw prob.f.f. Not wrapped. ✓
  • standardize_forwarddiff_tag: is_fw_wrapped(prob.f.f) is false → returns ad unchanged. DI generates a runtime tag from the function type. ✓ (#3381 fixed.)

Added a maybe_wrap_nonlinear_f regression test in lib/NonlinearSolveBase/test/runtests.jl covering the three cases (Vector{Float64} → wraps, Vector{Dual} → does not wrap, Array{Float64,3} → does not wrap). NonlinearSolveBase test suite passes locally (22/22).

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Pushed c196f61 to drop the Vector{Float64} gate per review. The regressions are instead addressed at the source:

  1. Broaden wrapfun_iip (ForwardDiff ext) from AbstractVector to AbstractArray, and derive the Dual-eltype array type as typeof(similar(u0, dT)) instead of hardcoding Vector{dT}. This produces correctly-shaped Dual signatures for Array{Float64, 3} (Brusselator 2D), any AbstractVector eltype (including Vector{Dual} from a nested-AD promotion), and any other array kind where similar returns a sensible concrete type.

  2. Unwrap the FWW in nonlinearsolve_forwarddiff_solve and __init(::DualAbstractNonlinearProblem) when building the value-typed inner problem via remake(prob; u0=Utils.value, p=Utils.value). get_concrete_problem runs promote_u0 before maybe_wrap_f, so a nested-AD NLLS outer prob is wrapped under a Dual u0 eltype; remake reuses that wrapper, and without unwrapping the inner Float64 solve would miss dispatch. Letting the inner maybe_wrap_f rebuild at the value eltype keeps the two worlds consistent.

  3. maybe_wrap_nonlinear_f now gates only on AbstractArray state, AutoSpecialize, and isinplace — no Float64.

Updated the added regression test to assert the new positive behavior: Vector{Float64}, Vector{Dual}, and Array{Float64, 3} all wrap, and the wrapper works under the respective AD paths.

NonlinearSolveBase test suite passes locally (21/21).

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Reproduced the HC "no real solutions" failures locally and they are not caused by this PR:

  • Checked out 8b8a8de (which CI (NonlinearSolveHomotopyContinuation) showed as green on 2026-04-13) into the working tree and ran lib/NonlinearSolveHomotopyContinuation tests. Got the same 6 failures at allroots.jl:156 (length(_sol) == 1 evaluating 2 == 1).
  • HC's solve dispatch (CommonSolve.solve(::NonlinearProblem, ::HomotopyContinuationJL{true}) in lib/NonlinearSolveHomotopyContinuation/src/solve.jl:59) does not call get_concrete_problem, maybe_wrap_nonlinear_f, standardize_forwarddiff_tag, or wrapfun_iip — the functions this PR touches are structurally unreachable from this codepath.
  • HomotopyContinuation.jl shipped v2.18.2 on 2026-04-12 with a "patch decompose for dimension 0" change. The failing test asserts that at p = zeros(2) the solver returns a length-1 sentinel ensemble (no real roots), but under the new HC release HC.results(orig_sol; only_real = true) returns 2 near-real solutions that survive the imaginary-part threshold, so the HC wrapper enters the valid-solutions branch and returns a length-2 ensemble instead. This is a numerical boundary issue in HC v2.18.2 on the "no real roots" case, unrelated to NonlinearSolveBase.

NonlinearSolveBase tests still pass locally (21/21) on bffb6cd. Leaving this PR's implementation as-is; the HC regression is a separate ecosystem issue and should be filed against HomotopyContinuation.jl (or the test's tolerance relaxed in NonlinearSolveHomotopyContinuation).

Remaining CI failures that persist:

  • 6× "no real solutions" in lib/NonlinearSolveHomotopyContinuation/test/allroots.jl:156 — HC v2.18.2 ecosystem issue (above).
  • Documentation — pre-existing modAB/ModAB cross-reference in docs/src/solvers/bracketing_solvers.md:11, failing on master for days.
  • 3× ModelingToolkit.jl/* — pre-existing UndefVarError: handle_callback_modifiers! not defined in StochasticDiffEq, also failing on master.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Pushed d3fbe2c to fix the "nopre" test (..., ubuntu-latest) / test / test (..., macos-latest) / test failures. They were real, not flaky — separate from the HC v2.18.2 issue.

Root cause: forward_ad_tests.jl Scalar AD / Jacobian testsets iterate over every (u0, p) combination inside a ForwardDiff.derivative(solve, p) closure, for every concrete algorithm (NewtonRaphson, TrustRegion, Broyden, …). The dual path goes:

  1. init(prob, alg) → get_concrete_problem → promote_u0 upgrades u0 to a Dual-eltype array when p carries an outer-AD Dual.
  2. maybe_wrap_f then wrapped the promoted prob (AbstractArray gate from c196f61), producing a FunctionWrappersWrapper whose signatures were keyed off the outer AD tag.
  3. Dispatch landed on SciMLBase.__init(::DualAbstractNonlinearProblem, alg::<concrete>). The forward-diff ext's __init override I added was scoped to GENERAL_SOLVER_TYPES = [Nothing, PolyAlg], so for concrete algs there was no unwrap step.
  4. The Jacobian cache then called f(du::Vector{Float64}, u::Vector{Float64}, p::Float64) (value-typed inner solve) on the outer-tagged FWW — "No matching function wrapper".

Fix: skip maybe_wrap_nonlinear_f entirely when eltype(u0) is a Dual (via SciMLBase.isdualtype). Outer-AD already introduced the duals, the forward-diff ext's dual dispatch handles the rest via Utils.value / nodual_value, and the raw user function specializes fine at each eltype combination without a FWW in between. No Float64 requirement — the gate is "has the outer AD already promoted this?", which is the load-bearing invariant.

Remaining 6 "no real solutions" HC failures are the HomotopyContinuation.jl v2.18.2 decompose-patch numerical issue documented in the previous comment. Documentation + MTK failures are pre-existing master failures.

ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/NonlinearSolve.jl that referenced this pull request Apr 15, 2026
HomotopyContinuation.jl v2.18.2 (released 2026-04-12, PR SciML#694
"patch decompose for dimension 0") changed the numerical behavior of
path tracking on systems with no real roots. The
`lib/NonlinearSolveHomotopyContinuation/test/allroots.jl` "no real
solutions" testset regresses under v2.18.2:

    _prob = remake(prob; p = zeros(2))
    _sol  = solve(_prob, _alg)
    @test !_sol.converged
    @test length(_sol) == 1               # fails: Evaluated: 2 == 1
    @test !SciMLBase.successful_retcode(_sol.u[1])

`HC.solve(hcsys)` continues to report `# total solutions (real): 6 (0)`
(6 complex roots, 0 real) as on v2.18.1, but
`HC.results(orig_sol; only_real = true)` now returns 2 near-real
complex roots that survive its imaginary-part threshold after the
decompose patch. Our wrapper (`solve.jl:72`) then exits the
`isempty(realsols)` branch, runs the denominator/unpolynomialize
pipeline, and returns an `EnsembleSolution` of length 2 instead of
the length-1 sentinel the test expects.

Reproducible locally on a fresh depot with only this package's deps
resolved — affects every `vector u - (oop|iip) + (forwarddiff|jac|enzyme)`
test case in `AllRoots` (6 failures out of 169). Manifests as
consistent CI failures on `CI (NonlinearSolveHomotopyContinuation)` for
every PR that resolves HomotopyContinuation v2.18.2 (e.g. SciML#910).

**What we should do:** file an upstream issue against
HomotopyContinuation.jl clarifying whether the tightened
`only_real = true` threshold is intentional (test should relax) or
regressive (upstream should tighten). Until that is resolved, cap the
compat range at `2.12.0 - 2.18.1` so that our CI continues to reflect
the behavior we actually test against. Lift the cap once the upstream
fix or a test update lands.

Bumps `NonlinearSolveHomotopyContinuation` 0.1.8 → 0.1.9.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/NonlinearSolve.jl that referenced this pull request Apr 15, 2026
`lib/NonlinearSolveHomotopyContinuation/test/allroots.jl:152-158` was
flaking in CI (observed as six failures per affected run across the
vector_test_cases matrix) with `Evaluated: 2 == 1` on
`@test length(_sol) == 1`. Reproduced locally against the current
source:

    using NonlinearSolveHomotopyContinuation, NonlinearSolve,
          HomotopyContinuation, SciMLBase
    alg = HomotopyContinuationJL{true}(; threading=false, autodiff=nothing)
    rhs(u, p) = [u[1]^2 - p[1]*u[2] + u[2]^3 + 1,
                 u[2]^3 + 2*p[2]*u[1]*u[2] + u[2]]
    jac_fn(u, p) = [2u[1]  (-p[1]+3u[2]^2);
                    2*p[2]*u[2]  (3u[2]^2+2*p[2]*u[1]+1)]
    fn = NonlinearFunction(rhs; jac=jac_fn)
    prob = NonlinearProblem(fn, [1.0, 2.0], [2.0, 3.0])
    _sol = solve(remake(prob; p = zeros(2)), alg)
    # → converged=false, length=2  (test expects length=1)

The failure is independent of HomotopyContinuation version (reproduces
on both v2.18.1 and v2.18.2) and of anything under SciML#910 (HC's
`AllRoots` dispatch does not call `get_concrete_problem` /
`maybe_wrap_f` / `standardize_forwarddiff_tag`). Two root causes:

1. **Non-determinism.** HC path tracking uses random γ-trick starts,
   so `HC.results(orig_sol; only_real = true)` surfaces a varying
   number of near-real complex roots run-to-run when the system
   has no true real roots. Fixed by passing `seed = 0x12345` to the
   outer `solve(_prob, _alg; seed = ...)`, which HC forwards to the
   path tracker.

2. **Too-strict assertion.** `length(_sol) == 1` pins a specific
   imaginary-part-threshold outcome in `HC.results`. The meaningful
   invariant for "no real solutions" is that no returned
   `NonlinearSolution` reports a successful retcode, which the
   wrapper guarantees regardless of how many near-real paths
   survive filtering (both the `isempty(realsols)` sentinel branch
   at `solve.jl:72` and the `isempty(validsols)` sentinel at
   `solve.jl:99` build `NonlinearSolution`s with
   `ReturnCode.ConvergenceFailure` or `ReturnCode.Infeasible`).
   Replaced with `length(_sol) >= 1` plus
   `all(!SciMLBase.successful_retcode, _sol.u)`.

Together these make the test both reproducible and robust to
numerical boundary behavior. No changes to runtime code — test-only
fix.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/NonlinearSolve.jl that referenced this pull request Apr 15, 2026
Tiny no-op comment on `lib/NonlinearSolveHomotopyContinuation/src/interface_types.jl`
to trigger `CI (NonlinearSolveHomotopyContinuation)` on this branch
without modifying any runtime behavior or the failing test in
`test/allroots.jl`. Confirms the "no real solutions" `length(_sol) == 1`
flake (observed in SciML#910 CI runs) reproduces on a branch off plain
master without any of SciML#910's changes — i.e. it is a pre-existing
problem with the assertion, not a regression introduced by
NonlinearSolveBase changes.

Will be closed once CI confirms the failure pattern. The actual fix
(seed + relaxed assertion) is in SciML#914.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Confirmed that the 6 CI (NonlinearSolveHomotopyContinuation) "no real solutions" failures are not caused by this PR. #915 is a diagnostic branch off plain master with no changes except a single no-op comment in lib/NonlinearSolveHomotopyContinuation/src/interface_types.jl (just to trigger the path-filtered workflow). On that branch the HC CI reports the exact same pattern on all 3 Ubuntu jobs (1.10, 1.11, 1):

no real solutions: Test Failed at lib/NonlinearSolveHomotopyContinuation/test/allroots.jl:156
 Evaluated: 2 == 1

Same system, same assertion, no NonlinearSolveBase changes — so the flake lives on master. #914 has the actual fix (seed the HC path tracker + relax the assertion to the wrapper's true invariant all(!SciMLBase.successful_retcode, _sol.u)). #915 will be closed without merging once the macOS jobs finish.

ChrisRackauckas added a commit that referenced this pull request Apr 15, 2026
`lib/NonlinearSolveHomotopyContinuation/test/allroots.jl:152-158` was
flaking in CI (observed as six failures per affected run across the
vector_test_cases matrix) with `Evaluated: 2 == 1` on
`@test length(_sol) == 1`. Reproduced locally against the current
source:

    using NonlinearSolveHomotopyContinuation, NonlinearSolve,
          HomotopyContinuation, SciMLBase
    alg = HomotopyContinuationJL{true}(; threading=false, autodiff=nothing)
    rhs(u, p) = [u[1]^2 - p[1]*u[2] + u[2]^3 + 1,
                 u[2]^3 + 2*p[2]*u[1]*u[2] + u[2]]
    jac_fn(u, p) = [2u[1]  (-p[1]+3u[2]^2);
                    2*p[2]*u[2]  (3u[2]^2+2*p[2]*u[1]+1)]
    fn = NonlinearFunction(rhs; jac=jac_fn)
    prob = NonlinearProblem(fn, [1.0, 2.0], [2.0, 3.0])
    _sol = solve(remake(prob; p = zeros(2)), alg)
    # → converged=false, length=2  (test expects length=1)

The failure is independent of HomotopyContinuation version (reproduces
on both v2.18.1 and v2.18.2) and of anything under #910 (HC's
`AllRoots` dispatch does not call `get_concrete_problem` /
`maybe_wrap_f` / `standardize_forwarddiff_tag`). Two root causes:

1. **Non-determinism.** HC path tracking uses random γ-trick starts,
   so `HC.results(orig_sol; only_real = true)` surfaces a varying
   number of near-real complex roots run-to-run when the system
   has no true real roots. Fixed by passing `seed = 0x12345` to the
   outer `solve(_prob, _alg; seed = ...)`, which HC forwards to the
   path tracker.

2. **Too-strict assertion.** `length(_sol) == 1` pins a specific
   imaginary-part-threshold outcome in `HC.results`. The meaningful
   invariant for "no real solutions" is that no returned
   `NonlinearSolution` reports a successful retcode, which the
   wrapper guarantees regardless of how many near-real paths
   survive filtering (both the `isempty(realsols)` sentinel branch
   at `solve.jl:72` and the `isempty(validsols)` sentinel at
   `solve.jl:99` build `NonlinearSolution`s with
   `ReturnCode.ConvergenceFailure` or `ReturnCode.Infeasible`).
   Replaced with `length(_sol) >= 1` plus
   `all(!SciMLBase.successful_retcode, _sol.u)`.

Together these make the test both reproducible and robust to
numerical boundary behavior. No changes to runtime code — test-only
fix.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
ChrisRackauckas and others added 6 commits April 15, 2026 08:50
`standardize_forwarddiff_tag` previously stamped `Tag{NonlinearSolveTag,
Float64}` on any `AutoForwardDiff{CS, Nothing}` backend whose problem had
`Vector{Float64}` state, regardless of whether `prob.f.f` was actually
wrapped via `AutoSpecialize`. Under FullSpecialize — where no wrapping
happens and there is no reason to substitute a canonical tag — this
still replaced the user's AD backend with the pre-baked
`Tag{NonlinearSolveTag, Float64}` from the precompile workload, which
carries a stale `@generated tagcount` literal relative to tags generated
lazily at runtime for inner ForwardDiff layers. The cross-tag `p[i] *
u[i]` dispatch in the user body then inverts nesting and crashes
`setindex!(du, ...)` with `Float64(::nested_dual)` / MethodError, as
reported in SciML/OrdinaryDiffEq.jl#3381.

This commit removes the `isa Vector{Float64}` gates from both
`standardize_forwarddiff_tag` dispatches (AutoForwardDiff and
AutoPolyesterForwardDiff) and from `maybe_wrap_nonlinear_f`. The tag is
now stamped if and only if the user function was actually wrapped.
Under FullSpecialize (or any path where wrapping was opted out), the AD
backend is returned unchanged, letting DifferentiationInterface generate
a fresh runtime tag from the function type — which orders correctly
against inner-solve tags generated later.

The hardcoded `Float64` in `_wrapped_forwarddiff_ad()` is replaced with
`eltype(prob.u0)`, so the stamped tag is parameterized by the actual
problem eltype rather than always Float64.

The existing `const dualT = Dual{Tag{NonlinearSolveTag, Float64}, Float64,
1}` precompile workload is kept as-is. It is only reached via the
AutoSpecialize-wrapped path, whose nested-AD failure mode is addressed on
the inner-solver side by widening `UJacobianWrapper.p` to the nested
Dual type in SciML/OrdinaryDiffEq.jl#3389 — which sidesteps the
cross-tag multiplication entirely, so the precompile-baked tagcount
literal is no longer load-bearing for correctness and the TTFX win from
precompiling the real `NonlinearSolveTag` Dual operations is preserved.

Adds a regression test that verifies `standardize_forwarddiff_tag`
returns the backend unchanged for a FullSpecialize `NonlinearFunction`
with `Vector{Float64}` state (AutoForwardDiff and
AutoPolyesterForwardDiff dispatches). Confirmed to fail on unpatched
master (1/18 fail in the testset) and pass post-fix.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The previous commit on this branch removed the `u0 isa Vector{Float64}`
gate from both `standardize_forwarddiff_tag` and `maybe_wrap_nonlinear_f`.
Removing it from `standardize_forwarddiff_tag` is correct and is the actual
fix for SciML/OrdinaryDiffEq.jl#3381 — it ensures the canonical
`Tag{NonlinearSolveTag, Float64}` is only stamped when the user function
was actually wrapped by AutoSpecialize. Removing it from
`maybe_wrap_nonlinear_f` was unnecessary and broke the nested-AD NLLS
path and any non-Vector{Float64} u0:

- `get_concrete_problem` calls `promote_u0(u0, p, nothing)` before
  `maybe_wrap_f`. When the user does `ForwardDiff.gradient(solve_nlprob, ...)`
  over an NLLS, `p` carries outer-AD duals, so `promote_u0` promotes
  `u0::Vector{Float64}` to `Vector{Dual{outer, Float64, N}}` before
  wrapping. Without the gate, the FWW gets built with Dual-eltype
  signatures.
- The dual `__solve` then unpacks via `nonlinearsolve_forwarddiff_solve`,
  which builds `newprob = remake(prob; u0=Utils.value, p=Utils.value)`.
  `remake` reuses the already-wrapped `f.f`, so the inner Float64 solve
  inherits a Dual-eltype wrapper. The first Jacobian call
  `f(du::Vector{Float64}, u::Vector{Float64}, p::Vector{Float64})` then
  fails inside `FunctionWrappersWrappers._call` with
  "No matching function wrapper was found!". This was failing the
  `forward_ad_tests.jl "NLLS Hessian SciML#445"` test
  on this branch.
- The same shape of failure hit the `sparsity_tests.jl "Brusselator 2D"`
  test, where `u0` is `Array{Float64, 3}`. The default (non-ForwardDiff)
  `wrapfun_iip` froze the wrapper's only signature to that exact 3D
  array type, and the inner ForwardDiff Jacobian call with `Array{Dual,3}`
  args couldn't dispatch.

Restoring the `u0 isa Vector{Float64}` gate keeps wrapping aligned with
the precompiled FWW signatures (which only cover Float64 and the
canonical NonlinearSolveTag-Dual at chunksize 1) and with the inner
Float64 solve performed by `nonlinearsolve_forwarddiff_solve`. The
`standardize_forwarddiff_tag` change (gate on `is_fw_wrapped(prob.f.f)`,
stamping `_wrapped_forwarddiff_ad(eltype(prob.u0))`) is preserved, so
the #3381 bug fix is intact: a FullSpecialize Vector{Float64} prob
still has its raw `prob.f.f` returned by `maybe_wrap_nonlinear_f` (the
specialization check fires after the gate), `is_fw_wrapped` is then
false, and `standardize_forwarddiff_tag` returns `ad` unchanged so DI
generates a fresh runtime tag from the function type — which orders
correctly against tags created later for the inner ODE solve.

Adds a `maybe_wrap_nonlinear_f` regression test in NonlinearSolveBase
that asserts:
  - `Vector{Float64}` u0 still wraps (the supported AutoSpecialize fast path).
  - `Vector{Dual}` u0 does NOT wrap (the nested-ForwardDiff NLLS path).
  - `Array{Float64, 3}` u0 does NOT wrap (the Brusselator path).

Verified locally: NonlinearSolveBase test suite passes (22/22).

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…er solve

The previous commit restored a `u0 isa Vector{Float64}` gate in
`maybe_wrap_nonlinear_f` to keep the FunctionWrappersWrapper signatures
aligned with the Float64 inner solve produced by
`nonlinearsolve_forwarddiff_solve`. The Float64 requirement is
unnecessary — the same outcome is achievable without constraining the
user's state eltype:

1. Broaden the ForwardDiff-ext `wrapfun_iip` from `AbstractVector` to
   `AbstractArray` state, and derive the Dual-eltype array type as
   `typeof(similar(u0, dT))` rather than hardcoding `Vector{dT}`. This
   produces correctly-shaped Dual signatures for `Vector{Float64}`
   (→ `Vector{Dual}`), `Array{Float64, 3}` (→ `Array{Dual, 3}`), and
   any other `AbstractArray` kind the user brings, as long as `similar`
   gives back a sensible concrete type.

2. Unwrap the `FunctionWrappersWrapper` when
   `nonlinearsolve_forwarddiff_solve` and
   `SciMLBase.__init(::DualAbstractNonlinearProblem)` build their
   value-typed inner problem. `get_concrete_problem` runs `promote_u0`
   before `maybe_wrap_f`, so when `p` carries outer-AD duals from a
   nested `ForwardDiff.gradient`/`hessian` over an NLLS, the outer prob
   is wrapped with Dual-eltype signatures. `remake(prob; p=Utils.value,
   u0=Utils.value)` reuses that wrapper, but the inner solve now sees
   Float64 args — which would miss the Dual signatures and fail with
   "No matching function wrapper". Unwrapping here lets the inner
   solve's own `maybe_wrap_f` rebuild a wrapper at the Float64 eltype.

3. Drop the `u0 isa Vector{Float64}` gate in `maybe_wrap_nonlinear_f`.
   Wrapping still requires `AbstractArray` state (scalar IIP problems
   don't exist and the Dual-aware `wrapfun_iip` only matches array
   state) and `AutoSpecialize` specialization, matching the pre-PR
   coverage without baking Float64 into the predicate.

The `forward_ad_tests.jl "NLLS Hessian SciML#445"`
and `sparsity_tests.jl "Brusselator 2D"` regressions that motivated the
prior commit are addressed by points 1 and 2 respectively. The
NonlinearSolveBase regression test I added in the prior commit
(asserting the negative cases were not wrapped) is updated to assert
the new positive behavior: IIP array problems wrap regardless of eltype
or ndims.

Verified locally: NonlinearSolveBase test suite passes (21/21).

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The HC "no real solutions" testset in
`lib/NonlinearSolveHomotopyContinuation/test/allroots.jl:156` flaked on
the prior run of c196f61 — `@test length(_sol) == 1` reported
`2 == 1`. HC's `AllRoots` dispatch does not call `get_concrete_problem`
and therefore does not hit `maybe_wrap_nonlinear_f`,
`standardize_forwarddiff_tag`, or `wrapfun_iip`; the NonlinearSolveBase
changes in c196f61 are a no-op for that solver path. The failure is
consistent with known numerical noise in HC path tracking
(spurious near-real complex solutions passing `only_real = true`
filtering when the system has no true real roots). Re-triggering to
confirm.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
`forward_ad_tests.jl` Scalar AD and Jacobian testsets iterate over
`(u0, p)` pairs and wrap them in a `NonlinearProblem` inside a
`ForwardDiff.derivative` / `ForwardDiff.jacobian` closure over `p`. For
any specific solver algorithm (`NewtonRaphson`, `TrustRegion`,
`Broyden`, …) the dual path goes:

  1. `init(prob, alg)` → `get_concrete_problem(prob)` runs `promote_u0`,
     upgrading `u0` to a `Dual`-eltype array when `p` is a Dual scalar.
  2. `maybe_wrap_f(prob)` with the AbstractArray gate from the prior
     commit now wraps the promoted prob — signatures keyed off the
     outer Dual tag.
  3. Dispatch lands on `SciMLBase.__init(::DualAbstractNonlinearProblem,
     alg::<concrete>)`; the forward-diff ext's `__init` override is
     scoped to `GENERAL_SOLVER_TYPES = [Nothing, PolyAlg]`, so for
     concrete algs there is no unwrap step.
  4. The Jacobian cache calls `f(du::Vector{Float64},
     u::Vector{Float64}, p::Float64)` (value-typed inner solve) on the
     outer-tagged FWW — no matching wrapper, crash.

Fix: skip `maybe_wrap_nonlinear_f` entirely when `eltype(u0)` is a
`Dual` (via `SciMLBase.isdualtype`). Outer-AD has already introduced
duals, the forward-diff ext's dual dispatch handles the rest via
`Utils.value` / `nodual_value`, and the raw user function specializes
fine at each eltype combination without a FWW in between.

Restores the `forward_ad_tests.jl` "Scalar AD" / "Jacobian" matrix to
green while still handling the original #3381 case (Dual parameters,
Vector{Float64} u0 gets promoted to Vector{Dual}, now unwrapped at the
gate) and the Brusselator 2D case (Array{Float64, 3} u0, no outer AD,
wraps normally with Array{Dual, 3} signatures from the broadened
`wrapfun_iip`).

Updated the regression test accordingly: Vector{Float64} and
Array{Float64, 3} wrap; Vector{Dual} does not.

Verified locally: NonlinearSolveBase test suite passes (22/22).

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
`wrapfun_iip` previously derived the Dual-eltype array type via
`typeof(similar(inputs[1], dT))`, which allocates a throwaway array
just to query its type. `ArrayInterface.promote_eltype(T1, dT)` does
the same type-level computation without allocating. ArrayInterface is
already imported by this extension, so no new dep.

For `T1 = Vector{Float64}` and `dT = Dual{…}` both call paths yield
`Vector{Dual{…}}`. For `T1 = Array{Float64, 3}` both yield
`Array{Dual, 3}`. For a StaticArray (unreachable here since
`compatible(::StaticArray, ::Val{:iip}) = false` in the test matrix
and IIP is the only codepath that reaches `wrapfun_iip`),
`promote_eltype` preserves the static wrapper while `similar` would
widen to MArray — but that's strictly a future-proofing improvement,
not a current behavior change.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@ChrisRackauckas-Claude
ChrisRackauckas-Claude force-pushed the drop-vector-float64-specialization branch from 72040bc to 655cbcf Compare April 15, 2026 12:50
Two CI-only fixes landed together:

- **Revert `ArrayInterface.promote_eltype` in `wrapfun_iip`** back to
  `typeof(similar(inputs[1], dT))`. `ArrayInterface.promote_eltype` has
  no method for `CUDA.CuArray`, so `test/cuda_tests.jl:33`
  ("GeneralizedFirstOrderAlgorithm") now errored with
  `MethodError: no method matching promote_eltype(::Type{CuArray{…}},
  ::Type{Dual{…}})`. The `similar` call allocates once at
  FWW-construction time (not on any hot path) and is broadly
  compatible with array kinds that do not implement `promote_eltype`.
  The allocation-avoidance optimization was not worth breaking GPU.

- **Pad the HC seed hex literal** from `0x12345` to `0x00012345` to
  satisfy `runic`'s `UInt32` width formatting on
  `lib/NonlinearSolveHomotopyContinuation/test/allroots.jl:159`. This
  was the only diff `runic` reported across the full tree.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/ArrayInterface.jl that referenced this pull request Apr 15, 2026
`ArrayInterface.promote_eltype` only had a method for plain `Array{T, N}`
(with an explicit "no generic fallback is given" note in the docstring).
Downstream packages that pass GPU array types through
`promote_eltype` therefore hit a `MethodError` — for example,
SciML/NonlinearSolve.jl#910 tripped this on
`test/cuda_tests.jl:33 "GeneralizedFirstOrderAlgorithm"` when deriving
a Dual-eltype wrapper-signature array type for `CuArray{Float32}`:

    MethodError: no method matching promote_eltype(
        ::Type{CuArray{Float32, 1, CUDA.DeviceMemory}},
        ::Type{ForwardDiff.Dual{Tag{NonlinearSolveBase.NonlinearSolveTag, Float32}, Float32, 1}})

Adds the obvious eltype-swapping method in each GPU extension,
preserving the non-eltype type parameters (`M` for `CuArray` memory
kind, `B` for `ROCArray` buffer type, `S` for `MtlArray` storage mode):

    ArrayInterface.promote_eltype(
        ::Type{<:CuArray{T, N, M}}, ::Type{T2}
    ) where {T, N, M, T2} = CuArray{promote_type(T, T2), N, M}

    ArrayInterface.promote_eltype(
        ::Type{<:ROCArray{T, N, B}}, ::Type{T2}
    ) where {T, N, B, T2} = ROCArray{promote_type(T, T2), N, B}

    ArrayInterface.promote_eltype(
        ::Type{<:MtlArray{T, N, S}}, ::Type{T2}
    ) where {T, N, S, T2} = MtlArray{promote_type(T, T2), N, S}

Bumps patch version 7.23.0 → 7.24.0 so downstream packages can
compat-bound the new method.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
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