2

这是一个最小的例子:

import _Differentiation

@differentiable(reverse)
func g(x: Double?) -> Double {
    if x == nil {
        return 0.0  // I don't care what this value is
    }
    else {
        return x! * x!
    }
}

@derivative(of: g)
func gVJP(x: Double?) -> (value: Double, pullback: (Double) -> Double?) {
    let value = g(x: x)
    
    func pullback(_ dOutput: Double) -> Double? {
        if x == nil {
            return nil // I don't care what this value is
        }
        else {
            return dOutput * 2.0 * x!
        }
    }
    
    return (value: value, pullback: pullback)
}

我收到以下编译器错误:

Function result's 'pullback' type does not match 'g(x:)'
1. 'pullback' does not have expected type '(Double.TangentVector) -> Optional<Double>.TangentVector' (aka '(Double) -> Optional<Double>.TangentVector')

我尝试将回调的返回类型定义为Optional<Double>.TangentVector,但这给了我错误,即我的回调的返回值为incompatible with return type 'Optional<Double>.TangentVector'

4

1 回答 1

2

的返回值pullback需要转换为 type Optional<Double>.TangentVector

import _Differentiation

@differentiable(reverse)
func g(x: Double?) -> Double {
    if x == nil {
        return 0.0  // I don't care what this value is
    }
    else {
        return x! * x!
    }
}

@derivative(of: g)
func gVJP(x: Double?) -> (value: Double, pullback: (Double) -> Optional<Double>.TangentVector) {
    let value = g(x: x)

    func pullback(_ dOutput: Double) ->Optional<Double>.TangentVector {
        if x == nil {
            return Optional<Double>.TangentVector(nil) // I don't care what this value is
        }
        else {
            return Optional<Double>.TangentVector(dOutput * 2.0 * x!)
        }
    }

    return (value: value, pullback: pullback)
}
于 2021-07-02T19:13:14.583 回答