Skip to content

Improve HomotopySweep adaptive step control: success expansion, quality-gated growth, trust-monitored secant predictor - #967

Merged
ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:homotopy-sweep-adaptive-control
Jul 9, 2026
Merged

ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:homotopy-sweep-adaptive-control

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Note

This PR should be ignored until reviewed by @ChrisRackauckas.

Follow-up to #962 (cf. this comment): improves the adaptive algorithm in HomotopySweep.

What was there before

The adaptive logic was failure-only: a rejected step halved dλ and the increment never grew back, so one hard region permanently degraded the resolution of the rest of the sweep. Warm starts were zeroth-order (reuse previous u).

What this adds

Three mechanisms from the predictor-corrector path-tracking literature, sized for a natural-parameter sweep whose corrector is a generic NonlinearSolve algorithm (no polynomial structure, no tangent/Jacobian access from the sweep itself):

  1. Success expansion (the classic success/failure heuristic, e.g. Timme, Mixed precision path tracking for polynomial homotopy continuation, Adv. Comput. Math. 47 (2021)): after expand_threshold consecutive accepted steps, dλ grows by expand_factor (default ×2), capped at max_step_factor of the span width.

  2. Quality-gated growth (a Deuflhard-style local error estimate): the known failure mode of the pure success/failure heuristic is expensive trial-and-error in hard regions (cf. Hao & Zheng 2020) — the step balloons on the easy stretch before a sharp turn, and each oversized rejection costs a full inner-solver iteration budget (measured: one rejection through the default polyalgorithm ≈ 600 residual evaluations). Expansion therefore additionally requires evidence of corrector headroom: either the secant prediction error is small relative to the recent solution movement (expand_quality), or the corrector converged within 2 iterations (which covers exponentially flattening path tails, where the relative error measure stays at a constant mediocre value while the absolute corrections become negligible).

  3. Trust-monitored secant predictor: warm starts extrapolate linearly through the last two accepted points, so the corrector starts on the path tangent. Right after a sharp turn a stale tangent predicts far off the path, so the secant's measured prediction error is compared against the trivial constant prediction each accepted step, with hysteresis: two consecutive good measurements to (re-)engage, any bad measurement or rejected step to disengage and fall back to the constant warm start. predictor = :constant restores the old warm-start behavior.

All defaults preserve the old semantics where it matters: expand_factor = 1 disables growth entirely, expand_quality = Inf disables the gate, adaptive = false fixed-step mode is untouched.

Measured behavior (local runs, Julia 1.11)

Sharp-turn path u*(λ) = 2tanh(20(λ-1/2)) with corrector residual x + 2sin(x) (spurious merit-stationary traps for warm-start error > ~2.09), default polyalgorithm, maxiters = 100:

