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

add function fleaves #73

Merged
merged 4 commits into from
Mar 11, 2024
Merged

add function fleaves #73

merged 4 commits into from
Mar 11, 2024

Conversation

CarloLucibello
Copy link
Member

@CarloLucibello CarloLucibello commented Mar 8, 2024

Adds utility function fflatten fleaves that flatten the leaves into an array, similarly to jax's tree_leaves.
Useful for models' parameters collection:

julia> using Flux

julia> m = Chain(Dense(2=>3, relu), Dense(3 => 2))
Chain(
  Dense(2 => 3, relu),                  # 9 parameters
  Dense(3 => 2),                        # 8 parameters
)                   # Total: 4 arrays, 17 parameters, 324 bytes.

julia> fleaves(m)
6-element Vector{Any}:
 Float32[-0.0102046095 -0.28821245; 0.4982538 0.23464581; -0.70785844 0.3291903]
 Float32[0.0, 0.0, 0.0]
 relu (generic function with 2 methods)
 Float32[0.57762665 -0.8608131 -0.5159058; -0.54350173 0.61605966 0.8265723]
 Float32[0.0, 0.0]
 identity (generic function with 1 method)

return Iterators.flatten(_map(recurse, func, yfuncs...))
x_children = children(x)
ys_children = map(children, ys)
return Iterators.flatten(_map(recurse, x_children, ys_children...))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no functional changes here, only improved clarity

@darsnack
Copy link
Member

darsnack commented Mar 9, 2024

Implementation looks good and I'm on board with adding something like this. Only thing is that this isn't jtu.tree_flatten. If it were, it should return the analog to a tree def as well. I would say jtu.tree_flatten is more like Optimisers.restructure except without concatenating the leaves.

It'd be nice to have something like a real jtu.tree_flatten, but for now I suggest renaming this to fleaves to match jtu.tree_leaves—which is what this actually is.

@CarloLucibello CarloLucibello changed the title add function fflatten add function fleaves Mar 9, 2024
@CarloLucibello
Copy link
Member Author

Changed name to fleaves

@CarloLucibello
Copy link
Member Author

this is ready to go

@CarloLucibello CarloLucibello merged commit 6778507 into master Mar 11, 2024
6 of 7 checks passed
@CarloLucibello CarloLucibello deleted the cl/fflatten branch April 2, 2024 12:39
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

Successfully merging this pull request may close these issues.

2 participants