Skip to content

Register precondition/postcondition as common solver keywords - #1449

Merged
ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:nonlinearfunction-conditioning-hooks
Aug 5, 2026
Merged

ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:nonlinearfunction-conditioning-hooks

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Important

This PR should be ignored until reviewed by @ChrisRackauckas.

Summary

Adds two optional fields to NonlinearFunction for declaring a nonlinear preconditioner, in the solver-composition sense of Brune, Knepley, Smith & Tu, Composing Scalable Nonlinear Algebraic Solvers (SIAM Review 57(4), 2015), i.e. the root-equivalent composed system

$$G\big(f(H(\tilde u, u_k), p), \tilde u, p\big) = 0$$

  • precondition — a left preconditioner G(fu, u, p) applied to the residual (in-place functions overwrite fu). Solvers replace the residual with the composed map everywhere: function evaluations, AD Jacobians, line-search merit functions, and termination criteria. G must be root-preserving.
  • postcondition — a right preconditioner / iterate corrector H(u_proposed, u_prev, p) (in-place functions overwrite u_proposed). Solvers apply it to every accepted iterate before evaluating the residual there, so residual/Jacobian stay consistent with corrected iterates. This is the hook for SPICE-style junction limiting — i.e. the corrector phase of the Predictor/Corrector Newton-Raphson (PCNR) method of Aadithya, Keiter & Mei — as well as projections and Dirichlet-type condensation. It corresponds to PETSc SNES post-check.

The fields are purely declarative here. Solver semantics are implemented in the companion NonlinearSolve.jl PR (which depends on this being released): addresses SciML/NonlinearSolve.jl#351.

Changes

  • NonlinearFunction struct: two new trailing fields/type-parameters precondition, postcondition (default nothing), threaded through both the NoSpecialize and specialized keyword-constructor branches.
  • __has_precondition/__has_postcondition existence helpers so constructor forwarding and remake work as for the other optional fields.
  • Docstring section documenting the contracts (root preservation for G, fixed-point identity for H, Jacobian conventions).
  • Tests in test/problem_building_test.jl covering construction (oop/iip), defaults, remake preservation, and constructor forwarding.
  • Version bump 3.36.0 → 3.37.0 (new feature, minor).

Verification

Ran locally on Julia 1.12.4:

  • GROUP=Core Pkg.test() — passed (includes the new testset).
  • The companion NonlinearSolve.jl branch exercises the hooks end-to-end against these fields (Newton/TrustRegion/LM/quasi-Newton/DFSane/SimpleNonlinearSolve paths), all green locally.

Process notes

Design per the discussion on SciML/NonlinearSolve.jl#351: hooks take iterate arguments so limiting can decide activation from the current iterate; freeze-per-iteration semantics are the solver's responsibility. Note for reviewers: remake(prob; f = new_f) merges function fields and lets nothing fields fall back to the old function's values, so downstream consumers cannot clear a consumed hook to nothing — NonlinearSolve.jl handles idempotence with a sentinel marker instead.

🤖 Generated with Claude Code

https://claude.ai/code/session_01B9GHoo4pFa3DU9yhyTkevL

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

CI triage of the first full run + new commit 542eb18:

  • SciMLBase's own suites: Core (lts/1/pre), Downstream (lts/1), Python, QA — all green. The tests/DownstreamAD (julia 1) and tests/SymbolicIndexingInterface (julia 1) failures were self-hosted runner disconnects ("runner lost communication with the server" annotations), not test failures.
  • One real regression found and fixed: SciMLSensitivity.jl/Core6's SteadyStateAdjoint failed with a MethodError — unwrapped_f(f::NonlinearFunction) reconstructs the function positionally with an explicit type-parameter list and was missed when adding the two fields. Fixed in 542eb18, which also fixes a latent off-by-one in that method's NoSpecialize branch (18 params for what were 17 fields — it threw "too many parameters" whenever hit, so it was dead code). Added a regression test across all three specialization modes, and verified the exact failing SciMLSensitivity path locally against the fix (Zygote.gradient through solve(remake(prob; p), NewtonRaphson(); sensealg = SteadyStateAdjoint(autojacvec = ReverseDiffVJP())) — gradients correct for iip and oop).
  • Remaining downstream failures are pre-existing on master: master's own IntegrationTest run (commit 641d5d0) fails the same OrdinaryDiffEq/LinearSolve/Catalyst/NonlinearSolve-Core jobs, and NonlinearSolve.jl/Core fails with the known Broyden robustness regression tracked in Master CI red since 2026-07-12: "23 Test Problems: Broyden" alg #4 broken-list mismatch, bisected to #1039 (merged via cancelled CI run) NonlinearSolve.jl#1083 (bisected there to NonlinearSolve#1039; unrelated to this PR).

