-
Notifications
You must be signed in to change notification settings - Fork 32
/
zygote.jl
293 lines (256 loc) · 8.45 KB
/
zygote.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
using .Zygote: Zygote, @adjoint, @nograd, pullback
using Compat: eachcol
@adjoint istraining() = true, _ -> nothing
@nograd Bijectors._debug
@adjoint function mapvcat(f, args...)
g(f, args...) = map(f, args...)
return pullback(g, f, args...)
end
@adjoint function eachcolmaphcat(f, x1, x2)
function g(f, x1, x2)
init = reshape(f(view(x1, :, 1), x2[1]), :, 1)
return reduce(hcat, [f(view(x1, :, i), x2[i]) for i in 2:size(x1, 2)]; init = init)
end
return pullback(g, f, x1, x2)
end
@adjoint function eachcolmaphcat(f, x)
function g(f, x)
init = reshape(f(view(x, :, 1)), :, 1)
return reduce(hcat, [f(view(x, :, i)) for i in 2:size(x, 2)]; init = init)
end
return pullback(g, f, x)
end
@adjoint function sumeachcol(f, x1, x2)
g(f, x1, x2) = sum([f(view(x1, :, i), x2[i]) for i in 1:size(x1, 2)])
return pullback(g, f, x1, x2)
end
@adjoint function logabsdetjac(b::Log{1}, x::AbstractVector)
return -sum(log, x), Δ -> (nothing, -Δ ./ x)
end
@adjoint function logabsdetjac(b::Log{1}, x::AbstractMatrix)
return -vec(sum(log, x; dims = 1)), Δ -> (nothing, .- Δ' ./ x)
end
# AD implementations
function jacobian(
b::Union{<:ADBijector{<:ZygoteAD}, Inverse{<:ADBijector{<:ZygoteAD}}},
x::Real
)
return Zygote.gradient(b, x)[1]
end
function jacobian(
b::Union{<:ADBijector{<:ZygoteAD}, Inverse{<:ADBijector{<:ZygoteAD}}},
x::AbstractVector{<:Real}
)
return Zygote.jacobian(b, x)
end
@adjoint function _logabsdetjac_scale(a::Real, x::Real, ::Val{0})
return _logabsdetjac_scale(a, x, Val(0)), Δ -> (inv(a) .* Δ, nothing, nothing)
end
@adjoint function _logabsdetjac_scale(a::Real, x::AbstractVector, ::Val{0})
J = fill(inv.(a), length(x))
return _logabsdetjac_scale(a, x, Val(0)), Δ -> (transpose(J) * Δ, nothing, nothing)
end
@adjoint function _logabsdetjac_scale(a::Real, x::AbstractMatrix, ::Val{0})
J = fill(size(x, 1) / a, size(x, 2))
return _logabsdetjac_scale(a, x, Val(0)), Δ -> (transpose(J) * Δ, nothing, nothing)
end
@adjoint function _logabsdetjac_scale(a::AbstractVector, x::AbstractVector, ::Val{1})
# ∂ᵢ (∑ⱼ log|aⱼ|) = ∑ⱼ δᵢⱼ ∂ᵢ log|aⱼ|
# = ∂ᵢ log |aᵢ|
# = (1 / aᵢ) ∂ᵢ aᵢ
# = (1 / aᵢ)
J = inv.(a)
return _logabsdetjac_scale(a, x, Val(1)), Δ -> (J .* Δ, nothing, nothing)
end
@adjoint function _logabsdetjac_scale(a::AbstractVector, x::AbstractMatrix, ::Val{1})
Jᵀ = repeat(inv.(a), 1, size(x, 2))
return _logabsdetjac_scale(a, x, Val(1)), Δ -> (Jᵀ * Δ, nothing, nothing)
end
## Positive definite matrices
@adjoint function replace_diag(::typeof(log), X)
f(i, j) = i == j ? log(X[i, j]) : X[i, j]
out = f.(1:size(X, 1), (1:size(X, 2))')
out, ∇ -> begin
g(i, j) = i == j ? ∇[i, j] / X[i, j] : ∇[i, j]
(nothing, g.(1:size(X, 1), (1:size(X, 2))'))
end
end
@adjoint function replace_diag(::typeof(exp), X)
f(i, j) = ifelse(i == j, exp(X[i, j]), X[i, j])
out = f.(1:size(X, 1), (1:size(X, 2))')
out, ∇ -> begin
g(i, j) = ifelse(i == j, ∇[i, j] * exp(X[i, j]), ∇[i, j])
(nothing, g.(1:size(X, 1), (1:size(X, 2))'))
end
end
@adjoint function pd_logpdf_with_trans(
d,
X::AbstractMatrix{<:Real},
transform::Bool,
)
return pullback(pd_logpdf_with_trans_zygote, d, X, transform)
end
function pd_logpdf_with_trans_zygote(
d,
X::AbstractMatrix{<:Real},
transform::Bool,
)
T = eltype(X)
Xcf = cholesky(X, check = false)
if !issuccess(Xcf)
Xcf = cholesky(X + max(eps(T), eps(T) * norm(X)) * I, check = true)
end
lp = getlogp(d, Xcf, X)
if transform && isfinite(lp)
U = Xcf.U
@inbounds for i in 1:dim(d)
lp += (dim(d) - i + 2) * log(U[i, i])
end
lp += dim(d) * log(T(2))
end
return lp
end
# Simplex adjoints
@adjoint function _simplex_bijector(X::AbstractVector, b::SimplexBijector{1})
return _simplex_bijector(X, b), Δ -> (simplex_link_jacobian(X)' * Δ, nothing)
end
@adjoint function _simplex_inv_bijector(Y::AbstractVector, b::SimplexBijector{1})
return _simplex_inv_bijector(Y, b), Δ -> (simplex_invlink_jacobian(Y)' * Δ, nothing)
end
@adjoint function _simplex_bijector(X::AbstractMatrix, b::SimplexBijector{1})
return _simplex_bijector(X, b), Δ -> begin
maphcat(eachcol(X), eachcol(Δ)) do c1, c2
simplex_link_jacobian(c1)' * c2
end, nothing
end
end
@adjoint function _simplex_inv_bijector(Y::AbstractMatrix, b::SimplexBijector{1})
return _simplex_inv_bijector(Y, b), Δ -> begin
maphcat(eachcol(Y), eachcol(Δ)) do c1, c2
simplex_invlink_jacobian(c1)' * c2
end, nothing
end
end
@adjoint function logabsdetjac(b::SimplexBijector{1}, x::AbstractVector)
return logabsdetjac(b, x), Δ -> begin
(nothing, simplex_logabsdetjac_gradient(x) * Δ)
end
end
@adjoint function logabsdetjac(b::SimplexBijector{1}, x::AbstractMatrix)
return logabsdetjac(b, x), Δ -> begin
(nothing, maphcat(eachcol(x), Δ) do c, g
simplex_logabsdetjac_gradient(c) * g
end)
end
end
# LocationScale fix
@adjoint function minimum(d::LocationScale)
function _minimum(d)
m = minimum(d.ρ)
if isfinite(m)
return d.μ + d.σ * m
else
return m
end
end
return pullback(_minimum, d)
end
@adjoint function maximum(d::LocationScale)
function _maximum(d)
m = maximum(d.ρ)
if isfinite(m)
return d.μ + d.σ * m
else
return m
end
end
return pullback(_maximum, d)
end
@adjoint function lower(A::AbstractMatrix)
return lower(A), Δ -> (lower(Δ),)
end
@adjoint function getpd(X::AbstractMatrix)
return LowerTriangular(X) * LowerTriangular(X)', Δ -> begin
Xl = LowerTriangular(X)
return (LowerTriangular(Δ' * Xl + Δ * Xl),)
end
end
@adjoint function pd_link(X::AbstractMatrix{<:Real})
return pullback(X) do X
Y = cholesky(X; check = true).L
return replace_diag(log, Y)
end
end
@adjoint function _inv_link_chol_lkj(y)
K = LinearAlgebra.checksquare(y)
w = similar(y)
z_mat = similar(y) # cache for adjoint
tmp_mat = similar(y)
@inbounds for j in 1:K
w[1, j] = 1
for i in 2:j
z = tanh(y[i-1, j])
tmp = w[i-1, j]
z_mat[i, j] = z
tmp_mat[i, j] = tmp
w[i-1, j] = z * tmp
w[i, j] = tmp * sqrt(1 - z^2)
end
for i in (j+1):K
w[i, j] = 0
end
end
function pullback_inv_link_chol_lkj(Δw)
LinearAlgebra.checksquare(Δw)
Δy = zero(y)
@inbounds for j in 1:K
Δtmp = Δw[j,j]
for i in j:-1:2
Δz = Δw[i-1, j] * tmp_mat[i, j] - Δtmp * tmp_mat[i, j] / sqrt(1 - z_mat[i, j]^2) * z_mat[i, j]
Δy[i-1, j] = Δz / cosh(y[i-1, j])^2
Δtmp = Δw[i-1, j] * z_mat[i, j] + Δtmp * sqrt(1 - z_mat[i, j]^2)
end
end
return (Δy,)
end
return w, pullback_inv_link_chol_lkj
end
@adjoint function _link_chol_lkj(w)
K = LinearAlgebra.checksquare(w)
z = similar(w)
@inbounds z[1, 1] = 0
tmp_mat = similar(w) # cache for pullback.
@inbounds for j=2:K
z[1, j] = atanh(w[1, j])
tmp = sqrt(1 - w[1, j]^2)
tmp_mat[1, j] = tmp
for i in 2:(j - 1)
p = w[i, j] / tmp
tmp *= sqrt(1 - p^2)
tmp_mat[i, j] = tmp
z[i, j] = atanh(p)
end
z[j, j] = 0
end
function pullback_link_chol_lkj(Δz)
LinearAlgebra.checksquare(Δz)
Δw = similar(w)
@inbounds Δw[1,1] = zero(eltype(Δz))
@inbounds for j=2:K
Δw[j, j] = 0
Δtmp = zero(eltype(Δz)) # Δtmp_mat[j-1,j]
for i in (j-1):-1:2
p = w[i, j] / tmp_mat[i-1, j]
ftmp = sqrt(1 - p^2)
d_ftmp_p = -p / ftmp
d_p_tmp = -w[i,j] / tmp_mat[i-1, j]^2
Δp = Δz[i,j] / (1-p^2) + Δtmp * tmp_mat[i-1, j] * d_ftmp_p
Δw[i, j] = Δp / tmp_mat[i-1, j]
Δtmp = Δp * d_p_tmp + Δtmp * ftmp # update to "previous" Δtmp
end
Δw[1, j] = Δz[1, j] / (1-w[1,j]^2) - Δtmp / sqrt(1 - w[1,j]^2) * w[1,j]
end
return (Δw,)
end
return z, pullback_link_chol_lkj
end