-
-
Notifications
You must be signed in to change notification settings - Fork 213
/
buffer.jl
61 lines (51 loc) · 1.45 KB
/
buffer.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
grad_mut(b::Buffer) = fill!(similar(b.data, Any), nothing)
grad_mut(b::Buffer{T}) where T<:Number = fill!(similar(b.data, float(T)), 0)
@nograd Buffer
@adjoint function getindex(b::Buffer, i...)
b[i...], function (Δ)
grad = grad_mut(__context__, b)
grad[i...] = accum(grad[i...], Δ)
return
end
end
@adjoint! function setindex!(b::Buffer, v, i...)
setindex!(b, v, i...), function (_)
grad = grad_mut(__context__, b)
v̄ = grad[i...]
zero = eltype(grad) <: Number ? 0 : nothing
if i isa NTuple{N,Integer} where N
grad[i...] = zero
else
grad[i...] .= zero
end
(nothing, v̄, map(_->nothing, i)...)
end
end
@adjoint! function copyto!(b::Buffer, xs)
copyto!(b, xs), function (_)
grad = grad_mut(__context__, b)
x̄s = copy(grad)
grad .= eltype(grad) <: Number ? 0 : nothing
return (nothing, x̄s)
end
end
@adjoint! function push!(b::Buffer, x)
push!(b, x), function (y)
grad = grad_mut(__context__, b)
return (nothing, pop!(grad))
end
end
_pullback(cx::AContext, ::typeof(Broadcast.materialize!), b::Buffer, x::AbstractArray) =
_pullback(cx, copyto!, b, x)
@adjoint function copy(b::Buffer)
res = copy(b)
function copy_sensitivity(b̄)
grad_mut(__context__, b)[:] .= vec(b̄)
return
end
function copy_sensitivity(b̄::Union{Tuple,AbstractVector{T}}) where {T<:AbstractArray}
grad_mut(__context__, b)[:] .= b̄
return
end
return res, copy_sensitivity
end