Skip to content

Fix Mooncake gradients through the MTKParameters rules - #5288

Open
utkuyilmaz1903 wants to merge 2 commits into
SciML:masterfrom
utkuyilmaz1903:mooncake-mtkparameters-tangent
Open

utkuyilmaz1903 wants to merge 2 commits into
SciML:masterfrom
utkuyilmaz1903:mooncake-mtkparameters-tangent

Conversation

@utkuyilmaz1903

@utkuyilmaz1903 utkuyilmaz1903 commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

The remake_buffer and SetInitialUnknowns rrules return the cotangent of the old parameter object as a Tangent{MTKParameters}, and MTKMooncakeExt only converted the NamedTuple form, so both @from_rrule pullbacks threw. That broke Mooncake through setp_oop and through remake(prob; u0), the example from #4180. The extension now converts the Tangent (it also triggers on ChainRulesCore, which Mooncake depends on anyway), and the remake_buffer pullback copies the cotangent of an array parameter, which was a view that @from_rrule can't accumulate.

A callable parameter whose value has a numeric field, like a ModelingToolkitNeuralNets network, broke the same paths: the value sits in the nonnumeric portion, Mooncake gives it a tangent, and the MTKParameters and remake_buffer rules passed that struct cotangent on to the bridge. Both rules now give nonnumeric no cotangent, which is how MTKMooncakeExt already treats it. This came up getting MethodOfLines' neural network tutorial to train with Mooncake.

test/extensions/mooncake.jl, against ForwardDiff master this PR
setp_oop(prob, [α, q[1]]) ArgumentError ✓
setp_oop(prob, q), array parameter ArgumentError ✓
remake(prob; u0) ArgumentError ✓
callable parameter, setp_oop and u0 MethodError ✓

The other AD files of the Extensions group pass as before, on Julia 1.10 and 1.13. Mooncake in the test env adds only Mooncake, DispatchDoctor and MistyClosures to the manifest.

Fixes SciML/SciMLSensitivity.jl#1712

@ChrisRackauckas

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

PR: #5288

Reviewed head: 9f8d0fc
Raw SHA-256: befbb3d477673681a62aa48e5104b538871dc41a47d9dd56a3b93c2aae226056
Source SHA-256: 33c88d05bcb81e9aa23f7caa47443b6d99059ef7a0c4bcc1db90997d8e5d5f6e
Source: operator-attested-codex-v1 (runner attested by pankgeorg)
Reviewer session: 01a22397-c647-7840-839b-943792a25521
Slot: 1
Confidence: unknown
Own risk fixed before author rating/discussion: yes
Redaction: ran (substitutions=0)

Risk assessment

  • Risk: medium-high (MH1)
  • Verdict: CHANGES
  • Reviewed head: 9f8d0fc

Review report

VERDICT: CHANGES
PR: #5288
Head: 9f8d0fc
Base: 91fd79e
Reviewer: codex-cli 0.172.0 / gpt-6.2-sol
Session: 01a22397-c647-7840-839b-943792a25521

Risk

medium-high (MH1: the shared reverse-mode rules change core parameter and initial-condition rebuilds on common differentiation paths).

The affected users are fitting or differentiating ModelingToolkit models with Mooncake or another ChainRules backend. The patch reaches setp_oop, remake(prob; u0), and MTKParameters reconstruction during differentiation. Its scope is the AD surrounding solves and initialization. The target diverged only in workflow files, and the patch applies cleanly to it.

