|
callAsFunction() isn't really intended to be used in a type like Dice there. It's a bad example. It's for Swift for TensorFlow's integration with Python, in which a bridged Python object can be called as a function. Functions are, of course, objects in Python, so that makes sense, but it would be a pain to have to call fn.call(bar) instead of fn(bar) when fn is a reference to a python object that is a function in its runtime. It's also used in TensorFlow models, in which callAsFunction() is usually implemented as passing the model's input through all the defined layers in it. This makes it easy to treat models as if they were functions, which they mathematically are, unlike Dice. Example: struct MLP: Layer {
var layer1 = Dense<Float>(inputSize: 2, outputSize: 10, activation: relu)
var layer2 = Dense<Float>(inputSize: 10, outputSize: 1, activation: relu)
@differentiable
func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> {
let h0 = layer1(input).withDerivative { print("∂L/∂layer1 =", $0) }
return layer2(h0)
}
}
(from: https://www.tensorflow.org/swift/tutorials/custom_differenti... ) |
It's a bad example enabled by a bad language feature. Just you wait until answers on stack overflow, sample code, and open source libs are littered with these "bad examples".
Meanwhile, this example is terrible. There is no real need for callAsFunction in your example when you could have added a simple named function on the object to do so. Better yet, you could define a protocol and make sure your layer conforms to said protocol.