Repository navigation
Backport Mooncake changes to v2 - #1318
Merged
ChrisRackauckas merged 7 commits intoApr 12, 2026
Merged
ChrisRackauckas merged 7 commits into
ChrisRackauckas merged 7 commits into
Conversation
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]>
3 of 4 tasks
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.
Backport Mooncake changes to v2
Cherry-picks all Mooncake-related commits from
masteronto the v2.154.0 base sothe Mooncake AD improvements can ship on the v2 release train without pulling in
the v3 breaking changes.
Commits backported (chronological)
1ee7c9bd9Add Mooncake rrule!! for tmap and responsible_map (master 4caeba9)a09f52ca3build: bump Mooncake compat in downstream CI (master fc8b382)23746cbf2Add Mooncake rrules for symbolic indexing of solutions (master 480674f)92dcfb477Enable Mooncake test for ODE observable autodiff (master 2a90d97)e8f9f1711Propagate parameter gradient through observable indexing rrule (master d8e49f5)75a4e7c3dMooncake observable AD: NonlinearSolution, vector, DAE, init param-grad (master 2aace14)Diff summary
All six cherry-picks applied cleanly with no conflicts. After the backport
ext/SciMLBaseMooncakeExt.jlandtest/downstream/observables_autodiff.jlarebyte-identical to master; the only difference in
test/downstream/Project.tomlis pinning
SciMLBase = "2"and keepingStochasticDelayDiffEq, both of whichare 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:
SciMLBaseMooncakeExtprecompiles and loads.SciMLBase.tmapMooncake rrule returns the correct gradient on aVector{Vector{Float64}}input (hand-computed reference).SciMLBase.responsible_mapMooncake rrule returns the correct gradient onthe same input.
The full downstream MTK + OrdinaryDiffEq + SciMLSensitivity symbolic-indexing
tests (
test/downstream/observables_autodiff.jl) were not run locally — thosedepend on the heavy downstream stack and should be exercised on CI.
Test plan
Downstreamtest group passes on CI (exercises the observable autodiff tests)Co-Authored-By: Chris Rackauckas [email protected]