ReverseDiff.jl
ReverseDiff.jl copied to clipboard
Custom `rrule` not working with ReverseDiff
Hello everyone,
First off, thank you all for your work on ReverseDiff.
I'm not sure whether this issue belongs here on in the ChainRules repo, so forgive me if it's not relevant here.
I have tried defining my own pullback using ChainRules, which claims to be compatible with ReverseDiff.
However, my attempts so far have been unsuccesful.
As a minimal example, take
using ChainRules, ChainRulesCore, ReverseDiff, Plots
function new_gradient(x)
return conj((abs(x / 2) + 1)^(-2))
end
function H(a)
return (sign(a) + 1) / 2
end
function ϕ(x)
return H(x[1])
end
@scalar_rule ϕ(x) new_gradient(x)
function ChainRulesCore.rrule(::typeof(ϕ), x::AbstractArray)
y = ϕ.(x)
function array_ϕ_pullback(ȳ)
println("Test.")
ϕ̄ = NoTangent()
x̄ = @thunk new_gradient.(x) * ȳ
return ϕ̄, x̄
end
return y, array_ϕ_pullback
end
gradplot = let
xs = -5:0.01:5
vals = [ϕ(x) for x in xs]
grads = [ReverseDiff.gradient(ϕ, [x]) for x in xs]
p = plot(xs, vals, label = "ϕ")
plot!(p, xs, getindex.(grads, 1), label = "∇ϕ")
p
end
My own rrules are never called.
Have I made an elementary mistake here, or is this actually a problem with ChainRules?
ReverseDiff does not use rrules automatically. You have to "import" them with @grad_from_chainrules: https://juliadiff.org/ReverseDiff.jl/dev/api/#ReverseDiff.@grad_from_chainrules