Skip to content

Let a driver defer the residual evaluation that ends a step - #1167

Merged
ChrisRackauckas merged 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:nsa-deferred-residual
Aug 15, 2026
Merged

ChrisRackauckas merged 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:nsa-deferred-residual

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Please ignore until reviewed by @ChrisRackauckas.

GeneralizedFirstOrderAlgorithmCache's step! always ends by evaluating the residual at the iterate it just landed on. A caller that drives the cache one step at a time and decides convergence itself — OrdinaryDiffEq's NonlinearSolveAlg is the motivating one — never reads that value on the iteration it stops at: it re-reinit!s at a new point, discarding it. That is one wasted f per stage solve, which on stiff ODE integration is 20–45% of all residual evaluations.

This adds an opt-in way to defer it. Nothing changes for existing callers: the new predicate defaults to false, and step!'s new keyword defaults to true.

API

  • NonlinearSolveBase.supports_deferred_residual(cache) -> Bool — whether step!(cache; evaluate_residual = false) is honoured. false for every cache that does not opt in.
  • NonlinearSolveBase.refresh_residual!(cache) — bring a deferred residual forward. One contract: evaluate at get_u, run the convergence check the step would have run, leave the cache as a plain step! would have; no-op when nothing is outstanding. There is a default refresh_residual!(::AbstractNonlinearSolveCache) = nothing so a driver can sync before every read without asking what kind of cache it holds.
  • InternalAPI.step!(cache; evaluate_residual::Bool = true) on GeneralizedFirstOrderAlgorithmCache.

Both new names are Compat.@compat public, documented, and added to docs/src/devdocs/internal_interfaces.md.

Where deferral is refused

evaluate_residual = false is a hint, not a command: step! gates on the same predicate a caller would query, so a package that passes it without checking cannot be burnt. It is honoured only when all three hold:

  1. Val{:None} globalization — a line search or trust region consumes the residual as it goes.
  2. A residual-only termination mode (AbsTerminationMode, AbsNormTerminationMode). Every AbstractSafeNonlinearTerminationMode is excluded: their stall/patience counters need the per-step u - uprev history that a deferred step cannot supply. Concretely, with the library default AbsNormSafeBestTerminationMode(...; max_stalled_steps = 32), deferral leaves u_cache == u, so step_norm_trace sees a permanent zero displacement and the cache reports ReturnCode.Stalled after 32 steps. Measured, with the guard removed: nsteps=33 retcode=Stalled; with it: nsteps=40 retcode=Default.
  3. An inactive trace — update_trace! reads get_fu.

The deferral is also settled at the top of the next step!, so interleaving deferred and non-deferred steps is safe.

Correctness of the flag

The outstanding-deferral flag lives on the cache and is set only inside the descent_result.success branch, when the evaluation was actually skipped. An earlier draft set it in the driver, which cannot tell whether step! did anything — CommonSolve.step! returns immediately on a terminated cache, and a failed descent never touches u. That draft cost 20–23% extra f on problems whose residual reaches exactly zero (linear, scalar, equilibrium starts), because each spurious refresh pays twice: the evaluation plus update_from_termination_cache!'s re-evaluation. With the invariant owned by the cache:

alg       problem            |   master    draft      fix | draft/mst  fix/mst
TRBDF2    linear1-iip        |    10920    13276    10736 |     1.216    0.983
TRBDF2    linear-oop-scalar  |    59780    72578    59778 |     1.214    1.000
KenCarp4  linear-oop-scalar  |    10187    12337    10187 |     1.211    1.000
FBDF      linear-oop-scalar  |     4671     5753     4671 |     1.232    1.000
QNDF      linear-oop-scalar  |     2323     2803     2323 |     1.207    1.000

Trajectory hashes identical across all three builds; no row worse than master.

Effect downstream

With the companion OrdinaryDiffEq change, over 60 configurations (5 stiff problems × TRBDF2/KenCarp4/FBDF/QNDF × rtol 1e-6/1e-9/1e-12): total f 10,857,930 → 6,587,656, per-config ratio median 0.787, worst 0.883 — and retcode, naccept, nreject, njacs, nw, nnonliniter, nnonlinconvfail and the achieved error are identical on all 120 rows, checked row by row rather than by summary.

Tests

New lib/NonlinearSolveFirstOrder/test/misc_tests__item7.jl, 144 assertions, covering the predicate over 12 cache configurations, the hint being refused, the settle-at-next-step path, and "a step that does nothing defers nothing". Negative controls, each run:

  • remove the outstanding-deferral guard → 8 failures, including Evaluated: 2 == 0 (the two f calls above);
  • restore the predicate that ignored the termination mode → the Stalled failure above;
  • remove the default refresh_residual! method → MethodError on a polyalgorithm cache.

GROUP=Core for NonlinearSolveFirstOrder passes. Runic and typos clean.

Versions

NonlinearSolveBase 2.44.0 → 2.45.0, NonlinearSolveFirstOrder 2.3.2 → 2.4.0 (its NonlinearSolveBase floor 2.42 → 2.45). Both additive.

Not addressed here

update_from_termination_cache! re-evaluates the residual at the identical (u, p) immediately after step!'s own evaluation. On a standalone NonlinearProblem that is ~40% of all residual evaluations. It is nearly free in the ODE driver (0–3 calls per solve, because the zeroed inner tolerances mean the inner check almost never terminates), so it is out of scope here — but it looks like a real saving for direct NonlinearSolve users and deserves its own issue.

🤖 Generated with Claude Code

`GeneralizedFirstOrderAlgorithmCache`'s unglobalized step ends by evaluating the residual at
the iterate it just produced. That value is the right-hand side of the *next* step, so a
driver that stops stepping — an implicit ODE integrator running one Newton iteration per
outer iteration — pays for an evaluation nothing reads. `step!` now takes
`evaluate_residual = false` to skip it and `refresh_residual!` settles it if the driver turns
out to want the residual after all.

The keyword is a hint, not an instruction. Deferring leaves `u_cache` equal to `u` and
reaches the termination check once per `refresh_residual!` instead of once per step, so a
mode reading a displacement or keeping a per-step history would be answering about a step
that never happened: the default `AbsNormSafeBestTerminationMode(...; max_stalled_steps =
32)` would report `ReturnCode.Stalled` on step 33 of any solve driven this way. A trace
likewise records the residual at the iterate the step landed on. `step!` therefore honours
the request only where `supports_deferred_residual` does, which requires a residual-only
termination mode and an inactive trace on top of `Val{:None}` globalization.

The cache tracks the outstanding evaluation itself, so `refresh_residual!` is free when
there is nothing to settle, the next `step!` settles one without being asked, and a driver
can sync ahead of every read of `get_fu` without asking which cache it is talking to.

NonlinearSolveBase 2.44.0 -> 2.45.0 and NonlinearSolveFirstOrder 2.3.2 -> 2.4.0, both
additive.

Co-Authored-By: Chris Rackauckas <[email protected]>
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review August 15, 2026 09:13
@ChrisRackauckas
ChrisRackauckas merged commit 2bf068a into SciML:master Aug 15, 2026
12 of 15 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.

2 participants