Skip to content

Form sparse JᵀJ in place in DampedNewtonDescent (LM normal-form step! allocations) - #1363

Merged
ChrisRackauckas merged 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:lm-iteration-alloc
Oct 16, 2026
Merged

ChrisRackauckas merged 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:lm-iteration-alloc

Conversation

@ChrisRackauckas-Claude

@ChrisRackauckas-Claude ChrisRackauckas-Claude commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

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. A Profile.Allocs run (sample_rate = 1, one step! 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 example KLUFactorization, LUFactorization or CholeskyFactorization) and the Jacobian is sparse. There, @bb cache.JᵀJ_cache = transpose(J) × J goes through MaybeInplace's SparseArrays method C .= A * B. That method materializes copy(transpose(J)) and a fresh spmatmul result every iteration: about 239 KB per step at n = 1000.

This PR adds Utils.normal_form_jacobian!!(JᵀJ, J, workspace), with a non-allocating SparseMatrixCSC method in NonlinearSolveBaseSparseArraysExt. The DampedNewtonDescentCache holds the workspace: a transpose buffer filled with transpose!, 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' Gustavson spcolmul! (first product assigned, the rest added with +=, no FMA), so the values are bitwise identical to transpose(J) * J. If the cached pattern does not match the structural product pattern of the current J, 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, with abstol = reltol = 0:

case (LM) master this PR
sparse 1000 Bratu, KLUFactorization, geodesic 239 360 B 0 B
sparse 1000 Bratu, KLUFactorization, disable_geodesic 239 360 B 0 B
sparse 1000 Bratu, default linsolve (SPQR least squares), geodesic 1 821 000 B 1 821 000 B (all SPQR, see below)
sparse 1000 Bratu, default, no geodesic 1 732 232 B 1 732 216 B (SPQR)
dense 100 in-place, default (dense QR least squares), geodesic / no geodesic 62 912 / 60 320 B same (LAPACK QR)
dense 100, LUFactorization 81 016 B same (lu of Symmetric copies)
dense 100, CholeskyFactorization 0 B 0 B
Rosenbrock SVector{2} OOP, geodesic / no geodesic 70 800 / 35 400 B same (StaticArrays \ → LAPACK)

Minimum solve times (BenchmarkTools @belapsed, two alternating master/branch runs; both runs agreed to within 1%):

case master this PR
sparse KLU, geodesic, maxiters = 50 13.77 ms 12.06 ms
sparse KLU, no geodesic, maxiters = 50 12.51 ms 10.89 ms
sparse KLU, geodesic, to convergence (abstol = 1e-10) 42.52 ms 37.12 ms
sparse KLU, no geodesic, to convergence 7.76 ms 6.74 ms
sparse KLU, no geodesic, single step! 206.9 µs 175.0 µs

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 with solve: 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 iterate u, norm(fu), retcode and all NLStats fields, then compared them by reinterpreting to UInt64:

dense_lin_geo     bitwise identical  (22 iterates)
dense_lin_lu_geo  bitwise identical  (22 iterates)
dense_lin_nogeo   bitwise identical  (22 iterates)
dense_nl_chol_geo bitwise identical  (88 iterates)
dense_nl_geo      bitwise identical  (88 iterates)
dense_nl_lu_nogeo bitwise identical  (23 iterates)
dense_nl_nogeo    bitwise identical  (23 iterates)
rosen_sv_geo      bitwise identical  (32 iterates)
rosen_sv_nogeo    bitwise identical  (18 iterates)
sparse_geo        bitwise identical  (166 iterates)
sparse_klu_geo    bitwise identical  (166 iterates)
sparse_klu_nogeo  bitwise identical  (30 iterates)
sparse_nogeo      bitwise identical  (30 iterates)
ALL IDENTICAL

The new test also checks normal_form_jacobian!! against transpose(J) * J bitwise (colptr, rowval, and nzval reinterpreted as UInt64) on square, tall and wide random sparse matrices, and checks the pattern-mismatch fallback.

Test (fails on master)

lib/NonlinearSolveFirstOrder/test/sparsity_tests__item3.jl uses LM with KLUFactorization on a 200-dim sparse Bratu problem, with and without geodesic acceleration, and asserts maximum(@allocated step!(cache)) < 1000 after warmup. On master (allocation testsets only, since normal_form_workspace does not exist there), with --check-bounds=yes:

step! does not allocate (disable_geodesic = Val{false}()): Test Failed at .../master_alloc_test.jl:31
   Evaluated: 47664 < 1000
step! does not allocate (disable_geodesic = Val{true}()): Test Failed at .../master_alloc_test.jl:31
   Evaluated: 47696 < 1000

The same file on this branch:

Test Summary:                         | Pass  Total   Time
Sparse normal-form LevenbergMarquardt |   14     14  10.5s

