Skip to content

improve performance of hessians with static arrays #751

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
12 changes: 11 additions & 1 deletion ext/ForwardDiffStaticArraysExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module ForwardDiffStaticArraysExt
using ForwardDiff, StaticArrays
using ForwardDiff.LinearAlgebra
using ForwardDiff.DiffResults
using ForwardDiff: Dual, partials, GradientConfig, JacobianConfig, HessianConfig, Tag, Chunk,
using ForwardDiff: Dual, partials, Partials, GradientConfig, JacobianConfig, HessianConfig, Tag, Chunk,
gradient, hessian, jacobian, gradient!, hessian!, jacobian!,
extract_gradient!, extract_jacobian!, extract_value!,
vector_mode_gradient, vector_mode_gradient!,
Expand Down Expand Up @@ -81,6 +81,16 @@ end
end
end

@generated function extract_jacobian(::Type{T}, ydual::Partials{M}, x::S) where {M, T, S<:StaticArray}
N = length(x)
result = Expr(:tuple, [:(partials(T, ydual[$i], $j)) for i in 1:M, j in 1:N]...)
return quote
$(Expr(:meta, :inline))
V = StaticArrays.similar_type(S, valtype(eltype($ydual)), Size($M, $N))
return V($result)
end
end

@inline function ForwardDiff.vector_mode_jacobian(f::F, x::StaticArray) where {F}
T = typeof(Tag(f, eltype(x)))
return extract_jacobian(T, static_dual_eval(T, f, x), x)
Expand Down
9 changes: 9 additions & 0 deletions test/HessianTest.jl
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,13 @@ end
@test ForwardDiff.hessian(x->dot(x,H,x), zeros(3)) ≈ [2 6 10; 6 10 14; 10 14 18]
end

@testset "allocation-free hessian with StaticArrays" begin
#https://github.com/JuliaDiff/ForwardDiff.jl/issues/720
g = r -> (r[1]^2 - 3) * (r[2]^2 - 2)
x = SA_F32[0.5, 2.7]
hres = DiffResults.HessianResult(x)
ForwardDiff.hessian!(hres, g, x)
@test @allocated(ForwardDiff.hessian!(hres, g, x)) == 0
end

end # module
Loading