Skip to content

Custom gradient for callable struct #135

Open

Description

@mcabbott

This doesn't seem to work, simple example:

struct Over{T} den::T end

(o::Over)(x) = x ./ o.den

using ReverseDiff

(o::Over)(x::ReverseDiff.TrackedArray) = ReverseDiff.track(o, x)

ReverseDiff.@grad function (o::Over)(x)
    ReverseDiff.value(x) ./ o.den, Δ -> (Δ .* o.den,)
end
# ERROR: UndefVarError: o not defined

This is the error after changing this line to closure = gensym(string(f)):

closure = gensym(f)

or equivalently defining

 Base.gensym(ex::Expr) = gensym(string(ex))

Activity

  1. added a commit that references this issue on Jul 3, 2020
  2. devmotion commented on Oct 5, 2026

    @devmotion
    Member

    @grad_from_chainrules doesn't support callable structs either:

    using ReverseDiff, ChainRulesCore
    
    struct Scale
        a::Float64
    end
    (s::Scale)(x) = s.a * sum(x)
    ChainRulesCore.rrule(s::Scale, x) = s(x), Δ -> (NoTangent(), fill(s.a * Δ, size(x)))
    
    ReverseDiff.@grad_from_chainrules (s::Scale)(x::ReverseDiff.TrackedArray)
    ERROR: LoadError: UndefVarError: `s` not defined in `Main`
    

    The macro takes fcall.args[1] (here s::Scale) as the function (L319) and splices it into typeof($f) and calls like rrule($f, ...), where s isn't bound (ReverseDiff master, b796032).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions