Skip to content

Differentiating ArrayPartitions in DEProblems #221

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 4 commits into from
Aug 11, 2022
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 src/zygote.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function ChainRulesCore.rrule(::Type{<:ArrayPartition}, x::S, ::Type{Val{copy_x}
function ArrayPartition_adjoint(_y)
y = Array(_y)
starts = vcat(0,cumsum(reduce(vcat,length.(x))))
NoTangent(), ArrayPartition(ntuple(i -> reshape(y[starts[i]+1:starts[i+1]], size(x[i]))), length(x)), NoTangent()
NoTangent(), ntuple(i -> reshape(y[starts[i]+1:starts[i+1]], size(x[i])), length(x)), NoTangent()
end

ArrayPartition(x, Val{copy_x}), ArrayPartition_adjoint
Expand Down
8 changes: 8 additions & 0 deletions test/adjoints.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using RecursiveArrayTools, Zygote, ForwardDiff, Test
using OrdinaryDiffEq

function loss(x)
sum(abs2,Array(VectorOfArray([x .* i for i in 1:5])))
Expand Down Expand Up @@ -30,10 +31,17 @@ function loss5(x)
sum(abs2,Array(ArrayPartition([x .* i for i in 1:5]...)))
end

function loss6(x)
_x = ArrayPartition([x .* i for i in 1:5]...)
_prob = ODEProblem((u,p,t)->u, _x, (0,1))
sum(abs2, Array(_prob.u0))
end

x = float.(6:10)
loss(x)
@test Zygote.gradient(loss,x)[1] == ForwardDiff.gradient(loss,x)
@test Zygote.gradient(loss2,x)[1] == ForwardDiff.gradient(loss2,x)
@test Zygote.gradient(loss3,x)[1] == ForwardDiff.gradient(loss3,x)
@test Zygote.gradient(loss4,x)[1] == ForwardDiff.gradient(loss4,x)
@test Zygote.gradient(loss5,x)[1] == ForwardDiff.gradient(loss5,x)
@test Zygote.gradient(loss6,x)[1] == ForwardDiff.gradient(loss6,x)