Skip to content

Quasi-Newton J⁻¹ init as a linsolve workspace: factorization + identity solve through the LinearSolve default - #1039

Merged
ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:maybe-pinv-workspace
Jul 12, 2026
Merged

ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:maybe-pinv-workspace

Conversation

@ChrisRackauckas-Claude

@ChrisRackauckas-Claude ChrisRackauckas-Claude commented Jul 11, 2026 •

Copy link
Copy Markdown
Member

Part of #1020 allocation work; follows #1038 (the dense-LU alias fix, second rung of the allocation ladder).

Note: This PR should be ignored until reviewed by @ChrisRackauckas.

What

Quasi-Newton update rules that store J⁻¹ (Broyden family) need an explicit inverse of the initial Jacobian. On master this went through a bespoke maybe_pinv!! mechanism: lu(A; check = false) (a full matrix copy) + LinearAlgebra.inv! (LAPACK getri, whose work array is larger than A itself), with an SVD pinv(A) fallback on singular input — re-run once per solve!, i.e. once per continuation step under reinit!/solve! cache reuse.

Per review direction ("just remove the pinv stuff? Just use the default linear solver?"), the pinv machinery is removed entirely. The init is now plainly solve A * X = I with the default linear solver:

  • Utils.inverse_jacobian_workspace(A::AbstractMatrix) builds a construct_linear_solver cache (linsolve = nothing, the LinearSolve default algorithm) over workspace-owned buffers: a promoted dense copy of A and an identity-matrix RHS. One factorization + one multi-RHS solve! gives X = A⁻¹. Buffers opt into alias_A = true/alias_b = true so the dense LU refactorizes in place (lu!) instead of copying A on every call.
  • Utils.inverse_jacobian!!(workspace, A::AbstractMatrix) refills the RHS with I (via the GPU-safe make_identity!!) and solves. The lincache copyto!s A into its internal buffer, preserving the caller-never-mutated contract. A nothing workspace (the preinverted-init path in NonlinearSolveQuasiNewton) builds a transient lincache; it allocates, but runs at most once per solve.
  • The generic pinv(A) fallback is deleted. The lincache method is widened from StridedMatrix to AbstractMatrix: structured input (e.g. Tridiagonal) gets dense workspace buffers via the size form of similar, and the SparseArrays extension keeps only a workspace method that densifies (Matrix(A)) — its call-side override is gone since the general method now covers sparse input.
  • The old names maybe_pinv!! / maybe_pinv!!_workspace are purged monorepo-wide (internal Utils functions; the only consumer is NonlinearSolveQuasiNewton, verified by grep).

