Skip to content

Reverse-mode rules for PDE solution wrappers behind discretizer hooks - #1630

Merged
ChrisRackauckas merged 9 commits into
SciML:masterfrom
utkuyilmaz1903:pde-solution-cotangent-hooks
Oct 22, 2026
Merged

ChrisRackauckas merged 9 commits into
SciML:masterfrom
utkuyilmaz1903:pde-solution-cotangent-hooks

Conversation

@utkuyilmaz1903

@utkuyilmaz1903 utkuyilmaz1903 commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Moves the rrules for sol[u(t, x)] and sol(t, x; dv) out of SciML/MethodOfLines.jl#698 into SciMLBase, where the wrapper types live, and dispatches down to the discretizer. Rules for ChainRulesCore, Mooncake and Enzyme.

  • AbstractDifferentiableDiscretizationMetadata opts a discretizer in. Not on by default because NeuralPDE's PINO solution evaluates the trained operator in sol(p, t) and Zygote already differentiates that by tracing; rules on every metadata would break it until NeuralPDE implements the hooks.
  • The discretizer implements pde_index_cotangent and pde_call_cotangent, plain code with no AD types: from the cotangent of a field or an evaluation they return the cotangent of original_sol.u and the observed terms (f, k, δ) to pull back through f(u[k], p, t[k]). Fallbacks error like the primal ones.
  • Each AD ext has rules for the wrapper constructors, sol[sym], sol[sym, inds...] and sol(args...; dv): it pulls the observed terms back with its own AD and hands the rest to the solver's rule for original_sol. Mooncake gets native rrule!!s like the existing ones for sol[sym], since @from_rrule can't take a config or a struct tangent. A gradient that reaches the wrapper through a field instead (sol.u[sym]) is an error in all three, not a zero.
  • Enzyme errors on observed terms for now: DiffEqBase's Enzyme rule passes the solution shadow to SciMLSensitivity, which doesn't read prob.p from it, so their parameter part would be dropped.
  • The metadata of a discretizer that opts in is NoTangent for Mooncake and inactive_type for Enzyme, it's a constant of the solve.
  • The call hook also returns the coordinate cotangents. Interpolations.jl has an rrule for the evaluation point, so gradient(x -> sol(t, x; dv), x0) already works on MOL master and Differentiate the PDE solution interface in reverse mode MethodOfLines.jl#698 was zeroing it.

Why here and not PDEBase: the rules have to call the hooks, and only SciMLBase can put rules on its own types without piracy. The discretizer side of the contract goes into PDEBase's interface page once this is in.

NeuralPDE plugs in the same way, metadata subtype plus the two hooks (original_sol is the OptimizationSolution); that is a follow-up on its side, nothing changes for it until then.

Tested in DownstreamAD with a time-dependent and a stationary dummy discretizer through Zygote, Mooncake and Enzyme against ForwardDiff: test/downstream/pde_solution_adjoints.jl passes 87/87 on Julia 1.10.11 and 1.13.2, with Mooncake 0.5.65, Enzyme 0.13.216, Zygote 0.7.13 and SciMLSensitivity 7.119.13.

MOL's side is SciML/MethodOfLines.jl#698. Its test/SolutionAD/solution_ad.jl at b69db1c2 passes 43/43 on the same Julia versions, in an environment made from test/SolutionAD/Project.toml with MethodOfLines and this branch as path sources and MOL's SciMLBase compat (3.59, for the release this goes into) relaxed, with ModelingToolkit 11.45.4, SciMLSensitivity 7.119.13 and Mooncake 0.5.64. That needs nothing else unreleased: under Mooncake the test takes the compiled ODE path and sets the parameters through SciMLStructures. Mooncake on the DAE path of discretize also needs Mooncake 0.5.65 (chalk-lab/Mooncake.jl#1385), and parameters from setp_oop need SciML/ModelingToolkit.jl#5288 (9f8d0fc82).

@utkuyilmaz1903
utkuyilmaz1903 marked this pull request as ready for review October 3, 2026 19:44
@ChrisRackauckas

Copy link
Copy Markdown
Member

Check Enzyme and Mooncake compatability? Since Zygote isn't used much anymore.

@utkuyilmaz1903

Copy link
Copy Markdown
Member Author

@ChrisRackauckas Reworked so ChainRulesCore, Mooncake and Enzyme each get their own rules, all tested against ForwardDiff. Mooncake works end to end on MOL (SciML/MethodOfLines.jl#698, with chalk-lab/Mooncake.jl#1385 and SciML/ModelingToolkit.jl#5288); Enzyme is blocked on EnzymeAD/Enzyme.jl#3855

@ChrisRackauckas

Copy link
Copy Markdown
Member

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

Independent review of 66decf3: changes needed before merge

Risk: medium (M1: new methods on external reverse-mode AD interfaces for opted-in PDE wrappers; the ordinary solve paths are unaffected).

The ChainRulesCore and Enzyme paths look right in what was checked, and the PR's own tests pass. The downstream PDE adjoint tests gave 75/75 on Julia 1.10, and test/pde_solutions.jl plus test/public_interface.jl gave 261 passing assertions. Two Mooncake cases silently return zero gradients, though. Both are confirmed with small reproducers below. In each, ForwardDiff and Zygote match the analytic derivative and Mooncake doesn't. Versions: Mooncake 0.5.65, Enzyme 0.13.216, SciMLSensitivity 7.119.13.

1. Mooncake drops coordinate-view gradients (ext/SciMLBaseMooncakeExt.jl:929)

For a minimal opted-in wrapper that evaluates sum(abs2, xs) and returns the coordinate cotangent 2Δ .* xs from its call hook, x -> A(x) differentiates correctly at [0.3, 0.4], but x -> A(view(x, :)) gives [0.0, 0.0] under Mooncake instead of [0.6, 0.8]. The rule accepts any AbstractArray, but it only accumulates when the Mooncake tangent is an Array. A view has a structured tangent, so it falls through to zero rdata. Suggested: propagate the hook's coordinate cotangent through structured array tangents, views included, and add a regression test. Representations that aren't supported should raise an explicit error rather than return zero.

Reproducer
using SciMLBase, Mooncake, DifferentiationInterface, ADTypes, Test
struct CoordinateMetadata <: SciMLBase.AbstractDifferentiableDiscretizationMetadata{Val(false)} end
const CoordinateSolution = SciMLBase.PDENoTimeSolution{T,N,S,CoordinateMetadata} where {T,N,S}
function coordinate_solution()
    fields = Dict(:u => [1.0])
    SciMLBase.PDENoTimeSolution{Float64,1,typeof(fields),CoordinateMetadata,Nothing,Nothing,Vector{Symbol},Vector{Symbol},Nothing,Nothing,Nothing,Nothing}(
        fields,nothing,nothing,[:x],[:u],CoordinateMetadata(),nothing,nothing,nothing,SciMLBase.ReturnCode.Success,nothing)
end
(A::CoordinateSolution)(xs::AbstractArray; dv=:u) = sum(abs2, xs)
SciMLBase.pde_call_cotangent(A::CoordinateSolution,args,dv,delta) = (nothing,(2 .* delta .* args[1],))
const A = coordinate_solution()
plain(x) = A(x)
viewed(x) = A(view(x,:))
for f in (plain,viewed)
    g = DifferentiationInterface.gradient(f,AutoMooncake(),[0.3,0.4])
    println(nameof(f), ": actual=",g," expected=",[0.6,0.8])
end
using ForwardDiff, Zygote
println("viewed ForwardDiff=",ForwardDiff.gradient(viewed,[0.3,0.4]))
println("viewed Zygote=",Zygote.gradient(viewed,[0.3,0.4])[1])
@test DifferentiationInterface.gradient(viewed,AutoMooncake(),[0.3,0.4]) ≈ [0.6,0.8]

2. Mooncake loses scalar parameter contributions from observed values (ext/SciMLBaseMooncakeExt.jl:862, and the constructor pullback at line 809)

The reproducer builds a real NonlinearSolution with fixed u = [2.0] and scalar prob.p = x[1], wraps it, and observes [p * sum(abs2, u)] through the observed-term hook. At x = [3.0] the loss is 12 and the derivative is [4.0]. ForwardDiff and Zygote give [4.0]; Mooncake gives [0.0]. The observed pullback sends the parameter contribution only to parameter fdata, so the scalar parameter rdata is discarded. The wrapper constructor likewise returns zero rdata for the original solution. Suggested: carry the observed parameter rdata back through the solution and wrapper pullbacks, with a scalar-parameter regression test, or at least reject parameter representations that aren't supported.

Reproducer
using SciMLBase, Mooncake, DifferentiationInterface, ADTypes
struct ObservedMetadata <: SciMLBase.AbstractDifferentiableDiscretizationMetadata{Val(false)} end
const ObservedSolution = SciMLBase.PDENoTimeSolution{T,N,S,ObservedMetadata} where {T,N,S}
obs(u,p) = [p * sum(abs2,u)]
function SciMLBase.PDENoTimeSolution(sol::SciMLBase.AbstractNonlinearSolution,md::ObservedMetadata)
    fields=Dict(:v=>obs(sol.u,sol.prob.p))
    SciMLBase.PDENoTimeSolution{Float64,1,typeof(fields),ObservedMetadata,typeof(sol),Nothing,Vector{Symbol},Vector{Symbol},typeof(sol.prob),Nothing,Nothing,Nothing}(
        fields,sol,nothing,[:x],[:v],md,sol.prob,nothing,nothing,sol.retcode,nothing)
end
Base.getindex(A::ObservedSolution,sym::Symbol)=A.u[sym]
SciMLBase.pde_index_cotangent(A::ObservedSolution,sym,delta)=(;u=nothing,observed=((obs,delta),))
residual(u,p)=u .- 2
function loss(x)
    p=x[1]
    prob=NonlinearProblem(residual,[2.0],p)
    sol=SciMLBase.build_solution(prob,nothing,[2.0],[0.0])
    SciMLBase.PDENoTimeSolution(sol,ObservedMetadata())[:v][1]
end
println("loss=",loss([3.0])," expected=12.0")
println("Mooncake=",DifferentiationInterface.gradient(loss,AutoMooncake(),[3.0])," expected=[4.0]")
using ForwardDiff, Zygote
println("ForwardDiff=",ForwardDiff.gradient(loss,[3.0]))
println("Zygote=",Zygote.gradient(loss,[3.0])[1])
using Test
@test DifferentiationInterface.gradient(loss,AutoMooncake(),[3.0]) ≈ [4.0]

Non-blocking

The PR body's verification paragraph doesn't give the exact commands and output for the MethodOfLines integration run. Adding those, plus the revisions of any upstream patches it needs, would help.

Not verified

The full DownstreamAD group, QA, the docs build, other Julia versions, and MethodOfLines' SolutionAD suite with the pending upstream fixes. The review didn't check whether the other red CI jobs also fail on master.


🤖 Posted by an AI agent — harness: codex-cli 0.163.0 (review), posted by Claude Code · model: gpt-6.1-sol (review); claude-opus-5-5 (posting)
Conversation: local session 01a150be-68b2-71f2-9774-8ae5c1859758 (no session URL); posted from https://claude.ai/code/session_0133iSjsLBByPU93BDEQkNDF

@utkuyilmaz1903

Copy link
Copy Markdown
Member Author

@ChrisRackauckas Fixed with tests. Views and ranges go through the AD’s own collect pullback now, and the observed parameter part is added with increment!!, so scalar and matrix p work too. Found and fixed two Enzyme issues on the same path while at it, and an argument Enzyme can’t push a cotangent through now errors instead of zeroing.

@ChrisRackauckas

Copy link
Copy Markdown
Member

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

Re-review of head c70735b (fresh-session Codex gpt-6.1-sol)

This re-reviews the two blocking Mooncake findings from the previous review (#1630 (comment)) and the commits pushed since (e097476, c70735b). The reviewer rated risk on its own before seeing any other rating. Its verdict is advice only: the PR is rated medium risk, so it still needs a maintainer's review before merge.

VERDICT: MERGE

Risk

medium (M1: new methods on external reverse-mode AD interfaces for explicitly opted-in PDE wrappers; ordinary solution paths retain their dispatch).

Blocking findings

None. Both first-review findings are resolved, confirmed by running.

Non-blocking findings

The claimed MethodOfLines integration run remains unverified here; its exact invocation and output are absent from the PR body.

What I ran

Reviewed c70735b, confirmed with git rev-parse HEAD, using git diff origin/master...HEAD and the two new commits separately. Read the PR/comments, linked MethodOfLines work, and risk rubric. There is no linked closing issue or root AGENTS.md/CLAUDE.md. Reviewer: Codex / gpt-6.1-sol.

Used a fresh copy of the first review's environment, re-developed this checkout into it, and ran Julia 1.10.12, Mooncake 0.5.65, Enzyme 0.13.216, SciMLSensitivity 7.119.13, Zygote 0.7.13. Julia threads: 4; precompile tasks: 4; OpenBLAS threads: 1. Interrupted automatic environment precompilation, then completed validation with JULIA_PKG_PRECOMPILE_AUTO=0.

Affected suites: exit 0, 348/348 assertions. Under julia +1.10 --project=<scratch env> -e ..., after Pkg.develop(path=pwd()) and printing versions, evaluated:

module CorePDE
    include(joinpath(ENV["PWD"], "test/pde_solutions.jl"))
    include(joinpath(ENV["PWD"], "test/public_interface.jl"))
end
module AdjointPDE
    include(joinpath(ENV["PWD"], "test/downstream/pde_solution_adjoints.jl"))
end

current_tests.log: 261/261 core/interface assertions, 87/87 adjoint assertions, including all three backends, all five parameter/rdata assertions, and the unsupported-cotangent error test.

Original reproducers, included unchanged by adversarial_probe.jl:

Probe Analytic / ForwardDiff Mooncake Enzyme
Coordinate view, input [0.3, 0.4] [0.6, 0.8] [0.6, 0.8] [0.6, 0.8]
Scalar observed parameter, input [3.0], loss 12 [4.0] [4.0] Explicit unsupported-observed-values ArgumentError

Zygote also matched both references. Enzyme intentionally rejects observed-parameter differentiation rather than returning zero.

Adversarial runs: invoked each probe with julia +1.10 --project=<scratch env> <probe>.jl; both exited 0.

  • adversarial_probe.jl: 19 returned gradients matched ForwardDiff, no mismatches. Covered strided/repeated SubArrays, reshapes, reshaped views, transposes, active ranges and a custom array containing a scalar and vector. Both backends returned [0.6, 0, 1, 0, 1.4] for the strided view, [1.2, 0.8] for repeated indices, and [0.95, 1.15] for active LinRange. Enzyme's mixed-array guard raised cannot return the cotangent.
  • parameter_probe.jl: 18 Mooncake gradients matched ForwardDiff, covering scalar, vector, tuple, NamedTuple, matrix, view, strided-view, range and mixed NamedTuple parameters in mutable stationary and immutable DAE problems. Tuple/NamedTuple/matrix gradients were [4, 4] and [13, 13], respectively. Enzyme rejected stationary observed paths explicitly; DAE probes errored at its linked mixed-activity constructor limitation.
  • Active range(start; step, length) errored under Enzyme. A standalone probe importing no SciML package reproduced EnzymeNoDerivativeError; ForwardDiff returned [4.2, 5.800000000000001] (range_baseline.log). No silent zero.

Failing-before controls, in an isolated scratch worktree with current test definitions:

  • On 66decf36, ran regression_control.jl under --project=<scratch env at 66decf36>: exit 1, 6 failed + 2 errored / 8. The view's coordinate derivative was 0 versus -0.47730243708724074; observed-parameter derivatives were [0] versus [12] or [14.25]; direct scalar-parameter rdata was [0] versus [1]. See before_regressions.log.
  • On immediate parent e0974764, ran error_control.jl in that environment: exit 1, 1 failed, because the new error assertion received no exception. Enzyme returned [0, 0, 0] versus ForwardDiff [-0.33411170595665957, -0.2386512185404711, -0.2386512185404711]. That committed assertion passes on the reviewed head. See before_error_guard.log.

git diff --check origin/master...HEAD passed. Final reviewed-checkout status was clean and HEAD unchanged. No checkout edits, commits, pushes or GitHub writes. All started commands finished.

What I did not verify

Full DownstreamAD/Core groups, QA, docs build, other Julia versions/dependency lower bounds, ComponentArrays, MethodOfLines' SolutionAD suite, pending upstream patches, or unrelated CI failures against master. Conclusions cover the exercised representations.

Links


🤖 Posted by an AI agent — harness: codex-cli 0.163.0 (review), posted by Claude Code (claude-opus-5-5) · model: gpt-6.1-sol
Conversation: local session 01a1549e-7d5e-7673-9d9e-d39044dbc893 (no session URL)

@ChrisRackauckas
ChrisRackauckas merged commit a0bacd1 into SciML:master Oct 22, 2026
67 of 73 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.

2 participants