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 rrule for NamedTuple merge #795

Merged
merged 4 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/rulesets/Base/base.jl
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,25 @@ function rrule(config::RuleConfig{>:HasReverseMode}, ::typeof(task_local_storage
end
return y, task_local_storage_pullback
end


oxinabox marked this conversation as resolved.
Show resolved Hide resolved
####
#### merge
####

function rrule(::typeof(merge), nt1::NamedTuple{F1}, nt2::NamedTuple{F2}) where {F1, F2}
oxinabox marked this conversation as resolved.
Show resolved Hide resolved
y = merge(nt1, nt2)
function merge_pullback(dy)
dnt1 = Tangent{typeof(nt1)}(;
(f1 => (f1 in F2 ? ZeroTangent() : getproperty(dy, f1)) for f1 in F1)...
)
dnt2 = Tangent{typeof(nt2)}(;
(f2 => getproperty(dy, f2) for f2 in F2)...
)
oxinabox marked this conversation as resolved.
Show resolved Hide resolved
return (NoTangent(), dnt1, dnt2)
end
merge_pullback(dy::AbstractThunk) = merge_pullback(unthunk(dy))
merge_pullback(x::AbstractZero) = (NoTangent(), x, x)

oxinabox marked this conversation as resolved.
Show resolved Hide resolved
return y, merge_pullback
end
5 changes: 5 additions & 0 deletions test/rulesets/Base/base.jl
Original file line number Diff line number Diff line change
Expand Up @@ -257,4 +257,9 @@ end
test_rrule(map, Multiplier(4.5), (6.7, 8.9), (0.1, 0.2, 0.3), check_inferred=false)
end
end

@testset "merge NamedTuple" begin
test_rrule(merge, (;a=1.0), (;b=2.0), check_inferred=false)
test_rrule(merge, (;a=1.0), (;a=2.0), check_inferred=false)
oxinabox marked this conversation as resolved.
Show resolved Hide resolved
end
end
Loading