Skip to content
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
7 changes: 4 additions & 3 deletions ext/RecursiveArrayToolsZygoteExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ using RecursiveArrayTools

using Zygote
using Zygote: FillArrays, ChainRulesCore, literal_getproperty, @adjoint
using Zygote.ChainRulesCore: AbstractZero

function ChainRulesCore.rrule(
T::Type{<:RecursiveArrayTools.GPUArraysCore.AbstractGPUArray},
Expand Down Expand Up @@ -90,23 +91,23 @@ end

function vofa_u_adjoint(d, A::RecursiveArrayTools.AbstractVectorOfArray)
m = map(enumerate(d)) do (idx, d_i)
isnothing(d_i) && return zero(A.u[idx])
(isnothing(d_i) || d_i isa AbstractZero) && return zero(A.u[idx])
d_i
end
return VectorOfArray(m)
end

function vofa_u_adjoint(d, A::RecursiveArrayTools.AbstractDiffEqArray)
m = map(enumerate(d)) do (idx, d_i)
isnothing(d_i) && return zero(A.u[idx])
(isnothing(d_i) || d_i isa AbstractZero) && return zero(A.u[idx])
d_i
end
return DiffEqArray(m, A.t)
end

@adjoint function literal_getproperty(A::ArrayPartition, ::Val{:x})
function literal_ArrayPartition_x_adjoint(d)
(ArrayPartition((isnothing(d[i]) ? zero(A.x[i]) : d[i] for i in 1:length(d))...),)
(ArrayPartition((isnothing(d[i]) || d[i] isa AbstractZero ? zero(A.x[i]) : d[i] for i in 1:length(d))...),)
end
A.x, literal_ArrayPartition_x_adjoint
end
Expand Down
19 changes: 19 additions & 0 deletions test/adjoints.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using RecursiveArrayTools, Zygote, ForwardDiff, ReverseDiff, Test
using Zygote: ChainRulesCore

function loss(x)
return sum(abs2, Array(VectorOfArray([x .* i for i in 1:5])))
Expand Down Expand Up @@ -99,3 +100,21 @@ end
let g = ReverseDiff.gradient(x -> sum(VectorOfArray([VectorOfArray([x])])), float.(1:3))
@test g ≈ ones(3)
end

# A `ZeroTangent`/`AbstractZero` slice in the cotangent (structural zero gradient)
# must be treated like an absent gradient instead of erroring on `size(::ZeroTangent)`.
let ext = Base.get_extension(RecursiveArrayTools, :RecursiveArrayToolsZygoteExt)
voa = VectorOfArray([Float64[i, i, i] for i in 1:3])
dea = DiffEqArray([Float64[i, i, i] for i in 1:3], 1:3)
d = Any[Float64[1, 1, 1], ChainRulesCore.ZeroTangent(), Float64[3, 3, 3]]
expected = [Float64[1, 1, 1], Float64[0, 0, 0], Float64[3, 3, 3]]

g_voa = ext.vofa_u_adjoint(d, voa)
@test g_voa isa VectorOfArray
@test g_voa.u == expected

g_dea = ext.vofa_u_adjoint(d, dea)
@test g_dea isa DiffEqArray
@test g_dea.u == expected
@test g_dea.t == dea.t
end
Loading