Skip to content

Skip redundant sparse-Jacobian structure rebuild in calc_J! - #3980

Merged
ChrisRackauckas merged 4 commits into
SciML:masterfrom
ChrisRackauckas-Claude:perf/skip-redundant-sparse-jac-rebuild
Jul 23, 2026
Merged

ChrisRackauckas merged 4 commits into
SciML:masterfrom
ChrisRackauckas-Claude:perf/skip-redundant-sparse-jac-rebuild

Conversation

@ChrisRackauckas-Claude

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

Copy link
Copy Markdown
Member

Draft — please ignore until reviewed by @ChrisRackauckas. Opened for visibility/review; end-to-end validation still in progress (see Validation status below).

What

calc_J! / calc_J_dae! rebuild a user-supplied sparse analytic Jacobian's sparsity structure on every evaluation:

set_all_nzval!(integrator.f.jac_prototype, true)
J .= true .* integrator.f.jac_prototype   # O(nnz) sparse broadcast + alloc
set_all_nzval!(J, false)
f.jac(J, uprev, p, t)

This was added in a1278ad for #2653 (a user jac_prototype whose pattern doesn't match what W needs). But f.jac only writes into already-stored entries, so J's structure is invariant after the first build. The rebuild only needs to run when J does not already match the prototype — in practice just the first call.

This PR guards the rebuild behind a same_sparsity_structure check via a new prepare_sparse_jac! helper. When J already matches the prototype (the common path — including the similar(jac_prototype) allocation that build_J_W uses), only the nzval zeroing runs. When it doesn't, the full rebuild runs exactly as before, preserving the #2653 fix.

It also stops a side effect: the old unconditional set_all_nzval!(jac_prototype, true) clobbers the user's jac_prototype.nzval to all-ones on every Jacobian evaluation. The fast path now leaves it untouched.

Why it matters

Most impactful for strict Rosenbrock methods (e.g. Rodas5P) that re-evaluate J every step, and for smaller stiff systems where the LU factorization does not dominate the step (on very large systems like BCR the ~40 ms sparse factorization dwarfs it).

