diff --git a/src/host/linalg.jl b/src/host/linalg.jl index 4373f655..324a1962 100644 --- a/src/host/linalg.jl +++ b/src/host/linalg.jl @@ -105,12 +105,13 @@ function transpose_f!(f, B::AnyGPUMatrix{T}, A::AnyGPUMatrix{T}) where T B end -function Base.copyto!(A::AbstractGPUArray{T,N}, B::Adjoint{T, <: AbstractGPUArray{T,N}}) where {T,N} - adjoint!(A, B.parent) -end - -function Base.copyto!(A::AbstractGPUArray{T,N}, B::Transpose{T, <: AbstractGPUArray{T,N}}) where {T,N} - transpose!(A, B.parent) +# `copyto!` copies all of the source in linear order into the leading elements of a +# destination of any shape. Only when the shapes match can the wrapper be applied in place. +for (W, f!) in ((:Adjoint, :adjoint!), (:Transpose, :transpose!)) + @eval function Base.copyto!(A::AbstractGPUArray{T,N}, B::$W{T, <:AbstractGPUArray{T,N}}) where {T,N} + axes(A) == axes(B) && return $f!(A, parent(B)) + copyto!(A, 1, Base.unalias(A, B), 1, length(B)) + end end function Base.copyto!(A::Array{T,N}, B::Adjoint{T, <:AbstractGPUArray{T,N}}) where {T,N} diff --git a/test/testsuite/linalg.jl b/test/testsuite/linalg.jl index 0cff5223..d0cc97a4 100644 --- a/test/testsuite/linalg.jl +++ b/test/testsuite/linalg.jl @@ -21,6 +21,22 @@ if ComplexF32 in eltypes @test compare(adjoint!, AT, rand(ComplexF32, 70, 45), rand(ComplexF32, 45, 70)) end + + # like Base, `copyto!` copies all of the wrapped source in linear order into the + # leading elements of a destination of any shape + @testset "copyto! from $f of a differently-shaped source" for f in (adjoint, transpose) + copy_wrapped!(x, y) = copyto!(x, f(y)) + @test compare(copy_wrapped!, AT, rand(Float32, 0), rand(Float32, 0)) + @test compare(copy_wrapped!, AT, rand(Float32, 40), rand(Float32, 32)) + @test compare(copy_wrapped!, AT, rand(Float32, 2, 3), rand(Float32, 2, 2)) + @test compare(copy_wrapped!, AT, rand(Float32, 70, 50), rand(Float32, 45, 70)) + if ComplexF32 in eltypes + @test compare(copy_wrapped!, AT, rand(ComplexF32, 32), rand(ComplexF32, 32)) + @test compare(copy_wrapped!, AT, rand(ComplexF32, 3, 3), rand(ComplexF32, 2, 3)) + end + @test_throws BoundsError copyto!(AT(rand(Float32, 2, 1)), f(AT(rand(Float32, 2, 2)))) + @test compare(x -> copyto!(x, f(x)), AT, rand(Float32, 2, 3)) + end end @testset "tr" begin