Skip to content

Backport Mooncake changes to v2 - #1318

Merged
ChrisRackauckas merged 7 commits into
SciML:v2-backportfrom
ChrisRackauckas-Claude:cc/mooncake-backport
Apr 12, 2026
Merged

ChrisRackauckas merged 7 commits into
SciML:v2-backportfrom
ChrisRackauckas-Claude:cc/mooncake-backport

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Backport Mooncake changes to v2

Cherry-picks all Mooncake-related commits from master onto the v2.154.0 base so
the Mooncake AD improvements can ship on the v2 release train without pulling in
the v3 breaking changes.

Commits backported (chronological)

  • 1ee7c9bd9 Add Mooncake rrule!! for tmap and responsible_map (master 4caeba9)
  • a09f52ca3 build: bump Mooncake compat in downstream CI (master fc8b382)
  • 23746cbf2 Add Mooncake rrules for symbolic indexing of solutions (master 480674f)
  • 92dcfb477 Enable Mooncake test for ODE observable autodiff (master 2a90d97)
  • e8f9f1711 Propagate parameter gradient through observable indexing rrule (master d8e49f5)
  • 75a4e7c3d Mooncake observable AD: NonlinearSolution, vector, DAE, init param-grad (master 2aace14)

Diff summary

 ext/SciMLBaseMooncakeExt.jl             | 541 +++++++++++++++++++++++++++++++-
 test/downstream/Project.toml            |   2 +-
 test/downstream/observables_autodiff.jl | 121 ++++---
 3 files changed, 616 insertions(+), 48 deletions(-)

All six cherry-picks applied cleanly with no conflicts. After the backport
ext/SciMLBaseMooncakeExt.jl and test/downstream/observables_autodiff.jl are
byte-identical to master; the only difference in test/downstream/Project.toml
is pinning SciMLBase = "2" and keeping StochasticDelayDiffEq, both of which
are pre-existing v2-base differences unrelated to this backport.

Verified locally

Loaded SciMLBase v2.154.0 + Mooncake 0.5.26 on Julia 1.11 and confirmed:

  • SciMLBaseMooncakeExt precompiles and loads.
  • SciMLBase.tmap Mooncake rrule returns the correct gradient on a
    Vector{Vector{Float64}} input (hand-computed reference).
  • SciMLBase.responsible_map Mooncake rrule returns the correct gradient on
    the same input.

The full downstream MTK + OrdinaryDiffEq + SciMLSensitivity symbolic-indexing
tests (test/downstream/observables_autodiff.jl) were not run locally — those
depend on the heavy downstream stack and should be exercised on CI.

Test plan

  • Downstream test group passes on CI (exercises the observable autodiff tests)
  • Mooncake extension precompiles on all supported Julia versions

Co-Authored-By: Chris Rackauckas [email protected]

claude and others added 7 commits April 11, 2026 19:51
This implements reverse-mode AD rules for SciMLBase.tmap and
SciMLBase.responsible_map functions, enabling Mooncake to
differentiate through ensemble solves.

Key implementation details:
- Uses Mooncake's fdata system for vector gradients (tangent field of CoDual)
- Prepares pullback caches during forward pass for nested AD
- Applies pullbacks in reverse order for responsible_map (for stateful f)

Closes https://github.com/SciML/DiffEqBase.jl/issues/1256

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Adds rrule!! primitives for `getindex(::AbstractTimeseriesSolution, sym)`
and `getindex(::AbstractTimeseriesSolution, sym, j)` so Mooncake can
differentiate through `sol[sys.x]` and `sol[sys.w]` (state and observable
indexing) without trying to differentiate through the SymbolicIndexingInterface
dispatch chain.

The dispatch chain uses hash-consed symbols (SymbolicUtils' BasicSymbolic
interning), task-local values, IdDicts, and atomic pointers — none of
which are differentiable infrastructure. Making the high-level indexing
operation a primitive bypasses all of that.

Implementation:
- State variables: scatter the output gradient directly into sol.u[k][i]
- Observables: build a Mooncake derived rule for the observed function
  via `build_rrule` and apply it. This is the Mooncake equivalent of how
  SciMLBaseChainRulesCoreExt uses `rrule_via_ad` to recurse into Zygote
  for the observable case.

Closes part of SciML#1207 (Mooncake SymbolicIndexingInterface AD support).

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The basic ODE observable autodiff (`sol[sys.w]`) now works with the
Mooncake `getindex` rrules added in this PR. Switch the @test_broken
to @test for that case.

