Skip to content

Fix Zygote ensemble adjoints (RAT v4 cotangent iteration + mutable-problem over-counting) and remove __getindex - #1384

Merged
ChrisRackauckas merged 3 commits into
SciML:masterfrom
ChrisRackauckas-Claude:claude/ensemble-adjoint-cotangent-fix
Jun 14, 2026
Merged

ChrisRackauckas merged 3 commits into
SciML:masterfrom
ChrisRackauckas-Claude:claude/ensemble-adjoint-cotangent-fix

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

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 __getindex scaffolding in the forward ensemble utility.

From #1381 (carried over unchanged)

  1. BoundsError crash — RAT v4 scalar cotangent iteration. Under RecursiveArrayTools v4, AbstractVectorOfArray (incl. EnsembleSolution/VectorOfArray) subtypes AbstractArray and iterates scalars in column-major order. Cotangents for tmap/responsible_map outputs 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 by unwrap_map_cotangent, which peels all AbstractVectorOfArray layers to the plain vector of per-element tangents in both ∇responsible_map and ∇tmap.

  2. Silent gradient over-counting — shared mutable problem. ODEProblem is a mutable struct, so Zygote routes field-access cotangents through the per-Context grad_mut accumulator, 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 of g₁ + g₂. Fixed by giving AbstractDEProblem a structural (immutable-style) literal_getfield pullback, mirroring the existing getproperty(::NonlinearProblem) precedent. Scoped to AbstractDEProblem so AbstractNonlinearProblem's nested-AD path is untouched.

New in this PR

  1. Remove __getindex. That helper existed only to special-case AbstractVectorOfArray cotangents inside responsible_map's reverse pass — a cotangent-shape concern living in the forward ensemble utility (the wrong layer). With unwrap_map_cotangent normalizing the cotangent at its source, responsible_map only ever sees plain index ranges (forward) or a plain vector (reverse), so the __getindex overloads are dead. Dropped them and index directly. (This is the cleaner alternative to Fix(ad): accesing per-trajectory fields #1380, which instead added another __getindex overload and only covered the serial path.)

Why not #1380

#1380 patches __getindex(::AbstractEnsembleSolution) in the forward utility, fixes only EnsembleSerial, and leaves EnsembleThreads broken (tmap uses plain getindex, not __getindex). #1380's threaded tests pass only because single-threaded CI falls back to EnsembleSerial. 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:

branch EnsembleSerial EnsembleThreads
master BoundsError BoundsError
#1380 ✓ BoundsError
this PR ✓ matches ForwardDiff ✓ matches ForwardDiff

Also confirmed: removing __getindex on 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 testset test/downstream/ensemble_adjoints.jl exercises this exact path (skipped on Julia 1.12+ due to known Zygote/1.12 issues).

🤖 Generated with Claude Code

claude and others added 3 commits June 10, 2026 01:57
…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]>
@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review June 14, 2026 09:17
@ChrisRackauckas
ChrisRackauckas merged commit e4e4c33 into SciML:master Jun 14, 2026
29 of 62 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.

3 participants