Repository navigation
Fix symbolic getindex under Zygote for array symbols and DAE solutions - #1623
Merged
ChrisRackauckas merged 5 commits intoOct 31, 2026
Conversation
…utions. Broaden solution getindex reverse rules to AbstractODESolution and scatter array-symbol cotangents by component so ODE/DAE symbolic indexing matches ForwardDiff under Zygote (SciML#1594). Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Cursor Agent <[email protected]> Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/goals/issue-backlog/jobs/fix-SciMLBase.jl-1594/log.txt on amdci2.julia.csail.mit.edu
Keep AbstractODESolution symbolic getindex for symbols only by pairing it with a more specific Integer/CartesianIndex adjoint (and a ChainRules NotSymbolic decline), and add Zygote DAE/RODE indexing regressions. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Cursor Agent <[email protected]> Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/goals/issue-backlog/jobs/fix-SciMLBase.jl-1594/log.txt on amdci2.julia.csail.mit.edu
Revert Integer/CartesianIndex adjoints to ODESolution and forward NotSymbolic indices through Array(sol) so DAE/RODE Zygote.gradient matches the AbstractArray path again (SciML#1594 review). Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Cursor Agent <[email protected]> Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/goals/issue-backlog/jobs/fix-SciMLBase.jl-1594/log.txt on amdci2.julia.csail.mit.edu
…n-symbolic path Rework of the previous commits on this branch. The ODESolution Zygote and ChainRules rules keep their master signatures; only the symbolic paths change: - Zygote, ODESolution: `odesolution_getindex_cotangent` expands an `ArraySymbolic` index (`sol[x]` for `x(t)[1:2]`) into its scalar components, fixing the `non-boolean (Num)` error. - ChainRules, ODESolution: the symbolic pullback scatters array-symbol cotangents per component instead of comparing a vector index to an Int. - ChainRules, other `AbstractODESolution`s (DAE, RODE): a new `rrule(getindex, ::AbstractODESolution, sym)` handles symbolic indices and `invoke`s the `AbstractTimeseriesSolution` rule (the generic AbstractArray rrule) for every non-symbolic index, so those results and errors are exactly master's. Zygote reaches it through its ChainRules bridge. Tests compare non-symbolic DAE/RODE indexing against the generic rrule and against central differences of the true primal, instead of Array(sol). Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Agent-Harness: Claude Code 2.1.280 Agent-Model: claude-opus-5-5 Agent-Session: https://claude.ai/code/session_01NdFVhANTF4nepTbqYxjfRP
… tests in DownstreamAD `Zygote.gradient(ps -> sum(abs2, sol(ps)[x][end]), ps)` for an array symbol `x` on an `ODESolution` failed with `MethodError: getindex(::Nothing, ::Int64)`: Zygote passes `nothing` for the timesteps the loss never reads, and `odesolution_getindex_cotangent` indexed into them. Those entries are now replaced by zeros before scattering. The same applies to observed array symbols (`obs_grads` called `reduce(hcat, Δ)` on the `nothing` entries). The new test file moves from `adjoints.jl` (SII_Downstream, which currently aborts earlier at `comprehensive_indexing.jl`) to its own testset in the DownstreamAD group, so CI runs it. Added ODE/DAE `sol[x][end]` and observed `sol[y][end]` cases to the ForwardDiff comparison. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> Agent-Harness: Claude Code 2.1.301 Agent-Model: claude-opus-5-5 Agent-Session: local session ID 1f24b4b1-61e2-4cc3-a226-82dc67734fb4 (headless claude -p, no URL)
ChrisRackauckas-Claude
force-pushed
the
fix-1594-symbolic-getindex-zygote
branch
from
October 31, 2026 11:58
18fdf40 to
b20ef1d
Compare
ChrisRackauckas
marked this pull request as ready for review
October 31, 2026 12:02
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1594: Zygote gradients through symbolic
getindexon solutions, including array symbols (sol[x]for@variables x(t)[1:2]) onODESolutionand scalar and array symbols onDAESolution.Please ignore this draft until it has been reviewed by @ChrisRackauckas.
What changed and why
The design rule is that only symbolic indices take new code paths. Every non-symbolic index (
Integer,CartesianIndex, ranges,Vector{Int}, Bool masks,Colon, multi-dimensional forms) reaches exactly the rule it used on master.ODESolutionunder Zygote (ext/SciMLBaseZygoteExt.jl): the rule signatures are master's. A 1-DSymbolics.Arris anAbstractVector, sosol[x]goes to the existingUnion{Tuple,AbstractVector}adjoint.odesolution_getindex_cotangentnow expands anArraySymbolicindex into its scalar components. Before this, it calledfindallover theArr, which caused thenon-boolean (Num)error. Non-symbolic vectors still go through the code unchanged.ODESolutionunder ChainRules (ext/SciMLBaseChainRulesCoreExt.jl): the symbolic pullback now scatters array-symbol cotangents per component. Before, it compared a vector index to anInt, which gave a silent zero gradient. Its body moved intosolution_getindex_pullbackso the next rule can reuse it.AbstractODESolutions: master has no SciML rule for these, so Zygote falls back to ChainRules' genericrrule(getindex, ::AbstractArray, inds...). The newrrule(getindex, ::AbstractODESolution, sym)handles symbolicsym. ForNotSymbolic()itinvokes the rrule forTuple{typeof(getindex), AbstractTimeseriesSolution, typeof(sym)}, which is the method dispatch picks without this one. The result or error is therefore identical to master by construction. Zygote reaches the new rule through its ChainRules bridge, and no Zygote@adjointis added for these types.Earlier rounds of this PR differentiated
Array(sol)for non-symbolic indices. That gave silently wrong gradients forRODESolutions[1:2](a timestep sub-solution, notArray(s)[1:2]) and made DAEs[1:2]succeed under AD even though the primal throws. This version removes that path.Verification
All runs used Julia 1.12.7 and the
test/downstreamManifest (MTK 11.45.1, SciMLSensitivity, Zygote 0.7.13). The master and b7c4187 baselines used the same Manifest with SciMLBase dev'd at those commits.A/B probe over every index class. ODE, DAE and RODE solutions were each tested with 17 index forms:
3,10,CartesianIndex(2,3),1:2,[1,3],2:2:4,Int[],trues(10),falses(2,5),:,(:,2),(1,2),(1:2,3),(1,:),(2,2:3),([1,2],:)andCartesianIndices. Each form went through three checks:Zygote.gradient(loss, sol),Zygote.pullback, and a directChainRulesCore.rrule. That is 153 outcome lines, each a gradient value or an error type and message.For example, b7c4187 gave
RODE (1:2,) grad => Array [2.0, 4.0, 0.0, ...], which is silently wrong. Master and this PR both giveERR DimensionMismatch.Test file
test/downstream/symbolic_getindex_zygote.jl:sol[x], ODEsol[x[1]], DAEsol[x], DAEsol[x[2]]and DAE[sol[x[1]], sol[x[2]]].ChainRulesCore.rrule(getindex, sol, idx...)equals the genericAbstractArrayrrule in primal value and cotangent, or throws the same error type. It also requires thatZygote.gradienteither throws or matches central differences of the true primals -> sum(abs2, Array(s[idx...])), computed by perturbingsol.u, so it does not rely onArray(sol)as an oracle. When the primal throws, the gradient must also throw.Groups.
test/downstream/adjoints.jl, the Adjoints set ofSII_Downstream, which includes the new file:Adjoints | Pass 93 Broken 5 Total 98. The 5@test_brokenare pre-existing inadjoints.jl.GROUP=Core:Testing SciMLBase tests passed.GROUP=QA(Aqua, including the ambiguity bound, and ExplicitImports):QA | Pass 123 Total 123.Test.detect_ambiguities(SciMLBase, SciMLBaseZygoteExt, SciMLBaseChainRulesCoreExt; recursive=true): 10 on master and the same 10 here. None involvegetindex.--checkandtyposare clean on the changed files.Not verified
GROUP=SII_Downstream. An earlier round reported an unrelatedcomprehensive_indexing.jlfailure (SCCNonlinearProblemhas no fieldu0).sol[[x[1], x[2]]], whosesymbolic_typeisNotSymbolic), and the 3-argument formssol[sym, j]andsol[sym, :]. All of these behave as on master. None is part of Symbolic getindex under Zygote: array symbols fail on ODESolution, no rule for DAESolution #1594.Pre-existing, not touched
ODESolutionsol[1:2, 3]gives a wrong gradient under Zygote. It does so identically on master and in this PR, and it is outside the scope of this PR.Risk assessment
getindexon timeseries solutions. Non-symbolic indices are unchanged by construction (invokeof the master method) and by the 153-line A/B. The new behaviour applies only to symbolic indices, which errored or gave zero gradients on master. No public API change.invokedecline design.🤖 Generated with Claude Code (model: claude-opus-5-5), round 4 author. Earlier rounds: Cursor Agent CLI (model: auto).
https://claude.ai/code/session_01NdFVhANTF4nepTbqYxjfRP
Risk assessment
Risk: medium
Blast radius: Reverse-mode AD (Zygote and ChainRules) of
getindexon timeseries solutions. The change has three parts. (1)ODESolutionsymbolic indexing: array-symbol cotangents are now scattered per component. (2) A newrrule(getindex, ::AbstractODESolution, sym)that catches every single-indexgetindexonDAESolution,RODESolutionand other non-ODESolutionsubtypes. For non-symbolic indices it hands back to the rule that dispatch would otherwise pick. (3) A refactor that moves the pullback into a sharedsolution_getindex_pullback. Main users affected: SciMLSensitivity, DiffEqFlux, and MTK users who differentiate throughsol[x]. The behaviour change is a bug fix on paths that used to error or silently return zero gradients, so a patch release is fine and no public API changes. No non-public dependency internals are used:invokeis in Base andArraySymbolicis public in SymbolicIndexingInterface. I found no other getindexrrulethat could cause ambiguity:rrule(::typeof(getindex).Evidence: I checked head
f7dbef77against base08f6f743, current master432e9856, and master runs70133024/140337ab. All 6 failing checks are pre-existing, so there are no regressions:tests / SymbolicIndexingInterface (julia 1)and(julia lts): same error on master,FieldError: SCCNonlinearProblem has no field u0incomprehensive_indexing.jl.SciMLSensitivity.jl/Core1: same Mooncake error atconcrete_solve_derivatives.jl:451as master.SciMLSensitivity.jl/Core6:236 passed, 1 errored, 4 broken, the same counts as master (Complex Matrix FiniteDiff Adjoint).SciMLSensitivity.jl/Core7:163 passed, 1 errored, the same counts as master (Fully Out of Place adjoint sensitivity).Catalyst/All/1(ReleaseTest):Permission deniedontest/extensions/Project.toml, also on master.DownstreamAD (1, lts), Downstream, QA, Core, SciMLSensitivity Core2/3/4/5/8 and DiffEqFlux all pass.
Gap the description doesn't disclose: the new
symbolic_getindex_zygote.jlis only included fromadjoints.jl, which runs inSII_Downstreamaftercomprehensive_indexing.jl. That group aborts on the pre-existing error before reaching "Adjoints", on head and on master. So none of the PR's new tests, and none ofadjoints.jl, have run in CI. The only evidence for them is the author's local runs. The description mentions thecomprehensive_indexingfailure but not this consequence. Smaller points:elseif !(zg isa Exception)). This is deliberate, and the ChainRules equivalence check partly covers it.ArraySymbolicpullback, ifvariable_indexreturns a vector containingnothing(some components observed), the gradient silently drops those components instead of erroring. It does this, and never errors, whenevervariable_indexis not a plainnothing. That is no worse than master's silent zero, but it is still silent.Δ[j][idx]will throw when a timestep's cotangent isnothingorZeroTangent.Independent review: Devin CLI / fusion-claude-opus-5-5-high-sidekick-swe-2-medium rated it medium, medium confidence: CI shows no regressions and handing non-symbolic indices back via
invokelooks sound by construction, but the new rule catches every non-ODESolutiongetindexunder AD and its own tests have never run in CI.Merge: needs human review. Findings:
invokedesign.adjoints.jlhave not run in CI becauseSII_Downstreamaborts early. Fix or reordercomprehensive_indexing.jl, or run the Adjoints set separately, before relying on the tests.🤖 Risk assessment posted by an AI agent (fleet master) — harness: Devin CLI / fusion-claude-opus-5-5-high-sidekick-swe-2-medium; dispatched by Devin CLI 3000.11.3 fleet-master caretaker, model Fusion (claude-opus-5-5 medium + swe-2 medium)
Conversation: local transcript (no session URL)
Agent follow-up
Fix pushed in
18fdf401: array-symbol gradients when the loss reads only some timesteps. On the previous head (2bebc267),Zygote.gradient(ps -> sum(abs2, sol(ps)[x][end]), ps)for an array symbolxon anODESolutionthrewMethodError: no method matching getindex(::Nothing, ::Int64). Zygote passesnothingfor the timesteps the loss never reads, andodesolution_getindex_cotangentindexed into them. The observed-symbol path broke the same way, becauseobs_gradscallsreduce(hcat, Δ)on those entries. Those entries are now replaced by zeros. This only runs whenany(isnothing, Δ), so any input that worked before goes through unchanged. DAE was already fine: Zygote's ChainRules bridge passesZeroTangentthere, and indexing it returns itself.Tests now run in CI.
symbolic_getindex_zygote.jlwas only included fromadjoints.jl, which is part of SII_Downstream. That group aborts on master atcomprehensive_indexing.jl(SCCNonlinearProblemhas no fieldu0), so CI never reached it. The file is now its own safetestset in the DownstreamAD group, which passes on master. New cases compared against ForwardDiff: ODEsum(abs2, sol[x][end]), an observed array symbolsum(abs2, sol[y][end])(withy[2]eliminated bymtkcompile), and DAEsum(abs2, sol[x][end]).Fail before, pass after (Julia 1.13.1,
test/downstreamenv):GROUP=DownstreamADviatest/runtests.jl(Julia 1.13.1):Autodiff Observable Functions | Pass 15,Symbolic solution getindex adjoints | Pass 96,Testing SciMLBase tests passed. The pre-existingEnsemble adjoint gradient correctness | Broken 1and the 0-testAutodiff Remakeare in files this PR does not touch.Other review points.
is_observed(sol, y) == trueandvariable_index(sol, y) === nothing. DAE therefore raises the existing explicit "AD of purely-symbolic slicing for observed quantities" error, and ODE goes through the observed path and matches ForwardDiff.2bebc267. None of them come from this PR:SciMLSensitivity.jl/Core4fails with EnzymeAssertionError: mi2 !== nothinginensembles.jlunderEnsembleThreads. The same failure appears in three sibling PR runs from the same hour: 38865299035, 38865274410 and 38865260844.SciMLSensitivity.jl/Core5fails athybrid_de.jl:64, whereloss < 1.0evaluated to2.235. That test seeds its Lux parameters from an unseededRandom.default_rng()and never indexes a solution: it usesArray(sol)[1:2, :]withReverseDiffAdjoint. Its initial loss was 678 in this run, against 520 and 64 in passing runs, and the loss decreased steadily over the run before stopping short of the threshold. I did not run a local seed-for-seed comparison.Catalyst/All/1(ReleaseTest) andtests / SymbolicIndexingInterfacealso fail on master run 38430497298 / 38430497911.invokedecline design from another harness is still needed.Not run locally: Julia LTS, QA (no exports, deps or public API touched), Mooncake/Enzyme on these losses.
🤖 Posted by an AI agent — harness: Claude Code 2.1.301 · model: claude-opus-5-5
Conversation: local session ID 1f24b4b1-61e2-4cc3-a226-82dc67734fb4 (headless, no URL)
Risk assessment (independent review, Codex Desktop (Codex core 0.164.0-alpha.11.1) gpt-6.1-sol, slot 1, head 18fdf40)
Review round 1, written by the reviewer named above (Codex Desktop (Codex core 0.164.0-alpha.11.1) / gpt-6.1-sol) 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: Scatters array-symbol cotangents, supplies symbolic indexing rules for non-ODE timeseries solutions, and fills unread Zygote timesteps with zeros. The relevant DownstreamAD job actually executes and passes 96 assertions using ForwardDiff and finite-difference comparisons.
Blast radius: ChainRules and Zygote getindex pullbacks for ODE/DAE/RODE/SDE solutions; symbolic array/state and observed-state indexing.
Evidence: DownstreamAD log explicitly reports Symbolic solution getindex adjoints 96/96; G2 is satisfied by executed CI, not just test wiring. Tests compare Zygote with ForwardDiff on ODE/DAE losses and compare non-symbolic saved-state gradients with central differences while retaining pre-existing errors. SII downstream still errors at comprehensive_indexing.jl:127/:164 with 3747 passes/2 errors, matching the sampled default run. Linked issue #1594 supplies the affected array-symbol/DAE losses.
Blocking findings
None.
Non-blocking findings
None.
What I ran
HEADwas verified equal to18fdf4013f5cfe093767532db32609ae9a99bdd9.git diff --checkexited 0. The diff was compared to the recorded live base through its merge base, not directly against unrelated base-only commits. Root/nested agent instructions and surrounding changed-code callers were inspected. Author metadata above is from the newest non-merge commit only; absent trailers are intentionallyunknown.No local Julia test was run for this PR. Test evidence below is from inspected CI logs; source/diff checks were run locally.
CI inspection:
gh run view <run-id> --repo SciML/SciMLBase.jl --log-failed, and for selected green jobsgh run view <run-id> --job <job-id> --repo SciML/SciMLBase.jl --log. Default-branch samples usedgh run list --repo SciML/SciMLBase.jl --branch master --event push --limit 5 --json databaseId,conclusion,headSha,url,name; completed failing runs were read rather than assuming equivalence from status alone.67 checks successful/skipped/neutral; 6 checks failed/cancelled/pending at the captured snapshot. These counts include external status checks.
Sampled current default-branch runs (status alone is not used to waive failures):
What I did not verify
No local reverse-mode/ForwardDiff/solver run or reviewer-reproduced failing-before comparison. Do not infer correctness of higher-rank, nested, GPU or all observed-DAE cases beyond the executed tests. Initial blind risk was preserved, but full prior-review blindness was not maintained when author descriptions containing embedded reviews were read.
This review continues the interrupted Codex session 01a18dad-6f75-7ae1-b6dc-3a84553833ec, retaining its exact-head checkouts, CI logs and sequential test evidence. The continuation session is 01a18db8-25fc-7b72-9d35-a1341e0ae484. Initial risk ratings were saved before author descriptions; those descriptions contained embedded earlier reviews, so complete prior-review blindness was not maintained. The initial findings were frozen before the explicit same-head review comparison; additional corroboration is identified as post-freeze. This limitation is disclosed rather than claiming full blind-first compliance.
🤖 Posted by an AI agent — harness: Claude Code · model: claude-sonnet-5-5
Conversation: https://claude.ai/code/session_01379heiiB35TtywhR7uSU74