|
1 | 1 | module DynamicExpressionsZygoteExt |
2 | 2 |
|
3 | | -import Zygote: gradient |
4 | | -import DynamicExpressions.ExtensionInterfaceModule: _zygote_gradient |
| 3 | +using Zygote: gradient |
| 4 | +import DynamicExpressions.ExtensionInterfaceModule: _zygote_gradient, ZygoteGradient |
5 | 5 |
|
6 | 6 | function _zygote_gradient(op::F, ::Val{1}) where {F} |
7 | | - function (x) |
8 | | - out = gradient(op, x)[1] |
9 | | - return out === nothing ? zero(x) : out |
10 | | - end |
| 7 | + return ZygoteGradient{F,1,1}(op) |
11 | 8 | end |
12 | | -function _zygote_gradient(op::F, ::Val{2}) where {F} |
13 | | - function (x, y) |
14 | | - (∂x, ∂y) = gradient(op, x, y) |
15 | | - return (∂x === nothing ? zero(x) : ∂x, ∂y === nothing ? zero(y) : ∂y) |
16 | | - end |
| 9 | +function _zygote_gradient(op::F, ::Val{2}, ::Val{side}=Val(nothing)) where {F,side} |
| 10 | + # side should be either nothing (for both), 1, or 2 |
| 11 | + @assert side === nothing || side in (1, 2) |
| 12 | + return ZygoteGradient{F,2,side}(op) |
| 13 | +end |
| 14 | + |
| 15 | +function (g::ZygoteGradient{F,1,1})(x) where {F} |
| 16 | + out = only(gradient(g.op, x)) |
| 17 | + return out === nothing ? zero(x) : out |
| 18 | +end |
| 19 | +function (g::ZygoteGradient{F,2,nothing})(x, y) where {F} |
| 20 | + (∂x, ∂y) = gradient(g.op, x, y) |
| 21 | + return (∂x === nothing ? zero(x) : ∂x, ∂y === nothing ? zero(y) : ∂y) |
| 22 | +end |
| 23 | +function (g::ZygoteGradient{F,2,1})(x, y) where {F} |
| 24 | + ∂x = only(gradient(Base.Fix2(g.op, y), x)) |
| 25 | + return ∂x === nothing ? zero(x) : ∂x |
| 26 | +end |
| 27 | +function (g::ZygoteGradient{F,2,2})(x, y) where {F} |
| 28 | + ∂y = only(gradient(Base.Fix1(g.op, x), y)) |
| 29 | + return ∂y === nothing ? zero(y) : ∂y |
17 | 30 | end |
18 | 31 |
|
19 | 32 | end |
0 commit comments