Repository navigation
Open
Description
After #481 , ishermitian is now broken (maybe other methods too?) when working with ForwardDiff.Dual.
julia> Pkg.status()
Status `/tmp/jl_gs3tnK/Project.toml`
[f6369f11] ForwardDiff v0.10.33
[37e2e46d] LinearAlgebra
julia> using LinearAlgebra, ForwardDiff
julia> x = [1 0.5; 0.5 1]
2×2 Matrix{Float64}:
1.0 0.5
0.5 1.0
julia> ishermitian(x)
true
julia> f(x) = sum(cholesky(reshape(x, 2, 2)))
f (generic function with 1 method)
julia> ForwardDiff.gradient(vec(x))
ERROR: MethodError: no method matching gradient(::Vector{Float64})
Closest candidates are:
gradient(::Any, ::StaticArraysCore.StaticArray) at ~/.julia/packages/ForwardDiff/eqMFf/src/gradient.jl:44
gradient(::Any, ::StaticArraysCore.StaticArray, ::ForwardDiff.GradientConfig) at ~/.julia/packages/ForwardDiff/eqMFf/src/gradient.jl:45
gradient(::Any, ::StaticArraysCore.StaticArray, ::ForwardDiff.GradientConfig, ::Val) at ~/.julia/packages/ForwardDiff/eqMFf/src/gradient.jl:46
...
Stacktrace:
[1] top-level scope
@ REPL[10]:1
julia> ForwardDiff.gradient(f, vec(x))
ERROR: PosDefException: matrix is not Hermitian; Cholesky factorization failed.
Stacktrace:
[1] checkpositivedefinite(info::Int64)
@ LinearAlgebra /opt/julia-1.8.2/share/julia/stdlib/v1.8/LinearAlgebra/src/factorization.jl:18
[2] cholesky!(A::Matrix{ForwardDiff.Dual{ForwardDiff.Tag{typeof(f), Float64}, Float64, 4}}, ::NoPivot; check::Bool)
@ LinearAlgebra /opt/julia-1.8.2/share/julia/stdlib/v1.8/LinearAlgebra/src/cholesky.jl:299
[3] #cholesky#162
@ /opt/julia-1.8.2/share/julia/stdlib/v1.8/LinearAlgebra/src/cholesky.jl:402 [inlined]
[4] cholesky (repeats 2 times)
@ /opt/julia-1.8.2/share/julia/stdlib/v1.8/LinearAlgebra/src/cholesky.jl:402 [inlined]
[5] f(x::Vector{ForwardDiff.Dual{ForwardDiff.Tag{typeof(f), Float64}, Float64, 4}})
@ Main ./REPL[9]:1
[6] vector_mode_dual_eval!
@ ~/.julia/packages/ForwardDiff/eqMFf/src/apiutils.jl:37 [inlined]
[7] vector_mode_gradient(f::typeof(f), x::Vector{Float64}, cfg::ForwardDiff.GradientConfig{ForwardDiff.Tag{typeof(f), Float64}, Float64, 4, Vector{ForwardDiff.Dual{ForwardDiff.Tag{typeof(f), Float64}, Float64, 4}}})
@ ForwardDiff ~/.julia/packages/ForwardDiff/eqMFf/src/gradient.jl:106
[8] gradient(f::Function, x::Vector{Float64}, cfg::ForwardDiff.GradientConfig{ForwardDiff.Tag{typeof(f), Float64}, Float64, 4, Vector{ForwardDiff.Dual{ForwardDiff.Tag{typeof(f), Float64}, Float64, 4}}}, ::Val{true})
@ ForwardDiff ~/.julia/packages/ForwardDiff/eqMFf/src/gradient.jl:19
[9] gradient(f::Function, x::Vector{Float64}, cfg::ForwardDiff.GradientConfig{ForwardDiff.Tag{typeof(f), Float64}, Float64, 4, Vector{ForwardDiff.Dual{ForwardDiff.Tag{typeof(f), Float64}, Float64, 4}}}) (repeats 2 times)
@ ForwardDiff ~/.julia/packages/ForwardDiff/eqMFf/src/gradient.jl:17
[10] top-level scope
@ REPL[11]:1This is because now the A[i,j] != adjoint(A[j,i]) check performed in ishermitian returns true.
Metadata
Metadata
Assignees
Labels
No labels
Activity
devmotion commentedon Nov 11, 2022
Maybe #481 should have been put in a breaking release after all. Maybe it would be safer to revert it and then prepare a breaking release with it?
mcabbott commentedon Nov 11, 2022
I'm sorry it broke things, but I think this is the intention.
While
xreally is Hermitian,x .+ Dual.(0, rand.())represents a small perturbation aroundx, and most such perturbed matrices will not be Hermitian. Using an algorithm which assumes they are will tend to give zero gradients in some directions. This seems exactly analogous to checkingdet(x) == 0etc.Hermitian(x .+ Dual.(0, rand.()))is of course still Hermitian, and has fewer independent directions of perturbation.torfjelde commentedon Nov 11, 2022
I'm with you on this, but at the same time it seems quite detrimental that we no longer can compute the gradient through methods such as
choleskyusing ForwardDiff.jl.EDIT: Am aware that we can just do
check=false, but still seems quite annoying in practice 😕torfjelde commentedon Nov 11, 2022
I see there has been quite extensive discussions about this change, so I'll stop complaining about some of the resulting inconvenience 👍
But do we have an idea of what's the best approach to deal with all of the downstream beaking code?
devmotion commentedon Nov 11, 2022
I'm with you regarding this argument. But I think it is problematic that 1) such a major change is released in a non-breaking release and breaks many downstream packages and applications and 2) it seems this is inconsistent with e.g. ChainRules which allows to compute derivatives of
cholesky(::StridedMatrix): https://github.com/JuliaDiff/ChainRules.jl/blob/1f4a8a9d86c79f024a911f61aa180bdc094bb8a3/src/rulesets/LinearAlgebra/factorization.jl#L491mcabbott commentedon Nov 11, 2022
That's a lot of plurals, but so far one link. Is the problem only
cholesky?Are there any examples where
choleskyis used by some meta-algorithm behind a check likeishermitian, or must it always be explicitly called? Knowingly calling it should perhaps be regarded as an assertion that you wish to constrainxto the subspace, like writingHermitian(x).A nearby example of checks working as intended is:
torfjelde commentedon Nov 12, 2022
I think it's fair to assume that this one particular test is not the only case where people are using ForwardDiff + cholesky, even if you exclude all the Turing-models using
Wishart(of which I know there are way more than just this one test).I'm a bit uncertain what you're asking here tbh. But I think it all just comes down to the following question: do you not think we should be able to differentiate through
cholesky?If yes, then we need
checkpositivedefiniteto returntrueifvalue.(x)is PD. Yes, you can wrap it inHermitian, or just passcheck=false, but that implies that you know it's Hermitian, meaning that, unless you constructed the matrix yourself, you need to callcheckpositivedefinitefirst.mcabbott commentedon Nov 12, 2022
I went looking and found many checks of what algorithm to use based on
istruietc. I am literally asking whether there are such paths which useishermitianand lead tocholesky. In LinearAlgebra or elsewhere. And if there are, whether they have additional non-error paths for generic matrices.I ask this to get an idea of the lay of the land, since probably you know this better. I have never wanted to have anything to do with
choleskyexcept for fixing problems like this.Maybe? I have not formed a very clear opinion.
Not obviously. We could also have a method like
cholesky(::AbstractArray{Dual})which does not check.Overloading
isposdeforishermitianto always ignore Dual means that things unrelated to Cholesky will get those versions.Yes. I think the question is what should happen if this matrix (which you didn't construct yourself) is not positive definite. Do you want an error? Or is there another path in your function?
If there is another path, then the claim of 481 is that AD ought to take that. Your function knows about dimensions outside of Hermitian, and AD ought to see them. The check is simply about what algorithm to use internally, not part of your function's contract.
If there is no other path, and the domain of your function is Hermitian matrices, it just happens to accept Matrix as a convenience. Then I guess it makes more sense to project the gradient onto that subspace.
The awkward thing is that I don't think it's easy for ForwardDiff to distinguish these situations. Is this "if" statement choosing an algorithm, or checking that input is legal?
The one clean way seems to be to push this to the type level. Don't check
isinteger(x)inside a function and throw, rather define the function for::Integerand let Julia throw a MethodError for you, is the idiom. But presumably it's hard to teach the whole world to callcholesky(Hermitian(x)).devmotion commentedon Nov 12, 2022
Maybe the cleanest and safest way would be to just fix and implement
choleskysimilar to ChainRules (which was also was ForwardDiff returned in previous versions), and only turn to more general approaches - which possibly could have other side effects - if it turns out that it is really needed?Not being able to use
cholesky(x)with ForwardDiff andx::StridedMatrixis a major issue for Turing and anyone who wants to usecholesky, so maybe we should not try to come up with a solution to every possible issue aroundcholeskybut just fix these regressions or revert the PR.ChainRules (and hence also Zygote) already decided how to handle these cases. A comparison of ForwardDiff 0.10.32, 0.10.33, and ChainRules/Zygote:
ForwardDiff 0.10.32:
ForwardDiff 0.10.33:
ChainRules 1.45.0:
Zygote 0.6.49:
Interestingly, FiniteDifferences is broken for all examples (errors or returns incorrect gradients).
FiniteDifferences :
There is an open issue that discusses issues with positive semi-definite matrices (JuliaDiff/FiniteDifferences.jl#52).
mcabbott commentedon Nov 12, 2022
One idea is to overload
ishermitianwith some kind of dep-warn which does the old thing, and tells you to put Hermitian there in future.To try this out.. the example in the top message doesn't work on any version, as the function doesn't make a scalar. Here's a version of it, and comparison to finite differences:
Looking for what else depends on
ishermitian, here's another example with a matrix function. Notice that the old gradient from ForwardDiff has a zero, where FiniteDifferences instead produces the matrix symmetrised.Notice also that inserting
Hermitianwrapper here does not send ForwardDiff down a path it can handle, and never did so.mcabbott commentedon Nov 12, 2022
That's a lot of text, note that your
fis different from the first message'sf.No,
FiniteDifferences.grad(fdm, g, x)is returning the same result as pre-481 ForwardDiff.I believe it is broken when it has
Hermitian(x)as an argument. In my example immediately above, this makes a Hermitian and writes into it, rather than projecting onto the symmetric space:At least this is wrong for reverse-mode AD, cotangents. I am less than 100% sure it's wrong for forward mode, tangents.
mcabbott commentedon Nov 12, 2022
Does this work? I am a little concerned it's going to introduce ambiguities. Also not sure it covers all cases:
torfjelde commentedon Nov 14, 2022
The reason why I didn't mention this approach is because I was thinking the same :/ Seems doomed to introduce a bunch of ambiguities given the amount of
AbstractArrayimpl floating around. But I don't currently see a better approach..torfjelde commentedon Nov 14, 2022
Ah gotcha!
choleskyis used heavily (and explicitly) in many implementations of distributions, and there are many use-cases where you want to be able to differentiate both wrt. realizations and the parameter of a distribution (any gradient-based sampler, MLE/MAP, etc.). And in these cases, you're usually updating these values, and so you're not being able to guarantee that the resulting matrix is Hermitian at any given time, i.e. you cannot just docholesky(Hermitian(x))orcholesky(x, check=false), unfortunately.mcabbott commentedon Nov 14, 2022
Not a very careful check, but with the above code, I wasn't sure whether Diagonal{Dual} would be ambiguous. But it seems not to be:
devmotion commentedon Apr 9, 2025
I just ran into this again - when debugging a bug on [email protected] 😄 I ran
On [email protected] this gives
And on ForwardDiff@1:
So ForwardDiff@1 fixed the inconsistency, but currently that's not very helpful for me 😄
(Maybe #589 would have helped to fix the
lmul!/*bug on [email protected])Of course, once I realized why and when it failed I could fix it on ForwardDiff@1 on my side:
But it doesn't help me on [email protected] which is my actual problem until the whole ecosystem has moved to ForwardDiff@1...
Found a workaround on [email protected] (which is the more obvious code anyways, but this comes from a package that I use):
Makes you distrust your AD systems though when you hit such bugs in such basic functionality...