Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type instability in jacobian! filling JacobianResult when using StaticArrays #639

Open
mapclyps opened this issue Apr 17, 2023 · 3 comments

Comments

@mapclyps
Copy link

Running the following code

using ForwardDiff
using StaticArrays

f(x)=SA[x[1]^2+x[2]^2, x[2]^2+x[3]^2]

x=SA[1.0,2,3]

y=f(x)

imdr=DiffResults.JacobianResult(y,x)

@code_warntype ForwardDiff.jacobian!(imdr,f,x) 

shows up as not type stable for me in Julia 1.8.5.
Maybe also related is this older topic on discourse https://discourse.julialang.org/t/am-i-using-diffresults-jl-correctly/35894

I think it is coming from

result = DiffResults.value!(d -> value(T,d), result, ydual)

Replacing the anonymous function d -> value(T,d) with Base.Fix1(value,T) fixes it for me.
I can make a PR in case this is the desired solution.

@mcabbott
Copy link
Member

Base.Fix1(value,T) fixes it for me.

This seems completely safe, a PR would be great.

mapclyps added a commit to mapclyps/ForwardDiff.jl that referenced this issue Apr 19, 2023
Replace an anonymous function with Base.Fix1 for type stability in some cases, see JuliaDiff#639
@ojwoodford
Copy link

Possibly related.

@mapclyps
Copy link
Author

I was trying to write a test for my proposed fix, but it did not have an inference issue in the tests. It seems like it depends on whether something else is executed before.

using ForwardDiff
using StaticArrays
using Test

sx = @SArray rand(3,3)
addone(A) = A.+one(eltype(A))
sy = addone(sx)

sresult = DiffResults.JacobianResult(sy, sx)
ff(A)=sin.(A)

@inferred ForwardDiff.jacobian!(sresult, ff, sx) #throws the error (type instability) as reported
@inferred ForwardDiff.jacobian!(sresult, addone, sx) #no error 

Swapping the last two lines, interestingly, removes the error entirely.
It seems that there is some hidden state or something?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants