Skip to content
Closed
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
18 changes: 18 additions & 0 deletions src/lib/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,24 @@ end
(Ā, )
end

@adjoint function LinearAlgebra.eigen(A::AbstractMatrix)
eV = eigen(A)
e,V = eV
n = size(A,1)
eV, function (Δ)
Δe, ΔV = Δ
if ΔV === nothing
(inv(V)'*Diagonal(Δe)*V', )
elseif Δe === nothing
F = [i==j ? 0 : inv(e[j] - e[i]) for i=1:n, j=1:n]
(inv(V)'*(F .* (V'ΔV))*V', )
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this is more gpu friendly

F = inv.(e .- e')
F[diagind(F)] .= 0

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was struggling to find the solution you hinted at with diagind, thanks!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if it is safe to divide by zero on the gpu or it could throw an error

else
F = [i==j ? 0 : inv(e[j] - e[i]) for i=1:n, j=1:n]
(inv(V)'*(Diagonal(Δe) + F .* (V'ΔV))*V', )
end
end
end

Zygote.@adjoint function LinearAlgebra.tr(x::AbstractMatrix)
# x is a squre matrix checked by tr,
# so we could just use Eye(size(x, 1))
Expand Down
12 changes: 12 additions & 0 deletions test/gradcheck.jl
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,18 @@ end
end
end

@testset "eigen" begin
rng, N = MersenneTwister(6865931), 8
for i = 1:5
A = randn(rng, N, N)
@test gradtest(A->abs.(eigen(A).values), A)
@test gradcheck(A) do A
e = eigen(A)
sum(real.(e.values)) + sum(real.(e.vectors))
end
end
end

using Distances

Zygote.refresh()
Expand Down