Skip to content

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

Open

Description

@mesonepigreco

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).

Activity

  1. dleather commented on Jul 26, 2024

    @dleather

    Im getting this issues too.

  2. yucheng-du commented on Dec 2, 2026

    @yucheng-du

    At the values in the example the matrix is exactly a*I, so both eigenvalues are a = 82.62687031649999. There is no unique first eigenvector at that point. For example, these two symmetric matrices approach the same input:

    q(A) = eigen(Symmetric(A)).vectors[:, 1]
    abs(dot(q([a-h 0; 0 a+h]), q([a h; h a])))

    The result was 0.70710678 for h from 1.0 down to 1e-10. The directions stay 45° apart, even allowing for an eigenvector sign flip. A zero Jacobian from the unwrapped call would also be misleading. On Julia 1.13.4 and ForwardDiff 1.5.0 the unwrapped call gives a MethodError.

    If the calculation needs the two modes together, an invariant such as tr(A) has a well-defined gradient ([1, 0, 1] for your three inputs). For an isolated mode, differentiating q*q' avoids sign flips. I compared that derivative to central differences on 36 matrices with distinct eigenvalues, with agreement in all three input directions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions