Repository navigation
Let a driver defer the residual evaluation that ends a step - #1167
Merged
ChrisRackauckas merged 2 commits intoAug 15, 2026
Merged
Conversation
`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
marked this pull request as ready for review
August 15, 2026 09:13
This was referenced Aug 16, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Please ignore until reviewed by @ChrisRackauckas.
GeneralizedFirstOrderAlgorithmCache'sstep!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'sNonlinearSolveAlgis 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 wastedfper 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, andstep!'s new keyword defaults totrue.API
NonlinearSolveBase.supports_deferred_residual(cache) -> Bool— whetherstep!(cache; evaluate_residual = false)is honoured.falsefor every cache that does not opt in.NonlinearSolveBase.refresh_residual!(cache)— bring a deferred residual forward. One contract: evaluate atget_u, run the convergence check the step would have run, leave the cache as a plainstep!would have; no-op when nothing is outstanding. There is a defaultrefresh_residual!(::AbstractNonlinearSolveCache) = nothingso a driver can sync before every read without asking what kind of cache it holds.InternalAPI.step!(cache; evaluate_residual::Bool = true)onGeneralizedFirstOrderAlgorithmCache.Both new names are
Compat.@compat public, documented, and added todocs/src/devdocs/internal_interfaces.md.Where deferral is refused
evaluate_residual = falseis 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:Val{:None}globalization — a line search or trust region consumes the residual as it goes.AbsTerminationMode,AbsNormTerminationMode). EveryAbstractSafeNonlinearTerminationModeis excluded: their stall/patience counters need the per-stepu - uprevhistory that a deferred step cannot supply. Concretely, with the library defaultAbsNormSafeBestTerminationMode(...; max_stalled_steps = 32), deferral leavesu_cache == u, sostep_norm_tracesees a permanent zero displacement and the cache reportsReturnCode.Stalledafter 32 steps. Measured, with the guard removed:nsteps=33 retcode=Stalled; with it:nsteps=40 retcode=Default.update_trace!readsget_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.successbranch, when the evaluation was actually skipped. An earlier draft set it in the driver, which cannot tell whetherstep!did anything —CommonSolve.step!returns immediately on a terminated cache, and a failed descent never touchesu. That draft cost 20–23% extrafon problems whose residual reaches exactly zero (linear, scalar, equilibrium starts), because each spurious refresh pays twice: the evaluation plusupdate_from_termination_cache!'s re-evaluation. With the invariant owned by the cache: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
f10,857,930 → 6,587,656, per-config ratio median 0.787, worst 0.883 — andretcode,naccept,nreject,njacs,nw,nnonliniter,nnonlinconvfailand 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:Evaluated: 2 == 0(the twofcalls above);Stalledfailure above;refresh_residual!method →MethodErroron a polyalgorithm cache.GROUP=CoreforNonlinearSolveFirstOrderpasses. Runic andtyposclean.Versions
NonlinearSolveBase2.44.0 → 2.45.0,NonlinearSolveFirstOrder2.3.2 → 2.4.0 (itsNonlinearSolveBasefloor 2.42 → 2.45). Both additive.Not addressed here
update_from_termination_cache!re-evaluates the residual at the identical(u, p)immediately afterstep!'s own evaluation. On a standaloneNonlinearProblemthat 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 directNonlinearSolveusers and deserves its own issue.🤖 Generated with Claude Code