Skip to content

Nonlinear preconditioning hooks: precondition (G) / postcondition (H) with PCNR limiting support - #1084

Merged
ChrisRackauckas merged 4 commits into
SciML:masterfrom
ChrisRackauckas-Claude:nonlinear-preconditioning-hooks
Aug 6, 2026
Merged

ChrisRackauckas merged 4 commits into
SciML:masterfrom
ChrisRackauckas-Claude:nonlinear-preconditioning-hooks

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Important

This PR should be ignored until reviewed by @ChrisRackauckas.

Note

Depends on SciML/SciMLBase.jl#1449 (adds the precondition/postcondition fields to NonlinearFunction, v3.37.0). CI here will fail to resolve until that PR is merged and released; all test groups below were run locally against the companion branch.

Closes #351.

Summary

Implements nonlinear preconditioner support in the sense of Brune, Knepley, Smith & Tu, Composing Scalable Nonlinear Algebraic Solvers (SIAM Review 57(4), 2015): the solver works with the root-equivalent composed system

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

where both hooks may depend on the current iterate (frozen within each iteration).

  • precondition (left, G(fu, u, p)) is implemented as a problem transformation (mirroring the bounds-transform pattern): before the cache is built, f is replaced by the composition u -> G(f(u,p), u, p) via a PreconditionWrapper. Every consumer — residual evaluations, AD Jacobians, line-search merit functions, termination criteria — sees the composed map, for every solver including SimpleNonlinearSolve and extension wrappers.
  • postcondition (right, H(u_proposed, u_prev, p)) is applied at the iterate-commit points of the solver step! loops (FirstOrder, QuasiNewton, Spectral families), before the residual is evaluated and convergence is tested at the new iterate, and once to the initial guess as H(u0, u0, p). A supports_postcondition(alg) trait guards against silent ignoring: unsupported algorithms (e.g. SimpleNonlinearSolve) throw an ArgumentError; poly-algorithms support it iff all sub-algorithms do.

This fully encapsulates the PCNR (Predictor/Corrector Newton-Raphson) method of Aadithya, Keiter & Mei for replacing device limiting in circuit simulation: predictor = the ordinary Newton step on the (user-formulated) augmented system, corrector = the postcondition limiter, and PCNR's consistency property holds structurally because residual/Jacobian are only ever evaluated at corrected iterates. (postcondition is the analogue of PETSc SNES post-check.)

Changes

  • NonlinearSolveBase (2.35.0 → 2.36.0): new src/conditioning.jl (PreconditionWrapper, needs_conditioning, transform_conditioned_problem, apply_postcondition!!, supports_postcondition trait, ComposedPrecondition sentinel); transform applied at the solve_call/init_call/__solve funnels (before the bounds transform); poly-algorithm trait; new names declared public with docstrings; SciMLBase compat 3.37.
  • NonlinearSolveFirstOrder (2.2.1 → 2.3.0), NonlinearSolveQuasiNewton (1.14.1 → 1.15.0), NonlinearSolveSpectralMethods (1.7.3 → 1.8.0): apply_postcondition!! at each iterate-commit point (LineSearch/TrustRegion/None branches; TrustRegion re-evaluates fu at the corrected iterate), supports_postcondition = true.
  • SimpleNonlinearSolve (2.13.0 → 2.14.0): the bypass CommonSolve.solve entries apply the conditioning transform, so precondition genuinely composes there and postcondition errors instead of being silently ignored.
  • NonlinearSolve (4.21.0 → 4.22.0): new tutorial docs/src/tutorials/nonlinear_preconditioning.md (registered in pages.jl) with a PCNR circuit-limiting walkthrough.
  • Tests in every touched sublibrary + an umbrella-level default-polyalgorithm test.

Design notes

  • The transform clears the consumed precondition with a ComposedPrecondition sentinel, not nothing: remake(prob; f = new_f) merges function fields and lets nothing fields fall back to the old function's values, which would resurrect the hook and double-wrap (caught by an integration test that inspects the wrapper type).
  • postcondition + lb/ub bounds throws: the bounds transform changes the iterate coordinates the hook would act on.
  • With precondition, user-supplied jac/jvp/vjp/jac_prototype/sparsity are documented to describe the composed residual; the default AD path differentiates the composition automatically.
  • sol.resid for preconditioned problems is the preconditioned residual (what the solver measured).

