Skip to content

Optimize sparse jacobian2W diagonal updates - #4663

Merged
ChrisRackauckas merged 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:jacobian2W-sparse-diag
Sep 28, 2026
Merged

ChrisRackauckas merged 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:jacobian2W-sparse-diag

Conversation

@ChrisRackauckas-Claude

@ChrisRackauckas-Claude ChrisRackauckas-Claude commented Sep 27, 2026 •

Copy link
Copy Markdown
Member

What changed and why

Sparse CSC matrices now update stored diagonal values through nonzeros using the column row indices, avoiding scalar sparse setindex! for the common full-diagonal case. If a diagonal slot is absent, the remaining entries use the existing scalar assignment behavior, which inserts those slots. Dense and non-CSC matrix paths are unchanged.

Review follow-up (Cursor Agent on top of Codex Luna)

Applied Devin SWE-2 review findings in 669ce01b70 on top of Codex Luna's c9304f0ec6:

  1. Added :_update_sparse_diagonal! to Differentiation QA all_qualified_accesses_are_public ignore list.
  2. Added a partial-diagonal sparsity test (sparse([1,1,2],[1,2,1],…)) covering the mixed fast-write / insertion path vs dense reference.
  3. Assert square W and loop over column count so a non-square W BoundsErrors like master.

Diagnosis (profile)

The supplied audit reported 19–25% of leaf samples in jacobian2W!. On this machine, a 400-sample profile did not reproduce that share: TRBDF2 had 15 frames on the target lines out of 41,833 collected frame IDs; KenCarp4 had 23/15,302. These raw frame counts are not leaf-sample percentages and are not directly comparable to the audit metric.

Verification (re-run after review fixes)

  • julia -m Runic --check --diff on the changed files: exit 0.
  • typos on the changed files: exit 0.
  • git diff --check: exit 0.
  • GROUP=Sparse: Non-Full Diagonal Sparsity Tests | 2 passed, 2 total; package tests passed.
  • GROUP=QA: JET 1/1, Aqua 19/19, JVPCache 13 pass / 2 broken; package tests passed.
  • GROUP=Core: DAE jacobian2W sparse 4/4, jacobian2W sparse 13/13 (includes new partial-diagonal coverage). Then errored in the untouched ScalarOperator mass matrix test (diag(::SciMLOperators.ScalarOperator) has no method at OrdinaryDiffEqSDIRK/src/generic_imex_perform_step.jl:59). Same pre-existing failure noted by Codex Luna; not introduced by this PR.

Failing-before/passing-after

With the new test present and the implementation/ext temporarily restored to origin/master, the focused test exited 1 with UndefVarError: _update_sparse_diagonal! not defined. With the implementation applied, the focused sparse test file passed, and the package Core run passed its jacobian2W sparse testset (now 13/13).

Before/after numbers (same machine)

Pinned to core 20, JULIA_NUM_THREADS=1, @benchmark minima, 40 samples and one evaluation per sample:

Solver Before After Change Allocations Bytes before → after
TRBDF2 0.529788 ms 0.513727 ms −3.0% 941 → 941 148,264 → 148,440
KenCarp4 0.905675 ms 0.797646 ms −11.9% 1,013 → 1,013 153,272 → 153,752
ImplicitEuler 5.296964 ms 4.639488 ms −12.4% 1,989 → 1,989 534,024 → 534,184

Behaviour-equivalence check

On the same sparse 100-state fixtures, results matched the master references exactly:

  • KenCarp4: success on both, 14 steps, maximum absolute error 0.0.
  • TRBDF2: success on both, 14 steps, maximum absolute error 0.0.
  • ImplicitEuler: success on both, 148 steps, maximum absolute error 0.0.

The master implementation inserts missing diagonal entries. The new missing-diagonal and partial-diagonal tests check CSC fallback insertion and the mixed path.

What was not verified

The Core group did not complete because of the ScalarOperator error above (pre-existing / unrelated). No downstream, GPU, or full Everything group was run.

Please ignore until reviewed by @ChrisRackauckas.

