The base layer class. Generally, a layer conducts feature transformation against a set of Tensor to generate a set of Tensor. Each layer may have some parameters.
| 35 | /// Generally, a layer conducts feature transformation against a set of Tensor |
| 36 | /// to generate a set of Tensor. Each layer may have some parameters. |
| 37 | class Layer { |
| 38 | public: |
| 39 | Layer() = default; |
| 40 | |
| 41 | /// Set meta data fields from a string representing a proto message. |
| 42 | /// 'in_shape' is the shape of the input feature for one sample |
| 43 | void Setup(const Shape& in_shape, const string& proto_str) { |
| 44 | LayerConf conf; |
| 45 | conf.ParseFromString(proto_str); |
| 46 | this->Setup(in_shape, conf); |
| 47 | } |
| 48 | |
| 49 | /// 'in_shapes' is the shape of the input feature for one sample |
| 50 | void Setup(const vector<Shape>& in_shapes, const string& proto_str) { |
| 51 | LayerConf conf; |
| 52 | conf.ParseFromString(proto_str); |
| 53 | this->Setup(in_shapes, conf); |
| 54 | } |
| 55 | |
| 56 | |
| 57 | // ============= Following Functions could be override ===================== |
| 58 | /// Destruct objects created by this layer. |
| 59 | virtual ~Layer() {}; |
| 60 | |
| 61 | /// Each layer sub-class would optionaly have a type name. |
| 62 | /// Used for debugging and logging. |
| 63 | virtual const std::string layer_type() const { return "Unknown"; } |
| 64 | |
| 65 | /// Set meta data fields configured in 'conf' (a proto message). |
| 66 | /// Some layers would use input tensor shapes for setting its parameter |
| 67 | /// shapes (e.g, desen layer and convolution layer). 'in_shape' provides such |
| 68 | /// shape info. It represents the shape of the Tensor (with a single sample) |
| 69 | /// from the last layer. |
| 70 | /// After calling Setup, the shape info of parameters should be accssed |
| 71 | /// correctly. Internal buffer/fields are set assuming batchsize is 1. |
| 72 | virtual void Setup(const Shape& in_sample, const LayerConf& conf) { |
| 73 | name_ = conf.name(); |
| 74 | // TODO(wangwei) load param values from checkpoint files. |
| 75 | } |
| 76 | |
| 77 | /// Used for layers that have multiple input tensors, e.g., concatenate layer. |
| 78 | virtual void Setup(const vector<Shape>& in_samples, const LayerConf& conf) { |
| 79 | name_ = conf.name(); |
| 80 | // TODO(wangwei) load param values from checkpoint files. |
| 81 | } |
| 82 | |
| 83 | /// Return the shape of the generated Tensor without the batchsize dimension |
| 84 | virtual const Shape GetOutputSampleShape() const { |
| 85 | LOG(FATAL) << "Pls override this function"; |
| 86 | return vector<size_t>{}; |
| 87 | } |
| 88 | /// Return the shape of the k-th generated tensor without the batchsize |
| 89 | /// dimension. Used for layers that generate multiple tensors. |
| 90 | virtual const Shape GetOutputSampleShape(int k) { |
| 91 | LOG(FATAL) << "Pls override this function"; |
| 92 | return vector<size_t>{}; |
| 93 | } |
| 94 |