Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom rrule not working with ReverseDiff #208

Open
Antomek opened this issue Sep 27, 2022 · 1 comment
Open

Custom rrule not working with ReverseDiff #208

Antomek opened this issue Sep 27, 2022 · 1 comment

Comments

@Antomek
Copy link

Antomek commented Sep 27, 2022

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?

@devmotion
Copy link
Member

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

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

No branches or pull requests

2 participants