Skip to content

Commit

Permalink
Merge pull request #186 from JuliaDiff/hesscache
Browse files Browse the repository at this point in the history
Refresh Hessian caches on run
  • Loading branch information
ChrisRackauckas authored Apr 16, 2024
2 parents bf30a03 + b06e3e7 commit 6250778
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
6 changes: 6 additions & 0 deletions src/hessians.jl
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ function finite_difference_hessian!(H,f,x,

if inplace === Val(true)
_xpp, _xpm, _xmp, _xmm = xpp, xpm, xmp, xmm
copyto!(xpp,x)
copyto!(xpm,x)
copyto!(xmp,x)
copyto!(xmm,x)
else # ignore the cache since immutable
xpp, xpm, xmp, xmm = copy(x), copy(x), copy(x), copy(x)
end

for i = 1:n
Expand Down
16 changes: 12 additions & 4 deletions test/finitedifftests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -348,17 +348,17 @@ end
_g(x) = x[1]^2 + x[2]
_∇g(x) = [2x[1], 1.0]
x = [1.0, 3.0]
fx = _g(x)
fx = _g(x)
c1, c2 = zero(x), zero(x)
c3 = zero(x)
res = zero(x)
gcache = FiniteDiff.GradientCache{Float64, Vector{Float64}, Vector{Float64}, Vector{Float64}, Val(:forward), Float64, Val(false)}(fx, c1, c2, c3)
FiniteDiff.finite_difference_gradient!(res, _g, x, gcache)
@test res _∇g(x)
@test res _∇g(x)
x = [2.7, 1.0]
gcache = @set gcache.fx = _g(x)
FiniteDiff.finite_difference_gradient!(res, _g, x, gcache)
@test res _∇g(x)
@test res _∇g(x)
end

# Jacobian tests
Expand Down Expand Up @@ -488,7 +488,7 @@ f_in = oopf(x)
@test err_func(FiniteDiff.finite_difference_jacobian(oopf, x, complex_cache), J_ref) < 1e-14
end

# Test default colorvec construction
# Test default colorvec construction
θ = rand(2)
y0 = rand(1)
cache = FiniteDiff.JacobianCache(copy(θ), copy(y0), copy(y0), Val(:forward))
Expand Down Expand Up @@ -540,3 +540,11 @@ Base.getindex(x::ImmutableVector, i::Integer) = x.x[i]
@test J Matrix(I, 2, 2)
end
end

@testset "Hessian Cache test" begin
# https://github.com/JuliaDiff/FiniteDiff.jl/issues/185
f(x) = sum(abs2, x)
x1, x2 = float.(1:4), float.(5:8);
@test FiniteDiff.finite_difference_hessian(f, x1, FiniteDiff.HessianCache(x1)) == Diagonal(2*ones(4))
@test FiniteDiff.finite_difference_hessian(f, x1, FiniteDiff.HessianCache(x2)) == Diagonal(2*ones(4))
end

0 comments on commit 6250778

Please sign in to comment.