Skip to content

Fix Zygote ensemble adjoints: RAT v4 cotangent iteration and mutable-problem gradient over-counting - #1381

Closed
ChrisRackauckas-Claude wants to merge 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:fix-ensemble-zygote-adjoints
Closed

ChrisRackauckas-Claude wants to merge 2 commits into
SciML:masterfrom
ChrisRackauckas-Claude:fix-ensemble-zygote-adjoints

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

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_internal wrapped as EnsembleSolution/VectorOfArray (via the EnsembleSolution constructor adjoint and RecursiveArrayTools' literal_getproperty(::AbstractVectorOfArray, Val(:u)) adjoint).

Under RecursiveArrayTools v4, AbstractVectorOfArray <: AbstractArray and iterates scalars in column-major order, so

SciMLBase.responsible_map((f, δ) -> f(δ), backs, Δ)

zips each trajectory pullback with a scalar Float64 instead of its per-trajectory tangent. SciMLSensitivity's adjoint_sensitivity_backpass then hits size(Δ)[end] on a 0-dim cotangent → BoundsError: attempt to access Tuple{} at index [0].

Fix: unwrap AbstractVectorOfArray cotangents 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 of g₁ + g₂ (where gᵢ is trajectory i's contribution, verified per-trajectory against ForwardDiff).

Mechanism: ODEProblem (like all SciML problem types) is a mutable struct, so Zygote routes its field-access cotangents through the per-Context mutable-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-trajectory solve rrules, see wrap_chainrules_input(dx::Ref) = wrap_chainrules_input(dx[])). Each trajectory's structural tangent then carries a snapshot of the running accumulator:

  • trajectory 1's tangent contains g₁
  • trajectory 2's tangent contains g₁ + g₂
  • reduce(accum, ...) → 2g₁ + g₂
  • the Jnew constructor pullback at the problem construction site adds the cache content g₁ + 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 giving Zygote.literal_getfield a structural (immutable-style) pullback for them. This mirrors the existing precedent in SciMLBaseChainRulesCoreExt for NonlinearProblem, which was added for exactly this reason:

# This is a workaround for the fact `NonlinearProblem` is a mutable struct. [...] The mutable struct
# causes accumulation anytime `getfield/property` is called, accumulating multiple times. This tries to treat
# AbstractDEProblem as immutable for the purposes of reverse mode AD.

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 of AbstractSciMLProblem) so that AbstractNonlinearProblem keeps its current behavior: its nested-AD path already produces partial-NamedTuple problem cotangents through the getproperty(::NonlinearProblem) rrule, and a full-NamedTuple pullback collides with those in Zygote.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-mismatch ArgumentError on a NonlinearProblem cotangent (the MTK initialization problem in nested AD) — verified by running the test with master's SciMLBaseZygoteExt.jl and 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() and EnsembleThreads() (covers both ∇responsible_map and ∇tmap)
  • GaussAdjoint, QuadratureAdjoint, InterpolatingAdjoint (all with ReverseDiffVJP)
  • with and without a ContinuousCallback + terminate!
  • per-trajectory-solution loss (s.u[end], the crashing form) and dense Array(sol) loss

All 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

…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]>
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