Flux.jl icon indicating copy to clipboard operation
Flux.jl copied to clipboard

Macro to display model struct the way Flux does

Open ericphanson opened this issue 1 year ago • 2 comments

Semi-related to #2043 😄. Custom model structs use

@functor MyModel

to define Functors.children etc. It would be nice if there was also

@define_layer_show MyModel

to generate a method for Base.show, like

using Flux
function Base.show(io::IO, m::MIME"text/plain", x::MyModel)
    if get(io, :typeinfo, nothing) === nothing  # e.g. top level in REPL
      Flux._big_show(io, x)
    elseif !get(io, :compact, false)  # e.g. printed inside a Vector, but not a Matrix
      Flux._layer_show(io, x)
    else
      show(io, x)
    end
  end
end

Alternatives:

  • I guess this could also be built into @functor but I suspect it might be better to keep it separate/ opt-in so you can define your own show method if you want. Also, adding it to @functor would also presumably be breaking since folks may have custom show methods already and that would generate method overwrite warnings and possibly break precompilation.
  • This could be done with an abstact type, but I think it's nice if folks are free to have their model partipicate in their own type hierarchy. But an abstract type seems OK too.

ericphanson avatar Aug 22 '22 11:08 ericphanson

I had a go in #1932 .

But right now I think a supertype like #2028 might be cleaner than having an ever-expanding the zoo of things you ought to invoke for good behaviour. Do you know of examples in the wild where the type hierarchy would clash?

mcabbott avatar Aug 22 '22 12:08 mcabbott

Do you know of examples in the wild where the type hierarchy would clash?

No, I don't.

But right now I think a supertype like https://github.com/FluxML/Flux.jl/pull/2028 might be cleaner than having an ever-expanding the zoo of things you ought to invoke for good behaviour.

Yeah, that makes sense. I actually do like the idea of a supertype to opt into nice fallbacks for common features; I think it's most problematic when it's a required part of the interface and you can't use Flux otherwise (rather than opting into some features). There's also always the wrapper thing of

struct MyModel{M<:FluxSuperType} <: MyCustomSuperType
    flux_model::M
end

folks can use if they need to.

ericphanson avatar Aug 22 '22 12:08 ericphanson