Risk assessment

  • Risk: medium
  • Blast radius: internal scalar-mass-matrix update for CPU SparseMatrixCSC; dense and other matrix paths remain unchanged; no public API changes.
  • Evidence: Sparse 2/2; QA Aqua/JET/JVPCache passed; Core sparse testsets passed (13/13); master solve outputs matched exactly; pinned minima improved 3.0–12.4% with allocation counts unchanged.
  • Independent review: Devin (swe-2-high), re-review at 669ce01: MERGE, low risk. Semantics verified bitwise over 200+ random and edge sparsity patterns in the first pass. The QA blocker (ExplicitImports ignore) is fixed. The partial-diagonal test catches an injected bug. The square-W guard preserves valid inputs.
  • Merge: low-risk candidate. The Differentiation QA, Sparse, ModelingToolkit and pre jobs pass. The Differentiation Core reds on Julia 1 and LTS are the known master diag(::ScalarOperator) error in the ScalarOperator mass matrix testset. Rosenbrock QA Rosenbrock32 perform_step! inference is a separate master issue (see Rosenbrock QA: skip Rosenbrock32 on singular-mass inference DAE #4668).

Original author: Codex CLI (model: gpt-6-luna). Review fixes: Cursor Agent (auto) session log /home/crackauc/sandbox/goals/performance/jobs/pr-jac2w-sparse/log-cu.txt.

ChrisRackauckas and others added 2 commits September 27, 2026 15:37
Update stored CSC diagonal entries directly and preserve insertion behavior for missing diagonals. Add sparse coverage for both structural cases.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Codex <[email protected]>
Agent-Harness: Codex CLI codex-cli 0.157.1
Agent-Model: gpt-6-luna
Agent-Session: local codex session (log /home/crackauc/sandbox/goals/performance/jobs/pr-jac2w-sparse/log.txt)
Ignore `_update_sparse_diagonal!` in Differentiation QA, cover the mixed
fast-write/insertion path, and reject non-square W before the column loop.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Cursor Agent <[email protected]>
Agent-Harness: Cursor Agent 2026.09.26-dd393fe
Agent-Model: unknown (Cursor auto)
Agent-Session: local cursor-agent session (log /home/crackauc/sandbox/goals/performance/jobs/pr-jac2w-sparse/log-cu.txt)
@hexaeder

Copy link
Copy Markdown
Contributor

When this PR is revisited, it might be worth widening its scope. A related problem sits in the same function, and one change could fix both.

The problem: For a CPU SparseMatrixCSC W with a non-scalar mass matrix (e.g. a Diagonal M in a DAE), W is assembled by @.. W = muladd(-mass_matrix, invdtgamma, J). Sparse broadcast doesn't store exact zeros. So whenever a Jacobian entry happens to be 0.0 in a step, it drops out of W's pattern and nnz(W) changes between steps. KLU and UMFPACK then can't reuse the symbolic factorization and run klu_analyze again. Concrete example: a power grid DAE (n = 192, Rodas5P, default PureKLU), nnz(W) changed on 102 of 128 steps. Redundant symbolic analysis took about 9 % of the whole solve.

The scalar branch optimized here has a milder form of the same problem. If J lacks some diagonal slots, copyto!(W, J) removes them from W every step, and the fallback inserts them again.

Instead of _update_sparse_diagonal!, you could add a dedicated jacobian2W!(W::SparseMatrixCSC, M, dtgamma::Number, J::SparseMatrixCSC) method in the SparseArrays ext:

  • Handle scalar M (UniformScaling, ScalarOperator) and Diagonal M. Other mass matrices keep the existing broadcast path.
  • Fill nonzeros(W) in one pass over the columns, merging J's row indices into W's. Slots that J doesn't have get 0.0, and the diagonal gets -mⱼ/dtgamma added. The pattern never changes, and stored zeros stay stored.
  • If W lacks a slot that J or nz(M) needs, widen W's pattern in place once to W ∪ J ∪ nz(M), then fill again. Afterwards the pattern stays fixed.
  • dae_jacobian2W! (W = J_u + cj·J_du, plus the J_du - J_u broadcast in calc_J_dae!) has the same zero-dropping and could get the same treatment.

This would keep the speed-up here (no scalar setindex!). A useful test: solve with a Rodas or FBDF on a small mass matrix DAE with a jac_prototype where one Jacobian entry is exactly 0.0 for part of the time span. Then check that nnz(W) stays constant over all steps.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

[Automated reply from an AI agent working on the SciML performance goal]

Thanks, this is a real problem, and the pattern-stable approach is the right fix. nnz(W) changing on 102 of 128 steps, forcing KLU/UMFPACK to redo klu_analyze, costs far more than the scalar setindex! loop this PR removes.

I'd like to keep this PR narrow. It is reviewed and measured, and its results are bitwise identical to master. The pattern-stable version goes in a follow-up PR, which I'm starting now and will link here when it's up. The plan follows your outline:

  • Method: a dedicated jacobian2W!(W::SparseMatrixCSC, M, dtgamma::Number, J::SparseMatrixCSC) in the SparseArrays extension, covering scalar M (UniformScaling, ScalarOperator) and Diagonal M.
  • Assembly: it fills nonzeros(W) in a single merge pass, keeping stored zeros. If W's pattern is missing entries, it widens once to W ∪ J ∪ nz(M).
  • DAE path: dae_jacobian2W! and calc_J_dae! get the same treatment.
  • Test: a small mass-matrix DAE with Rodas5P and FBDF, using a jac_prototype where one Jacobian entry is exactly 0.0 for part of the time span, asserting that nnz(W) stays constant over every step.

If you can share the power-grid DAE, or a reduced version of it, I'll use it as a benchmark to show the symbolic-analysis saving.

🤖 Posted by an AI agent: Claude Code (model: claude-opus-5-5[1m]), session https://claude.ai/code/session_01LPHREnnonfLg1VcE1EJovv

@hexaeder

Copy link
Copy Markdown
Contributor

If you can share the power-grid DAE, or a reduced version of it, I'll use it as a benchmark to show the symbolic-analysis saving.

Sure, here is a reproducing script: https://gist.github.com/hexaeder/75263ca756c42ff18fd8c41b54821dc8

It depends on downstream packages NetworkDynamics, PowerDynamics and ModelingToolkitBase so its not usable for the tests or anything but might be worth for validating the end to end fix in that other PR.

@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review September 28, 2026 11:58
@ChrisRackauckas
ChrisRackauckas merged commit f61e499 into SciML:master Sep 28, 2026
183 of 192 checks passed
ChrisRackauckas-Claude pushed a commit to ChrisRackauckas-Claude/OrdinaryDiffEq.jl that referenced this pull request Sep 28, 2026
Sparse broadcast of W = M/dtgamma - J drops exact zeros, so nnz(W)
fluctuates with the Jacobian's values and KLU/UMFPACK redo symbolic
analysis nearly every step. Give CPU SparseMatrixCSC W a dedicated
path in the SparseArrays extension for scalar (UniformScaling,
ScalarOperator) and Diagonal mass matrices: the first call widens the
pattern once to W ∪ J ∪ nz(M), and each call rewrites nonzeros(W) in
place — positionally when W and J already share a pattern, by a merge
pass otherwise — so the pattern no longer depends on values. Values
are bitwise identical to the copyto!/broadcast paths they replace,
including stored -0.0 semantics.

dae_jacobian2W! gets the same treatment for W = J_u + cj*J_du, and
calc_J_dae! uses a stable in-place J_du - J_u via
_sparse_pattern_stable_sub!, which falls back to broadcast for
non-CPU-sparse arrays.

Design from @hexaeder's comment on SciML#4663; stacked on that branch.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: devin 3000.11.3
Agent-Model: swe-2-high
Agent-Session: local Devin session (log /home/crackauc/sandbox/goals/performance/jobs/pr-pattern-stable-W/log.txt)
ChrisRackauckas referenced this pull request Sep 29, 2026
* Bump DiffEqBase to 7.21.3

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.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqBDF to 2.4.12

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.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqSDIRK to 2.9.7

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.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqRosenbrock to 2.7.5

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.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqLowOrderRK to 2.2.6

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.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqTsit5 to 2.1.5

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.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqVerner to 2.4.2

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.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

* Bump OrdinaryDiffEqSymplecticRK to 2.2.3

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.11.3 (Mac)
Agent-Model: Fusion (claude-opus-5-5 medium + swe-2 medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/helpful-exception.json

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
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.

3 participants