Add `_unwrap_grad` helper to bridge Zygote's NamedTuple-style gradient
access (`gs.u`) with Mooncake's Tangent (`gs.fields.u`).

Other Mooncake observable test cases (vector observable, init,
DAE init, full DAE adjoint) remain @test_broken for now — those use
different code paths not covered by the getindex rrule.

Verified: AutoMooncake on `sum(sol[sys.w])` for the Lorenz system
returns the expected gradient `[1.0, 1.0, 1.0, 0.0]` per timestep.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Extend `_observable_pullback_at!` to thread the parameter rdata from
the inner Mooncake `build_rrule` call back into `sol_fdata.prob.p`,
not just `sol_fdata.u`. This makes `gradient(sol -> sum(sol[sys.w]),
AutoMooncake(), sol)` produce non-zero gradients for parameters that
appear in the observable expression (e.g. `β` in `w = x + y + z + 2β`).

The accumulator `_accumulate_p_fdata!` walks the NamedTuple structure
of the parameter tangent (Tangent for immutable structs, MutableTangent
for mutable, FData for forward-data) and accumulates Vector-typed
leaves in place. This handles MTKParameters where the tangent for the
mutable struct is a MutableTangent containing a Tangent for the inner
parameter NamedTuple.

Verified: `gradient(sol -> sum(sol[sys.w]), AutoMooncake(), sol)` for
the Lorenz system + observable `w = x + y + z + 2β` returns
`gs.prob.p.tunable = [0.0, 0.0, 2988.0]` (where 2988 = 2 * length(sol)
= ∂(sum(w))/∂β). State gradient still matches FiniteDiff.

NonlinearSolution observable indexing is left as a known limitation —
the observed function for NonlinearSolution does internal symbolic
dispatch that Mooncake can't trace through.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Address remaining gaps from SciML#1316 in SymbolicIndexingInterface AD on the
Mooncake path.

## NonlinearSolution observable indexing (`isol[sym]`)

Add `rrule!!` for `getindex(::AbstractNonlinearSolution, sym)`. The
direct approach (let Mooncake trace `getter(sym, u, p)`) hits a symbolic
comparison inside MTK's `ObservedFunctionCache` that produces a `Num` in
boolean context. Workaround: call `inner = getter(sym)` *outside*
Mooncake tracing — `ObservedFunctionCache` returns the cached generated
function for that symbol when called with no extra args, and that inner
function takes plain numeric `(u, p)` arrays which Mooncake handles in
seconds.

## Vector-of-symbols observable indexing (`sol[[sym1, sym2]]`)

Add `rrule!!` for `getindex(::AbstractTimeseriesSolution, ::AbstractVector)`.
Factor the per-symbol pullback into `_scatter_symbol_timeseries!` so the
vector rrule can reuse it: it walks each symbol in the index vector and
applies the same state-vs-observable scatter logic.

## DAE observable test refresh

The hard-coded `du_ = [0.2, 1.0]` expected values in the De Sauty bridge
DAE test were stale (left over from an older MTK build). Both Zygote and
Mooncake actually produce `[-0.5, -1e-6]` per timestep on this
environment, and FiniteDiff agrees to ~1e-5 (FD step-size error).
Update the test to use the refreshed reference values, switch `==` to
`≈`, and enable the Mooncake variant.

## DAE adjoint with parameter gradient

Mooncake actually handles this case via its `build_rrule` path (which
doesn't go through ChainRules' `_solve_adjoint`), unlike Zygote which
hits a `getindex(::Nothing, ::Int64)` failure inside
`get_updated_symbolic_problem` for SCCNonlinearProblem initialization.
Enable the Mooncake test (Zygote still broken upstream) and update the
comment to describe the actual Zygote failure path instead of the stale
"PConstructorApplicator" reference.

## Init observable parameter-gradient comparison

Now that NonlinearSolution observable indexing works, enable the
Mooncake variant of the init test. It compares the parameter gradient
from `gradient(isol -> isol[sys.w], AutoMooncake(), isol)` against
ForwardDiff applied to the same inner observed function — they agree
exactly on the linear `w ~ x + y + z + 2β` expression.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
New minor release carrying the backported Mooncake AD changes
(tmap/responsible_map rrules and solution symbolic-indexing rrules).

Co-Authored-By: Chris Rackauckas <[email protected]>
@ChrisRackauckas
ChrisRackauckas merged commit a1addc8 into SciML:v2-backport Apr 12, 2026
32 of 45 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.

4 participants