Repository navigation
Fix Zygote ensemble adjoints: RAT v4 cotangent iteration and mutable-problem gradient over-counting - #1381
Closed
ChrisRackauckas-Claude wants to merge 2 commits into
Closed
Fix Zygote ensemble adjoints: RAT v4 cotangent iteration and mutable-problem gradient over-counting#1381ChrisRackauckas-Claude wants to merge 2 commits into
ChrisRackauckas-Claude wants to merge 2 commits into
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]>
This was referenced Jun 10, 2026
Co-Authored-By: Claude Fable 5 <[email protected]> Co-Authored-By: Chris Rackauckas <[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.
Fixes the root cause of SciML/SciMLSensitivity.jl#1478 (
BoundsError: attempt to access Tuple{} at index [0]when differentiating ensemble solves with GaussAdjoint/QuadratureAdjoint + callbacks), plus a second, silent gradient-correctness bug in the same code path that was exposed once the crash was fixed.Bug 1: crash from RAT v4 scalar iteration in the ensemble map pullbacks
When the loss accesses per-trajectory solutions (
sol.u,s.u[end], ...), the cotangent for the ensemble arrives at∇responsible_map_internal/∇tmap_internalwrapped asEnsembleSolution/VectorOfArray(via theEnsembleSolutionconstructor adjoint and RecursiveArrayTools'literal_getproperty(::AbstractVectorOfArray, Val(:u))adjoint).Under RecursiveArrayTools v4,
AbstractVectorOfArray <: AbstractArrayand iterates scalars in column-major order, sozips each trajectory pullback with a scalar
Float64instead of its per-trajectory tangent. SciMLSensitivity'sadjoint_sensitivity_backpassthen hitssize(Δ)[end]on a 0-dim cotangent →BoundsError: attempt to access Tuple{} at index [0].Fix: unwrap
AbstractVectorOfArraycotangents to the plain vector of per-element tangents before zipping with the pullbacks.This is not actually callback-specific (the no-callback case crashes identically with this loss form); callbacks just made it the reported reproducer.
Bug 2: silent gradient over-counting through the shared mutable problem
With the crash fixed, gradients were silently wrong: for a 2-trajectory ensemble the gradient came out as
3g₁ + 2g₂instead ofg₁ + g₂(wheregᵢis trajectoryi's contribution, verified per-trajectory against ForwardDiff).Mechanism:
ODEProblem(like all SciML problem types) is amutable struct, so Zygote routes its field-access cotangents through the per-Contextmutable-struct accumulator (grad_mut), keyed on the problem instance and shared across all pullback invocations of one context. The ensemble adjoints invoke one pullback per trajectory, each reading fields of the same shared problem; Zygote's Ref-identity protocol that normally prevents double counting breaks as soon as the cotangent is materialized at a ChainRules boundary (guaranteed here by the per-trajectorysolverrules, seewrap_chainrules_input(dx::Ref) = wrap_chainrules_input(dx[])). Each trajectory's structural tangent then carries a snapshot of the running accumulator:g₁g₁ + g₂reduce(accum, ...)→2g₁ + g₂Jnewconstructor pullback at the problem construction site adds the cache contentg₁ + g₂once more →3g₁ + 2g₂(exactly what was observed)This is the known Zygote limitation flagged in its own source (
# TODO captured mutables + multiple calls to back).Fix: treat
AbstractDEProblems as immutable for reverse-mode AD by givingZygote.literal_getfielda structural (immutable-style) pullback for them. This mirrors the existing precedent inSciMLBaseChainRulesCoreExtforNonlinearProblem, which was added for exactly this reason:The existing ensemble tests couldn't catch this because they only assert that optimization decreases the loss — a gradient that is wrong by trajectory-dependent positive factors still passes that.
The pullback is scoped to
AbstractDEProblem(not all ofAbstractSciMLProblem) so thatAbstractNonlinearProblemkeeps its current behavior: its nested-AD path already produces partial-NamedTupleproblem cotangents through thegetproperty(::NonlinearProblem)rrule, and a full-NamedTuplepullback collides with those inZygote.accum(ArgumentError: ... keys must be a subset of ...).While validating this I found that
test/downstream/remake_autodiff.jl(testset "split = false") currently errors on unmodified master with exactly that kind of key-mismatchArgumentErroron aNonlinearProblemcotangent (the MTK initialization problem in nested AD) — verified by running the test with master'sSciMLBaseZygoteExt.jland with this branch's: identical error either way, so it is pre-existing and unrelated to this PR. A separate bisect/investigation of that failure is underway.Tests
Added
test/downstream/ensemble_adjoints.jl, which compares Zygote ensemble gradients against ForwardDiff on per-trajectory reference solves across:EnsembleSerial()andEnsembleThreads()(covers both∇responsible_mapand∇tmap)GaussAdjoint,QuadratureAdjoint,InterpolatingAdjoint(all withReverseDiffVJP)ContinuousCallback+terminate!s.u[end], the crashing form) and denseArray(sol)lossAll 24 combinations now agree with ForwardDiff to
rtol = 1e-4. The original MRE from SciML/SciMLSensitivity.jl#1478 (Lux NN +EnsembleThreads+ContinuousCallback/terminate!+GaussAdjoint(autojacvec = ReverseDiffVJP())) runs and its gradient matches central finite differences.🤖 Generated with Claude Code