JuliaDiff / ForwardDiff.jl

Forward Mode Automatic Differentiation for Julia
Other
894 stars 148 forks source link

Bug (NaNs) when differentiating eigenvectors of Symmetric matrices #684

Open mesonepigreco opened 9 months ago

mesonepigreco commented 9 months ago

Hello, I noticed at a certain point my code started to crash because of some NaNs introduced by Forward diff when performing derivatives of the eigenvectors of matrix.

Here was my previous code (it was working at a certain point):

 function buggy(x)
       mat = zeros(eltype(x),(2, 2))
       mat[1,1] = x[1]
       mat[1,2] = x[2]
       mat[2,1] = x[2]
       mat[2,2] = x[3]
       (ω, pols) = eigen(Symmetric(mat))
       return pols
end

When differentiating with:

julia> vv = [82.62687031649999 0.0 82.62687031649999]
julia> ForwardDiff.jacobian(buggy, vv)
4×3 Matrix{Float64}:
 NaN  NaN   NaN
 NaN  -Inf  NaN
 NaN   Inf  NaN
 NaN  NaN   NaN

However, if I remove the specification that the matrix must be Symmetric, then it works.

function good(x)
       mat = zeros(eltype(x),(2, 2))
       mat[1,1] = x[1]
       mat[1,2] = x[2]
       mat[2,1] = x[2]
       mat[2,2] = x[3]
       (ω, pols) = eigen(mat)
       return pols
end
julia> ForwardDiff.jacobian(good, vv)
4×3 Matrix{Float64}:
 0.0  0.0  0.0
 0.0  0.0  0.0
 0.0  0.0  0.0
 0.0  0.0  0.0

I remember I had to specify Symmetric because, at a certain point, ForwardDiff was working only with that (I do not remember exactly).

dleather commented 3 months ago

Im getting this issues too.