Skip to content

HomotopySweep: solve the λspan[1] system first (fixes silent convergence to the wrong root) - #972

Merged
ChrisRackauckas merged 1 commit into
SciML:masterfrom
BatchZero:fix/homotopy-sweep-lambda0-anchor
Jun 30, 2026
Merged

ChrisRackauckas merged 1 commit into
SciML:masterfrom
BatchZero:fix/homotopy-sweep-lambda0-anchor

Conversation

@BatchZero

Copy link
Copy Markdown
Contributor

Summary

HomotopySweep (merged in #962) never solves the system at λspan[1]. The loop initializes λ = λspan[1] but the first inner solve runs at λspan[1] + dλ (default 0.1·span), warm-started directly from u0. For the canonical (0, 1) span that means the pure simplified system — the form the homotopy is specifically designed to make solvable from a cold start — is skipped, and the first solve happens on a system already 10% deformed toward actual.

This is not only a robustness loss. Adaptive bisection fires only on inner-solve failure, never on convergence to the wrong root — so when a poor u0 converges onto the wrong branch at λspan[1] + dλ, the sweep tracks that branch all the way to λ = 1 and returns a wrong root with a success retcode.

Reproduction (silent wrong root)

# actual u^2 - 4 has roots ±2; simplified u - 4 is linear (root +4), in the basin
# of the POSITIVE root and solvable from any guess.
H(u, p, λ) = [(1 - λ) * (u[1] - 4.0) + λ * (u[1]^2 - 4.0)]
prob = HomotopyProblem(H, [-10.0]; λspan = (0.0, 1.0))
sol = solve(prob, HomotopySweep())
sol.u[1]   # -2.0  (retcode Success) — WRONG; correct λ=0-anchored answer is +2.0

At λ = 0 the system is linear u - 4 = 0 → u = 4 (the positive basin). The merged sweep instead first solves at λ = 0.1 from u0 = -10, which converges to the negative branch ≈ -12.26, then tracks it to -2.

Why λspan[1]-first is the intended behavior

The homotopy contract is that simplified is chosen to converge from a cold start; that payoff only materializes if the sweep actually solves at λspan[1]. This is also what HomotopyProblem already documents: its u0 field is "the initial guess (a solution of the simplified system at λspan[1])". So the solver should establish that solution first and continue from it — not skip straight to a system already deformed toward actual.

Fix

Solve the system at λ = λspan[1] from u0 before the stepping loop; continue from that converged iterate. ~15 lines, loop body unchanged.

Contracts preserved:

  • Zero-width λspan (λ0 == λend): the anchor is the single target solve; success short-circuits, failure returns the inner retcode — same one-solve behavior as before, now handled explicitly by the anchor rather than the loop's λend-exclusion.
  • Adaptive bisection is unchanged for every continuation step. The anchor deliberately does not bisect: if simplified fails from u0, the homotopy premise is broken, so it fails fast with the inner retcode.
  • Failure contract (docstring updated): u is the last converged iterate, or u0 itself if the λspan[1] anchor solve failed. (The pre-fix code already returned never-converged u0 on a first-step failure, so the fix makes the documented contract more honest, not less.)

Behavior change (intended)

One input class flips from success to failure: a span whose λspan[1] system is not solvable from u0, but whose interior/target systems happen to be. Pre-fix, the first solve ran at λspan[1] + dλ and could opportunistically succeed there; post-fix the anchor solves λspan[1] first, fails, and returns the inner failure retcode (with u = u0). This is the correct outcome: HomotopyProblem documents u0 as a solution of the simplified system at λspan[1], so a u0 from which λspan[1] is unsolvable is a malformed homotopy problem — failing fast is more honest than opportunistically tracking an arbitrary branch from a partially-deformed start. (item10's old fixture was exactly this case, hence its rewrite.)

Tests

  • item15 — wrong-branch regression: the reproduction above must return +2 (pre-fix: -2).
  • item16 — anchor-failure contract: a system rootless at λspan[1] fails fast with the inner failure retcode (not Stalled), resid !== nothing, u left at u0.
  • item17 — zero-width λspan still solves exactly once and succeeds.
  • item10 rewritten to stay anchor-compatible: its λspan[1] system is now solvable (residual 0 at u0), so the sweep reaches continuation and the stall guard still fires when dλ underflows eps(λ) mid-sweep on a large-magnitude span. (The old fixture was rootless at λspan[1], which the anchor now correctly rejects up front — a behavior change, hence the rewrite.)

All other homotopy_sweep items pass unchanged (the rescue test item5, the happy paths, etc.).

Scope

lib/NonlinearSolveBase/src/homotopy_sweep.jl + tests only. No API change, no signature change, no new defaults.

The sweep initialized λ = λspan[1] but the first inner solve ran at λspan[1] + dλ
warm-started from u0, so the system at λspan[1] -- the `simplified` system for the
canonical (0, 1) span -- was never solved. Adaptive bisection only fires on
inner-solve failure, so a poor u0 that converges onto the wrong branch at
λspan[1] + dλ is tracked to a wrong root with a success retcode (e.g.
H = (1-λ)(u-4) + λ(u^2-4) from u0 = -10 returns -2 instead of +2).

Solve at λ = λspan[1] from u0 before stepping; continue from that iterate. The
zero-width-span, adaptive-bisection, and failure contracts are preserved -- a
failed anchor fails fast with the inner retcode and leaves u at u0.

Tests: item15 (wrong-branch regression -> +2), item16 (anchor-failure contract),
item17 (zero-width span); item10 rewritten to keep a solvable λspan[1] anchor so
it still exercises the mid-sweep stall guard.

Follow-up to SciML#962.
@BatchZero
BatchZero force-pushed the fix/homotopy-sweep-lambda0-anchor branch from 502ddbb to bde1d30 Compare June 16, 2026 05:24
@BatchZero

Copy link
Copy Markdown
Contributor Author

@ChrisRackauckas a nudge here too — a small, independent correctness fix that's been sitting since the 13th. HomotopySweep (merged in #962) never solves at λspan[1]: the first inner solve runs at λspan[1] + dλ, so a u0 that converges onto the wrong branch there returns the wrong root with a Success retcode — H = (1−λ)(u−4) + λ(u²−4) from u0 = −10 returns −2 instead of +2. The fix anchors the first solve at λspan[1]: ~15 lines in homotopy_sweep.jl plus regression tests, no API or signature change. NonlinearSolveBase Core is green on Julia 1/lts/pre; the failing checks are the repo's existing downstream / downgrade / SciPy / Trim runs, not this PR.

Comment on lines +5 to +8
# Stall guard: bisection must stop (not hang) once dλ underflows eps(λ) on a
# large-magnitude span. The λ = λspan[1] anchor is solvable from u0 (residual is
# exactly 0 there), so the sweep gets past the anchor and into continuation; every
# λ > λspan[1] is then rootless, so bisection drives dλ below eps(1e9) ≈ 1.2e-7 —

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.

I'm not sure I understand this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This test guards the stall path, not anything new in this PR — it just had to be rewritten because the new λspan[1] anchor changed what reaches that path.

What it asserts: on a large-magnitude span, once bisection shrinks dλ below the relative float resolution eps(λ), λ + dλ == λ and no further progress is possible, so the sweep must return Stalled rather than loop forever.

Why the contrived 1e9 span: I want to hit the next_λ == λ underflow guard specifically, not the absolute min_dλ = sqrt(eps) ≈ 1.5e-8 floor. At λ ≈ 1e9, eps(1e9) ≈ 1.2e-7 is larger than that floor, so dλ makes λ + dλ == λ first — the stall guard fires before bisection ever reaches min_dλ.

Why it changed from the old u² + 1 fixture: that one is rootless everywhere, including at λspan[1]. With the new anchor, the λspan[1] solve now fails up front and returns immediately, so the old fixture never reaches continuation/the stall guard at all. The new H = u² + (λ − 1e9) is solvable at λspan[1] = 1e9 (there H = u², residual is exactly 0 at u0 = 0), so the sweep clears the anchor; every interior λ > 1e9 is then rootless, bisection underflows, and Stalled fires as intended.

@ChrisRackauckas
ChrisRackauckas merged commit 133c5cd into SciML:master Jun 30, 2026
69 of 94 checks passed
ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/NonlinearSolve.jl that referenced this pull request Jul 9, 2026
…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 added a commit that referenced this pull request Jul 9, 2026
…ng loop (#967)

Rebase and consolidation of the #967 improvements onto current master (which
gained the λspan[1] anchor in #972 and the SciMLTesting test dispatch), plus
the inner-solver cache reuse now possible after #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 #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 #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 #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 <[email protected]>
Co-authored-by: Chris Rackauckas <[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.

2 participants