Skip to content
Merged
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
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
Copy link
Member

@gdalle gdalle Apr 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A good strategy to catch more bugs like that would be to initialize all caches with randomized versions of x, y and friends in the test suite. That's how I caught it with DifferentiationInterface.

# 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