Skip to content

Count Krylov Jacobian-vector products on the operator that performs them - #4193

Merged
ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:krylov-nf-accounting
Aug 9, 2026
Merged

ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:krylov-nf-accounting

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Closes #4162.

Please ignore until reviewed by @ChrisRackauckas.

What nf means

nf counts calls to f. That is what increment_nf!'s docstring says ("the RHS-evaluation counter"), what SciMLBase prints it as ("Number of function 1 evaluations"), and what every other increment site in the solver does — increment_nf!(stats, num_stages) after num_stages calls, and so on. It is not a cost model. This PR keeps that definition and makes the Krylov path obey it; the alternative, rescaling the finite-difference product to one "cost-equivalent" evaluation so it compares evenly with a dual-number product, would put a cost model into a counter nothing else treats as one, and would make nf disagree with a user counting their own f calls. The choice is written down in the new rhs_evals_per_jvp docstring.

Under that definition the 2-vs-1 split the issue points at is correct: FiniteDiff.finite_difference_jvp! really does call f twice per product (at x and at the perturbed point — verified in FiniteDiff 2.33.0, both :forward and :central), and a ForwardDiff product really is one call on a dual input. The measurement in the issue (24.96 µs vs 27.67 µs) says the finite-difference product is cheaper per unit of work, which is a real and useful fact, but it is not a statement about how many times f ran.

What was actually wrong

The accounting was wrong in three other ways, all of which made nf disagree with the true call count. Counting real f calls on a 24-state Allen-Cahn problem with FBDF(linsolve = KrylovJL_GMRES()), on master (9d23061ef8a2b155ca2b6ff78670f6e320967940):

configuration real f calls stats.nf on master stats.nf with this PR
matrix-free, AutoForwardDiff 219 151 219
matrix-free, AutoFiniteDiff 402 266 402
concrete_jac = true, AutoForwardDiff 243 62 243
concrete_jac = true, AutoFiniteDiff 427 63 427
MatrixOperator jac_prototype, AutoForwardDiff 38 151 38
MatrixOperator jac_prototype, AutoFiniteDiff 38 264 38
direct solver (control) 58 58 58
  1. linres.iters is not the number of products. A Krylov solve applies the operator more times than it reports iterations. The matrix-free rows under-count by 31% and 34%, which works out to about two extra products per solve over the 35 solves here: one is the Hegedűs warm start, which does an explicit mul!(similar(cache.b), cache.A, u) in LinearSolve/src/iterative_wrappers.jl before handing off to Krylov, and the rest is the initial residual.
  2. The jacvec path was invisible. The gate was linsolve.A.J isa AbstractSciMLOperator, but WOperator's mul! uses W.jacvec whenever it has one. With concrete_jac = true the Krylov solver keeps a concrete J for the preconditioner and does its products through W.jacvec, so the gate was false and none of the products were counted: 62 reported against 243 real.
  3. A concretizable operator was charged for products it does not pay for. A user-supplied MatrixOperator Jacobian applies a stored matrix and calls f zero times, but it satisfied the gate and was billed per iteration: 151 and 264 reported against 38 real.

The fix

Count the products on the operator that performs them, which is the only place that sees all of them and is already the approach drain_jvp_count! took for FIRK's ComplexWOperator in #4166 ("the counter lives on the operator rather than being inferred from the Krylov iteration count"). JVPCache gains an njvps tally; dolinsolve drains it through a drain_jvp_count! that is now shared with FIRK rather than duplicated. All three defects fall out: a MatrixOperator has no tally, a jacvec has one wherever it sits in the W, and the tally counts the products the solver never reported.

This also answers the #4166 follow-up noted in the issue. FIRK's separate ComplexWOperator.jvps field goes away — a ComplexWOperator applies the same real JVP operator its W does, so those products are already on that operator's tally and one jvp_counter method is all FIRK needs. FIRK's existing stats.nf == nf[] assertions in firk_krylov_tests.jl cover the migration.

Step counts are untouched in every configuration above (naccept = 27, nsolve = 35 before and after): this changes reporting only.

Failing before / passing after

New test asserts stats.nf == the counted number of f calls across the four configurations × two AD backends. On unmodified master, with the rhs_evals_per_jvp unit testset removed since the helper does not exist there:

AutoForwardDiff: Test Failed
  Expression: nf == real_f
   Evaluated: 151 == 219
AutoForwardDiff: Test Failed
  Expression: nf == real_f
   Evaluated: 62 == 243
AutoForwardDiff: Test Failed
  Expression: nf == real_f
   Evaluated: 151 == 38
AutoFiniteDiff: Test Failed
  Expression: nf == real_f
   Evaluated: 266 == 402
AutoFiniteDiff: Test Failed
  Expression: nf == real_f
   Evaluated: 63 == 427
AutoFiniteDiff: Test Failed
  Expression: nf == real_f
   Evaluated: 264 == 38

Test Summary:                                               | Pass  Fail  Total   Time
stats.nf counts every RHS evaluation the Krylov solve costs |   10     6     16  36.7s
ERROR: LoadError: Some tests did not pass: 10 passed, 6 failed, 0 errored, 0 broken.

The 10 passes are the direct-solver control and the successful_retcode checks. With the change:

Test Summary:                                               | Pass  Total   Time
stats.nf counts every RHS evaluation the Krylov solve costs |   16     16  36.0s
Test Summary:     | Pass  Total  Time
rhs_evals_per_jvp |    5      5  0.0s

Related context, not fixed here

The larger half of #4162 is upstream and is not touched. FiniteDiff.finite_difference_jvp! takes an f_in argument so a caller can hand it a cached f(x), but DifferentiationInterface's pushforward! does not pass it — confirmed still true in DifferentiationInterface 0.7.20, ext/DifferentiationInterfaceFiniteDiffExt/twoarg.jl, which calls finite_difference_jvp!(dy, fc!, x, dx, prep.cache; relstep, absstep, dir) with no f_in. So the base evaluation is recomputed on every matvec even though x is fixed for the whole linear solve, worth about 1.2× on that path. That fix belongs in DifferentiationInterface. When it lands, rhs_evals_per_jvp for AutoFiniteDiff becomes 1 and this is the one line that has to change; the docstring says so.

DifferentiationInterface is not a repo I have standing to file in, so this is reported here rather than opened there.

Verification

Julia 1.12.6. Resolved: LinearSolve 5.6.0, SciMLBase 3.43.0, SciMLOperators 1.26.1, ADTypes 1.22.4, FiniteDiff 2.33.0, DifferentiationInterface 0.7.20, Krylov 0.10.9.

GROUP=Core julia --project -e 'using Pkg; Pkg.test()' in lib/OrdinaryDiffEqDifferentiation:

DAE jacobian2W sparse |    4      4  50.9s
prepare_user_sparsity mass matrix |    9      9  3.3s
ScalarOperator mass matrix |    9      9  9m44.8s
nzval helpers |   26     26  40.9s
prepare_sparse_jac! |    9      9  0.5s
OOP J_t Tracking |    5      5  16.3s
Differentiation Trait Tests |    5      5  13.0s
Autodiff Error Tests |    4      4  3m32.8s
No Jac Tests  |    7      7  19.1s
Stale W Linear Operator Tests |   12     12  5m48.3s
Krylov warm_start default |    7      7  0.1s
Krylov nf accounting |   21     21  1m06.0s
     Testing OrdinaryDiffEqDifferentiation tests passed

GROUP=Core in lib/OrdinaryDiffEqFIRK, which carries the pre-existing stats.nf == nf[] assertions the ComplexWOperator counter migration has to keep passing:

FIRK Tests    |  107    107  4m48.6s
FIRK Krylov Tests |   93     93  8m11.8s
     Testing OrdinaryDiffEqFIRK tests passed

GROUP=QA in lib/OrdinaryDiffEqDifferentiation (JET + Aqua, which is where the ExplicitImports checks live and so where the new public declarations are exercised):

JET Tests     |    1      1  35.0s
Aqua          |   18     18  41.3s
     Testing OrdinaryDiffEqDifferentiation tests passed

GROUP=QA in lib/OrdinaryDiffEqFIRK fails, but it fails identically on unmodified master — run_api_docs reports :SciMLBase as an undocumented public name, which comes from the pre-existing @reexport using SciMLBase in OrdinaryDiffEqFIRK.jl and has nothing to do with this diff (Allocation Tests 5/5 and JET Tests 1/1 in the same group pass):

public API has docstrings: Test Failed at SciMLTesting.jl:1205
  Expression: isempty(undocumented)
   Evaluated: isempty([:SciMLBase])
Aqua | 19  1  20

I am confirming the master reproduction separately and will report it; it is not something this PR should carry a fix for.

Runic and typos are clean over the diff and the new test file.

Both PRs bump lib/OrdinaryDiffEqDifferentiation to 3.8.0 (each adds public API), so whichever merges second will conflict on that one line in Project.toml and on the public block; the rest of the two diffs is disjoint apart from dolinsolve itself.

Not verified

  • GPU, Downstream, and Documentation CI. The docs build was not run: no docs/ file, rendered API entry, or public name is touched (JVPCache is documented but internal, and the change to it is additive).
  • Test groups other than the ones listed above; in particular the Rosenbrock, SDIRK and StochasticDiffEq suites, which share dolinsolve but whose matrix-free paths are the same code as the ones exercised above.
  • AutoFiniteDifferences, which rhs_evals_per_jvp still maps to 2. It is unreachable through this path — prepare_jvp asserts DI.check_inplace(autodiff) and DifferentiationInterface declares inplace_support(::AutoFiniteDifferences) = InPlaceNotSupported() — so the branch is dead rather than tested. I kept it rather than deleting it because deleting a dead branch is a separate question from fixing the accounting; note that 2 would be wrong for it anyway, since central_fdm(5, 1) costs five evaluations per product.