🤖 Generated with Claude Code

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

CI status for head 542eb18 (final): 50 pass / 12 fail / 1 pending, and every failure is accounted for as not-this-PR:

  • The one real regression is confirmed fixed by CI: SciMLSensitivity Core1–Core8 all pass (Core6/Core8 failed on the previous head via the unwrapped_f MethodError).
  • Own suites all green: Core (lts/1/pre), DownstreamAD (lts/1), Python (×3), QA, SymbolicIndexingInterface (lts/pre; julia-1 still running). The two tests/Downstream (julia 1, pre) failures are self-hosted runner disconnects ("runner lost communication with the server" annotations) — a re-run should clear them; I don't have workflow-rerun permission on this repo.
  • The remaining 10 failures are the third-party integration jobs that fail identically on master (OrdinaryDiffEq ×6, Catalyst ×2, LinearSolve, and NonlinearSolve/Core with the known Broyden regression tracked in Master CI red since 2026-07-12: "23 Test Problems: Broyden" alg #4 broken-list mismatch, bisected to #1039 (merged via cancelled CI run) NonlinearSolve.jl#1083).

Ready for review.

🤖 Generated with Claude Code

Comment thread src/scimlfunctions.jl Outdated
Comment on lines +1938 to +1939
precondition::PC
postcondition::POC

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is the part which I struggled with so hard when trying to integrate it myself and I am still not sure if I just overthink this or if this is a true concern. Technically the left and right preconditioner are parts of the solver, but this design proposes, if I understand correctly, that the preconditioner is part of the function. But we also need some consistent way to communicate information about f to the preconditioner (e.g. decomposition or boundary information). So, is this really the way to go down?

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.

@termi-official That's a fair challenge and I don't think you're overthinking it. My take: the question isn't solver vs. function, it's who knows the preconditioner, and there are two genuinely different answers that want two different homes.

Model-declared conditioning. A diode's junction-limiting rule, a discretization's Dirichlet condensation, a Modelica-style homotopy annotation — these are properties of the equations. The solver cannot invent them; only whoever wrote the model knows them. Modelica puts homotopy(actual, simplified) in the model for exactly this reason, and this is the half this PR serves. It's not hypothetical: SciML/ModelingToolkit.jl#4774 (up now) adds a limited(actual, limiter) operator whose whole point is that a component library annotates a device once and every downstream nonlinear solve gets predictor/corrector limiting automatically. That composition needs a place on the function/problem for the model to put the thing; a solver keyword can't be filled in by a component library that has no idea which solver the end user will pick.

Solver-chosen conditioning. ASPIN with a particular subdomain decomposition, a field-split, an Anderson-mixing composition — these are numerical-method choices, and I agree they belong on the algorithm. This PR does not serve that half, and I don't think it should pretend to.

On "how do we communicate information about f to the preconditioner" — that's the sharpest part of your question. What exists today:

  • G(fu, u, p) gets the residual, the iterate, and the parameters, so anything the model routes through p (boundary data, coefficients, MTK bound parameters) is reachable;
  • H(u_proposed, u_prev, p) optionally takes the solver cache as a fourth argument (added this week — H(u_prop, u_prev, p, cache), PETSc-post-check style), which covers iteration count, current residual, tolerances;
  • structural data known at construction time — index sets, a decomposition, compiled per-quantity rules — goes in the closure/callable struct. The MTK layer does exactly this: its generated LimitedPostcondition captures the compiled limiters and their state indices.

What is genuinely not covered, and where I think your concern lands: a preconditioner that must be built from f at solve time — ASPIN partitioning derived from Jacobian sparsity that only exists once the cache is constructed, or a decomposition you want re-derived on reinit!. Closure capture is the wrong tool there.

The SciML precedent for that is LinearSolve's precs: not a preconditioner object on the operator, but a constructor passed to the solver — precs(W, p) -> (Pl, Pr) — which receives the problem data and returns the preconditioner pair. The nonlinear analogue would be an algorithm keyword along the lines of

NewtonRaphson(; nonlinear_precs = (f, u, p) -> (G, H))

evaluated at cache construction (and re-evaluated on reinit!), producing the same G/H the solver already knows how to apply. The two layers then compose cleanly rather than competing: the algorithm-side constructor wraps whatever the function declares, in the same way a linsolve preconditioner composes with a Jacobian the function supplied.

I'd rather land that as a follow-up than widen this PR, since it's additive and the field-side machinery is what it would reuse. But if you'd rather see the precs-style hook designed before the function-side fields are committed to — so the two are shaped together and we don't end up with a field-side API that the algorithm-side one has to work around — say so and I'll prototype it on this branch instead. You filed the issue and you've already hit the wall once trying to integrate this, so I'd weight your read on that heavily.

🤖 Generated with Claude Code

Nonlinear preconditioning is a solver-side concern: a left preconditioner
`G(fu, u, p)` on the residual and an iterate corrector
`H(u_proposed, u_prev, p[, cache])` applied to accepted iterates, in the sense
of Brune, Knepley, Smith & Tu (SIAM Review 57(4), 2015).

Registering them in `allowedkeywords` is the whole SciMLBase surface: they are
then ordinary solve options, so they can be supplied late at `solve`/`init` or
carried on a problem's `kwargs` and merged in like any other keyword, and a
misspelling is caught by the existing keyword validation. Semantics live in the
solver packages; see SciML/NonlinearSolve.jl#351.

Co-Authored-By: Chris Rackauckas <[email protected]>
@ChrisRackauckas-Claude
ChrisRackauckas-Claude force-pushed the nonlinearfunction-conditioning-hooks branch from 542eb18 to f07b0d0 Compare August 5, 2026 10:26
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Redesigned: these are now solve keywords, not NonlinearFunction fields

Per @ChrisRackauckas — and this also answers @termi-official's review objection directly, since a solve keyword is a solver-side option rather than a property of the function.

precondition and postcondition are now ordinary solver keywords. The entire SciMLBase surface is two entries in allowedkeywords (26-line diff, down from 112), and everything else follows from machinery that already exists:

  • Late binding. solve(prob, alg; postcondition = H) attaches limiting to an existing problem with no rebuild — the motivating case, and the one the field-based design could not serve.
  • Problem-level attachment for free. prob.kwargs are already merged into the solve keywords, with solve-time winning (same precedence as alias), so NonlinearProblem(f, u0, p; postcondition = H) works with no new machinery. That is how ModelingToolkit now attaches the corrector generated from limited(...).
  • Typo protection for free. postcondtion = H is rejected by the existing keyword validation instead of being silently dropped.

It also deletes the entire class of bug this PR kept hitting. Both defects found during review came from adding struct fields, not from the feature: remake merges function fields and let nothing fall back to the old function's value, resurrecting a consumed hook (which forced a ComposedPrecondition sentinel), and unwrapped_f reconstructs NonlinearFunction positionally, which broke SciMLSensitivity's SteadyStateAdjoint. With no new fields, neither exists — the sentinel is gone, replaced by a check on whether the residual is already wrapped.

Two caveats worth knowing

  1. Precedence is override, not compose. A corrector passed at solve replaces one carried on the problem; it does not run in addition to it. With a ModelingToolkit device library that declares limiting, passing your own silently drops the model's. Documented in the tutorial and the MTK docs.
  2. Forwarding from an ODEProblem to an implicit stepper's inner Newton solve is not automatic. prob.kwargs merge into the ODE solve's keywords, but OrdinaryDiffEq constructs its own nonlinear problem for the implicit stage and would need to forward postcondition into its nlsolver explicitly. That is the transient-circuit case; the keyword design makes it reachable, but it needs OrdinaryDiffEq work to actually land.

Verification (local, Julia 1.12, dev'd across the stack)

Rebased onto current master. Behaviour is unchanged from the field-based version, including the headline numbers:

Check Result
Late-bound postcondition on the PCNR diode circuit plain 179 steps → 11, problem object untouched and re-solving at 179
Same corrector carried on the problem instead 11 steps, identical
Solve-time corrector overriding a problem-level one override observed
precondition (asinh) on the scalar diode 57 → 9 steps
Four-argument corrector receiving the cache receives nothing at the initial guess, then the real cache
Solver coverage NewtonRaphson, TrustRegion, LevenbergMarquardt, Broyden, Klement, DFSane, default polyalg, init/solve!
Guards unsupported solver throws, lb/ub combination throws, precondition still composes on the SimpleNonlinearSolve path
Typo postcondtion rejected by allowedkeywords
Tutorial all 7 @example blocks execute, same numbers

Suites: SciMLBase problem_building_test.jl (both testsets), NonlinearSolveBase Core (26/26 in the new testset, suite green), ModelingToolkitBase limited_operator.jl 29/29 including a new override test. NonlinearSolveFirstOrder Core was still running when this was written; I'll report it.

🤖 Generated with Claude Code

@ChrisRackauckas-Claude ChrisRackauckas-Claude changed the title Add precondition/postcondition nonlinear preconditioning hooks to NonlinearFunction Register precondition/postcondition as common solver keywords Aug 5, 2026
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review August 5, 2026 10:33
@ChrisRackauckas
ChrisRackauckas merged commit 76406c4 into SciML:master Aug 5, 2026
35 of 63 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