Blocking findings

  • P1 · lib/ModelingToolkitBase/ext/MTKChainRulesCoreExt.jl:180 — The SetInitialUnknowns pullback zeros the old buffer’s untouched slots and keeps the overwritten ones. Replacing the first entry of [4.0, 5.0] with 10.0 gives a sum of 15.0. Head Mooncake returned [1.0, 0.0] for the old buffer, while the analytical and ForwardDiff gradient is [0.0, 1.0]. The mask predates the patch, and the new Mooncake adapter exposes the wrong result where the merge base raised an unsupported-tangent error. Mask siu.idxs_in_initials in both SetInitialUnknowns pullbacks. Assert an old-buffer gradient of [0.0, 1.0] and a replacement gradient of [1.0].

  • P2 · lib/ModelingToolkitBase/ext/MTKChainRulesCoreExt.jl:49 — The generic MTKParameters constructor pullback discards callable cotangents for every ChainRules consumer. For a callable Gain(k) stored in nonnumeric and evaluated at 3.0, Zygote returned the analytical derivative 3.0 on the merge base and nothing on head. Restore forwarding in the generic constructor rule and apply the inactivity policy in Mooncake’s adapter. A universal inactivity policy would require an explicit compatibility decision. Add a regression asserting that Zygote still returns 3.0 while the existing Mooncake tests with a fixed callable pass.

  • P2 · lib/ModelingToolkitBase/ext/MTKChainRulesCoreExt.jl:157 — remake_buffer_pullback still extracts a structured cotangent for a replacement callable. On head, a single setp_oop call replacing a numeric coefficient and a fixed Gain(3.0) raised a Mooncake ArgumentError when differentiating only the coefficient. ForwardDiff returned [6.0]. Under Mooncake’s inactive-callable policy, return NoTangent() for that replacement entry before extracting its cotangent. If active callable replacements are intended, implement structured tangent accumulation instead. Assert that a mixed update with a fixed callable returns [6.0].

Nonblocking findings

None

What I ran

  • diff -qr before head, diff -qr before target, and git apply --check --directory=target changes.diff. The patch accounts for six changed files, and the target application check passed.
  • uname -m, julia --version, and offline Pkg.resolve() / Pkg.instantiate() in snapshot-specific environments. The probes ran on ARM64 with Julia 1.13.4, Mooncake 0.5.73, and matching dependency versions.
  • julia --startup-file=no --project=.julia-scratch/"$v"-env .julia-scratch/array-review.jl on both snapshots. Whole-array remake_buffer raised an unsupported-tangent error on the merge base and returned [0.6, 2.0] on head. ForwardDiff and the analytical gradient of the sum-of-squares loss agreed exactly.
  • Ran pullback-review.jl, zygote-review.jl, callable-replacement-review.jl, and isolated-mask-fix-review.jl with the scratch Julia projects. They reproduced the three findings above. Changing only the mask in the isolated rule produced the expected old and replacement cotangents.
  • Ran adapter-accumulation-review.jl with the head project. Two successive contributions to the same nonzero accumulator produced the expected tunables [6.0, 5.0] and initials [9.0]. The second contribution omitted initials, which checks that the adapter preserves earlier data.
  • Filtered ci.json with jq and traced the test entry points. The exact-head ModelingToolkitBase Extensions jobs succeeded on Julia 1 and LTS. The group directly includes mooncake.jl at lib/ModelingToolkitBase/test/runtests.jl:148. Its five assertions use ForwardDiff as an independent AD reference, and the patch retains the existing tests. Julia 1 Extensions · Julia LTS Extensions

What I did not verify

  • The local using Test; include("head/lib/ModelingToolkitBase/test/extensions/mooncake.jl") runs had produced no test summary when I finished the review. The scoped probes establish the before/after behavior above, and the exact-head jobs supply head ODE coverage. A completed run of all five cases against both snapshots with the same dependency versions would establish the full end-to-end before/after result.
  • Local execution was CPU-only. GPU, Reactant, and MPI execution were outside the exercised paths. The benchmark check records supplied conclusions without before/after measurements.

Head link: 9f8d0fc


🤖 Posted by an AI agent — harness: codex-cli 0.172.0 · model: gpt-6.2-sol
Conversation: local session 01a22397-c647-7840-839b-943792a25521 (no session URL)

This branch has not been deployed

No deployments
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.

Mooncake gradient through solve fails when the parameters come from setp_oop

2 participants