Skip to content

Reuse the finite-difference JVP base evaluation across a linear solve - #4287

Merged
ChrisRackauckas merged 4 commits into
SciML:masterfrom
ChrisRackauckas-Claude:jvp-samepoint-basecache
Sep 13, 2026
Merged

ChrisRackauckas merged 4 commits into
SciML:masterfrom
ChrisRackauckas-Claude:jvp-samepoint-basecache

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

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 on update_coefficients!, so f(u) is constant across every matrix-vector product a Krylov solve takes at that point. It was being recomputed per product: an AutoFiniteDiff matrix-free solve cost 2 RHS evaluations per matvec where AutoForwardDiff cost 1.

JuliaDiff/DifferentiationInterface.jl#1061 (released in DifferentiationInterface 0.7.21) made DI.prepare_pushforward_same_point cache that base evaluation and thread it into FiniteDiff.finite_difference_jvp!'s f_in. prepare_jvp was calling plain prepare_pushforward, so it never saw the benefit. It now respecializes the prep to the point, lazily on the first product after update_coefficients! — a point set but never applied costs nothing, and the two update_coefficients! calls a WOperator makes when its J and its jacvec are the same operator still fix the point once.

stats.nf follows: rhs_evals_per_jvp drops to 1 for AutoFiniteDiff, and the per-point base evaluations are tallied separately in the new nbase_evals, so the reported count stays exactly equal to the real one.

Compat: DifferentiationInterface = "0.7.21" (was "0.7.18"); OrdinaryDiffEqDifferentiation 3.9.0 → 3.10.0.

Failing before / passing after

The new unit test drives a JVPCache directly: one update_coefficients!, then K products. It must cost K + 1 RHS evaluations, not 2K.

On the unfixed source (git checkout of operators.jl, new test kept):

AutoFiniteDiff: Test Failed at .../discriminate.jl:35
  Expression: NCALLS[] == K + per_point
   Evaluated: 10 == 6

Test Summary:                                                   | Pass  Fail  Total  Time
the finite-difference base evaluation is shared across products |    5     1      6  3.6s
  AutoFiniteDiff                                                |    2     1      3  3.3s
  AutoForwardDiff                                               |    3            3  0.3s
ERROR: LoadError: Some tests did not pass: 5 passed, 1 failed, 0 errored, 0 broken.

With the fix applied:

Test Summary:                                                   | Pass  Total  Time
the finite-difference base evaluation is shared across products |    6      6  1.2s

(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 a MethodError.) 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, f calls counted by a counter inside the RHS:

real f calls stats.nf naccept nreject nsolve best time
AutoFiniteDiff, master 80463 80463 553 47 788 2.5098 s
AutoFiniteDiff, this PR 41415 41415 553 47 788 2.1468 s
AutoForwardDiff (both) 39020 39020 553 47 788 2.3510 s

1.94× fewer RHS evaluations, 1.17× faster wall clock, bit-identical step statistics. AutoFiniteDiff now edges out AutoForwardDiff on this problem instead of trailing it. stats.nf equals 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::Any dispatch 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.

$ GROUP=Core julia --project=lib/OrdinaryDiffEqDifferentiation -e 'using Pkg; Pkg.test()'
Test Summary:        | Pass  Total   Time
Krylov nf accounting |   33     33  48.0s
Test Summary:                 | Pass  Total     Time
Stale W Linear Operator Tests |   12     12  5m43.0s
...
     Testing OrdinaryDiffEqDifferentiation tests passed

$ GROUP=QA julia --project=lib/OrdinaryDiffEqDifferentiation -e 'using Pkg; Pkg.test()'
Test Summary: | Pass  Total   Time
JET Tests     |    1      1  35.7s
Test Summary: | Pass  Total   Time
Aqua          |   19     19  38.5s
     Testing OrdinaryDiffEqDifferentiation tests passed

$ GROUP=Core julia --project=lib/OrdinaryDiffEqBDF -e 'using Pkg; Pkg.test()'
Test Summary:         | Pass  Total     Time
BDF Convergence Tests |   84     84  4m01.4s
Test Summary:        | Pass  Total     Time
BDF Regression Tests |   35     35  4m03.8s
...
     Testing OrdinaryDiffEqBDF tests passed

$ julia --project=lib/OrdinaryDiffEqFIRK -e 'using Pkg; Pkg.test()'
Test Summary:     | Pass  Total     Time
FIRK Krylov Tests |   93     93  5m47.1s
...
     Testing OrdinaryDiffEqFIRK tests passed

Runic and typos are clean on the changed files.

Two pre-existing broken testsets showed up and are unrelated to this change: OrdinaryDiffEqBDF's 2 @test_broken in dae_initialization_tests.jl, and OrdinaryDiffEqFIRK's 5 broken = true AllocCheck assertions on the direct-solver perform_step! path (no JVPCache involved).

Not verified

  • GPU groups, downstream packages, and the docs build — no GPU here, and nothing in this PR touches a docstring that is rendered or any public API entry.
  • AutoFiniteDifferences (FiniteDifferences.jl). DifferentiationInterface does not specialize prepare_pushforward_same_point for it, so it keeps rhs_evals_per_jvp == 2 and gains nothing; that path is modelled, not measured.

Worth pushing back on

  • The staleness contract. Caching f(u) means a caller that mutates the contents of the array J.u aliases and then applies the operator without calling update_coefficients! now gets a stale base evaluation, where before it got a fresh one. I audited the callers — newton.jl compute_step! mutates ustep then calls update_coefficients! before dolinsolve; 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 :public list, but stats.nf for existing AutoFiniteDiff + 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 precomputed y into the prep rather than have prepare_pushforward_same_point call f itself. 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

Comment on lines +205 to +208
prep = DI.prepare_pushforward_same_point(
op.f, op.du, op.prep, op.backend, u, (u,),
DI.ConstantOrCache(p), DI.Constant(t)
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this allocate?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 both AutoFiniteDiff and AutoForwardDiff. FiniteDiff is the only backend in DI 0.7.21 that overrides it, and it writes f(u) into the preallocated prep.f_in and returns prep; every other backend hits the generic fallback (check_prep, a pure type check, then return prep).
  • set_jvp_point! statically — 0 B. prep === op.prep held on every point-fix I ran, so DIPushforward is never rebuilt with current DI; the new_op branch only exists because the DI API does not guarantee the same prep comes back.
  • Through JVPCache, where jvp_op is Any — first mul! after update_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-storing op into the Any field). That is paid once per update_coefficients! — once per Newton/W update — and amortized over every product the Krylov solve takes at the point. The per-product cost is unchanged (64 B, the Any dispatch that predates this PR).

So: ~110–190 B once per linearization point, 0 B per additional product.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines 34 to 39
@@ -33,6 +38,8 @@ can be shared by several `W`s.
p::Any
t::Any

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
jvp_op
f
du
u
p
t

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

ChrisRackauckas and others added 4 commits September 13, 2026 16:48
`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)
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review September 13, 2026 20:56
@ChrisRackauckas
ChrisRackauckas merged commit b9e8cd2 into SciML:master Sep 13, 2026
77 of 81 checks passed
ChrisRackauckas added a commit that referenced this pull request Sep 14, 2026
- 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]>
ChrisRackauckas added a commit that referenced this pull request Sep 14, 2026
- 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]>
ChrisRackauckas added a commit that referenced this pull request Sep 14, 2026
- 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]>
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.

AutoFiniteDiff JVP recomputes f(x) on every Krylov matvec; nf accounting double-counts it

2 participants