Skip to content

@grad fails for qualified function names (gensym(::Expr)) #318

Closed

Description

@devmotion

@grad fails at macro expansion time if the function name is qualified, e.g. M.f or Base.:*:

using ReverseDiff

module M
    f(x) = sum(abs2, x)
end

M.f(x::ReverseDiff.TrackedArray) = ReverseDiff.track(M.f, x)
ReverseDiff.@grad function M.f(x)
    xv = ReverseDiff.value(x)
    return M.f(xv), Δ -> (2 .* Δ .* xv,)
end
ERROR: LoadError: MethodError: no method matching gensym(::Expr)
Stacktrace:
 [1] var"@grad"(__source__::LineNumberNode, __module__::Module, expr::Any)

Expected: this defines the rule, like it does for an unqualified name. Qualified names are the normal way to add a rule for a function you don't own, e.g. a Base or LinearAlgebra function for your own array type. @grad_from_chainrules LinearAlgebra.dot(...) already handles them.

Cause: closure = gensym(f) assumes f is a Symbol. A plain gensym(:grad) (or gensym()) would be enough. This is the same line as #135 (callable structs), but a fix for that issue alone won't necessarily cover this case.

ReverseDiff master (b796032, v1.18.4), Julia 1.13.1.

Activity

  1. gezerui888 commented on Nov 7, 2026

    @gezerui888

    I'd like to fix this. I reproduced the qualified-name failure and have a fix with regression tests ready.

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