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

Allow gradients in fmap #1

Merged
merged 15 commits into from
Nov 21, 2021
23 changes: 23 additions & 0 deletions src/functor.jl
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,24 @@ end

isleaf(x) = functor(x)[1] === ()

# for Chain
function functor_tuple(f, x::Tuple, dx::Tuple)
Copy link
Member

Choose a reason for hiding this comment

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

I don't think x is a tuple

Suggested change
function functor_tuple(f, x::Tuple, dx::Tuple)
function functor_tuple(f, x, dx::Tuple)

map(x, dx) do x, x̄
fmap1(f, x, x̄)
end
end
functor_tuple(f, x, dx) = f(x, dx)
functor_tuple(f, x, ::Nothing) = x

# @functor Chain
# Chain -> func = (layers = (Dense,Dense),), gs -> (layers...)
function fmap1(f, x, dx)
func, re = functor(x)
map(func, dx) do x, x̄
functor_tuple(f, x, x̄)
end |> re
end

function fmap1(f, x)
func, re = functor(x)
re(map(f, func))
Expand All @@ -36,3 +54,8 @@ function fmap(f, x; cache = IdDict())
haskey(cache, x) && return cache[x]
cache[x] = isleaf(x) ? f(x) : fmap1(x -> fmap(f, x, cache = cache), x)
end

DhairyaLGandhi marked this conversation as resolved.
Show resolved Hide resolved
function fmap(f, x, dx...; cache = IdDict())
haskey(cache, x) && return cache[x]
cache[x] = isleaf(x) ? f(x, dx...) : fmap1((x...) -> fmap(f, x..., cache = cache), x, dx...)
end