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
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "FiniteDiff"
uuid = "6a86dc24-6348-571c-b903-95158fe2bd41"
version = "2.33.0"
version = "2.33.1"

[deps]
ArrayInterface = "4fba245c-0d91-5ea0-9b3e-6abc04ee57a9"
Expand Down
23 changes: 17 additions & 6 deletions src/jvp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,11 @@ end
absstep = relstep)

Cache-less.

Neither `x` nor `f_in` is modified: the internally-built cache perturbs a copy of `x`,
and only reads `f_in`. Use the cached method with a `JVPCache` built by the
non-allocating `JVPCache(x1, fx1, fdtype)` constructor to opt into perturbing arrays
you own.
"""
function finite_difference_jvp!(jvp,
f,
Expand All @@ -238,12 +243,18 @@ function finite_difference_jvp!(jvp,
f_in = nothing;
relstep = default_relstep(fdtype, eltype(x)),
absstep = relstep)
if !isnothing(f_in)
cache = JVPCache(x, f_in, fdtype)
elseif fdtype == Val(:forward)
fx = zero(x)
f(fx, x)
cache = JVPCache(x, fx, fdtype)
if fdtype == Val(:forward)
if isnothing(f_in)
fx = zero(x)
f(fx, x)
else
fx = f_in
end
cache = JVPCache(copy(x), fx, fdtype)
elseif !isnothing(f_in)
# f_in is unusable for a non-forward difference, but it does pin down the
# size of the function output, which `JVPCache(x, fdtype)` has to guess.
cache = JVPCache(copy(x), zero(f_in), fdtype)
else
cache = JVPCache(x, fdtype)
end
Expand Down
23 changes: 23 additions & 0 deletions test/cache_reuse_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -159,4 +159,27 @@ end
end
end

# Aliasing x into the internally-built cache also broke :central-with-f_in numerically:
# the second evaluation landed back on x instead of x + ϵv, halving the answer.
@testset "cache-less JVP does not mutate the caller's x" begin
sq!(y, x) = (y[1] = x[1]^2 + x[2]; y[2] = x[1] * x[2]; y)
x_ref = [1.0, 2.0]
v = [1.0, 0.5]
jvp_ref = [2x_ref[1] 1.0; x_ref[2] x_ref[1]] * v
f_in = sq!(zeros(2), x_ref)

cases = ((Val(:forward), nothing), (Val(:forward), f_in),
(Val(:central), nothing), (Val(:central), f_in))

@testset "$(fdtype), f_in=$(fin0 !== nothing)" for (fdtype, fin0) in cases
x = copy(x_ref)
fin = fin0 === nothing ? nothing : copy(fin0)
jvp = zeros(2)
FiniteDiff.finite_difference_jvp!(jvp, sq!, x, v, fdtype, fin)
@test x == x_ref
fin === nothing || @test fin == f_in
@test jvp≈jvp_ref atol=1e-6
end
end

end # outer testset
Loading