Local validation

  • Runic (julia -m Runic --check) and typos pass on all changed files.
  • GROUP=Core NonlinearSolveFirstOrder: Testing NonlinearSolveFirstOrder tests passed
  • GROUP=QA NonlinearSolveFirstOrder: QA | 20 20 / tests passed
  • GROUP=Core NonlinearSolveBase: Testing NonlinearSolveBase tests passed
  • GROUP=QA NonlinearSolveBase: QA | 20 20 / tests passed. ExplicitImports flagged the extension's access to the two new internal Utils names. They were added to the existing internal-name ignore list in test/qa/qa.jl, which already covers structural_sparse, make_sparse, linsolve_workspace and similar names.

Remaining allocations (not patched here: they belong to other packages)

  • Dense default LM (~60–63 KB/step). In the :least_squares mode, LinearSolve's QR is applied to the stacked [J; √D] (200×100). LinearAlgebra.qr! → LAPACK.geqrt! allocates the T block-reflector matrix and the work array (2 × 28.8 KB). ldiv!(::QR, b) copies b, and gemqrt! allocates a work array. Fixing this belongs in LinearSolve's QRFactorization cache, which would need to keep T and the work buffers and call LAPACK.geqrt!(A, T) directly.
  • Sparse default LM (~1.8 MB/step). SPQR runs a fresh qr of the stacked sparse matrix every step (the CHOLMOD/SPQR conversions _extract_args/SparseMatrixCSC copies, plus SuiteSparse-internal mallocs that Profile.Allocs does not see), and \ on the SPQR factor goes through getindex_cols and invperm. This is SparseArrays/SuiteSparse territory. Separately, the default LM on this square sparse problem is about 150× slower than LM with KLUFactorization (≈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.
  • LUFactorization on the normal-form matrix (81 KB/step). Utils.maybe_symmetric wraps A in Symmetric, and LinearSolve's LU path calls lu(::Symmetric), which copies through copymutable_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.
  • SVector OOP (35–71 KB/step). NativeJLLinearSolveCache calls A \ b on a non-square SMatrix. StaticArrays forwards that to a heap Matrix pivoted QR (geqp3!/ormqr! work arrays).

Not verified

  • Julia LTS (1.10) and pre-release were not run locally; only 1.12.4. The kernel relies on spcolmul!'s accumulation order, which I checked in the 1.12 SparseArrays stdlib only. The bitwise test would catch a difference on other versions.
  • GPU sparse arrays: the new method dispatches only on SparseMatrixCSC, so other sparse types keep the old path. Not exercised.
  • The :minimum_norm mode (J × transpose(J)) and NewtonDescent's normal form (newton.jl) use the same allocating sparse product and are left unchanged.
  • Downstream packages, docs build (only internal docstrings changed; checkdocs = :exports), and the full GROUP=All/Everything suite were not run.

Risk assessment

  • Risk: low
  • Blast radius: internal to DampedNewtonDescent (LevenbergMarquardt and anything else using it), and only when J is a SparseMatrixCSC in the normal-form or normal-form-damping least-squares modes. No public API change. The new Utils functions are internal.
  • Evidence: bitwise-identical iterates and stats on 13 cases; the allocation test fails on master (47 664 B) and passes here (0 B); Core and QA pass for NonlinearSolveFirstOrder and NonlinearSolveBase.
  • Independent review: pending
  • Merge: needs human review until the independent review is done.

🤖 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)

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]>
@ChrisRackauckas

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

Independent review (Devin CLI 3000.11.3, model fusion-claude-opus-5-5-high-sidekick-swe-2-medium): MERGE, risk low.

Full review

VERDICT: MERGE
RISK: low

Blocking findings

None.

Non-blocking findings

  1. The test doesn't check that the solver result is correct, and it doesn't cover reinit (AGENTS.md asks for both). lib/NonlinearSolveFirstOrder/test/sparsity_tests__item3.jl:35-51 only asserts @allocated step! < 1000. It runs with abstol = reltol = 0 and never checks the iterate or the residual. AGENTS.md says to "exercise parameter-changing reinitialization … on these paths". The new kernel is checked bitwise in the unit testset, so the risk is small.
    • Confirmed by running: my own probe compared the solver-level LM+KLU and LM+UMFPACK iterates with master, and they are bitwise identical. It also showed that reinit!(cache, u0; p = p2) followed by solve! matches a fresh solve bitwise (details in "What I ran").
    • Suggested change: add sol = solve(prob, alg); @test SciMLBase.successful_retcode(sol) && norm(sol.resid) < 1e-8, plus one reinit! with a changed p.
  2. After a pattern change, every later call takes the allocating fallback. This is suspected from reading only; I did not probe the repeat behaviour.
    • When the pattern of J changes, transpose! resizes workspace.Jᵀ and the fallback (C .= transpose(J) * J) rebuilds C. That is correct, and my probe checked the results for grow, shrink, empty, return-to-original, a dropped entry and a wrong row count.
    • If the broadcast ever drops an exact numerical zero from C, the structural count nfilled will never match again, so every later call would fall back. That still gives correct results, but it allocates the same way master does.
    • In my cancellation probe the broadcast kept the stored zero (nnz = 4), so this did not happen there.
  3. Stacking with Eliminate TrustRegion sparse per-step JᵀJ allocations #1366. Eliminate TrustRegion sparse per-step JᵀJ allocations #1366 (TrustRegion) contains this PR's commit verbatim and builds on Utils.normal_form_workspace / normal_form_jacobian!!. The interface fits, but Eliminate TrustRegion sparse per-step JᵀJ allocations #1366 has to be rebased after this lands, or it will be reviewed with this diff duplicated inside it.
  4. The PR body says "Remaining allocations" are all in other packages. That claim, the Profile.Allocs attribution and the timing tables were not rerun here. Treat them as the author's claims.
  5. Red CI checks are pre-existing, not caused by this PR. The failing checks are Core lts (solve!() inference, test/Core/core_tests__item3.jl:27), Trim macOS (a CpuId precompile segfault), SCCNonlinearSolve (isconcretetype) and benchmark lts. The first two fail the same way on master at 8a86577a, in run https://github.com/SciML/NonlinearSolve.jl/actions/runs/37942671576. For SCCNonlinearSolve, master's Sublibrary CI at 0055e314 (run 37266049518) shows the same job failing; I did not open its log. I did not check benchmark lts on master.

