Can I not use a buffer with AD as below?
using ForwardDiff
function buf(x)
similar(x)
end
function test(x; sto=buf(x))
sto .= x.^2
sum(sto.^2)
end
function grad(x; sto=buf(x))
ForwardDiff.gradient(x -> test(x; sto=sto), x)
end
x = rand(2, 2)
This throws an error:
julia> grad(x; sto=buf(x))
ERROR: MethodError: no method matching Float64(::ForwardDiff.Dual{ForwardDiff.Tag{var"#316#317"{Matrix{Float64}}, Float64}, Float64, 4})
Closest candidates are:
(::Type{T})(::Real, ::RoundingMode) where T<:AbstractFloat at rounding.jl:200
(::Type{T})(::T) where T<:Number at boot.jl:760
(::Type{T})(::AbstractChar) where T<:Union{AbstractChar, Number} at char.jl:50
...
This works:
julia> ForwardDiff.gradient(x -> test(x; sto=buf(x)), x)
2×2 Matrix{Float64}:
2.66201 0.00867353
0.205537 2.72375