-
Notifications
You must be signed in to change notification settings - Fork 31
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
Accumulate NamedTuple + Tangent #88
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,11 +5,25 @@ struct DiffractorRuleConfig <: RuleConfig{Union{HasReverseMode,HasForwardsMode}} | |
@Base.constprop :aggressive accum(a::Tuple, b::Tuple) = map(accum, a, b) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I get some errors from this adding tuples of mis-matched lengths, which I haven't tracked down. Not touched in this PR. What I don't know here is whether |
||
@Base.constprop :aggressive @generated function accum(x::NamedTuple, y::NamedTuple) | ||
fnames = union(fieldnames(x), fieldnames(y)) | ||
isempty(fnames) && return :((;)) # code below makes () instead | ||
gradx(f) = f in fieldnames(x) ? :(getfield(x, $(quot(f)))) : :(ZeroTangent()) | ||
grady(f) = f in fieldnames(y) ? :(getfield(y, $(quot(f)))) : :(ZeroTangent()) | ||
Expr(:tuple, [:($f=accum($(gradx(f)), $(grady(f)))) for f in fnames]...) | ||
end | ||
@Base.constprop :aggressive accum(a, b, c, args...) = accum(accum(a, b), c, args...) | ||
@Base.constprop :aggressive accum(a::NoTangent, b) = b | ||
@Base.constprop :aggressive accum(a, b::NoTangent) = a | ||
@Base.constprop :aggressive accum(a::NoTangent, b::NoTangent) = NoTangent() | ||
@Base.constprop :aggressive accum(a::AbstractZero, b) = b | ||
@Base.constprop :aggressive accum(a, b::AbstractZero) = a | ||
@Base.constprop :aggressive accum(a::AbstractZero, b::AbstractZero) = NoTangent() | ||
|
||
using ChainRulesCore: Tangent, backing | ||
|
||
function accum(x::Tangent{T}, y::NamedTuple) where T | ||
# @warn "gradient is both a Tangent and a NamedTuple" x y | ||
_tangent(T, accum(backing(x), y)) | ||
end | ||
accum(x::NamedTuple, y::Tangent) = accum(y, x) | ||
# This solves an ambiguity, but also avoids Tangent{ZeroTangent}() which + does not: | ||
accum(x::Tangent{T}, y::Tangent) where T = _tangent(T, accum(backing(x), backing(y))) | ||
|
||
_tangent(::Type{T}, z) where T = Tangent{T,typeof(z)}(z) | ||
_tangent(::Type, ::NamedTuple{()}) = NoTangent() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is JuliaDiff/ChainRulesCore.jl#581 now