Skip to content
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

Adjoint for ForwardDiff.jacobian #968

Merged
merged 4 commits into from
May 15, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions src/lib/forward.jl
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,7 @@ forwarddiff(f, x) = f(x)
y, J = forward_jacobian(f, x)
return y, ȳ -> (nothing, reshape_scalar(x, J*vec_scalar(ȳ)))
end

# Use this to allow second derivatives
mcabbott marked this conversation as resolved.
Show resolved Hide resolved
@adjoint ForwardDiff.gradient(f, x) = pullback(forwarddiff, x -> ForwardDiff.gradient(f, x), x)
@adjoint ForwardDiff.jacobian(f, x) = pullback(forwarddiff, x -> ForwardDiff.jacobian(f, x), x)
29 changes: 29 additions & 0 deletions test/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,32 @@ end
@test Jxy[ys] ≈ [1 0 0; 0 1 0]
@test Jxy[xs] ≈ [2 6 4 8; 2 6 4 8]
end

using ForwardDiff

@testset "adjoints of ForwardDiff functions" begin
f1(x) = ForwardDiff.gradient(x -> sum(exp.(x.+1)), x)
x1 = randn(3,7)
@test Zygote.jacobian(f1, x1)[1] ≈ ForwardDiff.jacobian(f1, x1)

f2(x) = ForwardDiff.jacobian(x -> log.(x[1:3] .+ x[2:4]), x)
x2 = rand(5) .+ 1
@test Zygote.jacobian(f2, x2)[1] ≈ ForwardDiff.jacobian(f2, x2)

# Tests from https://github.com/FluxML/Zygote.jl/issues/769
f(x) = [2x[1]^2 + x[1],x[2]^2 * x[1]]
g1(x) = sum(ForwardDiff.jacobian(f,x))
out,back = Zygote.pullback(g1,[2.0,3.2])
stakehouse = back(1.0)[1]
@test typeof(stakehouse) <: Vector
@test size(stakehouse) == (2,)
@test stakehouse ≈ ForwardDiff.gradient(g1,[2.0,3.2])

g2(x) = prod(ForwardDiff.jacobian(f,x))
out,back = Zygote.pullback(g2,[2.0,3.2])
@test_skip back(1.0)[1] == ForwardDiff.gradient(g2,[2.0,3.2]) # contains NaN, @adjoint prod isn't careful

g3(x) = sum(abs2,ForwardDiff.jacobian(f,x))
out,back = Zygote.pullback(g3,[2.0,3.2])
@test back(1.0)[1] == ForwardDiff.gradient(g3,[2.0,3.2])
end