FluxML/Functors.jl

Passing field names to @functor for typed struct gives constructor error

andrschl opened this issue · 2 comments

I am not sure whether this is intended or not, but when trying to specify the trainable parameters in the following code a "no method matching error" for the constructor is returned.

struct MyLayer{R, S, T}
    a::R
    b::S
    c::T
end
Flux.@functor MyLayer (a,b)
m = MyLayer(Dense(1,10,tanh), Dense(1,10,tanh), zeros(5))
Flux.destructure(m) # returns no method matching error for the constructor

In the last sentence of the corresponding section in the documentation it is mentioned that a corresponding constructor has to exist. However, it is not clear to me how this constructor should look like.

This issue seems to be the same as the one discussed in #3. You can check the comments therein for a solution to your problem: Instead of Flux.@functor MyLayer (a,b) you can define

function Functors.functor(::Type{<:MyLayer}, x)
    function reconstruct_MyLayer(xs)
        return MyLayer(xs.a, xs.b, x.c)
    end
    return (a = x.a, b = x.b), reconstruct_MyLayer
end

addressed in #7