Skip to content

Stop tying the state Jacobian's finite-difference direction to tdir - #4543

Merged
ChrisRackauckas merged 3 commits into
SciML:masterfrom
ChrisRackauckas-Claude:fd-jacobian-direction
Sep 13, 2026
Merged

ChrisRackauckas merged 3 commits into
SciML:masterfrom
ChrisRackauckas-Claude:fd-jacobian-direction

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Closes #4537. Ignore until reviewed by @ChrisRackauckas. Draft.

What changed and why

1. The state Jacobian no longer follows tdir. jacobian/jacobian! set the finite-difference perturbation direction from diffdir(integrator), which is +1 for tdir > 0 and -1 for tdir < 0:

-    if dense isa AutoFiniteDiff
-        dense = SciMLBase.@set dense.dir = diffdir(integrator)
-    end

diffdir exists to keep a time stencil inside the integration interval near an endpoint — that is what its docstring says. Perturbing u has no such constraint, so ∂f/∂u was being computed as a forward difference going forwards and a backward difference going backwards: two matrices agreeing only to O(sqrt(eps)). The in-place path did the same thing by selecting between two prepared configs (jac_config[1]/[2]); it now always uses the one config, and build_jac_config stops preparing a second.

That also removes a nonsense case: complex-step finite differencing does not use dir at all, yet the in-place path was still switching configs on diffdir, so AutoFiniteDiff(fdtype = Val(:complex)) was reversible out-of-place but not in-place.

2. The out-of-place tgrad guard now tests the resolved backend. calc_tderivative had

-        if alg_autodiff isa AutoFiniteDiff
+        if autodiff_alg isa AutoFiniteDiff

alg_autodiff there is the accessor function imported from this module, never an AutoFiniteDiff, so the branch never ran: the out-of-place time derivative always differenced in the +t direction, meaning the endpoint safeguard was dead on that path and it could evaluate f past the end of tspan on the final step. I observed the backward run evaluating at t + 7.446e-7 where it should have used t - 7.446e-7. calc_tderivative! (in-place) selects the right config and was unaffected. Unlike the state Jacobian, the time stencil legitimately follows the integration direction, and it stays reversal-symmetric: a backward difference in the mirrored problem's time is a forward difference in the original's.

Why it matters for solve(prob)

With no algorithm given, prepare_alg(::Nothing, ...) and __init/__solve supply DefaultODEAlgorithm(autodiff = AutoFiniteDiff()) (lib/OrdinaryDiffEqDefault/src/default_alg.jl:85-101), so every default stiff solve differenced its Jacobian in the direction of integration. Robertson forward versus the mirrored problem backward: 115 steps against 120.

Verification

New lib/OrdinaryDiffEqDifferentiation/test/fd_direction_tests.jl, registered in runtests.jl. On a tspan symmetric about zero the mirror t -> -t is exact in IEEE arithmetic and round-to-nearest is sign-symmetric, so the forward and mirrored-backward |dt| sequences must agree bitwise — asserted with ==, not ≈. Covers forward-difference, complex-step, in-place and out-of-place, a non-autonomous problem so the tgrad path is exercised, solve(prob) with no algorithm, and forward-mode AD as a guard. OrdinaryDiffEqDefault joins the test target so the default path can be tested directly.

Failing on master (git checkout origin/master -- lib/OrdinaryDiffEqDifferentiation/src):

Test Summary:                                  | Pass  Fail  Total     Time
finite-difference Jacobian direction           |   10    14     24  1m31.1s
  Rodas5P/FiniteDiff rober oop                 |          1      1     1.4s
  Rodas5P/FiniteDiff rober iip                 |          1      1     0.0s
  Rodas5P/FiniteDiff nonautonomous oop         |          1      1     0.0s
  Rodas5P/FiniteDiff nonautonomous iip         |          1      1     0.0s
  Rosenbrock23/FiniteDiff rober oop            |          1      1     0.0s
  Rosenbrock23/FiniteDiff rober iip            |          1      1     0.0s
  Rosenbrock23/FiniteDiff nonautonomous oop    |          1      1     0.0s
  Rosenbrock23/FiniteDiff nonautonomous iip    |          1      1     0.0s
  FBDF/FiniteDiff rober oop                    |          1      1     0.0s
  FBDF/FiniteDiff rober iip                    |          1      1     0.0s
  FBDF/FiniteDiff nonautonomous oop            |    1            1     0.0s
  FBDF/FiniteDiff nonautonomous iip            |    1            1     0.0s
  Rodas5P/FiniteDiff complex rober oop         |    1            1     0.0s
  Rodas5P/FiniteDiff complex rober iip         |          1      1     0.0s
  Rodas5P/FiniteDiff complex nonautonomous oop |    1            1     0.0s
  Rodas5P/FiniteDiff complex nonautonomous iip |          1      1     0.0s
  Rodas5P/ForwardDiff rober oop                |    1            1     0.0s
  Rodas5P/ForwardDiff rober iip                |    1            1     0.0s
  Rodas5P/ForwardDiff nonautonomous oop        |    1            1     0.0s
  Rodas5P/ForwardDiff nonautonomous iip        |    1            1     0.0s
  default algorithm                            |    2     2      4    25.8s
    rober oop                                  |          1      1     0.0s
    rober iip                                  |          1      1     0.0s
    nonautonomous oop                          |    1            1     0.0s
    nonautonomous iip                          |    1            1     0.0s

Passing with the fix:

Test Summary:                        | Pass  Total     Time
finite-difference Jacobian direction |   24     24  1m33.3s

A wider sweep on this branch — 4 problems (Robertson, stiff Van der Pol, stiff linear, non-autonomous) x 5 algorithm variants x 3 controllers x in-place/out-of-place = 120 cases, 0 direction-dependent, including solve(prob).

Because this changes FD Jacobian entries by O(sqrt(eps)) for every finite-difference user, I ran the suites of every package that consumes them (Julia 1.10.11):

Testing OrdinaryDiffEqRosenbrock tests passed
Testing OrdinaryDiffEqSDIRK tests passed
OrdinaryDiffEqBDF:              0 passed, 4 failed, 0 errored, 18 broken
                                (FBDF/DFBDF Runtime Allocation Check x4 - pre-existing)