Verification (all run locally, Julia 1.12.4, against SciMLBase#1449)

Suite Result
NonlinearSolveBase Core (incl. new transform unit tests) passed
NonlinearSolveFirstOrder Core (incl. new conditioning integration tests) passed
NonlinearSolveQuasiNewton Core (incl. new postcondition test) passed
NonlinearSolveSpectralMethods Core (incl. new DFSane postcondition test) passed
SimpleNonlinearSolve Core (incl. new compose/throw tests) passed
NonlinearSolve umbrella Core (incl. default-polyalg hook test) passed, except two pre-existing master failures in "23 Test Problems: Broyden" (no hooks involved) — reproduced on clean master, bisected to #1039, tracked in #1083; the new hooks testset passes 4/4
Tutorial @example blocks executed verbatim all succeed

Measured behavior (verified by running, not estimated):

  • Scalar diode from v0 = 2.0 V: plain NewtonRaphson 57 steps → asinh-preconditioned 9 steps.
  • PCNR diode circuit (Vs=5, R=1k, augmented [v, vj], pnjlim postcondition) from zeros: plain 179 steps → limited 11 steps; TrustRegion and LevenbergMarquardt also converge with the hook.
  • SimpleNewtonRaphson at maxiters=15: plain fails, asinh-preconditioned succeeds (proves the composition actually applies on the bypass path).

Process log

  1. Read issue Nonlinear Preconditioner Support #351 + the PCNR paper; concluded PCNR = iterate-dependent right preconditioning applied as a per-iteration corrector with consistent re-evaluation (discussion in the issue-linked conversation).
  2. Extended NonlinearFunction in SciMLBase (companion PR), then implemented G as an init-time problem transformation and H as commit-point application, following the existing bounds-transform architecture.
  3. Found and fixed two integration bugs by running locally: (a) remake field-merge resurrecting the consumed hook (fixed with sentinel), (b) SimpleNonlinearSolve bypassing the funnels (fixed at its entry points, with an error guard for H).
  4. One test-design fix: a saturating G = r/(1+|r|) on a residual linear in u makes Gauss-Newton diverge (derivative decays faster than the function) — replaced with a row re-weighting G and documented the "compress selectively" guidance in the tutorial.

🤖 Generated with Claude Code

https://claude.ai/code/session_01B9GHoo4pFa3DU9yhyTkevL

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

New commit 7b9f590: postcondition hooks may now accept the solver cache as a fourth argument — H(u_proposed, u_prev, p, cache) — dispatched by arity (applicable; four-arg preferred when both exist), analogous to PETSc post-check receiving the SNES object. Contract:

  • cache is the solver's AbstractNonlinearSolveCache; hooks must use only the documented public accessors. To that end get_nsteps was added and get_u/get_fu/get_nsteps are now declared public (joining the already-public get_abstol/get_reltol), with the interface docstring updated.
  • cache === nothing for the initial-guess correction H(u0, u0, p, nothing), which runs before any cache exists — four-argument hooks must accept nothing there (documented in the SciMLBase docstring, apply_postcondition!! docstring, and the tutorial).
  • Enables solver-state-aware correctors, e.g. Xyce-style iteration-staged limiting; the tutorial gained a staged-pnjlim @example using get_nsteps (verified: converges in 11 steps).

Re-verified locally after the change (Julia 1.12.4): NonlinearSolveBase Core (28/28 in the hooks testset, incl. new arity-dispatch unit tests), NonlinearSolveFirstOrder Core (incl. a 4-arg integration test asserting the hook sees nothing once and a real cache thereafter), NonlinearSolveQuasiNewton Core, NonlinearSolveSpectralMethods Core — all passed; all 7 tutorial blocks execute. Companion docstring commit pushed to SciML/SciMLBase.jl#1449 (docs-only, no version change).

🤖 Generated with Claude Code

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

CI note: no workflow runs have been scheduled for this fork PR (zero check-runs on both pushed heads; SciML/SciMLBase.jl runs the same account's fork PRs fine, so this repo's Actions settings appear to gate fork workflows behind maintainer approval). @ChrisRackauckas — when you get to the review, the workflows will need the "Approve and run" click. Note CI here is expected to fail dependency resolution until SciML/SciMLBase.jl#1449 is merged and released (NonlinearSolveBase now requires SciMLBase ≥ 3.37); all seven local test suites are green as documented above.

🤖 Generated with Claude Code

@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

…dition

Implements the `precondition` (left preconditioner G) and `postcondition`
(iterate corrector H) solve keywords registered in SciMLBase, per the
composed-solver framework of Brune, Knepley, Smith & Tu (SIAM Review 2015),
solving G(f(H(u_tilde, u_k), p), u_tilde, p) = 0.

- G is applied as a problem transformation at the solve/init funnels, so the
  composed residual is what every consumer sees: function evaluations, AD
  Jacobians, line-search merit functions, and termination. It works with every
  solver that consumes the problem function, including SimpleNonlinearSolve.
- H is read from the cache's keywords and applied at the iterate-commit points
  of the first-order, quasi-Newton, and spectral step! loops (and once to u0),
  before the residual is evaluated there. A supports_postcondition trait makes
  unsupported solvers throw rather than silently ignore it. Correctors may take
  the solver cache as an optional fourth argument, for which get_nsteps joins
  get_u/get_fu/get_abstol/get_reltol as public cache accessors.

Both are ordinary solve keywords rather than function properties, so they can be
bound late — solve(prob, alg; postcondition = H) needs no rebuild of the problem
— or carried on the problem and forwarded like any other option, with the
solve-time value winning as for alias. This is what makes them usable for
solver-chosen preconditioning (ASPIN-style) as well as model-declared limiting.

Fully encapsulates the PCNR predictor/corrector limiting method of Aadithya,
Keiter & Mei: the predictor is the ordinary Newton step on the augmented system,
the corrector is the postcondition, and consistency holds structurally because
residuals are only evaluated at corrected iterates. Adds a tutorial with a
pnjlim diode-circuit walkthrough (179 -> 11 Newton steps) and asinh residual
compression (57 -> 9 steps).

Requires SciMLBase >= 3.43. Fixes SciML#351.

Co-Authored-By: Chris Rackauckas <[email protected]>
@ChrisRackauckas-Claude
ChrisRackauckas-Claude force-pushed the nonlinear-preconditioning-hooks branch from 5e01573 to 97bce87 Compare August 5, 2026 10:40
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

SciMLBase 3.43.0 is registered (JuliaRegistries/General#163665 merged), so this PR's dependency is now resolvable and CI can run for the first time.

Verified against the released SciMLBase rather than a local checkout — a fresh environment with only this branch's sublibraries dev'd resolves SciMLBase v3.43.0 from the registry, and the full option matrix passes there:

  • late-bound postcondition: 179 → 11 steps, problem object untouched
  • the same corrector carried on the problem instead: 11 steps
  • solve-time corrector overriding a problem-level one: observed
  • precondition (asinh) on the scalar diode: 57 → 9 steps
  • four-argument corrector receiving the cache (nothing at the initial guess, then the real cache)
  • solver coverage: NewtonRaphson, TrustRegion, LevenbergMarquardt, Broyden, Klement, DFSane, default polyalgorithm, init/solve!
  • guards: unsupported solver throws, lb/ub combination throws, precondition still composes on the SimpleNonlinearSolve path
  • postcondtion typo rejected by allowedkeywords

Suite status on this exact head (97bce870, rebased onto current master): NonlinearSolveBase Core green (26/26 in the new testset), NonlinearSolveFirstOrder Core green (11/11 and 18/18 in the two new testsets), all 7 tutorial @example blocks execute.

@ChrisRackauckas — this repo gates fork-PR workflows, so CI here needs an "Approve and run" click; no workflow run has ever been scheduled for this PR.

🤖 Generated with Claude Code

post-check receiving the `SNES` object):

```@example preconditioning
H_staged! = function (up, uprev, p, cache)

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.

It should always have the 4th argument, it should just have a constant definition to simplify the code.

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.

Done in 6a4ccea. postcondition now always takes (u_proposed, u_prev, p, cache); correctors that don't need solver state just ignore the argument. That let me delete the applicable arity detection entirely — the apply path is now a direct call, and the initial-guess correction passes nothing for the cache. Propagated through the docs, all tests, and ModelingToolkit's generated LimitedPostcondition (SciML/ModelingToolkit.jl#4774).

Comment on lines +222 to +224
[bound constraints tutorial](bound_constraints.md); `postcondition` combined with
`lb`/`ub` is rejected since the bounds transform changes the iterate coordinates the
corrector would act on.

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.

It shouldn't be rejected, it should compose, but the user needs a warning here that the condition is imposed on the transformed variable.

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.

Done in 6a4ccea — they compose now. Since the bounds transform runs after this pass, every in-loop application of the corrector sees the unconstrained coordinate, so the warning says exactly that: the condition is imposed on the transformed iterate, not the original bounded variable. It goes through a new postcondition_bounds_transform verbosity toggle (WarnLevel by default). One consequence worth flagging: I skip the initial-guess correction when bounds are active, so that every application happens in the same coordinate system rather than the first one being in user coordinates and the rest in transformed ones.

Comment on lines +228 to +231
- **Signatures.** Out-of-place problems use `Gfu = G(fu, u, p)` and
`u_new = H(u_proposed, u_prev, p)`; in-place problems mutate the first argument:
`G(fu, u, p) -> nothing` overwrites `fu`, `H(u_proposed, u_prev, p) -> nothing`
overwrites `u_proposed`.

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.

This is just for the docstring.

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.

Done in 6a4ccea — the signature bullet is out of the tutorial and the full in-place/out-of-place signatures for both options now live in the solve docstring's keyword list (lib/NonlinearSolveBase/src/solve.jl), alongside the error-control and miscellaneous options.

Comment on lines +232 to +235
- **Precedence.** A value passed to `solve`/`init` overrides one carried on the
problem; it does not compose with it. If a model-generating package (for example a
ModelingToolkit component library with device limiting) attached a corrector to the
problem, passing your own at solve time replaces it entirely.

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.

This is all kwargs, no need here

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.

Done in 6a4ccea — dropped. Ordinary keyword precedence applies and doesn't need restating in a tutorial.

Comment on lines +246 to +252
- **Solver support.** The first-order (`NewtonRaphson`, `TrustRegion`,
`LevenbergMarquardt`, ...), quasi-Newton (`Broyden`, `Klement`, ...), and spectral
(`DFSane`) families and poly-algorithms composed of them support `postcondition`;
unsupported solvers (e.g. SimpleNonlinearSolve or external wrappers) throw an
`ArgumentError` rather than silently ignoring it. `precondition` is a problem
transformation and works with every solver that consumes the problem function,
including SimpleNonlinearSolve.

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.

This error should be able to be turned off via SciMLLogging.

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.

Done in 6a4ccea — it's now the unsupported_postcondition verbosity toggle instead of a bare throw. Worth noting the default behaviour is unchanged: SciMLLogging raises an ErrorException at ErrorLevel, so an unsupported solver still stops rather than silently dropping the corrector — but it's now silenceable (verbose = NonlinearVerbosity(SciMLLogging.None())), which the tests cover in both the base and SimpleNonlinearSolve suites.

…reports

Addresses @ChrisRackauckas's review on SciML#1084:

- postcondition correctors now always take the solver cache as a fourth
  argument; correctors that do not need it ignore the parameter. Dropping the
  arity detection simplifies the apply path to a direct call.
- postcondition and lb/ub now compose instead of being rejected. Bounds are
  handled by transforming to an unconstrained variable, so the corrector acts on
  the transformed iterate; that change of coordinates is reported through the new
  postcondition_bounds_transform verbosity toggle, and the initial-guess
  correction is skipped so every application happens in the same space.
- the unsupported-solver report goes through SciMLLogging as the new
  unsupported_postcondition toggle rather than a bare throw: it still raises by
  default (SciMLLogging raises at ErrorLevel) but can be turned down.
- tutorial: cite the PCNR paper where the circuit example introduces it, drop the
  Schur-complement paragraph, and drop the signature and precedence bullets --
  signatures now live in the solve docstring, and precedence is ordinary keyword
  behaviour.

Co-Authored-By: Chris Rackauckas <[email protected]>
ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/ModelingToolkit.jl that referenced this pull request Aug 6, 2026
Follows the postcondition contract change in SciML/NonlinearSolve.jl#1084:
correctors always receive the solver cache as a fourth argument. The generated
LimitedPostcondition accepts and ignores it, since limiters are functions of the
iterate and parameters only.

Co-Authored-By: Chris Rackauckas <[email protected]>
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review August 6, 2026 12:16
@ChrisRackauckas
ChrisRackauckas merged commit 4aad487 into SciML:master Aug 6, 2026
99 of 103 checks passed
ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/NonlinearSolve.jl that referenced this pull request Aug 7, 2026
test/Core/core_tests__item23.jl asserts that `postcondtion` is rejected by
SciMLBase's common keyword whitelist, so the misspelling is the point of the
test and cannot be corrected. The Spell Check workflow has failed on every PR
since SciML#1084 introduced that test.

Allow it via `[type.jl.extend-identifiers]`: scoped to Julia sources and to the
exact, case-sensitive identifier, so the same typo is still caught in prose, in
a compound name, or in any other capitalization.

Co-Authored-By: Chris Rackauckas <[email protected]>
ChrisRackauckas added a commit that referenced this pull request Aug 7, 2026
…ks (#1141)

* Document NonlinearSolveBase public API added by the preconditioning hooks

`run_api_docs` requires every name in NonlinearSolveBase's public API to
have a docstring and to be rendered in a `@docs` block under docs/src.
#1084 made nine names public without docs entries, which fails the QA
group.

Add docstrings for the three cache accessors (`get_u`, `get_fu`,
`get_nsteps`) and render all nine in docs/src/devdocs/internal_interfaces.md.

Co-Authored-By: Chris Rackauckas <[email protected]>

* Tell typos the deliberate keyword misspelling in the test is intentional

test/Core/core_tests__item23.jl asserts that `postcondtion` is rejected by
SciMLBase's common keyword whitelist, so the misspelling is the point of the
test and cannot be corrected. The Spell Check workflow has failed on every PR
since #1084 introduced that test.

Allow it via `[type.jl.extend-identifiers]`: scoped to Julia sources and to the
exact, case-sensitive identifier, so the same typo is still caught in prose, in
a compound name, or in any other capitalization.

Co-Authored-By: Chris Rackauckas <[email protected]>

---------

Co-authored-by: ChrisRackauckas-Claude <[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.

Nonlinear Preconditioner Support

2 participants