Skip to content

Gradients for batched_adjoint etc. #272

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

Merged
merged 3 commits into from
Jan 20, 2021
Merged
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions src/batched/batchedadjtrans.jl
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,12 @@ end
Base.unsafe_convert(::Type{Ptr{T}}, A::BatchedAdjOrTrans{T}) where {T} =
Base.unsafe_convert(Ptr{T}, parent(A))

# Gradients
function ChainRulesCore.rrule(::typeof(batched_transpose), A::AbstractArray{<:Any,3})
b_transpose_back(Δ) = (NO_FIELDS, batched_transpose(Δ))
batched_transpose(A), b_transpose_back
end
function ChainRulesCore.rrule(::typeof(batched_adjoint), A::AbstractArray{<:Any,3})
b_adjoint_back(Δ) = (NO_FIELDS, batched_adjoint(Δ))
batched_adjoint(A), b_adjoint_back
end
8 changes: 7 additions & 1 deletion test/batchedmul.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using NNlib, Test, LinearAlgebra
using NNlib: storage_type, storage_typejoin, is_strided,
batched_mul!, _unbatch, _copy_if_faster, BatchedAdjoint
batched_mul!, _unbatch, _copy_if_faster,
BatchedAdjoint, BatchedTranspose

function bmm_test(a,b; transA = false, transB = false)
bs = size(a,3)
Expand Down Expand Up @@ -232,9 +233,14 @@ end

end

FiniteDifferences.to_vec(x::BatchedAdjoint) = FiniteDifferences.to_vec(collect(x))
FiniteDifferences.to_vec(x::BatchedTranspose) = FiniteDifferences.to_vec(collect(x))

@testset "AutoDiff" begin
M, P, Q = 13, 7, 11
B = 3
gradtest(batched_mul, randn(rng, M, P, B), randn(rng, P, Q, B))
gradtest(batched_mul, batched_adjoint(randn(rng, P, M, B)), randn(rng, P, Q, B))
gradtest(batched_mul, randn(rng, M, P, B), batched_transpose(randn(rng, Q, P, B)))
end