What I ran

All on Julia 1.12.7, macOS arm64. I used separate dev'd envs for the PR head and for the merge base 0055e314 (taken with git archive into scratch/master).

  • The PR's new test file, run with --check-bounds=yes: passes. Results: kernel testset 12/12, step! alloc testsets 1/1 each.
  • The alloc testsets alone, against master: fail. Observed Evaluated: 55152 < 1000. This confirms the test fails without the fix (the author reported 47 664 B; the number is machine-dependent).
  • Kernel probe (scratch/kernel_probe.jl): 914/914 pass. Coverage:
    • 300 random m×n sparse matrices (1–80 per side, densities 0–0.4), values rescaled by up to e^±30 and changed three times on a fixed pattern; each result compared bitwise (colptr, rowval, nzval as UInt64) with transpose(J) * J.
    • Explicit stored zeros and exact cancellation, which keep their structural entries.
    • Pattern grow, shrink, empty, return-to-original and dropped-entry cases, all equal to the dense product.
    • A wrong row count, which goes through the size-check fallback.
    • Int32 indices with Float32 values: correct and 0 bytes allocated.
    • A mismatched workspace eltype, which takes the generic path.
  • Solver probe (scratch/solver_probe.jl): PR and master bitwise identical in all 15 cases. I ran it in both envs and compared every step's u and norm(fu), plus sol.u, retcode and all NLStats fields. Cases:
    • LM on a 300-dim sparse Bratu NonlinearProblem and on a 119×60 tall sparse NonlinearLeastSquaresProblem (whose J has stored zeros at u0), each with KLU, UMFPACK and the default linsolve, with and without geodesic acceleration.
    • LM+KLU with a parameter-changing reinit!, compared against a fresh solve.
    • TrustRegion(KLU) and PseudoTransient(KLU) on the Bratu problem.
    • A side observation: LM without geodesic stalls on Bratu at a residual of 1.6e-9, identically on master, so it is not caused by this PR.
  • Formatting and comments:
    • julia +1.12 --project=@runic -m Runic --check on the changed files: OK.
    • typos on the changed files: OK.
    • The diff adds 3 comment lines out of 165 added lines.
  • SparseArrays internals: I read the 1.12 and 1.10 stdlib sources.
    • spcolmul! has the same accumulation order in both: nzA[kp] * nzB, the first product assigned and the rest added with +=.
    • *(::AdjOrTrans{<:Any,<:AbstractSparseMatrixCSC}, ::SparseOrTri) is spmatmul(copy(A), B).
    • transpose! → halfperm! resizes the destination rather than throwing when nnz grows.
  • CI logs: checked the PR's checks and master's CI. The NonlinearSolveFirstOrder Core lts job runs the new testset and passes (Sparse normal-form LevenbergMarquardt | 14 14).

What I did not verify

  • The benchmark timings and the per-case byte counts for dense, SPQR and static configurations in the PR body. I also did not check the Profile.Allocs attribution of the remaining allocations.
  • Running locally on Julia 1.10 or pre-release. I relied on CI for those: the FirstOrder Core lts and pre jobs are green.
  • The GROUP=QA and GROUP=Core suites locally. I relied on CI, where the NonlinearSolveBase and FirstOrder QA and Core jobs are green.
  • GPU or non-CSC sparse types. These dispatch to the unchanged generic path, which I confirmed by reading only.

🤖 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
Conversation: local Claude session 3c311569-dda6-4687-bc9f-65febb212c33 (fleet master)

@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review October 16, 2026 18:49
@ChrisRackauckas
ChrisRackauckas merged commit e903b6b into SciML:master Oct 16, 2026
101 of 104 checks passed
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)
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