|
| 1 | +module DiffEqBaseEnzymeExt |
| 2 | + |
| 3 | +using DiffEqBase |
| 4 | +import DiffEqBase: value |
| 5 | +isdefined(Base, :get_extension) ? (import Enzyme) : (import ..Enzyme) |
| 6 | + |
| 7 | +using ChainRulesCore |
| 8 | +using EnzymeCore |
| 9 | + |
| 10 | +function EnzymeCore.EnzymeRules.augmented_primal(config::EnzymeCore.EnzymeRules.ConfigWidth{1}, func::Const{typeof(DiffEqBase.solve_up)}, ::Type{Duplicated{RT}}, prob, sensealg::Union{Const{Nothing}, Const{<:DiffEqBase.AbstractSensitivityAlgorithm}}, u0, p, args...; kwargs...) where RT |
| 11 | + @inline function copy_or_reuse(val, idx) |
| 12 | + if EnzymeCore.EnzymeRules.overwritten(config)[idx] && ismutable(val) |
| 13 | + return deepcopy(val) |
| 14 | + else |
| 15 | + return val |
| 16 | + end |
| 17 | + end |
| 18 | + |
| 19 | + @inline function arg_copy(i) |
| 20 | + copy_or_reuse(args[i].val, i+5) |
| 21 | + end |
| 22 | + |
| 23 | + res = DiffEqBase._solve_adjoint(copy_or_reuse(prob.val, 2), copy_or_reuse(sensealg.val, 3), copy_or_reuse(u0.val, 4), copy_or_reuse(p.val, 5), SciMLBase.ChainRulesOriginator(), ntuple(arg_copy, Val(length(args)))...; |
| 24 | + kwargs...) |
| 25 | + |
| 26 | + dres = deepcopy(res[1])::RT |
| 27 | + for v in dres.u |
| 28 | + v.= 0 |
| 29 | + end |
| 30 | + tup = (dres, res[2]) |
| 31 | + return EnzymeCore.EnzymeRules.AugmentedReturn{RT, RT, Any}(res[1], dres, tup::Any) |
| 32 | +end |
| 33 | + |
| 34 | +function EnzymeCore.EnzymeRules.reverse(config::EnzymeCore.EnzymeRules.ConfigWidth{1}, func::Const{typeof(DiffEqBase.solve_up)}, ::Type{<:Duplicated{RT}}, tape, prob, sensealg::Union{Const{Nothing}, Const{<:DiffEqBase.AbstractSensitivityAlgorithm}}, u0, p, args...; kwargs...) where RT |
| 35 | + dres, clos = tape |
| 36 | + dres = dres::RT |
| 37 | + dargs = clos(dres) |
| 38 | + for (darg, ptr) in zip(dargs, (func, prob, sensealg, u0, p, args...)) |
| 39 | + if ptr isa EnzymeCore.Const |
| 40 | + continue |
| 41 | + end |
| 42 | + if darg == ChainRulesCore.NoTangent() |
| 43 | + continue |
| 44 | + end |
| 45 | + ptr.dval .+= darg |
| 46 | + end |
| 47 | + for v in dres.u |
| 48 | + v.= 0 |
| 49 | + end |
| 50 | + return ntuple(_ -> nothing, Val(length(args)+4)) |
| 51 | +end |
| 52 | + |
| 53 | +end |
0 commit comments