Repository navigation
Fix Zygote ensemble adjoints (RAT v4 cotangent iteration + mutable-problem over-counting) and remove __getindex - #1384
Merged
ChrisRackauckas merged 3 commits intoJun 14, 2026
Conversation
…problem gradient over-counting Fixes the root cause of SciML/SciMLSensitivity.jl#1478 plus a silent gradient-correctness bug in the same code path. 1. Under RecursiveArrayTools v4, AbstractVectorOfArray iterates scalars, so mapping trajectory pullbacks over an EnsembleSolution/VectorOfArray-wrapped cotangent in the tmap/responsible_map adjoints handed each pullback a scalar instead of its per-trajectory tangent, crashing in SciMLSensitivity with `BoundsError: attempt to access Tuple{} at index [0]`. Unwrap such cotangents to the plain vector of per-element tangents first. 2. SciML problem types are mutable structs, so Zygote accumulates their field-access cotangents in the context-wide grad_mut cache keyed on the problem instance. The per-trajectory pullbacks all read fields of the same shared problem, and once the Ref-identity protocol is broken by materialization at a ChainRules boundary, each trajectory's structural tangent snapshots the running total: a 2-trajectory ensemble returned 3g1 + 2g2 instead of g1 + g2. Treat AbstractSciMLProblem as immutable for reverse-mode AD via a structural literal_getfield pullback, mirroring the NonlinearProblem getproperty rrule in SciMLBaseChainRulesCoreExt. Adds downstream tests comparing Zygote ensemble gradients against ForwardDiff per-trajectory references across EnsembleSerial/EnsembleThreads, Gauss/Quadrature/Interpolating adjoints, with and without terminate! callbacks, for both solution-indexing and Array(sol) losses. Co-Authored-By: Claude Fable 5 <[email protected]> Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]> Co-Authored-By: Chris Rackauckas <[email protected]>
The `__getindex` helper existed only to special-case `AbstractVectorOfArray` cotangents inside `responsible_map`'s reverse pass: under RecursiveArrayTools v4 a `VectorOfArray`/`EnsembleSolution` is an `AbstractArray` with scalar column-major linear indexing, so `Δ[i]` returned a scalar instead of trajectory `i`'s tangent. That cotangent-shape concern lives in the forward ensemble utility, the wrong layer. The Zygote extension now normalizes the cotangent at its source (`unwrap_map_cotangent` in `∇responsible_map`/`∇tmap`), peeling all `AbstractVectorOfArray` layers to the plain vector of per-element tangents before re-mapping over the pullbacks. With that in place `responsible_map` only ever sees plain index ranges (forward) or a plain vector (reverse), so the `__getindex` overloads are dead. Drop them and index directly. Verified against ForwardDiff on an EnsembleProblem per-trajectory loss (`sum(sum(sum, s.u) for s in sol.u)`, GaussAdjoint + ReverseDiffVJP) for both EnsembleSerial and EnsembleThreads at -t 8. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5 <[email protected]>
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.
Important
This PR should be ignored until reviewed by @ChrisRackauckas.
Supersedes #1381 — contains all of #1381's changes plus the follow-up cleanup that #1381's approach makes possible. Open #1381 can be closed in favor of this.
What this does
Fixes AD through
solve(::EnsembleProblem, ...)when the loss reads per-trajectory solution fields (for s in sol.u; s.u[end]; ...), the root cause of SciML/SciMLSensitivity.jl#1478, and removes the now-redundant__getindexscaffolding in the forward ensemble utility.From #1381 (carried over unchanged)
BoundsErrorcrash — RAT v4 scalar cotangent iteration. Under RecursiveArrayTools v4,AbstractVectorOfArray(incl.EnsembleSolution/VectorOfArray) subtypesAbstractArrayand iterates scalars in column-major order. Cotangents fortmap/responsible_mapoutputs arrive wrapped in those containers, so zipping them with the per-trajectory pullbacks fed scalars where per-trajectory tangents were expected →BoundsError: attempt to access Tuple{} at index [0]in SciMLSensitivity. Fixed byunwrap_map_cotangent, which peels allAbstractVectorOfArraylayers to the plain vector of per-element tangents in both∇responsible_mapand∇tmap.Silent gradient over-counting — shared mutable problem.
ODEProblemis amutable struct, so Zygote routes field-access cotangents through the per-Contextgrad_mutaccumulator, shared across the per-trajectory pullbacks that all read the same problem. Once a cotangent is materialized at a ChainRules boundary (guaranteed by the per-trajectory solve rrules) Zygote's Ref-identity de-dup breaks, so trajectory tangents carry snapshots of the running accumulator → e.g.3g₁ + 2g₂instead ofg₁ + g₂. Fixed by givingAbstractDEProblema structural (immutable-style)literal_getfieldpullback, mirroring the existinggetproperty(::NonlinearProblem)precedent. Scoped toAbstractDEProblemsoAbstractNonlinearProblem's nested-AD path is untouched.New in this PR
__getindex. That helper existed only to special-caseAbstractVectorOfArraycotangents insideresponsible_map's reverse pass — a cotangent-shape concern living in the forward ensemble utility (the wrong layer). Withunwrap_map_cotangentnormalizing the cotangent at its source,responsible_maponly ever sees plain index ranges (forward) or a plain vector (reverse), so the__getindexoverloads are dead. Dropped them and index directly. (This is the cleaner alternative to Fix(ad): accesing per-trajectory fields #1380, which instead added another__getindexoverload and only covered the serial path.)Why not #1380
#1380 patches
__getindex(::AbstractEnsembleSolution)in the forward utility, fixes onlyEnsembleSerial, and leavesEnsembleThreadsbroken (tmapuses plaingetindex, not__getindex). #1380's threaded tests pass only because single-threaded CI falls back toEnsembleSerial. This PR fixes both paths at the correct layer and removes the scaffolding entirely.Verification (run locally, Julia 1.11.9,
-t 8)Per-trajectory loss
sum(sum(sum, s.u) for s in sol.u),GaussAdjoint(autojacvec=ReverseDiffVJP()), compared against a ForwardDiff reference:EnsembleSerialEnsembleThreadsAlso confirmed: removing
__getindexon top of the unwrap leaves both paths passing (the overloads were dead). Runic clean on the changed file.I ran the targeted repro and Runic locally; I did not run the full
Pkg.test()suite. The carried-over downstream testsettest/downstream/ensemble_adjoints.jlexercises this exact path (skipped on Julia 1.12+ due to known Zygote/1.12 issues).🤖 Generated with Claude Code