Skip to content

OrdinaryDiffEqExplicitRK: make indexed dense interpolation generic over Θ type - #4704

Merged
ChrisRackauckas merged 5 commits into
SciML:masterfrom
ChrisRackauckas-Claude:erk-interp-generic-bi
Nov 3, 2026
Merged

ChrisRackauckas merged 5 commits into
SciML:masterfrom
ChrisRackauckas-Claude:erk-interp-generic-bi

Conversation

@ChrisRackauckas-Claude

@ChrisRackauckas-Claude ChrisRackauckas-Claude commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Summary

generic_rk_interpolant! staged per-stage interpolation weights through a Float64 scratch buffer (ExplicitRKConstantCache.bi), so sol(t; idxs) and sol(out, t; idxs) threw Float64(::ForwardDiff.Dual) whenever Θ (or the state) carried dual partials — i.e. differentiating the interpolation point through ForwardDiff broke on the indexed path only. Each weight is now evaluated inline with eval_poly_derivative, matching fused_rk_interpolant_fallback!, and the unused bi buffer is removed from the constant cache. The indexed in-place kernel replaces the per-stage k[i][idxs] SubArray views with scalar loops for Array outputs with integer index vectors; a broadcast/view fallback is retained for other out/idxs types.

Round 2: the scalar loops now validate idxs with checkbounds(y₀, idxs) plus an axes(ki) == axes(y₀) check per stage before their @inbounds reads, so out-of-range idxs throws BoundsError even under OrdinaryDiffEqCore < 4.18.1, where the upstream _check_interpolant_idxs check (#4607) is absent. The order-0/order-N loop bodies are folded into indexed_rk_interpolant_stages! via a Val flag, which folds to the exact original expressions.

Regression tests

New testsets in lib/OrdinaryDiffEqExplicitRK/test/interpolation_tests.jl:

  • idxs interpolation under ForwardDiff Dual times differentiates through sol(t; idxs), sol(out, t; idxs), and sol(t, Val{1}; idxs) for scalar and vector indices. On the unfixed code it reports 2 passed, 5 errored with Float64(::ForwardDiff.Dual) MethodErrors; with the fix 7 passed, 7 total.
  • generic_rk_interpolant! validates idxs calls the kernel directly with idxs = [1, 4] on a length-3 state and expects BoundsError for order 0 and 1, plus DimensionMismatch for a wrong-length out. A child Julia process runs the out-of-range call with --check-bounds=auto; the test passes only when the explicit checkbounds guard throws BoundsError. With that guard removed, the child exits without observing BoundsError, and the Core group fails (35 passed, 1 failed). With the guard restored, Core passes 36/36.

Performance (same machine, JULIA_NUM_THREADS=1 taskset -c 12, @benchmark minima, 1000 interpolation points, round-2 head with the bounds check)

path master head allocs (identical both)
sol(out,t; idxs=[1,2]) 317.9 μs 173.0 μs (−46%) 2 / 80 B total per call
sol(out,t,Val{1}; idxs=[1,2]) 258.7 μs 199.1 μs (−23%) 2 / 80 B total per call
sol(t; idxs=[1,2]) loop 233.2 μs 197.4 μs (−15%) 2003 / 80096 B total per call
sol(out,t) control 223.8 μs 129.5 μs 0

Correction to the round-1 table: the indexed kernel allocates zero bytes per call — @allocated over the 1000-point loop with idxs hoisted is 0 B on both master and head; the 80 B above is the one-time [1,2] literal inside each benchmarked call. Scalar-idxs and control timings move between runs on this shared box (the unchanged control drifted ~40% here), so treat non-indexed deltas as noise.

Float64 results are bitwise identical to master: reinterpret(UInt64, …) over 1369 values covering sol(t;idxs), sol(out,t;idxs), Val{0..3} orders, scalar/range/vector/duplicate idxs, in-place and OOP problems, and Tsit5 + DormandPrince tableaus (independent of the reviewer's 3198-case sweep). Under an OrdinaryDiffEqCore 4.18.0 pin, sol(zeros(2), t; idxs=[1,5000000]) throws BoundsError on this head (it returned garbage before the checkbounds); sol(out,t;idxs=[1,4]) → BoundsError; wrong-length out → DimensionMismatch.

Test tails

  • GROUP=Core julia +1.12 --project -e 'using Pkg; Pkg.test()' (from lib/OrdinaryDiffEqExplicitRK):

    Test Summary:    | Pass  Total     Time
    Generic RK Tests |   36     36  2m51.9s
         Testing OrdinaryDiffEqExplicitRK tests passed
    EXIT 0
    
  • GROUP=QA julia +1.12 --project -e 'using Pkg; Pkg.test()' (with JULIA_REVISE_POLL=1 for this machine's inotify exhaustion):

    Test Summary:    | Pass  Total     Time
    Generic RK Tests |   36     36  2m35.5s
    Test Summary:    | Pass  Total     Time
    Allocation Tests |    1      1  1m05.0s
    Test Summary: | Pass  Broken  Total     Time
    JET Tests     |    1       2      3  1m29.3s   # the 2 broken are pre-existing `broken = true` markers
    Test Summary: | Pass  Total     Time
    Aqua          |   21     21  1m24.1s
         Testing OrdinaryDiffEqExplicitRK tests passed
    EXIT 0
    
  • Julia 1.10.12, the package test harness test/runtests.jl run in the fresh resolved scratch/env110 environment (Pkg.test on 1.10 cannot use this checkout’s 1.12-resolved package manifest):

    Test Summary:                                   | Pass  Total     Time
    idxs interpolation under ForwardDiff Dual times |    7      7  1m12.4s
    Test Summary:                          | Pass  Total  Time
    Generic RK Tests |   36     36  1m34.3s
    EXIT 0
    
  • Runic --inplace clean on all changed files; typos clean.

Not verified

  • The generic fallback branch (non-Array out, Bool mask idxs) is type-corrected but only exercised via scalar-idxs calls; GPU/StaticArray outputs were not benchmarked.
  • JET needed JULIA_REVISE_POLL=1 on this machine (inotify exhaustion); behavior is equivalent, but that flag isn't the CI default.
  • Merge conflicts: textual only, with Fix scalar indexing in fallback compute_stages! for >17-stage tableaus #4705 — both PRs touch [extras]/the test target in lib/OrdinaryDiffEqExplicitRK/Project.toml (ForwardDiff vs JLArrays) and append a testset at the end of test/interpolation_tests.jl; whichever merges second rebases keeping both sides. Fix ExplicitRK tableau c eltype for Float32 time #4702 merges cleanly.

For reviewers to push back on

  • The axes(ki) == axes(y₀) guard assumes stage derivatives share the state's axes — true for every solver-internal caller; a direct caller with mismatched k now gets DimensionMismatch instead of a garbage read.
  • generic_rk_interpolant(!) lose their bi positional argument and ExplicitRKConstantCache a field — internal, non-exported APIs; the reviewer grepped the monorepo and all installed SciML packages and found no outside callers.
  • Bitwise identity is verified on this machine (x86-64); worth confirming on a different arch since it depends on evaluation order.

Please ignore until reviewed by @ChrisRackauckas.

Risk assessment

  • Risk: medium. Internal, non-exported API; Float64 results bitwise-identical to master.
  • Blast radius: indexed sol(t; idxs)/sol(out, t; idxs) for ExplicitRK only; full-state and non-indexed paths unchanged.
  • Evidence: GROUP=Core and GROUP=QA Pkg.test green on 1.12 (35/35), 1.10 green; bitwise check 1369/1369; BoundsError restored under Core 4.18.0.
  • Merge: draft — please ignore until reviewed by @ChrisRackauckas. Textual conflict with Fix scalar indexing in fallback compute_stages! for >17-stage tableaus #4705 noted above.

Independent review: Claude Code (claude-opus-5-5) rated it medium, high confidence: bitwise identical to master over 3198 interpolation cases, indexed paths 25-50% faster; unchecked @inbounds reads under older Core (fixed in round 2). Re-review pending.
Round 2 (Claude Code claude-opus-5-5): risk low, high confidence. The OOB fix is verified with Core pinned to 4.18.0 (BoundsError), all 3198 cases are bitwise identical, and there is no perf regression. The one should-fix (the bounds test did not discriminate under Pkg.test's --check-bounds=yes) is fixed in round 3 (b14e91c) with a --check-bounds=auto subprocess test, which fails without the check and passes with it. The orchestrator checked that delta.

🤖 Original implementation by Devin CLI 3000.11.3 (model: swe-2-high), transcript /log.txt; round 3 update by Codex CLI codex-cli 0.159.3 (model: gpt-6-luna), local session log /log3c.txt. Independent review by Claude Code (model: claude-opus-5-5[1m]): https://claude.ai/code/session_01LPHREnnonfLg1VcE1EJovv

Risk assessment (independent review, codex-cli gpt-6-astra, reviewed head 4443036)

  • Risk: medium
  • Blast radius: ExplicitRK indexed dense interpolation, its internal cache and polynomial helpers; no exported/public names removed. The documented helper is explicitly under “Internal Interpolation Utilities” and is not declared public.
  • Evidence: Reviewed head 4443036; end-of-review SHA matches. I ran GROUP=Core JULIA_NUM_THREADS=4 JULIA_NUM_PRECOMPILE_TASKS=4 julia +release --project=pr-4704/lib/OrdinaryDiffEqExplicitRK -e 'using Pkg; Pkg.test()' with a workspace depot: Generic RK Tests 43/43 passed, Julia 1.13.2. This includes Dual interpolation, explicit bounds checks, and existing JLArrays tests. Log: evidence/4704-test.log. CI snapshot: 21 pass, 106 pending, one skipped, one failed. I read the failed job log: Enzyme AssertionError: mi2 !== nothing in SciMLSensitivity threaded ensemble differentiation using Tsit5, outside ExplicitRK. Latest completed master Core4 passed; latest master runs are queued, so this is inferred unrelated, not a confirmed master reproduction. Failure: https://github.com/SciML/OrdinaryDiffEq.jl/actions/runs/38859058853/job/116836959423 ; completed master: https://github.com/SciML/OrdinaryDiffEq.jl/actions/runs/38561320093/job/115842815127 . No PR-caused regression found; pending ExplicitRK CI remains relevant.
  • Independent review: codex-cli 0.162.1 gpt-6-astra rated it medium, high confidence: focused Core tests pass and indexed weights preserve Dual types with explicit bounds validation. Rating recorded before reading the author's risk assessment.
  • Merge: auto-merge candidate — targeted functional checks pass, no test weakening, public API break, or identified PR-caused CI failure.

🤖 Posted by an AI agent — harness: codex-cli · model: gpt-6-astra (independent reviewer; appended by Claude Code 2.1.301 · claude-opus-5-5)
Conversation: https://claude.ai/code/session_01VZjwf7Ux9YtTzwHGHMqnsq

ChrisRackauckas and others added 3 commits October 4, 2026 07:22
…er Θ type

generic_rk_interpolant! staged per-stage interpolation weights through a
Float64 buffer (ExplicitRKConstantCache.bi), so sol(t; idxs) and
sol(out, t; idxs) threw Float64(::Dual) when Θ or the state carried
ForwardDiff partials. Evaluate each weight with eval_poly_derivative at
the point of use, as fused_rk_interpolant_fallback! already does, and
drop the now-unused bi buffer from the constant cache. The indexed
in-place kernel also replaces per-stage k[i][idxs] views with scalar
loops; Float64 results are bitwise identical and allocations unchanged.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: Devin CLI 3000.11.3
Agent-Model: swe-2-high
Agent-Session: local session, transcript /home/crackauc/sandbox/goals/performance/jobs/pr-erk-dual-interp/log.txt on amdci2
…ernel

The scalar-indexed loops read y₀[idx] and k[i][idx] under @inbounds; with
OrdinaryDiffEqCore < 4.18.1 there is no upstream idxs validation, so an
out-of-range idxs silently read out-of-bounds memory where master threw
BoundsError. Validate idxs against y₀ (and assert each stage shares its
axes) before the loops. Also folds the duplicated order-0/order-N loop
bodies into indexed_rk_interpolant_stages! via a Val flag that compiles
to the original expressions.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: Devin CLI 3000.11.3
Agent-Model: swe-2-high
Agent-Session: local session, transcript /home/crackauc/sandbox/goals/performance/jobs/pr-erk-dual-interp/log.txt on amdci2
Run the direct out-of-range kernel call in a child Julia process with bounds checks set to auto, and require the explicit guard to raise BoundsError. Remove the duplicate validation comment.

Co-Authored-By: Chris Rackauckas <[email protected]>

Co-Authored-By: Codex <[email protected]>

Agent-Harness: Codex CLI codex-cli 0.159.3

Agent-Model: gpt-6-luna

Agent-Session: local codex session (log /home/crackauc/sandbox/goals/performance/jobs/pr-erk-dual-interp/log3c.txt on amdci2)
Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: Devin CLI 3000.11.3 (conflict resolution), Claude Code 2.1.285 (orchestration)
Agent-Model: fusion-claude-opus-5-5-high-sidekick-swe-2-medium
Agent-Session: local Claude session 3c311569-dda6-4687-bc9f-65febb212c33 (fleet master); Devin log /Users/chrisrackauckas/sandbox/master/fusion-fixes/SciML_OrdinaryDiffEq.jl-4704/log.txt
@ChrisRackauckas

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

Merged the default branch into this PR (clean merge, no conflicts; head eb05871) so CI runs on current master. Its earlier failures in SciMLSensitivity Core1 and the downgrade jobs were fixed on master after this PR's last CI run.


🤖 Posted by an AI agent — harness: Devin CLI 3000.11.3 (merge), Claude Code 2.1.285 (posting) · model: fusion-claude-opus-5-5-high-sidekick-swe-2-medium
Conversation: local Claude session 3c311569-dda6-4687-bc9f-65febb212c33 (fleet master)

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

Independent review (Codex CLI 0.166.0 / gpt-6.1-sol), session 01a1983b-1c97-7862-8c6a-1d2fb917efac, reviewed head 4443036

  • Verdict: MERGE
  • Risk: medium-high (MH1: indexed interpolation changes from throwing on Dual times to preserving their derivatives and adds a scalar accumulation specialization.)
  • Round / slot: 1 / 1
  • Blocking priorities: none

Review written by the reviewer named above in a session other than the PR author's, and copied here by the posting agent without change to its findings. The posting agent did not re-run the reviewer's commands.

Summary: The PR preserves Dual-valued interpolation weights for indexed ExplicitRK dense output and removes their shared scratch buffer. The added ForwardDiff regression fails on base and passes on head; independent polynomial probes pass with no blocking defect found.

Blast radius: ExplicitRK indexed dense interpolation, derivative orders 0–3, and its internal constant cache; the dedicated Tsit5 algorithm and default solver selection are untouched.

Evidence: Head: 42/42 in-process assertions from the PR test file; independent polynomial and JLArray probes: 65/65. Base: the identical added ForwardDiff testset has 2 passes and 5 errors; head has 7/7 passes. The analytic decay derivative and separate closed-form polynomial provide G1 evidence; ForwardDiff and the changed JLArray fallback were exercised (G2), and repeated calls with changing time/derivative types exercise removal of the shared weight buffer (G3). CI: 127 successful, three skipped, one failed; the same failed Enzyme threaded-ensemble assertion occurs in completed master CI.

Blocking findings

None.

Non-blocking findings

None.

What I ran

Git inspection (exit 0): git rev-parse HEAD, git rev-parse origin/master, git diff --stat origin/master...HEAD, git diff origin/master...HEAD, git fetch origin '+refs/pull/4704/head:refs/remotes/pr/4704' master, git merge-base origin/master HEAD, and git diff --numstat 59ba40e4b5bbae713d8df7b792f6ea62f033ff78 HEAD. The live head matched TARGET. The local master tracking ref was newer than the PR base; its merge-base with the reviewed head equals Base above. Read all five changed files, surrounding cache/interpolation dispatch and Core validation, test wiring, and the internal-utilities documentation entry.

Read-only GitHub checks: gh pr view 4704 --repo SciML/OrdinaryDiffEq.jl --json number,url,state,isDraft,headRefOid,baseRefName,baseRefOid; gh pr checks 4704 --repo SciML/OrdinaryDiffEq.jl (exit 1 for the failed check); description/status JSON; gh api --paginate repos/SciML/OrdinaryDiffEq.jl/pulls/4704/commits; and gh issue view 4607 --repo SciML/OrdinaryDiffEq.jl --json title,body,state (exit 0). The PR is open and draft. The newest non-merge PR commit is 141ab03; attribution below uses its trailers only.

Three Julia invocations, sequential, Julia 1.13.2 on aarch64. Each used JULIA_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 TMPDIR="$PWD/tmp" JULIA_DEPOT_PATH="$REVIEW_DEPOT:" JULIA_PKG_PRECOMPILE_AUTO=0 timeout 3600 julia +1.13.2 --startup-file=no --compiled-modules=existing SCRIPT, where REVIEW_DEPOT is the coordinator-provided shared depot. Temporary environments developed local DiffEqBase, OrdinaryDiffEqCore and OrdinaryDiffEqExplicitRK, with ForwardDiff 1.3.3, JLArrays 0.3 and SciMLBase 3.58.0; the base environment reused identical dependency versions with source paths switched to the extracted merge-base.

  • SCRIPT=run-head.jl: exit 1 before any assertion, because the temporary environment omitted a direct SciMLBase dependency. This was an environment setup error; the next invocation corrected that dependency.
  • SCRIPT=run-head-probe.jl: exit 0. Evaluated lib/OrdinaryDiffEqExplicitRK/test/interpolation_tests.jl with only its subprocess construction/assertion omitted to preserve the one-process limit. Output: 42/42 passed, including idxs interpolation under ForwardDiff Dual times | 7 7 and generic_rk_interpolant! validates idxs | 4 4. Bounds checks ran in-process under the default auto mode. Additional output: Independent indexed polynomial, orders 0:3 and Dual times | 61 61; JLArray indexed interpolation, no scalar indexing | 4 4. The independent oracle was the closed-form polynomial y = y0 + dtk(theta + 2theta^2 + 3theta^3) and its analytic derivatives, covering scalar/range/vector/duplicate/Boolean/empty selections, Array and view outputs, static mutable outputs, Dual times and stage-axis validation. JLArray probes exercised the changed indexed fallback for all four derivative orders with scalar indexing disabled.
  • SCRIPT=run-base.jl: exit 1, expected regression failure. Executed the unchanged added ForwardDiff testset against sources extracted with git archive 59ba40e4b5bbae713d8df7b792f6ea62f033ff78 lib. Output: idxs interpolation under ForwardDiff Dual times | 2 passed, 5 errored, 7 total; errors are MethodError: no method matching Float64(::ForwardDiff.Dual...) when indexed interpolation stores a Dual weight in the Float64 scratch buffer. Thus the added bug-fix test fails on base and passes on head in my own runs.

CI logs inspected: ExplicitRK Core, Julia 1 reports Generic RK Tests | 43 43 and tests passed, including the subprocess assertion omitted locally. ExplicitRK lts, prerelease and QA checks also succeeded. PR downstream failure, read using gh run view 38859058853 --repo SciML/OrdinaryDiffEq.jl --log-failed, reports EnsembleThreads(): AssertionError: mi2 !== nothing in Enzyme's threaded differentiation rules. Compared recent default-branch runs using gh run list --repo SciML/OrdinaryDiffEq.jl --branch master --event push --limit 5 and completed Downstream workflow runs; completed master downstream run, read with gh run view 41319752001 --repo SciML/OrdinaryDiffEq.jl --log-failed, contains the same Core4 ensemble test and exact assertion. Log downloads succeeded after moving gh's cache into the review workspace; the initial default-cache attempt was blocked by filesystem permissions.

What I did not verify

No whole-package, downstream or QA suites were run locally, and no performance benchmark or broad bitwise-identity sweep was repeated. Physical CUDA/ROCm hardware, reverse-mode AD, Reactant, MPI, other platforms and older OrdinaryDiffEqCore versions were not tested locally; the changed array fallback was exercised with JLArray and the changed AD behavior with ForwardDiff. The subprocess assertion ran in CI, not in the local review. The added direct-helper bounds testset was not run on base because its helper signature changes in this PR; failing-before evidence targets the public ForwardDiff interpolation regression. No upstream writes were performed.

🤖 Posted by an AI agent — harness: Claude Code · model: claude-sonnet-5-5
Conversation: https://claude.ai/code/session_01379heiiB35TtywhR7uSU74

@ChrisRackauckas-Claude
ChrisRackauckas-Claude marked this pull request as ready for review November 2, 2026 02:07
@ChrisRackauckas
ChrisRackauckas merged commit 5bd4232 into SciML:master Nov 3, 2026
130 of 131 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.

2 participants