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

Rule for permutedims #559

Merged
merged 5 commits into from
Jan 12, 2022
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
25 changes: 25 additions & 0 deletions src/rulesets/Base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,34 @@ function rrule(::typeof(reshape), A::AbstractArray, dims::Union{Colon,Int}...)
return reshape(A, dims...), reshape_pullback
end

#####
##### `permutedims`
#####

function rrule(::typeof(permutedims), x::AbstractVector)
project = ProjectTo(x)
permutedims_pullback_1(dy) = (NoTangent(), project(permutedims(unthunk(dy))))
return permutedims(x), permutedims_pullback_1
end

function rrule(::typeof(permutedims), x::AbstractArray, perm)
project = ProjectTo(x)
iperm = invperm(perm)
sethaxen marked this conversation as resolved.
Show resolved Hide resolved
permutedims_pullback_2(dy) = (NoTangent(), project(permutedims(unthunk(dy), iperm)), NoTangent())
return permutedims(x, perm), permutedims_pullback_2
end

function rrule(::typeof(PermutedDimsArray), x::AbstractArray, perm)
project = ProjectTo(x)
iperm = invperm(perm)
permutedims_pullback_3(dy) = (NoTangent(), project(permutedims(unthunk(dy), iperm)), NoTangent())
return PermutedDimsArray(x, perm), permutedims_pullback_3
end

#####
##### `repeat`
#####

function rrule(::typeof(repeat), xs::AbstractArray; inner=ntuple(Returns(1), ndims(xs)), outer=ntuple(Returns(1), ndims(xs)))

project_Xs = ProjectTo(xs)
Expand Down
12 changes: 12 additions & 0 deletions test/rulesets/Base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,18 @@ end
test_rrule(reshape, rand(4, 5), 2, :)
end

@testset "permutedims + PermutedDimsArray" begin
test_rrule(permutedims, rand(5))
test_rrule(permutedims, rand(3, 4), (2, 1))
@test invperm((3, 1, 2)) != (3, 1, 2)
test_rrule(permutedims, rand(3, 4, 5), (3, 1, 2))

@test_skip test_rrule(PermutedDimsArray, rand(3, 4, 5), (3, 1, 2))
x = rand(2, 3, 4)
dy = rand(4, 2, 3)
@test rrule(permutedims, x, (3, 1, 2))[2](dy)[2] == rrule(PermutedDimsArray, x, (3, 1, 2))[2](dy)[2]
end

@testset "repeat" begin

test_rrule(repeat, rand(4, ))
Expand Down