Repository navigation
Form sparse JᵀJ in place in DampedNewtonDescent (LM normal-form step! allocations) - #1363
Merged
ChrisRackauckas merged 2 commits intoOct 16, 2026
Merged
Conversation
In the normal-form (and least-squares with normal-form damping) modes, `transpose(J) × J` on a SparseMatrixCSC went through MaybeInplace's sparse fallback, which materializes `copy(transpose(J))` and a fresh `spmatmul` product every iteration (~239 KB/step for LevenbergMarquardt with KLUFactorization on a 1000-dim tridiagonal problem). `Utils.normal_form_jacobian!!` now writes the values into the cached JᵀJ pattern using a transpose buffer and a dense accumulator held in the descent cache. The accumulation order matches SparseArrays' Gustavson spmatmul, so results are bitwise identical; a pattern mismatch falls back to the allocating product. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Agent-Harness: Claude Code Agent-Model: claude-opus-5-5 Agent-Session: https://claude.ai/code/session_01LPHREnnonfLg1VcE1EJovv
ChrisRackauckas-Claude
pushed a commit
to ChrisRackauckas-Claude/NonlinearSolve.jl
that referenced
this pull request
Oct 7, 2026
Reuse Utils.normal_form_jacobian!! / normal_form_workspace from SciML#1363 in MoreTrustRegionDescent so sparse TrustRegion no longer rebuilds JᵀJ via MaybeInplace's allocating CSC product each Jacobian update. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Cursor Agent <[email protected]> Agent-Harness: Cursor Agent CLI Agent-Model: auto Co-authored-by: Cursor <[email protected]>
Member
Independent review (Devin CLI 3000.11.3, model fusion-claude-opus-5-5-high-sidekick-swe-2-medium): MERGE, risk low. Full reviewVERDICT: MERGE Blocking findingsNone. Non-blocking findings
What I ranAll on Julia 1.12.7, macOS arm64. I used separate dev'd envs for the PR head and for the merge base
What I did not verify
🤖 Posted by an AI agent — harness: Devin CLI 3000.11.3 (review), Claude Code 2.1.285 (posting) · model: fusion-claude-opus-5-5-high-sidekick-swe-2-medium |
ChrisRackauckas
marked this pull request as ready for review
October 16, 2026 18:49
This was referenced Oct 16, 2026
ChrisRackauckas
referenced
this pull request
Oct 30, 2026
Bump versions: NonlinearSolveBase 2.55.1 Merge master to include Core inference fix Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Agent-Harness: Claude Code 2.1.302 Agent-Model: claude-sonnet-5-5 Claude-Session: https://claude.ai/code/session_01VZjwf7Ux9YtTzwHGHMqnsq Co-Authored-By: Codex <[email protected]> Agent-Harness: Codex CLI Agent-Model: gpt-6-luna Agent-Session: local fixer job SciML__NonlinearSolve.jl__1378 (no session URL)
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.
What changed and why
The audit flagged LevenbergMarquardt as allocating ~63 KB per
step!on a 100-dim dense in-place problem and ~1.8 MB per step on a 1000-dim sparse one, and suspected geodesic acceleration, MaybeInplace fallbacks and the damping updates. AProfile.Allocsrun (sample_rate = 1, onestep!after 3 warmup steps) does not support that suspicion for the default configuration. Every sampled allocation there is inside LinearAlgebra, SparseArrays or SuiteSparse, reached through LinearSolve. None is in NonlinearSolveBase or NonlinearSolveFirstOrder code. The geodesic, damping and MaybeInplace broadcast paths allocate nothing. AllocCheck's 158 sites are static possibilities, not allocations that actually happen. Details are in "Remaining allocations" below.The one per-iteration allocation that is in NonlinearSolve code is in the normal-form path, where a linsolve needs a square
A(for exampleKLUFactorization,LUFactorizationorCholeskyFactorization) and the Jacobian is sparse. There,@bb cache.JᵀJ_cache = transpose(J) × Jgoes through MaybeInplace'sSparseArraysmethodC .= A * B. That method materializescopy(transpose(J))and a freshspmatmulresult every iteration: about 239 KB per step at n = 1000.This PR adds
Utils.normal_form_jacobian!!(JᵀJ, J, workspace), with a non-allocatingSparseMatrixCSCmethod inNonlinearSolveBaseSparseArraysExt. TheDampedNewtonDescentCacheholds the workspace: a transpose buffer filled withtranspose!, a dense accumulator and a flag vector. The kernel writes the values into the existing JᵀJ pattern. It accumulates the column products in exactly the same order as SparseArrays' Gustavsonspcolmul!(first product assigned, the rest added with+=, no FMA), so the values are bitwise identical totranspose(J) * J. If the cached pattern does not match the structural product pattern of the currentJ, it falls back to the old allocating expression. The generic method is that old expression, so dense, static, operator and every other type are unchanged.Before / after (julia 1.12.4,
taskset -c 102, machine heavily loaded)step!bytes after 3 warmup steps, withabstol = reltol = 0:KLUFactorization, geodesicKLUFactorization,disable_geodesicLUFactorizationluofSymmetriccopies)CholeskyFactorizationSVector{2}OOP, geodesic / no geodesic\→ LAPACK)Minimum solve times (BenchmarkTools
@belapsed, two alternating master/branch runs; both runs agreed to within 1%):maxiters = 50maxiters = 50abstol = 1e-10)step!Total solve allocations for sparse KLU, 50 iterations: 13.9 MB → 2.0 MB.
Bitwise identity
The following were run on master and on this branch, step by step with
step!and then withsolve: all 13 cases in the table (dense linear and nonlinear, sparse Bratu, default, LU, Cholesky and KLU linsolves, static OOP, each with and without geodesic acceleration). The script serialized every iterateu,norm(fu),retcodeand allNLStatsfields, then compared them by reinterpreting toUInt64:The new test also checks
normal_form_jacobian!!againsttranspose(J) * Jbitwise (colptr,rowval, andnzvalreinterpreted asUInt64) on square, tall and wide random sparse matrices, and checks the pattern-mismatch fallback.Test (fails on master)
lib/NonlinearSolveFirstOrder/test/sparsity_tests__item3.jluses LM withKLUFactorizationon a 200-dim sparse Bratu problem, with and without geodesic acceleration, and assertsmaximum(@allocated step!(cache)) < 1000after warmup. On master (allocation testsets only, sincenormal_form_workspacedoes not exist there), with--check-bounds=yes:The same file on this branch:
Local validation
julia -m Runic --check) andtypospass on all changed files.GROUP=CoreNonlinearSolveFirstOrder:Testing NonlinearSolveFirstOrder tests passedGROUP=QANonlinearSolveFirstOrder:QA | 20 20/tests passedGROUP=CoreNonlinearSolveBase:Testing NonlinearSolveBase tests passedGROUP=QANonlinearSolveBase:QA | 20 20/tests passed. ExplicitImports flagged the extension's access to the two new internalUtilsnames. They were added to the existing internal-name ignore list intest/qa/qa.jl, which already coversstructural_sparse,make_sparse,linsolve_workspaceand similar names.Remaining allocations (not patched here: they belong to other packages)
:least_squaresmode, LinearSolve's QR is applied to the stacked[J; √D](200×100).LinearAlgebra.qr!→LAPACK.geqrt!allocates theTblock-reflector matrix and the work array (2 × 28.8 KB).ldiv!(::QR, b)copiesb, andgemqrt!allocates a work array. Fixing this belongs in LinearSolve'sQRFactorizationcache, which would need to keepTand the work buffers and callLAPACK.geqrt!(A, T)directly.qrof the stacked sparse matrix every step (the CHOLMOD/SPQR conversions_extract_args/SparseMatrixCSCcopies, plus SuiteSparse-internal mallocs thatProfile.Allocsdoes not see), and\on the SPQR factor goes throughgetindex_colsandinvperm. This is SparseArrays/SuiteSparse territory. Separately, the default LM on this square sparse problem is about 150× slower than LM withKLUFactorization(≈2 s vs ≈13 ms for 50 iterations). Whether the default should prefer the normal form for square sparse problems is a design question, and this PR does not change it.LUFactorizationon the normal-form matrix (81 KB/step).Utils.maybe_symmetricwrapsAinSymmetric, and LinearSolve's LU path callslu(::Symmetric), which copies throughcopymutable_oftype. Passing the plain matrix instead would change the bits, because a GEMM-formed JᵀJ is not guaranteed to be exactly symmetric. That needs a LinearSolve-side fix.SVectorOOP (35–71 KB/step).NativeJLLinearSolveCachecallsA \ bon a non-squareSMatrix. StaticArrays forwards that to a heapMatrixpivoted QR (geqp3!/ormqr!work arrays).Not verified
spcolmul!'s accumulation order, which I checked in the 1.12 SparseArrays stdlib only. The bitwise test would catch a difference on other versions.SparseMatrixCSC, so other sparse types keep the old path. Not exercised.:minimum_normmode (J × transpose(J)) andNewtonDescent's normal form (newton.jl) use the same allocating sparse product and are left unchanged.checkdocs = :exports), and the fullGROUP=All/Everythingsuite were not run.Risk assessment
DampedNewtonDescent(LevenbergMarquardt and anything else using it), and only whenJis aSparseMatrixCSCin the normal-form or normal-form-damping least-squares modes. No public API change. The newUtilsfunctions are internal.🤖 Generated with Claude Code (model: claude-opus-5-5) https://claude.ai/code/session_01LPHREnnonfLg1VcE1EJovv
Independent review: Devin Fusion (fusion-claude-opus-5-5-high-sidekick-swe-2-medium) rated it low, verdict MERGE: #1363 (comment)