controller residual evals rejected steps
naive growth (no gate, no trust) 1406 2
+ quality gate 808 1
+ trust monitoring + hysteresis (this PR's default) 98 0
old behavior (no growth), secant 142 0

Smooth cubic path u*(λ) = 1 + λ: secant predictor 36 evals vs 64 constant; easy sweeps finish in 5 steps instead of 11 (growth doubling to the cap).

Tests

Four new test items (registered in test/runtests.jl):

  • item15: constructor defaults + validation for the new kwargs
  • item16: expansion takes strictly fewer steps; max_step_factor cap binds, including over an nsteps-derived initial step
  • item17: secant predictor spends strictly fewer residual evaluations than :constant on a linear path
  • item18: sharp-turn problem — sweep bisects through the turn, the increment regrows on the far shoulder (≥2× within the post-rejection accepted steps), and takes strictly fewer steps than expand_factor = 1

Local test results: all 18 homotopy sweep items pass (86 assertions), NonlinearSolveBase QA (Aqua + ExplicitImports) passes 14/14, Runic check clean. One pre-existing test (item7, aliasing) caught a real bug in an intermediate version of this PR — the θ measurement must not reuse the guess buffer the inner solver may have mutated in place — which is fixed and the test passes.

NonlinearSolveBase bumped 2.31.0 → 2.32.0.

Possible follow-ups (out of scope here)

  • Pseudo-arclength reparameterization for folds (the item6 fold test currently — correctly — reports failure; arclength continuation could follow the path around the turning point)
  • Hao & Zheng (2020)-style augmented systems tracking the minimum Jacobian eigenvalue near bifurcations
  • Higher-order (Padé / polynomial) predictors once more accepted points are retained

🤖 Generated with Claude Code

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Two follow-up commits since the initial push:

For context when reading this PR's CI: master is currently red for unrelated, pre-existing reasons — Runic format-check failures on six sublibrary test/runtests.jl files from #961 (#969), pre-existing :example_block docs errors (large_systems.md, snes_ex2.md), a stale DiffEqBase = "6.213.0" compat in test/trim/Project.toml, a long-standing Downgrade Sublibraries FastClosures lower-bound conflict, and self-hosted-runner infra flakes (gitconfig lock races, lost runners). The signal jobs for this PR are the Core test group (homotopy sweep items 1–18) and the NonlinearSolveBase sublibrary CI.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Pushed Develop in-repo sources for base-env test groups on Julia < 1.11, fixing the only PR-attributable CI failure (tests / Core (julia lts) on both platforms).

Root cause: the root test env's [sources] table is ignored on Julia < 1.11, and unlike the sublibrary and dep-adding group paths, the base-env group path in test/runtests.jl never developed the in-repo paths. So the lts Core jobs resolved NonlinearSolveBase 2.31.0 from the registry and tested that instead of the PR branch — failing on this PR's new kwargs with a kwerr, and silently testing stale sublibrary code on lts for any PR before it. This is also the same mechanism behind the registry-lag Core (julia lts, macos) failure on master at 633d93a (the #962 merge ran CI before 2.31.0 had propagated to the pkg servers).

Verification: ran the full root GROUP=Core suite via Pkg.test() on a fresh Julia 1.10.11 resolve locally — all 49 testsets pass, including the previously-failing HomotopySweep step-control kwargs validation + defaults (18/18), exit 0.

Status of the remaining red checks on the previous run, none PR-caused:

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Final CI status — all PR-relevant jobs green

Green (caused by / exercising this PR's code):

  • tests / Core — all 6 variants (julia 1 / lts / pre × ubuntu / macos), including the lts jobs that the _develop_inrepo_sources commit fixed. The homotopy sweep test items 1–18 run here.
  • sublibraries / lib/NonlinearSolveBase — Core (julia 1 / lts / pre) and QA (julia 1 / lts), all pass.
  • tests / Adjoint, Bounds, NoPre, QA, Verbosity, Wrappers, Downstream — all variants pass.
  • Downgrade / Downgrade Tests - Core, Spell Check, runic-suggestions, all other sublibrary jobs — pass.
  • OrdinaryDiffEq.jl Interface + Regression downstream — pass.

Red, none caused by this PR:

Net: every job that compiles or tests this PR's changes is green. Remaining reds are pre-existing (#968 fixed in-PR, #969/#970/#971 filed) or self-hosted-runner infra.

ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/NonlinearSolve.jl that referenced this pull request Jun 13, 2026
The root test env's [sources] table is ignored on Julia < 1.11, so the
base-env Core group tested the registered NonlinearSolveBase (2.31.0)
instead of this branch's 2.32.0, failing on lts with
`UndefVarError: ArcLengthContinuation not defined`. Develop the in-repo
paths first, as the sublibrary and dep-adding group paths already do.

(Same fix as SciML#967; expect a trivial merge with whichever lands first.)

Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Chris Rackauckas <[email protected]>
…ng loop

Rebase and consolidation of the SciML#967 improvements onto current master (which
gained the λspan[1] anchor in SciML#972 and the SciMLTesting test dispatch), plus
the inner-solver cache reuse now possible after SciML#1008.

Adaptive step control (the classic predictor-corrector success/failure
heuristic, e.g. Timme 2021):
  - `expand_threshold` consecutive accepted steps grow dλ by `expand_factor`,
    capped at `max_step_factor` of the span; a rejected step still halves it.
  - Expansion is gated on a Deuflhard-style local error estimate
    (`expand_quality`): the secant prediction's error must be small relative
    to the recent solution movement, OR the corrector must have converged
    within 2 iterations (covers exponentially flattening paths where the
    relative measure stalls). This keeps the increment from ballooning right
    before a sharp turn, where an oversized step is rejected only after the
    inner solver exhausts its iterations.
  - `predictor = :secant` (default) warm-starts the corrector by linear
    extrapolation through the last two accepted points, trust-monitored with
    hysteresis: measured prediction error no better than half the trivial
    constant prediction — or any rejected step — falls back to the constant
    warm start until two consecutive accepted steps measure good quality
    again. `:constant` restores the previous warm-start behavior.

Cache-reusing, non-allocating driver:
  - `FixLambda` is mutable: the wrapped inner function is built once and
    advancing λ is a field write.
  - The inner solver is `init`ed once and re-driven per step with
    `reinit!`/`solve!` (requires the SciML#1008 LinearSolveParameters fix), reusing
    its workspace instead of reconstructing the solver each step; the anchor
    solve is the cache's first `solve!`.
  - The sweep's own state (`u`, `u_prev`, warm-start and quality-gate scratch)
    lives in preallocated buffers: in-place extrapolation, `Utils.norm_op`
    norms without temporaries, and buffer-swap acceptance. Immutable /
    StaticArray / scalar `u` takes a compile-time non-mutating branch.

The λspan[1] anchor, its retcode semantics, and the zero-width-span behavior
from SciML#972 are preserved verbatim. `expand_factor = 1, predictor = :constant`
reproduces the previous fixed-increment behavior.

Verified locally (Julia 1.11): all 21 homotopy_sweep test items pass (94
assertions) — master's 1-17 (incl. the SciML#972 anchor tests and the aliasing
test) plus new items 18-21 covering kwarg validation, growth + caps, secant
corrector-work reduction, and regrowth after bisecting a hard region. Stats
are per-solve under the reused cache (verified), so the corrector-cheap gate
is unaffected. Whole-solve allocations: scalar default 68176 -> 51840 B; the
few-step scalar SimpleNewtonRaphson case pays for the one-time cache init
(23888 -> 29328 B), which amortizes over longer continuations — the loop is
the regime this solver targets.

Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Chris Rackauckas <[email protected]>
@ChrisRackauckas-Claude
ChrisRackauckas-Claude force-pushed the homotopy-sweep-adaptive-control branch from 42cd2ed to a6478cf Compare July 9, 2026 21:51
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Rebased onto current master as a single consolidated commit (a6478cfc) — the old branch predated the SciMLTesting test-dispatch refactor and #972's λspan[1] anchor, so a literal rebase conflicted on every hunk; the features were re-applied onto master's current file instead.

What the PR now contains:

  1. Adaptive step control (unchanged in substance from the original PR): success-streak expansion capped at max_step_factor, the expand_quality Deuflhard-style gate (with the corrector-cheap ≤2-iterations bypass), and the trust-monitored secant predictor with hysteresis. expand_factor = 1, predictor = :constant reproduces the old fixed-increment behavior.
  2. Cache-reusing, non-allocating loop (new since the last review; requires Fix reinit! resetting LinearSolveParameters to a Missing p-type #1008, now merged): FixLambda is mutable so the wrapped inner function is built once and advancing λ is a field write; the inner solver is inited once and re-driven per step via reinit!/solve! (the anchor solve is the cache's first solve!); the sweep's own state lives in preallocated buffers (in-place extrapolation, Utils.norm_op norms, buffer-swap acceptance) with a compile-time non-mutating branch for immutable/StaticArray/scalar u.
  3. HomotopySweep: solve the λspan[1] system first (fixes silent convergence to the wrong root) #972's anchor semantics preserved verbatim — anchor-failure retcodes, zero-width-span behavior, and master's test items 15–17 all pass unchanged. The four adaptive-control tests are renumbered to items 18–21 (adjusted for the anchor's extra λ₀ evaluation in the counting tests).

Verification (local, Julia 1.11): all 21 homotopy_sweep items pass (94 assertions), including the aliasing test (item 7) against the cached path. sol.stats.nsteps confirmed per-solve under a reused cache, so the corrector-cheap gate is unaffected. Runic clean. No version bump (maintainer downgraded prior bumps in 90b090c, so leaving versioning to the release process).

Allocation honesty: whole-solve scalar default 68176 → 51840 B; the few-step scalar SimpleNewtonRaphson case pays the one-time cache-init (23888 → 29328 B), which amortizes over longer continuations — the loop is the regime the cache interface targets, per review direction. A SimpleHomotopySweep (direct-solve, non-allocating on StaticArrays, in SimpleNonlinearSolve) is coming as the companion PR for the light case.

@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review July 9, 2026 23:36
@ChrisRackauckas
ChrisRackauckas merged commit 8658a3d into SciML:master Jul 9, 2026
92 of 93 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