Component measurement on a 1122×1122, 31 369-nnz Jacobian (BCR's W), Julia 1.11:

time
structure rebuild (old, per jac eval) ~78 µs
guarded (new, fast path) ~14 µs
saved per Jacobian evaluation ~64 µs
(for scale) the Jacobian evaluation itself ~39 µs

The rebuild costs ~2× the Jacobian evaluation it precedes.

Correctness

Verified standalone that old and new produce byte-identical colptr/rowval/nzval in both cases:

The only observable difference is that the new fast path preserves the user's jac_prototype.nzval instead of clobbering it to ones.

The same_sparsity_structure fallback (no SparseArrays extension loaded) returns false, so any non-CSC path conservatively takes the rebuild branch. The change is a pure no-op that skips provably-redundant work and self-corrects (if f.jac ever did alter structure, the guard fails next call and rebuilds).

Validation status

  • Semantic equivalence proven (both Strict in-place sparse Jacobians now cause errors when they don't anticipate the mass matrix #2653 branches) — codified as test/prepare_sparse_jac_tests.jl (9 tests, passing)
  • Branch builds and precompiles (incl. SparseArrays extension)
  • End-to-end A/B on OREGO/ROBER/HIRES/POLLU/Brusselator × Rodas5P/FBDF — all Success, identical solver stats baseline vs patched; ~1–4% faster on jac-heavy Rodas5P, neutral on FBDF (full table in a comment below)
  • Neighboring functional tests pass (dae_jacobian2w_sparse_tests covering the calc_J_dae! change, nzval_helpers_tests, nojac_tests)
  • Runic-clean (all source files + new test)

Draft pending review by @ChrisRackauckas.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LWooL8qipuUf7nTrDUUzqY

For a user-supplied sparse analytic Jacobian, calc_J!/calc_J_dae! rebuilt J's
sparsity structure on *every* evaluation via `J .= true .* jac_prototype`
(added in a1278ad for issue SciML#2653). f.jac only writes into already-stored
entries, so J's structure is invariant after the first build; the rebuild is a
per-eval O(nnz) sparse broadcast plus allocation that is only needed when J does
not already match the prototype.

Guard the rebuild behind a `same_sparsity_structure` check via a new
`prepare_sparse_jac!` helper. When J already matches the prototype (the common
path, including the `similar(jac_prototype)` allocation build_J_W uses), only the
nzval zeroing runs; otherwise the full rebuild runs exactly as before, so the
SciML#2653 mismatch case is preserved.

This also stops clobbering the user's `jac_prototype.nzval` to all-ones as a side
effect of every Jacobian evaluation (the old unconditional
`set_all_nzval!(jac_prototype, true)`); the fast path now leaves it untouched.

Measured on a 1122x1122, 31k-nnz Jacobian: rebuild ~78us -> guarded ~14us
(~64us saved per Jacobian evaluation). Most impactful for strict Rosenbrock
methods (e.g. Rodas5P) that re-evaluate J every step, and for smaller stiff
systems where the LU factorization does not dominate the step.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LWooL8qipuUf7nTrDUUzqY
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

End-to-end A/B results

Baseline vs this branch, same script in each env, Julia 1.11. Each problem's standard dense RHS is modelingtoolkitized and rebuilt with jac=true, sparse=true so the sparse calc_J! path is exercised. abstol=reltol=1e-8, @belapsed.

Solver statistics (njacs/nf/naccept) are identical between baseline and patched on every problem — the fix changes only timing, not the numerics.

Problem n nnz(J) njacs (Rodas5P) Rodas5P baseline Rodas5P patched Δ
OREGO 3 7 1138 4.51 ms 4.31 ms −4.4%
ROBER 3 8 190 0.846 ms 0.828 ms −2.1%
HIRES 8 25 164 1.088 ms 1.079 ms −0.8%
POLLU 20 86 68 0.737 ms 0.734 ms −0.4%
BRUSS100 200 800 349 31.34 ms† 31.09 ms† −0.8%
BRUSS400 800 3200 354 117.6 ms 115.5 ms −1.8%

† BRUSS100 re-measured over 40 independent solves (medians shown) after an initial run produced a contention outlier; the clean numbers are consistent with the rest.

FBDF is within noise of zero on all of these — it performs very few Jacobian evaluations (1–11 here), so there is almost nothing to save.

Honest read

The isolated operation drops cleanly (rebuild ~78 µs → ~14 µs, a 5.6× reduction of that step), but end-to-end this is a small, strictly-positive, zero-downside improvement (~1–4% on Jacobian-heavy Rodas5P, neutral on FBDF), not a dramatic speedup — the rebuild is only a slice of the total step, and the relative benefit shrinks as the LU factorization comes to dominate (on very large systems like BCR it is lost entirely behind the ~40 ms factorization). The value is that it removes provably-redundant per-eval work and fixes the jac_prototype.nzval clobbering side effect, with no numerical change and no regressions.

Covers the has_jac + sparse jac_prototype path (the branch guarded by
prepare_sparse_jac!), which the existing nonfulldiagonal_sparse test does not
reach (it supplies only a jac_prototype, hitting the AD path). Asserts, for both
the matching-structure fast path and the mismatched-structure rebuild path, that
the result is byte-identical to the old unconditional rebuild, and that the fast
path no longer clobbers the user's jac_prototype.nzval.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LWooL8qipuUf7nTrDUUzqY
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Validation update

  • Semantic equivalence proven (byte-identical output on both the matching and Strict in-place sparse Jacobians now cause errors when they don't anticipate the mass matrix #2653-mismatch paths) — now codified as test/prepare_sparse_jac_tests.jl (9 tests, passing)
  • End-to-end A/B on OREGO/ROBER/HIRES/POLLU/Brusselator × Rodas5P/FBDF — all Success, identical solver statistics baseline vs patched (table above); ~1–4% faster on jac-heavy Rodas5P, neutral on FBDF
  • Neighboring functional tests pass against the patched sublib: dae_jacobian2w_sparse_tests (covers the calc_J_dae! change), nzval_helpers_tests, nojac_tests
  • Runic-clean (all three source files + the new test)

Note: the existing nonfulldiagonal_sparse test supplies only a jac_prototype (no analytic jac), so it exercises the AD/coloring branch, not the has_jac branch changed here — hence the new dedicated test for the analytic-sparse-jac path.

ArrayInterface 7.28 adds a public `same_sparsity_structure(A, B)` (JuliaArrays/
ArrayInterface.jl#496), so drop the local copy and its SparseArrays-extension
method and call the public API from `prepare_sparse_jac!`. Removes the
duplication and lets the sparse-structure check improve/extend (dense, GPU
CSC/CSR, structured types) in one shared place.

- raise ArrayInterface compat floor 7.19 -> 7.28 (the version that adds the
  function); OrdinaryDiffEqDifferentiation 3.3.1 -> 3.3.2
- test now imports same_sparsity_structure from ArrayInterface

Behavior-preserving: the call site is gated by `is_sparse_csc`, so both arguments
are always `SparseMatrixCSC` and hit ArrayInterface's CSC method (identical
colptr/rowval comparison). End-to-end solves are unchanged (identical njacs/
naccept), and the sublib test passes against ArrayInterface 7.28.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LWooL8qipuUf7nTrDUUzqY
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Restacked onto the public ArrayInterface.same_sparsity_structure

The structural-equality helper this PR introduced is now public API in ArrayInterface 7.28 (JuliaArrays/ArrayInterface.jl#496, registering in JuliaRegistries/General#162114). This commit drops the local copy and calls the public function instead:

  • removed the local same_sparsity_structure (core fallback + SparseArrays-ext method); prepare_sparse_jac! now calls ArrayInterface.same_sparsity_structure
  • ArrayInterface compat floor 7.19 → 7.28; OrdinaryDiffEqDifferentiation 3.3.1 → 3.3.2

Behavior-preserving. The call site is gated by is_sparse_csc, so both arguments are always SparseMatrixCSC and hit ArrayInterface's CSC method (the same colptr/rowval comparison the local copy did). Validated locally against the merged ArrayInterface 7.28: the sublib test passes (9/9), and an end-to-end OREGO solve (sparse analytic Jacobian, Rodas5P + FBDF) returns Success with identical njacs/naccept to before the restack.

CI note: this PR's CI will stay red until ArrayInterface 7.28 merges into General (#162114 — checks pass, pending AutoMerge). Once it lands, the compat floor resolves and CI should go green with no further changes.

@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review July 23, 2026 13:23
@ChrisRackauckas
ChrisRackauckas merged commit a09809a into SciML:master Jul 23, 2026
20 of 22 checks passed
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