Skip to content

fix: reinit! on forwarddiff cache #491

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 1, 2024
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
3 changes: 1 addition & 2 deletions src/forward_diff.jl
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,9 @@ function InternalAPI.reinit!(
cache::NonlinearSolveForwardDiffCache, args...;
p = cache.p, u0 = NonlinearSolveBase.get_u(cache.cache), kwargs...
)
inner_cache = InternalAPI.reinit!(
InternalAPI.reinit!(
cache.cache; p = nodual_value(p), u0 = nodual_value(u0), kwargs...
)
cache.cache = inner_cache
cache.p = p
cache.values_p = nodual_value(p)
cache.partials_p = ForwardDiff.partials(p)
Expand Down
31 changes: 31 additions & 0 deletions test/forward_ad_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,34 @@ end

@test hess1≈hess2 atol=1e-3
end

@testitem "reinit! on ForwardDiff cache SciML/NonlinearSolve.jl#391" tags=[:core] begin
using ForwardDiff

function multiple_solves(ps::Vector)
res = similar(ps, 4, length(ps))
for (i, p) in enumerate(ps)
prob = NonlinearProblem{false}((u, p) -> u .* u .- p, rand(4), ps[i])
sol = solve(prob)
res[:, i] .= sol.u
end
return sum(abs2, res)
end

function multiple_solves_cached(ps::Vector)
res = similar(ps, 4, length(ps))
prob = NonlinearProblem{false}((u, p) -> u .* u .- p, rand(4), ps[1])
cache = init(prob, NewtonRaphson())
for (i, p) in enumerate(ps)
reinit!(cache; p)
sol = solve!(cache)
res[:, i] .= sol.u
end
return sum(abs2, res)
end

ps = collect(1.0:5.0)

@test ForwardDiff.gradient(multiple_solves, ps) ≈
ForwardDiff.gradient(multiple_solves_cached, ps)
end
Loading