Semantics on the native fast paths (mirroring construct_linear_solver's routing)

  • Singular dense/sparse/structured input: the result is the default algorithm's singular-LU → pivoted-QR least-squares generalized inverse, not the SVD pinv — a different finite matrix with the same fitness for quasi-Newton initialization (finite, correct shape, A * X * A ≈ A). Regression-tested on those properties.
  • Number / Diagonal: an explicit zero-guarded inverse (Utils.safe_inv: iszero(x) ? zero(inv(x)) : inv(x)), the scalar analog of the least-squares rescue. Bit-identical values to the old pinv(x) / pinv.(D).
  • SMatrix: keeps pinv. Verified empirically that Broyden(init_jacobian = Val(:true_jacobian)) with SVector states reaches this function (always with a nothing workspace); static solves bypass the heap-allocated LinearSolve cache, and a singular initial Jacobian must stay finite where the native \ would error. Singular-SA init still returns a finite matrix (solver reports Stalled, no throw), matching master.
  • inverse_jacobian!! on a general matrix requires LinearSolve to be loaded, like every other construct_linear_solver consumer; the only caller (NonlinearSolveQuasiNewton) has it as a hard dependency.

Merge with master

The branch merges current master: #1035 (the NLSB QA ExplicitImports fix) and #1038 (the alias_A_for_refactorization trait). The predicted one-line conflict in construct_linear_solver is resolved here: the alias kwarg now defaults to nothing, deferring to #1038's trait (owned-copy refactorization buffer); an explicit LinearAliasSpecifier from a caller that owns A/b outright (this workspace) is a forced override that skips the defensive copy. Master's new lu_refactorization_allocs.jl suite passes on the merged result.

Versioning

NonlinearSolveBase is at 2.35.0 on this branch (public construct_linear_solver gains the alias keyword). NonlinearSolveQuasiNewton now requires the new internal names, so its NonlinearSolveBase compat floor is raised to 2.35 and it is bumped to 1.13.4.

Numbers (carried over from the previous revision, re-asserted by the test suite on this one)

inverse_jacobian!! repeated call, well-conditioned dense 51×51 Float64 (sizeof(A) = 20 808 B):

allocations/call
master (lu + inv!) 47 648 B
this PR (LinearSolve default, alias_A = true) 480 B (lu! ipiv + wrapper)

Per continuation step (the @allocated slope harness from test/Core/arclength_tests__item8.jl, N1 = 50 / N2 = 250 fixed-step, n = 50, default inner polyalgorithm): secant 54.4 → 34.4 KB/step, tangent 75.5 → 55.3 KB/step. On the merged tree the repeated-call measurement was re-run and is unchanged (480 B). #1038 is not yet merged, so these still include LinearSolve's ~21.5 KB/step lu refactorization copy in the descent lincaches that #1038 removes; the two changes compose.

Tests (all run locally against the dev'd packages)

  • lib/NonlinearSolveBase/test/inverse_jacobian_workspace.jl (renamed, Core group): nonsingular general/triu/tril match inv(A); input non-mutation; repeated-call stability; re-inverting the returned inverse; nothing-workspace path; singular finite/A*X*A ≈ A/no workspace poisoning; @allocated < sizeof(A) on repeated calls; sparse through the lincache; structured (Tridiagonal) through the lincache; Number/Diagonal/SMatrix fast paths incl. singular values.
  • Pkg.test() for NonlinearSolveBase — passed (50 workspace assertions + full Core group).
  • Pkg.test() for NonlinearSolveQuasiNewton — full suite passed.
  • GROUP=QA for both packages — passed (ExplicitImports ignore lists updated for the renames).
  • All test/Core/homotopy* + test/Core/arclength* files — passed.
  • End-to-end: Broyden(init_jacobian = Val(:true_jacobian)) with sparse jac_prototype + SparseMatrixColorings converges (Success, resid ≈ 1.3e-13); same with SVector states (Success, resid ≈ 2.6e-14); scalar Broyden incl. zero init; Klement dense/SA; LimitedMemoryBroyden (the BroydenLowRankJacobian passthrough).

🤖 Generated with Claude Code

@ChrisRackauckas-Claude ChrisRackauckas-Claude changed the title Use the maybe_pinv!! workspace: allocation-free quasi-Newton initial J⁻¹ Allocation-free quasi-Newton initial J⁻¹: route maybe_pinv!! through the LinearSolve default Jul 11, 2026
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Revised per review (e3d0e9a7): "should it just use the default linear solver?" — yes, it does now.

What changed relative to the previous revision:

  • Utils.maybe_pinv!!(::StridedMatrix) no longer hand-rolls lu! + issuccess + istriu/istril fast paths + a pinv fallback. The workspace is now a construct_linear_solver cache with linsolve = nothing (the LinearSolve default algorithm) over workspace-owned buffers (promoted A copy + identity-matrix RHS); each call refills the RHS with I, hands A to the lincache (which copyto!s it internally — caller's A still never mutated), and returns the multi-RHS solve! solution. The default's singular-LU → pivoted-QR rescue subsumes the bespoke fallback, so all the special-case code is deleted (utils.jl body went from ~40 lines to ~10).
  • construct_linear_solver gained an alias::LinearAliasSpecifier kwarg (default unchanged) so the workspace can opt into alias_A = true on its owned buffer — without it, LinearSolve's registered dense LU does a full lu(A) copy per refactorization (measured 21.5 KB/call, which would have failed the allocation regression test). This is the same in-place path Dense LU refactorization without the per-step A copy #1038 opts into via its trait; the two PRs touch the same init call and need a one-line merge resolution.
  • Documented semantics change: exactly singular input now yields the pivoted-QR least-squares generalized inverse, not the SVD pinv; triangular inverses are no longer post-processed to an exactly-zero triangle. The regression test asserts the properties that matter (finite, correct shape, A*X*A ≈ A, nonsingular ≈ inv(A), non-mutation, allocation bound) instead of pinv equality.
  • NonlinearSolveBase bumped 2.34.1 → 2.35.0 (public construct_linear_solver gains a keyword).

Re-measured (LinearSolve 4.2.1): 480 B per repeated maybe_pinv!! call at n = 51 — identical to the hand-rolled revision; 34.4 KB/step secant, 55.3 KB/step tangent on the item8 continuation harness (previous revision: 34.0/54.9 — noise).

Verified locally: Pkg.test() NonlinearSolveBase (all pass, incl. 33 workspace assertions + linear_solver_routing.jl), Pkg.test() NonlinearSolveQuasiNewton (all pass), all test/Core/homotopy* + arclength* files (414/414).

🤖 Generated with Claude Code

ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/NonlinearSolve.jl that referenced this pull request Jul 11, 2026
…olve

Per review on SciML#1039 ("just remove the pinv stuff? Just use the default
linear solver?"): purge the maybe_pinv!! mechanism and name entirely.
The quasi-Newton inverse-Jacobian init is now Utils.inverse_jacobian!! /
Utils.inverse_jacobian_workspace — solve A * X = I with the default
linear solver.

- Delete the generic pinv(A) fallback; widen the lincache-backed methods
  from StridedMatrix to AbstractMatrix. Structured input (Tridiagonal,
  Symmetric, ...) gets dense workspace buffers via the size form of
  similar; the identity RHS refill goes through the GPU-safe
  make_identity!!.
- The SparseArrays extension keeps only the densifying workspace method;
  its call-side override is covered by the general AbstractMatrix method.
- Number/Diagonal invert through Utils.safe_inv (zero-guarded inverse,
  bit-identical values to the old pinv scalar/broadcast paths), the
  scalar analog of the default solver's least-squares rescue.
- SMatrix keeps pinv: Broyden(init_jacobian = Val(:true_jacobian)) with
  SVector states reaches this function (verified empirically, always
  with a nothing workspace); static solves bypass the LinearSolve cache
  and singular initial Jacobians must stay finite where \ would error.
- Rename all call sites (NonlinearSolveQuasiNewton solve.jl,
  BroydenLowRankJacobian passthrough), the test file, and the QA
  ExplicitImports ignore lists.
- NonlinearSolveQuasiNewton 1.13.4; its NonlinearSolveBase compat floor
  raised to 2.35 (it now requires the new internal names).

Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Chris Rackauckas <[email protected]>
@ChrisRackauckas-Claude ChrisRackauckas-Claude changed the title Allocation-free quasi-Newton initial J⁻¹: route maybe_pinv!! through the LinearSolve default Quasi-Newton inverse-Jacobian init through the default linear solver (removes the pinv machinery) Jul 11, 2026
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Final revision per review ("just remove the pinv stuff? Just use the default linear solver?"):

  • pinv machinery purged. maybe_pinv!!/maybe_pinv!!_workspace are gone; the init is now Utils.inverse_jacobian!! / Utils.inverse_jacobian_workspace — solve A * X = I with the default linear solver. The generic pinv(A) fallback is deleted and the lincache path widened from StridedMatrix to AbstractMatrix (structured input gets dense buffers; the sparse ext keeps only its densifying workspace method).
  • Native fast paths: Number/Diagonal use an explicit zero-guarded inverse (identical values to the old scalar pinv); SMatrix keeps pinv — verified empirically that SArray Broyden Val(:true_jacobian) reaches this function, and singular static init must stay finite where \ errors.
  • Merged master: picks up Fix NonlinearSolveBase QA: import ArrayInterface via its owner in SparseArrays ext #1035 (QA fix) and Dense LU refactorization without the per-step A copy #1038, resolving the predicted construct_linear_solver conflict — the alias kwarg is now a caller-forced override (default nothing) of the alias_A_for_refactorization trait.
  • Verified locally on the merged tree: NLSB + QuasiNewton full Pkg.test and GROUP=QA all pass (incl. the 50-assertion renamed workspace suite and Dense LU refactorization without the per-step A copy #1038's new LU-refactorization alloc tests); all homotopy/arclength Core files 430/430; sparse/SA/scalar end-to-end solves converge; repeated-call allocation unchanged at 480 B (< sizeof(A)).

@ChrisRackauckas-Claude ChrisRackauckas-Claude changed the title Quasi-Newton inverse-Jacobian init through the default linear solver (removes the pinv machinery) Quasi-Newton J⁻¹ init as a linsolve workspace: factorization + identity solve through the LinearSolve default Jul 11, 2026
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Renamed per review: Utils.linsolve_workspace / Utils.linsolve_identity!! (and the QuasiNewton cache field) — the mechanism is one factorization + a multi-RHS solve against I; no inversion happens anywhere. The inverse-Broyden/Klement state is an explicit approximate-inverse matrix (their rank-1 updates operate on it), which is why the identity solve is materialized at init.

On the StaticArrays question: LinearSolve does have a static fast path (defaultalg(::SMatrix) → LU/SVD), but it currently returns retcode = Success with u = [Inf NaN; …] on singular input — filed as SciML/LinearSolve.jl#1084. Until that's fixed, SMatrix keeps pinv (finite generalized inverse on a singular initial Jacobian, allocation-free at static sizes); switching it to the static path once #1084 lands is noted as a follow-up.

Post-rename verification: full Pkg.test for NonlinearSolveBase and NonlinearSolveQuasiNewton both pass (Testing … tests passed, exit 0). Commit 962cada79.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Rebased onto current master (post-#1040) and squashed to a single clean commit. Since the branch's 5 incremental commits were iterations of the same functions against a since-diverged master, I reconstructed the net diff rather than replay conflicts: verified the result is exactly the intended 13 files with no scratch/leaked-env artifacts, hand-merged the 3 Project.tomls that both this PR and #1040 touch (no clobbering), and confirmed no maybe_pinv leftovers.

Compat: LinearSolve floor raised to 4.3 (the SMatrix static SVD rescue from SciML/LinearSolve.jl#1085) and ceiling opened to 5 — "4.3, 5". The realized stack install stays on 4.3.x because the other sublibs still cap LinearSolve at 4; full 5.0 support is a separate cross-sublib bump, and this PR is verified working on both.

Verified locally:

  • NLSB linsolve_workspace unit tests: 50/50 on LinearSolve 4.3.0 AND 5.0.0
  • End-to-end SMatrix + dense Broyden/Klement true_jacobian init: all Success (SMatrix resid 1.3e-14)
  • Full NonlinearSolveQuasiNewton Pkg.test: passed on 4.3

Allocation note (LinearSolve 4.3, this branch): quasi-Newton SMatrix true_jacobian init is allocation-free through the static path (0 B, same as the old pinv); dense continuation inner solve! is 0 B/iteration.

ChrisRackauckas added a commit that referenced this pull request Jul 11, 2026
…1043)

Widen the LinearSolve [compat] ceiling to include 5 in every monorepo
Project.toml that still capped it at 4, so the full stack can resolve
LinearSolve 5.0. Lower bounds are preserved (only the ceiling widens).

Compat + version bumps (minor, per SemVer for a widened compat range):
- NonlinearSolve (root):        LinearSolve 3.48, 4 -> 3.48, 4, 5   v4.20.4 -> v4.21.0
- NonlinearSolveFirstOrder:     LinearSolve 2.36.1, 3, 4 -> +5      v2.1.3  -> v2.2.0
- NonlinearSolveQuasiNewton:    LinearSolve 2.36.1, 3, 4 -> +5      v1.13.3 -> v1.14.0
- docs env:                     LinearSolve 2, 3, 4 -> 2, 3, 4, 5
- test/gpu env:                 LinearSolve 3.48, 4 -> 3.48, 4, 5

NonlinearSolveBase is handled by #1039 (LinearSolve 4.3, 5) and is not
touched here. No code changes: no package reads LinearSolution.cache
(the 4->5 break); LinearSolve results are consumed only via retcode/u.

Co-authored-by: ChrisRackauckas-Claude <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
…ty solve

Replace the bespoke pinv machinery in the quasi-Newton inverse-Jacobian
initialization with a plain A·X = I solve through the shared LinearSolve
stack. Utils.linsolve_workspace / linsolve_identity!! build a
default-algorithm linear-solve cache once and solve against an identity
RHS; no matrix is inverted. Sparse A routes through the same cache
(pinv has no sparse method). Number/Diagonal use a zero-guarded
safe_inv (bit-identical to the old pinv values).

SMatrix solves A·X = I through LinearSolve's static fast path directly,
whose SVD rescue (SciML/LinearSolve.jl#1085, LinearSolve ≥ 4.3) returns
the finite min-norm generalized inverse on a singular initial Jacobian —
the behavior pinv provided — allocation-free. Compat: LinearSolve
"4.3, 5".

Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Chris Rackauckas <[email protected]>
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review July 12, 2026 05:03
@ChrisRackauckas
ChrisRackauckas merged commit 6a7687f into SciML:master Jul 12, 2026
84 of 95 checks passed
ChrisRackauckas added a commit that referenced this pull request Jul 12, 2026
…e correct minimum (2.34) (#1050)

PR #1039 raised the floor to "2.35", anticipating a future NonlinearSolveBase
release. The internal rename it actually depends on (maybe_pinv!! ->
linsolve_identity!!/linsolve_workspace) already landed in the currently
registered NonlinearSolveBase 2.34.0. The 2.35 floor is unregistrable (no such
version exists) and was causing NonlinearSolveQuasiNewton 1.13.3 (the
currently registered version, which predates the rename) to fail to
precompile against NonlinearSolveBase >= 2.34 for any fresh install.
@JamesWrigley JamesWrigley mentioned this pull request Jul 13, 2026
5 tasks done
ChrisRackauckas added a commit that referenced this pull request Jul 23, 2026
Problem #1 (Generalized Rosenbrock) solved with
Broyden(; init_jacobian = Val(:true_jacobian), update_rule = Val(:bad_broyden))
sits on a knife-edge. After #1039 changed the Jacobian inverse initialization
from inv!(lu(A)) to linsolve_identity!!, the ulp-level difference (~1e-13) flips
this problem between converging and not, so it randomly passes and fails.

Marking it `broken` is not enough: when it happens to converge it errors as an
unexpected pass. Use the harness's existing skip_tests mechanism instead so the
case is skipped in both directions.

Co-authored-by: ChrisRackauckas-Claude <[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