|
| 1 | +// RUN: %target-swift-frontend -c -enable-library-evolution %s |
| 2 | + |
| 3 | +// https://github.com/swiftlang/swift/issues/55179 |
| 4 | +// Explicitly use minimal type expansion on autodiff-related types. |
| 5 | +// Autodiff happens on function types, so in general it does not know |
| 6 | +// if the function in question is resilient or not. Using minimal expansion |
| 7 | +// provides an universally conservative approach. |
| 8 | + |
| 9 | +import _Differentiation |
| 10 | + |
| 11 | +public class Tracked<T> {} |
| 12 | +extension Tracked: Differentiable where T: Differentiable {} |
| 13 | + |
| 14 | +@differentiable(reverse) |
| 15 | +func callback(_ x: inout Tracked<Float>.TangentVector) {} |
| 16 | + |
| 17 | +extension Differentiable { |
| 18 | + /// Applies the given closure to the derivative of `self`. |
| 19 | + /// |
| 20 | + /// Returns `self` like an identity function. When the return value is used in |
| 21 | + /// a context where it is differentiated with respect to, applies the given |
| 22 | + /// closure to the derivative of the return value. |
| 23 | + @inlinable |
| 24 | + @differentiable(reverse, wrt: self) |
| 25 | + func withDerivative(_ body: @escaping (inout TangentVector) -> Void) -> Self { |
| 26 | + return self |
| 27 | + } |
| 28 | + |
| 29 | + @inlinable |
| 30 | + @derivative(of: withDerivative) |
| 31 | + internal func _vjpWithDerivative( |
| 32 | + _ body: @escaping (inout TangentVector) -> Void |
| 33 | + ) -> (value: Self, pullback: (TangentVector) -> TangentVector) { |
| 34 | + return (self, { grad in |
| 35 | + var grad = grad |
| 36 | + body(&grad) |
| 37 | + return grad |
| 38 | + }) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +@differentiable(reverse) |
| 43 | +public func caller(_ x: Tracked<Float>) -> Tracked<Float> { |
| 44 | + return x.withDerivative(callback) |
| 45 | +} |
0 commit comments