Skip to content

Commit

Permalink
fix view & its zero-arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
mcabbott committed Aug 9, 2022
1 parent ad8a5f5 commit 93e05b4
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/rulesets/Base/indexing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ function rrule(::typeof(getindex), x::Tuple, ::Colon)
return x, getindex_back_4
end


#####
##### getindex(::AbstractArray)
#####
Expand Down Expand Up @@ -174,6 +173,15 @@ function rrule(::typeof(view), x::AbstractArray, inds...)
return view(x, inds...), view_pullback
end

function rrule(::typeof(view), x::AbstractArray, i::Integer, jkl::Integer...)
# This case returns a zero-dim array, unlike getindex. So we fool ∇getindex:
function view_pullback_0(dy)
nots = map(Returns(NoTangent()), (i, jkl...))
return (NoTangent(), thunked∇getindex(x, dy, i:i, jkl...), nots...)
end
return view(x, i, jkl...), view_pullback_0
end

#####
##### setindex!
#####
Expand Down
1 change: 1 addition & 0 deletions test/rulesets/Base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,7 @@ end
@test [5 0; 6 0] == @inferred unthunk(rrule(findmin, [1 2; 3 4], dims=2)[2]((hcat([5,6]), nothing))[2])
test_rrule(findmin, rand(3,4), fkwargs=(dims=1,), output_tangent = (rand(1,4), NoTangent()))
test_rrule(findmin, rand(3,4), fkwargs=(dims=2,))
test_rrule(findmin, rand(3,4), fkwargs=(dims=(1,2),))
end

@testset "$imum" for imum in [maximum, minimum]
Expand Down
2 changes: 1 addition & 1 deletion test/rulesets/Base/indexing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ end

test_rrule(view, rand(3, 4), :, 1)
test_rrule(view, rand(3, 4), 2, [1, 1, 2])
@test_broken test_rrule(view, rand(3, 4), 3, 4) # This is why ∇getindex needs one more argument, dammit
test_rrule(view, rand(3, 4), 3, 4)
end

@testset "setindex!" begin
Expand Down

0 comments on commit 93e05b4

Please sign in to comment.