Repository navigation
Assemble sparse FIRK stage matrices over stored structure - #4669
Merged
ChrisRackauckas merged 4 commits intoOct 4, 2026
Merged
Conversation
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
marked this pull request as ready for review
October 4, 2026 14:20
This was referenced Oct 11, 2026
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>
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.
What changed and why
Every FIRK stage-matrix rebuild (
W = -γ·M + J, plus the complex stagematrices W2/W3) iterated
CartesianIndices(J)and performed n²SparseMatrixCSC.setindex!calls — each insertion into an unstoredposition is O(nnz) — once per Jacobian refresh in
firk_perform_step.jland
firk_addsteps.jl(RadauIIA3/5/9, AdaptiveRadau). A single helper,firk_W!, now handles all eight call sites. ForSparseMatrixCSCJ + 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 documentedSparseMatrixCSCconstructor,copyto!). A genericmuladdloopmethod 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 complexscale times an unstored
0.0produces-0.0 - 0.0im, whichsetindex!inserts because it is not=== zero. So every complex Wcarried a dense pattern into LU on master. The merge produces the
correct union pattern instead.
Diagnosis (profile)
Profile.printon 30 sparse RadauIIA5 solves (n=100 tridiagonaljac_prototype,mass_matrix = I), same machine:SparseArrays/src/sparsematrix.jl setindex!633 total / 178 own
setindex!absent;firk_W!~6 own samples totalVerification
@muladdentrywise loop on the n=200 problem across I,LinearAlgebra.Diagonal, and off-pattern sparse mass matrices, realand complex scales — the merge computes each value with a single
muladd(scale, M[row,col], J[row,col]), matching master's fusedarithmetic 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).
diagonal, stored zeros, exact cancellation, grow/shrink reuse of W,
W denser than J, 1×1, empty):
firk_W!agrees with the entrywiseloop on every case.
— {sparse, dense} J × {I, diagonal, off-pattern sparse} mass ×
{RadauIIA5, RadauIIA9, AdaptiveRadau} × endpoint-only and dense-output
(dense output exercises the
firk_addsteps.jlsites). Fulltrajectories, not just endpoints.
jac_prototypeand bothI(default) and non-identity diagonalmass matrices for RadauIIA3, RadauIIA5, RadauIIA9, AdaptiveRadau and
threaded AdaptiveRadau, compared against the
dense-
jac_prototypesolve withdense = true(exercises all eightfirk_W!call sites including addsteps). The unit testset coverssparse,
I, andDiagonalmass matrices with real and complexscales against entrywise
muladdsemantics.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 onmaster). 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,BenchmarkToolsminimum of 3samples, n=200 stiff tridiagonal ODE, tspan (0, 0.1),
abstol=reltol=1e-8.
everystep=save_everystep=true(exercises_ode_addsteps!). Head = 516e827.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
muladdentrywise 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
mass_matrixtypes (e.g.AbstractSciMLOperator) — theydispatch to the generic
muladdloop, matching master.julia pre.Test output tails
GROUP=Core (
lib/OrdinaryDiffEqFIRK, includes the new testsets):GROUP=QA:
Runic: only two pre-existing hunks in
firk_perform_step.jlthat areidentical on master (not introduced here).
typosclean over thediff. 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,RadauIIA9andAdaptiveRadausolves (including threadedAdaptiveRadauand the dense-output_ode_addsteps!paths) whereJandWareSparseMatrixCSCand the mass matrix isUniformScaling,DiagonalorSparseMatrixCSC. Those cases now take the new O(nnz) merge infirk_W!, and the complex stage matricesW2/W3get a smaller stored pattern than master's fully dense one. That can change the sparse LU fill and move results at the rounding level. DenseJ, other mass-matrix types, theConstantCache(out-of-place) paths and the Krylovset_W_gamma!branch still run the old entrywise loop.SparseArraysbecomes a direct dependency (stdlib, compat1.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, theSparseMatrixCSCconstructor) pluscopyto!.Evidence: Head
755d14bhas 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 mastera50e0d7.downgrade-sublibraries / test (lib/OrdinaryDiffEqDifferentiation):MethodError: no method matching diag(::ScalarOperator), the same on mastera50e0d7.SciMLSensitivity.jl/Core1: Mooncake error atconcrete_solve_derivatives.jl:451, the same on mastera50e0d7anda329b3b.tests / GPU:QNDF [jac=CSC, mass=diag_cu]givesgpu_mismatchatdae_tests.jl:481(a BDF test, not FIRK), "172 passed, 1 failed". The same failure is on master0fac2d0(the PR's base) and3178b19, and GPU has been red on master since4e8d61f.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 entrywisemuladd, and a sparse-vs-dense solve comparison withatol1e-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:
755d14b, a later test-only commit.firk_addsteps.jlis not under@muladdon master. The 4 addsteps call sites therefore change from an unfuseda*b + cto a fusablemuladd, which can differ by an ulp when the mass entries are not 0 or 1.AdaptiveRadauloop now makes one pass per stage instead of one fused pass), so a real slowdown is unlikely, but nothing measured rules it out.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
Wassembly 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
Wchanges, 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)