OrdinaryDiffEqDifferentiation:  11 passed, 0 failed, 1 errored
                                (get_fresh_jacobian sparse pattern - pre-existing, see #4542)

Both remaining failures reproduce on unmodified master. I ran the Differentiation suite on master to confirm and root-caused that one: it is a test-harness ordering bug (JET runs before the functional tests in the same process and clobbers extension-provided methods), filed as #4542 with a verified fix — not related to this diff.

What I did not verify

  • GPU and Downstream groups, Julia pre.
  • Sparse/colored finite-difference Jacobians beyond what nojac_tests.jl and the Sparse group already cover; the AutoSparse wrapper path goes through the same single config now, but I did not write a targeted sparse reversal test.
  • Whether any accuracy benchmark shifts. FD Jacobian entries change by O(sqrt(eps)) for backward solves (forward solves are unchanged, since diffdir already returned +1 there away from the endpoint), so results should move only within finite-difference noise — but I did not run a convergence study to confirm it.

Worth pushing back on

  • build_jac_config now returns (config, config) for the finite-difference case, matching what the non-FD branch already did. The tuple shape is preserved so callers are untouched, but if you would rather collapse jac_config to a single value throughout, that is a follow-up.
  • The second commit enables direction-following for the out-of-place tgrad, which changes results for out-of-place Rosenbrock with AutoFiniteDiff on non-autonomous problems. I believe that is the intended behavior (the in-place path already does it, and it is what stops the stencil leaving tspan), but it is a behavior change in the opposite direction from commit 1, so please read them as a pair.
  • diffdir is now referenced only from derivative_utils.jl. It is still exported from the module; I left that alone.

🤖 Generated with Claude Code (model: claude-opus-5[1m], harness: Claude Code 2.1.269)

https://claude.ai/code/session_01JQATpLKMyYX3VbPPX8qdeE

ChrisRackauckas and others added 3 commits September 12, 2026 17:21
`jacobian`/`jacobian!` set the finite-difference perturbation direction from
`diffdir(integrator)`, which is +1 for tdir > 0 and -1 for tdir < 0. That makes
∂f/∂u a forward difference when integrating forwards and a backward difference
when integrating backwards - two different matrices, agreeing only to
O(sqrt(eps)).

`diffdir` exists to keep a *time* stencil inside the integration interval near
an endpoint (see its docstring). Perturbing `u` has no such constraint, so the
state Jacobian should not consult it. Use whatever `dir` the user's
`AutoFiniteDiff` carries, and prepare one config instead of a forward/backward
pair.

This is why `solve(prob)` was not reversible in time: with no algorithm given,
`prepare_alg`/`__init` supply `DefaultODEAlgorithm(autodiff = AutoFiniteDiff())`,
so every default stiff solve differenced its Jacobian in the direction of
integration. On Robertson, forward took 115 steps and the mirrored backward
problem 120.

Fixes the same defect for the in-place complex-step path, which was selecting
between the two prepared configs even though complex-step does not use `dir`.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Agent-Harness: Claude Code 2.1.269
Agent-Model: claude-opus-5[1m]
Agent-Session: https://claude.ai/code/session_01JQATpLKMyYX3VbPPX8qdeE
Claude-Session: https://claude.ai/code/session_01JQATpLKMyYX3VbPPX8qdeE
`calc_tderivative` guarded the finite-difference direction with

    if alg_autodiff isa AutoFiniteDiff

but `alg_autodiff` there is the accessor function imported from this module, not
the resolved backend `autodiff_alg`. A function is never an `AutoFiniteDiff`, so
the branch never ran and the out-of-place time derivative always differenced in
the +t direction - meaning the "keep the stencil inside tspan" safeguard was
dead on that path and could evaluate `f` past the end of the interval on the
final step. `calc_tderivative!` (in-place) selects the right config via
`diffdir(integrator) > 0` and was unaffected.

Unlike the state Jacobian, the time stencil legitimately follows the
integration direction, and it stays reversal-symmetric: a backward difference
in the mirrored problem's time is a forward difference in the original's.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Agent-Harness: Claude Code 2.1.269
Agent-Model: claude-opus-5[1m]
Agent-Session: https://claude.ai/code/session_01JQATpLKMyYX3VbPPX8qdeE
Claude-Session: https://claude.ai/code/session_01JQATpLKMyYX3VbPPX8qdeE
…andling

Covers the finite-difference Jacobian (forward, complex-step, in-place and
out-of-place), the non-autonomous case so the time-derivative path is exercised,
`solve(prob)` with no algorithm, and forward-mode as a guard. `OrdinaryDiffEqDefault`
joins the test target so the default path can be exercised directly.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Agent-Harness: Claude Code 2.1.269
Agent-Model: claude-opus-5[1m]
Agent-Session: https://claude.ai/code/session_01JQATpLKMyYX3VbPPX8qdeE
Claude-Session: https://claude.ai/code/session_01JQATpLKMyYX3VbPPX8qdeE
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review September 13, 2026 06:57
@ChrisRackauckas
ChrisRackauckas merged commit 4672278 into SciML:master Sep 13, 2026
184 of 188 checks passed
ChrisRackauckas added a commit that referenced this pull request Sep 13, 2026
- Stop tying the state Jacobian's finite-difference direction to tdir (#4543)
- Extend OrdinaryDiffEqCore.dtnew_modification instead of shadowing it (#4547)
- Pick the DAE initialization dt by magnitude, not signed min (#4549)
- Accept a callable stage predictor on the nlsolve algorithms (#4539)
- Run the QA test group last in every sublibrary that ran it first (#4551)
- Apply stage limiters in every StabilizedRK method (#4550)



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 13, 2026
- Stop tying the state Jacobian's finite-difference direction to tdir (#4543)
- Extend OrdinaryDiffEqCore.dtnew_modification instead of shadowing it (#4547)
- Pick the DAE initialization dt by magnitude, not signed min (#4549)
- Accept a callable stage predictor on the nlsolve algorithms (#4539)
- Run the QA test group last in every sublibrary that ran it first (#4551)
- Apply stage limiters in every StabilizedRK method (#4550)
- Release OrdinaryDiffEqNonlinearSolve 2.9.8 (#4552)
- Declare OrdinaryDiffEqCore.dtnew_modification public (#4553)
- Fix baseline spelling and whitespace checks in tests (#4524)
- Raise OrdinaryDiffEqNonlinearSolve floor for stage_predictor (#4554)



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.

solve(prob) is not time-reversible: finite-difference Jacobians take their perturbation direction from diffdir

2 participants