Repository navigation
Solve the trust-region subproblem nearly exactly (Moré) and make it the TrustRegion default - #1287
Conversation
700a685 to
5077b4a
Compare
…he default `TrustRegion(subproblem = TrustRegionSubproblem.More)` — now the default — solves the least-squares subproblem `min ‖Jp + f‖` subject to `‖Dp‖ ≤ Δ` nearly exactly via Moré's safeguarded Newton iteration on the damping parameter `λ` (MINPACK `lmpar`, Nocedal & Wright §4.3), paired with Moré's step-following radius update (MINPACK `lmder`). This is the subproblem solve that TrustRegionLeastSquares.jl and SciPy TRF use to reach 100% on the benchmark suite. On the 88-problem Moré–Garbow–Hillstrom + Hock–Schittkowski suite from the TrustRegionLeastSquares.jl README, the previous default dogleg subproblem solves 83/88 (identical to the released implementation); the Moré subproblem solves 88/88, including the ill-conditioned and badly scaled cases (mgh18, mgh19, tp267, tp272, tp333) where the polygonal dogleg path stagnates or converges to worse local minima, and the rank-deficient mgh34 where an undamped solve on a singular system cannot proceed. The dogleg subproblem remains available via `TrustRegionSubproblem.Dogleg` and its implementation is unchanged. The damped system is solved in whichever form the Jacobian representation and `linsolve` support, rather than always forming `JᵀJ`: the augmented least-squares system `[J; √λD] p = [-f; 0]` directly for concrete Jacobians (the condition number of `J` is never squared, the augmented matrix has full column rank for λ > 0, and sparse Jacobians stay sparse), the equivalent damped normal equations for `linsolve`s that only accept square systems (and for scalars and static arrays), a stacked `FunctionOperator` for matrix-free Jacobians with least-squares Krylov solvers, and a `JᵀJ + λI` operator for square-only Krylov solvers. Convertible operator `jac_prototype`s are materialized only when the linear solver requires a concrete matrix. A `predicted_reduction` descent extra carries the MINPACK-form model reduction `½‖Jp‖² + λ‖Dp‖²`, avoiding the cancellation of `-gᵀp - ½pᵀJᵀJp` on ill-conditioned problems, and a nonpositive model reduction now rejects the step instead of computing a positive ρ ratio. `AbstractDescentDirection` and the new `TrustRegionSubproblem` enum are public API: `TrustRegion` accepts custom descent implementations through `subproblem` alongside the enum choices. Generated with [Devin](https://devin.ai) Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Agent-Harness: Devin CLI 3000.10.21 Agent-Model: SWE-2 Max Agent-Session: /home/crackauc/.local/share/devin/cli/summaries/history_6a75b67bca6d40a2.md (local Devin CLI transcript; earlier sessions: /home/crackauc/.local/share/devin/cli/summaries/history_34d32feac8b94b6d.md, /home/crackauc/.local/share/devin/cli/summaries/history_93828a790ce74f44.md, /home/crackauc/history_b90eec6928b74857.md)
5077b4a to
3b13615
Compare
… λ-loop On the default dense path the Jacobian is now factorized once per Jacobian via a pivoted Householder QR (a port of MINPACK qrfac with the reflectors packed into the factor buffer), and each damping iteration eliminates the √λD block against the triangular R with n Givens rotations (qrsolv) to form the upper-triangular S with SᵀS = Pᵀ(JᵀJ + λD²)P directly. Per-λ work is the O(n²) sweep plus triangular solves — no (m+n)×n refactorization, no JᵀJ formation, and no allocations outside init. The safeguarded λ-iteration and the scalar setup (Δ, the u₀ bound, initial λ) run behind function barriers so the union-typed lincache/dtd fields dispatch once per call instead of boxing per iteration; the workspace variants are listed concretely so isa-narrowed calls union-split to static dispatch. The extras NamedTuple is built with the same field shape on every return path so the DescentResult param stays concrete, and `linres.u`'s `Any` inference through the unioned lincache call is bypassed with copyto! on the concrete gn buffer. Results (TrustRegionLeastSquares 88-problem NLLS suite, dogleg → Moré): 83/88 → 88/88 converged, median 0.219 → 0.190 ms per solve, total steps 5736 → 3862. On the SciMLBenchmarks 23 NonlinearProblems the success set is unchanged (21/23) and the median slowdown dropped from ~6× to 1.3×. End-to-end allocations on a 2000-step run dropped from ~68k to under 100 — fewer than Dogleg's. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Agent-Harness: Devin CLI 3000.10.27 Agent-Model: SWE-2 Max Agent-Session: /home/crackauc/.local/share/devin/cli/summaries/history_7011e97d708b489a.md
|
Pushed
Figure and CSVs on the |
A rank-deficient R leaves the undamped Gauss-Newton system underdetermined. The lmpar helpers followed MINPACK's convention of zeroing the null-space components — the "basic solution" — which silently returns an arbitrary, generally not minimum-norm, point of the solution manifold. Both triangular solves now report failure: _more_lmpar_gn! returns false when nsing < n so the caller falls through to the damped iteration (whose λ > 0 system is nonsingular and yields the regularized minimum-norm step), and _more_lmpar_qrsolv! returns false when S's diagonal has a zero, letting the safeguarded λ-loop tighten the bracket and retry. The failure-path DescentResult extras likewise stop fabricating values for return-type uniformity: λ was reported as 0, which downstream reads as "undamped Gauss-Newton" (RadiusUpdateSchemes.More expands the radius on iszero(λ)). The extras now carry NaN sentinels — the shape is unchanged so inference is unaffected — and skip_solve reports success = false, since a Moré direction is Δ-dependent and cannot honestly be skipped. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Agent-Harness: Devin CLI 3000.10.27 Agent-Model: SWE-2 Max Agent-Session: /home/crackauc/.local/share/devin/cli/summaries/history_977c086cdf324660.md
|
Pushed
Verified: 88/88 on the NLLS suite ( |
TrustRegion() keeps the Moré default; the alias forwards every keyword except subproblem, which is fixed to TrustRegionSubproblem.Dogleg (a Dogleg descent instance is accepted, other values throw). This makes the low-latency option discoverable as a top-level algorithm. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Agent-Harness: Devin CLI 3000.10.27 Agent-Model: SWE-2 Max Agent-Session: /home/crackauc/.local/share/devin/cli/summaries/history_45276113e0414e71.md
|
Added a TrustRegionDogleg() # == TrustRegion(subproblem = TrustRegionSubproblem.Dogleg)
🤖 Generated with Devin (harness: Devin CLI 3000.10.27, model: SWE-2 Max). Session transcript (local): /home/crackauc/.local/share/devin/cli/summaries/history_45276113e0414e71.md |
…olve The lincache field's pinned union of UnionAll members could not be union-split, leaving dynamic dispatch in solve! (JET failures in the trim test). All runtime gates are now compile-time inferable: - `has_scaling` is a `Val` field on MoreTrustRegionDescent, so `dtd`'s type is fixed per algorithm. - The `m >= n` runtime gate is gone: the lmpar workspace zero-pads underdetermined Jacobians to `n` rows. Padded rows stay zero through the Householder sweep, `R` comes out rank-deficient, the Gauss-Newton step is declined, and the lambda iteration solves the correct damped system. `could_lmpar` alone now decides the cache flavor. - The linsolve_kwargs whitelist check is `@generated` on the NamedTuple keys so it folds; a runtime Bool here split the cache type and broke `@inferred init`. CUDA fixes: augmented/rhs/qrhs/op_state.Jv buffers are allocated via `similar` on the state/Jacobian device; the damping diagonal block and the scaling/maxdiag reductions broadcast instead of scalar-indexing under `allowscalar(false)`. Operator Jacobians with the default linsolve now take the normal-form operator `x -> (J'J + lambda I)x`: square and SPD, so DefaultLinearSolver works. The non-square `[J; sqrt(lambda) I]` operator hit a broken `init(::LinearCache)` dispatch under LinearSolve 5.6.0 (downgrade CI). Also fix `qtbf` never being refreshed when the Gauss-Newton solve returns early on a rank-deficient `R` — the lambda loop read stale or uninitialized transformed residuals. Regression tests: underdetermined `m < n` and rank-deficient solves (both verified to fail on the unfixed ordering). Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Agent-Harness: Devin CLI 3000.10.27 Agent-Model: SWE-2 Max Agent-Session: /home/crackauc/.local/share/devin/cli/summaries/history_973cf49908cf4f10.md
|
Latest push ( Trim/JET (was 54 reports → now 0): the CUDA: augmented/rhs/qrhs/op-state buffers now allocate via downgrade-sublibraries (LinearSolve 5.6.0): operator Jacobians with the default Also fixed: Re-verified on the refactored code: 88/88 on the least-squares benchmark suite, 78/78 on the least-squares test group, inference tests clean, zero allocations in the lmpar hot path and the solve-level step. |
The broadcast fallbacks in _more_scaling_init/update! and _more_maxdiag use diag() for GPU arrays; the name was not imported into NonlinearSolveBase, which errored the CUDA testset. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Agent-Harness: Devin CLI 3000.10.27 Agent-Model: SWE-2 Max Agent-Session: /home/crackauc/.local/share/devin/cli/summaries/history_973cf49908cf4f10.md
|
CI on Now green:
Remaining 5 failures (all verified pre-existing/flaky):
Locally re-verified after the inference refactor: 88/88 on the least-squares benchmark suite, 78/78 in the least-squares test group, inference tests clean, zero allocations in the lmpar hot path. |
Ships the near-exact (More) trust-region subproblem solver, now the TrustRegion default (#1287). Minor rather than patch because the default numerical behaviour changes; minor rather than major follows @ChrisRackauckas's call on the same question for NeuralPDE's default AD backend. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.273 Agent-Model: claude-opus-5[1m] Agent-Session: 6a01e420-3436-4518-83cc-6cd853283cfb (local transcript; this harness publishes no conversation URL)
Ships the near-exact (More) trust-region subproblem solver, now the TrustRegion default (#1287). Minor rather than patch because the default numerical behaviour changes; minor rather than major follows @ChrisRackauckas's call on the same question for NeuralPDE's default AD backend. Agent-Harness: Claude Code 2.1.273 Agent-Model: claude-opus-5[1m] Agent-Session: 6a01e420-3436-4518-83cc-6cd853283cfb (local transcript; this harness publishes no conversation URL) Co-authored-by: Claude <[email protected]>
Ships the first-order half of the near-exact (More) trust-region subproblem solver made the TrustRegion default in #1287. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.273 Agent-Model: claude-opus-5[1m] Agent-Session: 6a01e420-3436-4518-83cc-6cd853283cfb (local transcript; this harness publishes no conversation URL)
Ships the first-order half of the near-exact (More) trust-region subproblem solver made the TrustRegion default in #1287. Agent-Harness: Claude Code 2.1.273 Agent-Model: claude-opus-5[1m] Agent-Session: 6a01e420-3436-4518-83cc-6cd853283cfb (local transcript; this harness publishes no conversation URL) Co-authored-by: Claude <[email protected]>
v2.9.0 imports MoreTrustRegionDescent, TrustRegionSubproblem and AbstractDescentDirection from NonlinearSolveBase; those were added in NonlinearSolveBase 2.52.0 by #1287. The compat floor still allowed 2.50, so a resolver picking 2.51.1 gets a package that fails to load. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.273 Agent-Model: claude-opus-5[1m] Agent-Session: 6a01e420-3436-4518-83cc-6cd853283cfb (local transcript; this harness publishes no conversation URL)
) v2.9.0 imports MoreTrustRegionDescent, TrustRegionSubproblem and AbstractDescentDirection from NonlinearSolveBase; those were added in NonlinearSolveBase 2.52.0 by #1287. The compat floor still allowed 2.50, so a resolver picking 2.51.1 gets a package that fails to load. Agent-Harness: Claude Code 2.1.273 Agent-Model: claude-opus-5[1m] Agent-Session: 6a01e420-3436-4518-83cc-6cd853283cfb (local transcript; this harness publishes no conversation URL) Co-authored-by: Claude <[email protected]>
Summary
Makes
TrustRegion()solve its subproblem nearly exactly — Moré's safeguarded iteration on the damping parameter (MINPACKlmpar), paired with Moré's step-following radius update (lmder) — and flips the default from dogleg tosubproblem = TrustRegionSubproblem.More. This is the recipe TrustRegionLeastSquares.jl and SciPy TRF use to reach 100% on the standard benchmark suite.Motivation. Rerunning the 88-problem Moré–Garbow–Hillstrom + Hock–Schittkowski benchmark from TrustRegionLeastSquares.jl's README against this branch, the released dogleg path solves 83/88 — identical results to the released 4.30/4.31 implementation. The failures (
mgh18,mgh19,tp267,tp272,tp333) are ill-conditioned or badly scaled problems where the two-segment polygonal dogleg path approximates the trust-region solution curveδu(λ)poorly: the solver either stagnates inside the 32-step stall window or converges to a worse local basin (mgh19settles at cost 0.0438 vs. reference 0.0201).mgh34is a rank-1 linear least-squares problem whoseJᵀJis exactly singular. The releasedLevenbergMarquardtfails the same 5/88 in the benchmark's saved results, driven by damping-update pathologies on the same class.With the new default
TrustRegion(), all 88/88 problems converge to the reference-best cost.What changed
MoreTrustRegionDescent(NonlinearSolveBase, exported): a safeguarded Newton iteration onφ(λ) = ‖Dδu(λ)‖ − Δpicksλso the damped step lands on the trust-region boundary (relative step-norm tolerance 1e-4, ≤10 iterations, warm-started λ). A Gauss–Newton step lying inside the region short-circuits withλ = 0. On a linear-solve failure the bracket lower bound tightens andλgrows — matchinglmpar.lmpar/qrsolv, not a per-λ refactorization.Jis factorized once per Jacobian by a pivoted Householder QR (a port of MINPACKqrfacstoring the reflectors packed into the factor buffer — allocation-free, no LAPACK work-vector). Each λ then eliminates√λDagainst the triangularRwithnGivens rotations (qrsolv), producing the upper-triangularSwithSᵀS = Pᵀ(JᵀJ + λD²)Pdirectly. Per-λ work is an O(n²) sweep plus triangular solves —JᵀJis never formed, the(m+n)×naugmented system is never rebuilt, and the whole inner loop allocates nothing.linsolve, otherlinsolve_kwargs, orm < n: the augmented system[J; √λD]goes tolinsolve(LinearSolve picks pivoted QR for rectangularA). κ(J) is never squared and[J; √λD]is full column rank forλ > 0;vcatkeeps sparse Jacobians sparse.linsolves (e.g.LUFactorization,KrylovJL_GMRES), scalars, andStaticArrays: the equivalent damped normal equations(JᵀJ + λDᵀD)δu = −Jᵀfu, reusing the existingneeds_square_Atrait.[J; √λI]is applied as a stackedFunctionOperator— a rectangular operator, so the defaultlinsolveauto-selects LSMR andJis never materialized. Square-only Krylov solvers get aJᵀJ + λIoperator instead (declared symmetric positive-definite, so CG applies).jac_prototypes (e.g.MatrixOperator) are materialized once per solve only whenlinsolveneeds a concreteA; a genuinely matrix-freeJwith a concrete-only solver throws a descriptiveArgumentErrorat init.RadiusUpdateSchemes.More: Moré's step-following radius update — onρ < shrink_threshold,Δ ← shrink_factor · min(Δ, 10‖Dδu‖); onρ ≥ expand_thresholdorλ = 0,Δ ← expand_factor · ‖Dδu‖. Auto-selected forsubproblem = TrustRegionSubproblem.More, together withlmpar's initial radius and 1e-3 step threshold.½‖Jδu‖² + λ‖Dδu‖²through apredicted_reductionextra, avoiding the cancellation of−gᵀδu − ½δuᵀJᵀJδuon ill-conditionedJ. A nonpositive predicted reduction (denom ≥ 0) now yieldsρ = −1— previously a step predicted by the model and observed to worsen could produce a positive ratio and be accepted.TrustRegionSubproblem(exportedEnumXenum,Dogleg/More) andAbstractDescentDirectionare public API in NonlinearSolveBase:subproblemaccepts the enum or a custom descent implementation, so both are documented extension points.subproblem = TrustRegionSubproblem.Doglegremains fully supported and unchanged; the 23-problem suite keeps every radius-scheme variant on dogleg and addsTrustRegion()(the new default) as a ninth entry — broken set[11, 21], identical to dogleg's.Performance
Benchmarked both subproblems end-to-end (median of repeated solves, this branch):
88-problem NLLS suite (TrustRegionLeastSquares README problems):
TrustRegionSubproblem.DoglegTrustRegionSubproblem.MoreMoré takes 33% fewer steps — each accepted step lands nearer the trust-region-optimal point — and after the
lmpar/qrsolvrework its per-step cost is on par with dogleg's, so the median solve is now slightly faster. On the 5 problems dogleg fails, Moré is also faster in wall time (tp2670.02×,tp3330.05×,mgh18/tp2720.14×,mgh190.36×) because dogleg burns all 400 iterations before failing.SciMLBenchmarks 23 NonlinearProblems (rootfinding): identical success — 21/23 both, same broken set
[11, 21]— median 1.31× per-solve (was ~5.9× before thelmparrework). The remaining gap is dominated by the two Hammarling matrix-square-root problems (14→24.5 ms, 30→71.7 ms), which are pathological MaxIters cases where the safeguarded λ-iteration runs several sweeps per step.Allocations. The dense
lmparpath allocates nothing outsideinit: theqrfacrefactorization,Qᵀfapplication, and per-λ Givens sweep + triangular solves all run in place on workspace buffers. A 2000-step MaxIters run on the Hammarling problem dropped from ~68k allocations (augmented per-λ path) to 87 total — fewer than dogleg's 90. The λ-iteration runs behind a function barrier so the union-typedlincache/dtdfields dispatch once per call; listing the workspace variants concretely (_MoreLmparWorkspace{Float32/Float64}) letsisa-narrowed calls union-split to static dispatch, and everyDescentResult.extrasreturn builds the same NamedTuple shape so the result type stays concrete.subproblem = TrustRegionSubproblem.Doglegkeeps the old behavior available for latency-sensitive rootfinding.Implementation notes
construct_linear_solver, the sharedLinearSolveJLCache,needs_square_A/needs_concrete_Atraits,linsolve_kwargs, sparsejac_prototypes,pre_invertedJacobians, andreinit!.lmparworkspace (_MoreLmparWorkspace) replaces the linear cache on the dense default path:qrfacstoresR's off-diagonals in the strict upper of the factor buffer with reflector vectors in the lower trapezoid (MINPACK layout),Rdiag/ipvtcarry the diagonal and permutation, andqrsolv's Givens sweep leavesSassdiag+ the strict lower of the work matrix for the follow-upq = (JᵀJ + λD²)⁻¹D²psolve (q = P S⁻¹ S⁻ᵀ D̃²z— two triangular sweeps). The GN direction is a rank-truncatedP R⁻¹ Qᵀ(−f)on the same factors.nfactorsincrements once per Jacobian,nsolvesper λ.λ = 0) and every damped solve: for operator Jacobians theFunctionOperatoris created once and its closures read a mutable(J, λ)cell, soλupdates never rebuildA(avoidingset_lincache_A!'scopyto!on operators).reuse_A_if_factorizationlets the damped factorization serve the follow-upqsolve — computed on the augmented path asA \ [0; Dp/√λ]sinceAᵀ[0; Dp/√λ] = D²pexactly.Jᵀfuis reused across rejected retries (Jacobian-reuse path) and invalidated viacallback_into_cache!when a step is accepted.dtdstoresDᵀDsoDδu/D²δuare diagonal scaling, not matrix products.Jᵀfubuffers live in the vectorized linear-algebra space (length(u)/length(fu)vectors);δukeeps the state shape andUtils.restructuremaps between them — matrix-shaped states work.Jᵀfu = 0(model-stationary →p = 0), and the λ flooreps·maxdiag(JᵀJ)/min(diag D²)under normal form, below which no positive-definite factorization can succeed (the augmented path needs onlyepssince it stays full rank).Test plan
least_squares_tests__item6.jl(58 tests): 16 hard benchmark problems (incl.mgh16/18/19/34,tp267/272/312/333) solved to reference cost under:noneand:jacobianscaling; scalar states;SVector; sparsejac_prototypestaying sparse; matrix-shapedu;LUFactorizationnormal-form routing; matrix-free LSMR (augmented op) and GMRES (normal-form op);MatrixOperatormaterialization under LU vs. matrix-free under Krylov;reinit!; invalidsubproblem/scaling errors.final_costat or below the reference best on every problem;mgh34's saved CSV reference is corrupted —-4.25is impossible for a least-squares objective — so it is scored against the true optimum 3.0676 that every converged reference solver reaches).TrustRegion()broken set[11, 21]— identical tosubproblem = TrustRegionSubproblem.Dogleg.qrfac/qrsolvverified againstqr!(ColumnNorm())and direct augmented/normal-equation solves to ~1e-15 on random, square, tall, rank-deficient, zero-column, ill-scaled, andFloat32Jacobians.@inferred init(prob, TrustRegion())— the descent cache'sdtd/lincache/augmented/rhs/qrhsfields are pinned unions so runtime gates don't split the cache type).NonlinearSolveitems exercising the default: reinit, matrix-state, polyalg-inclusion, ForwardDiff-through-solve (13,886 tests forTrustRegion()alone).implicit_sensitivity_solvenon-public import in the ForwardDiff ext;nlls_solve_adjoint_dp/solve_callunrendered public names) — pre-existing, unrelated.typosclean.linkcheck = false(this machine has no external network — linkcheck is left to CI; the diff adds no external links).checkdocs = :exportspasses.Known unrelated failure
bounded_default_tests.jlfails on master too: upstream commit52b7e8cmadeSobolMultistartthe bounded default, soinit(prob)returns a deferredNonlinearSolveNoInitCacheand the test'scache.cachesaccess is stale. Reproduced on a clean master checkout; a fix is prepared as a separate PR.🤖 Generated with Devin (harness: Devin CLI 3000.10.27, model: SWE-2 Max)
Session: local Devin CLI transcript
/home/crackauc/.local/share/devin/cli/summaries/history_977c086cdf324660.md(earlier sessions:history_7011e97d708b489a.md,history_6a75b67bca6d40a2.md,history_6c57b556d8b14ef0.md,history_34d32feac8b94b6d.md,history_93828a790ce74f44.md,history_b90eec6928b74857.md)