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

Unthunk each element in ∇eachslice #814

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
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
8 changes: 5 additions & 3 deletions src/rulesets/Base/indexing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -262,20 +262,22 @@ end
# Using Val(dim) here is worth a factor of 2 in this, on Julia 1.8-
# @btime rrule(eachcol, $([1 2; 3 4]))[2]($([[10, 20], [30, 40]]))
function ∇eachslice(dys_raw, x::AbstractArray, vd::Val{dim}) where {dim}
dys = unthunk(dys_raw)
dys = unthunk.(unthunk(dys_raw))
i1 = findfirst(dy -> dy isa AbstractArray, dys)
if i1 === nothing # all slices are Zero!
return _zero_fill!(similar(x, float(eltype(x)), axes(x)))
end

T = Base.promote_eltype(dys...)
# The whole point of this gradient is that we can allocate one `dx` array:
dx = similar(x, T, axes(x))
for i in axes(x, dim)
slice = selectdim(dx, dim, i)
if dys[i] isa AbstractZero
dy = dys[i]
if dy isa AbstractZero
_zero_fill!(slice) # Avoids this: copyto!([1,2,3], ZeroTangent()) == [0,2,3]
else
copyto!(slice, dys[i])
copyto!(slice, dy)
end
end
return ProjectTo(x)(dx)
Expand Down
Loading