Repository navigation
Reuse the finite-difference JVP base evaluation across a linear solve - #4287
ChrisRackauckas merged 4 commits into
Conversation
aa08a93 to
0587d33
Compare
| prep = DI.prepare_pushforward_same_point( | ||
| op.f, op.du, op.prep, op.backend, u, (u,), | ||
| DI.ConstantOrCache(p), DI.Constant(t) | ||
| ) |
There was a problem hiding this comment.
Measured on Julia 1.12 (JVPCache driving the real call path): the DI call itself allocates nothing; the only cost is the jvp_op::Any boxing boundary, once per linearization point.
DI.prepare_pushforward_same_point— 0 B under static dispatch for bothAutoFiniteDiffandAutoForwardDiff. FiniteDiff is the only backend in DI 0.7.21 that overrides it, and it writesf(u)into the preallocatedprep.f_inand returnsprep; every other backend hits the generic fallback (check_prep, a pure type check, thenreturn prep).set_jvp_point!statically — 0 B.prep === op.prepheld on every point-fix I ran, soDIPushforwardis never rebuilt with current DI; thenew_opbranch only exists because the DI API does not guarantee the same prep comes back.- Through
JVPCache, wherejvp_opisAny— firstmul!afterupdate_coefficients!is 176–256 B vs the 64 B steady-state, i.e. ~110–190 B of boxing (the(op, n)return tuple plus re-storingopinto theAnyfield). That is paid once perupdate_coefficients!— once per Newton/Wupdate — and amortized over every product the Krylov solve takes at the point. The per-product cost is unchanged (64 B, theAnydispatch that predates this PR).
So: ~110–190 B once per linearization point, 0 B per additional product.
There was a problem hiding this comment.
Update: applied the concreteness suggestion (fields are now @concrete type parameters) and also chased down the residual 64 B/product — it was the two reshape calls wrapping the tangents. reshape(::Array, dims) allocates a new Array header over the shared data ref (base/reshapedarray.jl), so every product paid two fresh Vector headers. Now skipped when the solver's shape already matches the linearization point's; the different-shaped path keeps the Array-typed reshape that check_prep's tangent-type signature needs.
Measured on this push (Julia 1.12, min of 30): update_coefficients!, sync_jvp_point!, set_jvp_point!, and steady-state mul! are all 0 B for both AutoFiniteDiff and AutoForwardDiff. The different-shaped reshape path (e.g. matrix u) is verified correct against a hand-rolled FD.
test/nf_accounting_tests.jl passes locally: 16/16 stats.nf, 7/7 rhs_evals_per_jvp, 10/10 base-evaluation-sharing (incl. the JVP correctness check).
There was a problem hiding this comment.
Added an AllocCheck test in test/qa/jvp_alloc_tests.jl (4722c92), wired into the QA group.
Results: update_coefficients!, sync_jvp_point!, and set_jvp_point! all report 0 check_allocs sites for both AutoFiniteDiff and AutoForwardDiff, and a user-supplied f.jvp is clean end-to-end (mul! itself: 0 sites, 0 B runtime). mul! over a DI backend is asserted at run time — @allocated mul!(Jv, J, v) == 0 for both a steady-state product and the point-fixing product after update_coefficients!.
Its residual check_allocs sites (12 for FiniteDiff, 6 for ForwardDiff) all live inside the DI backend pushforward! internals — conditional unaliascopy/copy sites in finite_difference_jvp!'s broadcasts and make_dual! that never fire for the distinct preallocated buffers used here — so those entries are marked broken = true tracking DI, matching the known_broken convention in OrdinaryDiffEqAdamsBashforthMoulton's qa suite. If DI ever sheds them the entries flip to unexpected-pass.
Local run: JVPCache allocation checks | 13 Pass, 2 Broken, 15 Total.
| @@ -33,6 +38,8 @@ can be shared by several `W`s. | |||
| p::Any | |||
| t::Any | |||
There was a problem hiding this comment.
| jvp_op | |
| f | |
| du | |
| u | |
| p | |
| t |
There was a problem hiding this comment.
Applied in 49388d5. One note on the trade-off: with jvp_op concrete, a set_jvp_point! that ever returns a different-typed operator (a backend answering prepare_pushforward_same_point with a different prep type) will now throw on the J.jvp_op = new_op store rather than adapt — unreachable with DI 0.7.21 since every backend returns its input prep, but that is the case the new_op branch exists for. u/p/t/du concreteness adds no new constraint beyond what check_prep's signature already enforces.
`JVPCache`'s linearization point only moves on `update_coefficients!`, so `f(u)` is constant for every product a Krylov solve takes. It was being recomputed per product: an `AutoFiniteDiff` matrix-free solve cost 2 RHS evaluations per matvec where `AutoForwardDiff` cost 1. Specialize the DifferentiationInterface prep to the point with `prepare_pushforward_same_point`, which as of DifferentiationInterface 0.7.21 threads the cached value into `FiniteDiff.finite_difference_jvp!`'s `f_in`. The point is fixed lazily on the first product after `update_coefficients!`, so a point set but never applied is free and the two `update_coefficients!` calls a `WOperator` makes when its `J` and `jacvec` are the same operator fix it once. `stats.nf` follows: `rhs_evals_per_jvp` drops to 1 for `AutoFiniteDiff` and the per-point base evaluations are tallied separately in `nbase_evals`. Fixes SciML#4162. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Cxo7SXiywZHBsAtfubAQ3H
`@concrete` promotes each untyped field to a type parameter, so `jvp_op`, `f`, `du`, `u`, `p`, `t` are now concretely typed and applying the operator no longer crosses an `Any` dispatch boundary. Fixing a linearization point is allocation-free where it cost ~110-190 B of boxing per `update_coefficients!` (the `(op, n)` return tuple plus re-storing `op` into the `Any` field). 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.10.21 Agent-Model: SWE-2 Max Agent-Session: local session sulfuric-aftermath (/home/crackauc/.local/share/devin/cli/transcripts/sulfuric-aftermath.json)
`reshape(::Array, dims)` allocates a new `Array` header over the shared data ref (base/reshapedarray.jl), so wrapping the tangents cost two fresh `Vector` headers per product — ~64 B/matvec. Only pay it when the solver hands us a different shape than the linearization point's; a same-shaped vector is passed through. `mul!` is now allocation-free in the common case while the different-shaped path keeps the `Array`-typed reshape that `check_prep`'s tangent-type signature needs. 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.10.21 Agent-Model: SWE-2 Max Agent-Session: local session sulfuric-aftermath (/home/crackauc/.local/share/devin/cli/transcripts/sulfuric-aftermath.json)
`check_allocs` proves the point-fixing half statically allocation-free (`update_coefficients!`, `sync_jvp_point!`, `set_jvp_point!`: 0 sites for both `AutoFiniteDiff` and `AutoForwardDiff`), while `mul!` is asserted at run time — zero bytes per product, including the product that fixes the point after `update_coefficients!`. A user-supplied `f.jvp` is clean end to end under `check_allocs` too. `mul!`'s residual `check_allocs` sites all live inside the DI backend `pushforward!` internals — conditional `unaliascopy` sites that never fire for the distinct preallocated buffers used here — so they are tracked as broken until DifferentiationInterface sheds them, matching the convention in OrdinaryDiffEqAdamsBashforthMoulton's qa suite. 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.10.21 Agent-Model: SWE-2 Max Agent-Session: local session sulfuric-aftermath (/home/crackauc/.local/share/devin/cli/transcripts/sulfuric-aftermath.json)
4722c92 to
64d8eed
Compare
- Fix SBDF order ramp, history-shift timing, and dt-change reset (#4366) - Release OrdinaryDiffEqBDF 2.4.10 (#4558) - Fix the sub-cache used by in-place interpolation for alg_choice 2 and 4 (#4556) - Reuse the finite-difference JVP base evaluation across a linear solve (#4287) - only allow diagonal M for ESDIRK (#4560) Agent-Harness: Claude Code Agent-Model: claude-opus-5[1m] Claude-Session: https://claude.ai/code/session_014FEzNTLFutCmTEAZ3zBg5R Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
- Raise OrdinaryDiffEqNonlinearSolve floor for stage_predictor (#4554) - Release OrdinaryDiffEqCore 4.17.3 (#4557) - Fix SBDF order ramp, history-shift timing, and dt-change reset (#4366) - Release OrdinaryDiffEqBDF 2.4.10 (#4558) - Fix the sub-cache used by in-place interpolation for alg_choice 2 and 4 (#4556) - Reuse the finite-difference JVP base evaluation across a linear solve (#4287) - only allow diagonal M for ESDIRK (#4560) Agent-Harness: Claude Code Agent-Model: claude-opus-5[1m] Claude-Session: https://claude.ai/code/session_014FEzNTLFutCmTEAZ3zBg5R Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
- Fix SBDF order ramp, history-shift timing, and dt-change reset (#4366) - Release OrdinaryDiffEqBDF 2.4.10 (#4558) - Fix the sub-cache used by in-place interpolation for alg_choice 2 and 4 (#4556) - Reuse the finite-difference JVP base evaluation across a linear solve (#4287) - only allow diagonal M for ESDIRK (#4560) Agent-Harness: Claude Code Agent-Model: claude-opus-5[1m] Claude-Session: https://claude.ai/code/session_014FEzNTLFutCmTEAZ3zBg5R Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This PR was opened by a coding agent — please ignore it until reviewed by @ChrisRackauckas.
Fixes #4162.
What changed and why
A
JVPCache's linearization point only moves onupdate_coefficients!, sof(u)is constant across every matrix-vector product a Krylov solve takes at that point. It was being recomputed per product: anAutoFiniteDiffmatrix-free solve cost 2 RHS evaluations per matvec whereAutoForwardDiffcost 1.JuliaDiff/DifferentiationInterface.jl#1061 (released in DifferentiationInterface 0.7.21) made
DI.prepare_pushforward_same_pointcache that base evaluation and thread it intoFiniteDiff.finite_difference_jvp!'sf_in.prepare_jvpwas calling plainprepare_pushforward, so it never saw the benefit. It now respecializes the prep to the point, lazily on the first product afterupdate_coefficients!— a point set but never applied costs nothing, and the twoupdate_coefficients!calls aWOperatormakes when itsJand itsjacvecare the same operator still fix the point once.stats.nffollows:rhs_evals_per_jvpdrops to 1 forAutoFiniteDiff, and the per-point base evaluations are tallied separately in the newnbase_evals, so the reported count stays exactly equal to the real one.Compat:
DifferentiationInterface = "0.7.21"(was"0.7.18");OrdinaryDiffEqDifferentiation3.9.0 → 3.10.0.Failing before / passing after
The new unit test drives a
JVPCachedirectly: oneupdate_coefficients!, then K products. It must costK + 1RHS evaluations, not2K.On the unfixed source (
git checkoutofoperators.jl, new test kept):With the fix applied:
(The version run against the unfixed source is the same test with the two new names —
base_evals_per_jvp_point,nbase_evals— dropped, so it fails on behaviour rather than on aMethodError.) The testset also checks the JVP still matches a hand-rolled forward difference, so the caching cannot silently return a stale product.End-to-end measurement
2D Brusselator, N=32 (2048 ODEs),
FBDF(linsolve = KrylovJL_GMRES(), concrete_jac = false),reltol = abstol = 1e-6,tspan = (0.0, 11.5), Julia 1.12.7,BLAS.set_num_threads(1), best of 5 runs,fcalls counted by a counter inside the RHS:fcallsstats.nfAutoFiniteDiff, masterAutoFiniteDiff, this PRAutoForwardDiff(both)1.94× fewer RHS evaluations, 1.17× faster wall clock, bit-identical step statistics.
AutoFiniteDiffnow edges outAutoForwardDiffon this problem instead of trailing it.stats.nfequals the real count on both revisions — the accounting was already exact and stays exact.Per-product allocations are unchanged (64 B, from the
jvp_op::Anydispatch that was already there); fixing a point costs ~130–210 B once per linear solve.Verification
All run locally on this branch, Julia 1.12.7.
Runic and
typosare clean on the changed files.Two pre-existing broken testsets showed up and are unrelated to this change:
OrdinaryDiffEqBDF's 2@test_brokenindae_initialization_tests.jl, andOrdinaryDiffEqFIRK's 5broken = trueAllocCheck assertions on the direct-solverperform_step!path (noJVPCacheinvolved).Not verified
AutoFiniteDifferences(FiniteDifferences.jl). DifferentiationInterface does not specializeprepare_pushforward_same_pointfor it, so it keepsrhs_evals_per_jvp == 2and gains nothing; that path is modelled, not measured.Worth pushing back on
f(u)means a caller that mutates the contents of the arrayJ.ualiases and then applies the operator without callingupdate_coefficients!now gets a stale base evaluation, where before it got a fresh one. I audited the callers —newton.jlcompute_step!mutatesustepthen callsupdate_coefficients!beforedolinsolve;calc_W!and the FIRK operators update the point before any product — and this is the same contract every caching SciMLOperator already relies on. But it is a real narrowing of what the operator tolerates, and it is the thing to look at first if something downstream misbehaves.rhs_evals_per_jvp(AutoFiniteDiff())changed from 2 to 1. It is not in the:publiclist, butstats.nffor existingAutoFiniteDiff+ Krylov runs will roughly halve. That is the point of the PR, not a regression — it now reports what actually happened — but it will move numbers in anyone's saved benchmark output.Follow-up, not in this PR
The base evaluation this PR spends once per linear solve is work
_compute_rhs!has already done immediately beforehand (k = f(ustep, p, tstep)). Eliminating it entirely needs a DifferentiationInterface API to inject a precomputedyinto the prep rather than haveprepare_pushforward_same_pointcallfitself. Worth raising upstream separately — it is ~800 of the 41415 calls in the benchmark above, so small.🤖 Generated with Claude Code
https://claude.ai/code/session_01Cxo7SXiywZHBsAtfubAQ3H