Worth pushing back on

  • njvps is a plain Int incremented in mul!. That is safe today because nothing in this repo applies a shared JVPCache from more than one thread (FIRK's AdaptiveRadau stage operators all share the W1.jacvec and run sequentially), but it is a counter in a hot path with no synchronisation, and if a threaded stage solve ever lands it becomes a race. The pre-existing ComplexWOperator.jvps had the same property.
  • Draining in dolinsolve attributes any products applied outside a linear solve to the next solve. The total stays right; the per-step attribution can be off by one solve.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Confirming the FIRK GROUP=QA failure mentioned in the Verification section is pre-existing and not caused by this PR. Same command on the unmodified base commit 9d23061ef8a2b155ca2b6ff78670f6e320967940, in a clean worktree:

Allocation Tests |      5      5  3m05.7s
JET Tests        |    1      1  48.5s
public API has docstrings: Test Failed at SciMLTesting.jl:1205
  Expression: isempty(undocumented)
   Evaluated: isempty([:SciMLBase])
Aqua             |   19     1     20  1m23.6s
ERROR: LoadError: Some tests did not pass: 19 passed, 1 failed, 0 errored, 0 broken.
ERROR: Package OrdinaryDiffEqFIRK errored during testing

Identical counts and identical single failure to the branch run. :SciMLBase is reported as an undocumented public name because lib/OrdinaryDiffEqFIRK/src/OrdinaryDiffEqFIRK.jl does @reexport using SciMLBase, which puts the module's own name into names(OrdinaryDiffEqFIRK). Being tracked and fixed separately; nothing in this diff touches it.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Root cause of the pre-existing FIRK QA failure above, so it does not get mistaken for something this PR should carry: it is a SciMLTesting regression, not an OrdinaryDiffEq one, and it affects the whole monorepo rather than FIRK.

@reexport using SciMLBase puts :SciMLBase into names(pkg), and SciMLBase has no module docstring. Up to SciMLTesting v2.6.1 the check tested !occursin("No documentation found", ...), but Julia renders an undocumented module as "No docstring found for public module ...", so the substring never matched and modules were silently counted as documented. SciMLTesting v2.6.2 (PR #41, commit 6d0dd9e) switched to Base.Docs.hasdoc, which correctly returns false, and the latent gap became a hard failure everywhere. 26 sublibraries here do that reexport and all fail identically; so do the StochasticDiffEq sublibs and DelayDiffEq. FIRK's test/qa/qa.jl is byte-identical to BDF's, SDIRK's and Tsit5's, so there is no FIRK-local misconfiguration to fix.

CI brackets the registration exactly: a run at 2026-08-05T03:11 on v2.6.1 was green, a run at 2026-08-05T12:39 on v2.6.2 was red, and the General registration of v2.6.2 merged at 04:01 between them.

It is already fixed upstream and merged — SciMLTesting PR #45, commit 1796019, version = "2.6.3" — but v2.6.3 is not in the General registry yet, which is the only remaining action. Verified locally: FIRK master with a Pkg.develop'd SciMLTesting 2.6.3 turns Public API documentation green. FIRK's compat is SciMLTesting = "2.1", so it picks 2.6.3 up with no bump.

Deliberately not adding a local ignore = (:SciMLBase,) here: it would have to be repeated across ~38 qa.jl files and all of it becomes dead weight the moment 2.6.3 registers.

Links:

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Re-ran the Core group on the exact pushed commit (the Verification section's numbers were taken before the public declarations and version bumps were added). Same result, lib/OrdinaryDiffEqDifferentiation, GROUP=Core:

DAE jacobian2W sparse |    4      4  8.9s
prepare_user_sparsity mass matrix |    9      9  2.9s
ScalarOperator mass matrix |    9      9  8m11.2s
nzval helpers |   26     26  29.7s
prepare_sparse_jac! |    9      9  0.5s
OOP J_t Tracking |    5      5  18.4s
Differentiation Trait Tests |    5      5  8.7s
Autodiff Error Tests |    4      4  3m06.2s
No Jac Tests  |    7      7  16.8s
Stale W Linear Operator Tests |   12     12  6m54.2s
Krylov warm_start default |    7      7  0.1s
Krylov nf accounting |   21     21  1m05.5s
     Testing OrdinaryDiffEqDifferentiation tests passed

`stats.nf` counts calls to `f`, and on the matrix-free Krylov path it did not.
`linres.iters` is fewer than the products a Krylov solve applies (the warm start
and the initial residual each cost one), the `linsolve.A.J isa
AbstractSciMLOperator` gate missed the `jacvec` that `WOperator`'s `mul!`
actually uses when a concrete `J` is kept for the preconditioner, and a
user-supplied `MatrixOperator` Jacobian was billed per iteration for products
that evaluate `f` zero times.

Give `JVPCache` an `njvps` tally and drain it in `dolinsolve`, the approach
`drain_jvp_count!` already took for FIRK's `ComplexWOperator`; the two now share
one implementation. `nf` matches a user's own count of `f` calls exactly across
matrix-free, `concrete_jac`, `MatrixOperator` and direct-solver runs.

`rhs_evals_per_jvp` records why a finite-difference product counts as two
evaluations and a dual-number product as one.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01F75XsVeZ94QH3PmCuq6QUF
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review August 9, 2026 11:12
@ChrisRackauckas
ChrisRackauckas merged commit b9889d3 into SciML:master Aug 9, 2026
138 of 185 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.

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

2 participants