Skip to content

Commit a55adb1

Browse files
authored
Improve performance of derivative with FiniteDifferences and ForwardDiff (#97)
1 parent 1e20549 commit a55adb1

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

ext/AbstractDifferentiationFiniteDifferencesExt.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,9 @@ function AD.pullback_function(ba::AD.FiniteDifferencesBackend, f, xs...)
3232
end
3333
end
3434

35+
# Better performance: issue #87
36+
function AD.derivative(ba::AD.FiniteDifferencesBackend, f::TF, x::Real) where {TF<:Function}
37+
return (ba.method(f, x),)
38+
end
39+
3540
end # module

ext/AbstractDifferentiationForwardDiffExt.jl

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ AD.primal_value(x::AbstractArray{<:ForwardDiff.Dual}) = ForwardDiff.value.(x)
4141

4242
# these implementations are more efficient than the fallbacks
4343

44+
function AD.derivative(::AD.ForwardDiffBackend, f, x::Real)
45+
return (ForwardDiff.derivative(f, x),)
46+
end
47+
4448
function AD.gradient(ba::AD.ForwardDiffBackend, f, x::AbstractArray)
4549
cfg = ForwardDiff.GradientConfig(f, x, chunk(ba, x))
4650
return (ForwardDiff.gradient(f, x, cfg),)
@@ -50,7 +54,7 @@ function AD.jacobian(ba::AD.ForwardDiffBackend, f, x::AbstractArray)
5054
cfg = ForwardDiff.JacobianConfig(AD.asarray f, x, chunk(ba, x))
5155
return (ForwardDiff.jacobian(AD.asarray f, x, cfg),)
5256
end
53-
AD.jacobian(::AD.ForwardDiffBackend, f, x::Number) = (ForwardDiff.derivative(f, x),)
57+
AD.jacobian(::AD.ForwardDiffBackend, f, x::Real) = (ForwardDiff.derivative(f, x),)
5458

5559
function AD.hessian(ba::AD.ForwardDiffBackend, f, x::AbstractArray)
5660
cfg = ForwardDiff.HessianConfig(f, x, chunk(ba, x))

0 commit comments

Comments
 (0)