@@ -109,35 +109,48 @@ function with_logabsdet_jacobian(f::Base.ComposedFunction, x)
109109end
110110
111111
112- function _with_ladj_on_mapped (@nospecialize (map_or_bc:: F ), y_with_ladj:: NoLogAbsDetJacobian ) where {F<: Union{typeof(map),typeof(broadcast)} }
113- return y_with_ladj
114- end
112+ _with_ladj_on_mapped (y_with_ladj:: NoLogAbsDetJacobian ) = y_with_ladj
115113
116- function _with_ladj_on_mapped (map_or_bc :: F , y_with_ladj:: Tuple{Any,Real} ) where {F <: Union{typeof(map),typeof(broadcast)} }
117- return y_with_ladj
118- end
114+ _with_ladj_on_mapped (y_with_ladj:: Tuple{Any,Real} ) = y_with_ladj
115+
116+ _with_ladj_on_mapped ( :: AbstractArray{<:NoLogAbsDetJacobian{F,T}} ) where {F,T} = NoLogAbsDetJacobian {F,T} ()
119117
120118_get_all_first (x) = map (first, x)
121- # Use x -> x[2] instead of last, using last causes horrible performance in Zygote here:
122- _sum_over_second (x) = sum (x -> x[2 ], x)
119+ _get_second (x) = x[2 ]
120+ # Use _get_second instead of last, using last causes horrible performance in Zygote here:
121+ _sum_over_second (x) = sum (_get_second, x)
123122
124- function _with_ladj_on_mapped (map_or_bc :: F , y_with_ladj) where {F <: Union{typeof(map),typeof(broadcast)} }
123+ function _with_ladj_on_mapped (y_with_ladj)
125124 y = _get_all_first (y_with_ladj)
126125 ladj = _sum_over_second (y_with_ladj)
127126 (y, ladj)
128127end
129128
129+ _combine_y_ladj (l:: NoLogAbsDetJacobian , @nospecialize (r:: NoLogAbsDetJacobian )) = l
130+ _combine_y_ladj (l:: NoLogAbsDetJacobian , @nospecialize (r:: Tuple{Any,Real} )) = l
131+ _combine_y_ladj (@nospecialize (l:: Tuple{Any,Real} ), r:: NoLogAbsDetJacobian ) = r
132+ _combine_y_ladj (l:: Tuple{Any,Real} , r:: Tuple{Any,Real} ) = ((l[1 ]. .. , r[1 ]), l[2 ] + r[2 ])
133+
134+ function _with_ladj_on_mapped (y_with_ladj:: Tuple {NoLogAbsDetJacobian, Vararg{Union{NoLogAbsDetJacobian, Tuple{Any,Real}}}})
135+ return first (y_with_ladj)
136+ end
137+
138+ function _with_ladj_on_mapped (y_with_ladj:: Tuple {Tuple{Any,Real}, Vararg{Union{NoLogAbsDetJacobian, Tuple{Any,Real}}}})
139+ a, bs = first (y_with_ladj), Base. tail (y_with_ladj)
140+ return foldl (_combine_y_ladj, bs, init = ((a[1 ],), a[2 ]))
141+ end
142+
130143function with_logabsdet_jacobian (mapped_f:: Base.Broadcast.BroadcastFunction , X)
131144 f = mapped_f. f
132145 y_with_ladj = broadcast (Base. Fix1 (with_logabsdet_jacobian, f), X)
133- _with_ladj_on_mapped (broadcast, y_with_ladj)
146+ _with_ladj_on_mapped (y_with_ladj)
134147end
135148
136149function with_logabsdet_jacobian (mapped_f:: Base.Fix1{<:Union{typeof(map),typeof(broadcast)}} , X)
137150 map_or_bc = mapped_f. f
138151 f = mapped_f. x
139152 y_with_ladj = map_or_bc (Base. Fix1 (with_logabsdet_jacobian, f), X)
140- _with_ladj_on_mapped (map_or_bc, y_with_ladj)
153+ _with_ladj_on_mapped (y_with_ladj)
141154end
142155
143156
0 commit comments