8 #include "caffe/blob.hpp"
9 #include "caffe/common.hpp"
10 #include "caffe/proto/caffe.pb.h"
11 #include "caffe/util/device_alternate.hpp"
16 * @brief An interface for the units of computation which can be composed into a
19 * Layer&s must implement a Forward function, in which they take their input
20 * (bottom) Blob&s (if any) and compute their output Blob&s (if any).
21 * They may also implement a Backward function, in which they compute the error
22 * gradients with respect to their input Blob&s, given the error gradients with
23 * their output Blob&s.
25 template <typename Dtype>
29 * You should not implement your own constructor. Any set up code should go
30 * to SetUp(), where the dimensions of the bottom blobs are provided to the
33 explicit Layer(const LayerParameter& param)
34 : layer_param_(param) {
35 // The only thing we do is to copy blobs if there are any.
36 if (layer_param_.blobs_size() > 0) {
37 blobs_.resize(layer_param_.blobs_size());
38 for (int i = 0; i < layer_param_.blobs_size(); ++i) {
39 blobs_[i].reset(new Blob<Dtype>());
40 blobs_[i]->FromProto(layer_param_.blobs(i));
47 * @brief Implements common layer setup functionality.
49 * @param bottom the preshaped input blobs
51 * the allocated but unshaped output blobs, to be shaped by Reshape
53 * Checks that the number of bottom and top blobs is correct.
54 * Calls LayerSetUp to do special layer setup for individual layer types,
55 * followed by Reshape to set up sizes of top blobs and internal buffers.
56 * Sets up the loss weight multiplier blobs for any non-zero loss weights.
57 * This method may not be overridden.
59 void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
60 CheckBlobCounts(bottom, *top);
61 LayerSetUp(bottom, top);
67 * @brief Does layer-specific setup: your layer should implement this function
71 * the preshaped input blobs, whose data fields store the input data for
74 * the allocated but unshaped output blobs
76 * This method should do one-time layer specific setup. This includes reading
77 * and processing relevent parameters from the <code>layer_param_</code>.
78 * Setting up the shapes of top blobs and internal buffers should be done in
79 * <code>Reshape</code>, which will be called before the forward pass to
80 * adjust the top blob sizes.
82 virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
83 vector<Blob<Dtype>*>* top) {}
86 * @brief Adjust the shapes of top blobs and internal buffers to accomodate
87 * the shapes of the bottom blobs.
89 * @param bottom the input blobs, with the requested input shapes
90 * @param top the top blobs, which should be reshaped as needed
92 * This method should reshape top blobs as needed according to the shapes
93 * of the bottom (input) blobs, as well as reshaping any internal buffers
94 * and making any other necessary adjustments so that the layer can
95 * accomodate the bottom blobs.
97 virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
98 vector<Blob<Dtype>*>* top) = 0;
101 * @brief Given the bottom blobs, compute the top blobs and the loss.
104 * the input blobs, whose data fields store the input data for this layer
106 * the preshaped output blobs, whose data fields will store this layers'
108 * \return The total loss from the layer.
110 * The Forward wrapper calls the relevant device wrapper function
111 * (Forward_cpu or Forward_gpu) to compute the top blob values given the
112 * bottom blobs. If the layer has any non-zero loss_weights, the wrapper
113 * then computes and returns the loss.
115 * Your layer should implement Forward_cpu and (optionally) Forward_gpu.
117 inline Dtype Forward(const vector<Blob<Dtype>*>& bottom,
118 vector<Blob<Dtype>*>* top);
121 * @brief Given the top blob error gradients, compute the bottom blob error
125 * the output blobs, whose diff fields store the gradient of the error
126 * with respect to themselves
127 * @param propagate_down
128 * a vector with equal length to bottom, with each index indicating
129 * whether to propagate the error gradients down to the bottom blob at
130 * the corresponding index
132 * the input blobs, whose diff fields will store the gradient of the error
133 * with respect to themselves after Backward is run
135 * The Backward wrapper calls the relevant device wrapper function
136 * (Backward_cpu or Backward_gpu) to compute the bottom blob diffs given the
139 * Your layer should implement Forward_cpu and (optionally) Forward_gpu.
141 inline void Backward(const vector<Blob<Dtype>*>& top,
142 const vector<bool>& propagate_down,
143 vector<Blob<Dtype>*>* bottom);
146 * @brief Returns the vector of learnable parameter blobs.
148 vector<shared_ptr<Blob<Dtype> > >& blobs() {
153 * @brief Returns the layer parameter.
155 const LayerParameter& layer_param() const { return layer_param_; }
158 * @brief Writes the layer parameter to a protocol buffer
160 virtual void ToProto(LayerParameter* param, bool write_diff = false);
163 * @brief Returns the scalar loss associated with a top blob at a given index.
165 inline Dtype loss(const int top_index) const {
166 return (loss_.size() > top_index) ? loss_[top_index] : Dtype(0);
170 * @brief Sets the loss associated with a top blob at a given index.
172 inline void set_loss(const int top_index, const Dtype value) {
173 if (loss_.size() <= top_index) {
174 loss_.resize(top_index + 1, Dtype(0));
176 loss_[top_index] = value;
180 * @brief Returns the layer type as an enum value.
182 virtual inline LayerParameter_LayerType type() const {
183 return LayerParameter_LayerType_NONE;
187 * @brief Returns the layer type name.
189 virtual inline const string& type_name() const {
190 return LayerParameter_LayerType_Name(type());
194 * @brief Returns the exact number of bottom blobs required by the layer,
195 * or -1 if no exact number is required.
197 * This method should be overridden to return a non-negative value if your
198 * layer expects some exact number of bottom blobs.
200 virtual inline int ExactNumBottomBlobs() const { return -1; }
202 * @brief Returns the minimum number of bottom blobs required by the layer,
203 * or -1 if no minimum number is required.
205 * This method should be overridden to return a non-negative value if your
206 * layer expects some minimum number of bottom blobs.
208 virtual inline int MinBottomBlobs() const { return -1; }
210 * @brief Returns the maximum number of bottom blobs required by the layer,
211 * or -1 if no maximum number is required.
213 * This method should be overridden to return a non-negative value if your
214 * layer expects some maximum number of bottom blobs.
216 virtual inline int MaxBottomBlobs() const { return -1; }
218 * @brief Returns the exact number of top blobs required by the layer,
219 * or -1 if no exact number is required.
221 * This method should be overridden to return a non-negative value if your
222 * layer expects some exact number of top blobs.
224 virtual inline int ExactNumTopBlobs() const { return -1; }
226 * @brief Returns the minimum number of top blobs required by the layer,
227 * or -1 if no minimum number is required.
229 * This method should be overridden to return a non-negative value if your
230 * layer expects some minimum number of top blobs.
232 virtual inline int MinTopBlobs() const { return -1; }
234 * @brief Returns the maximum number of top blobs required by the layer,
235 * or -1 if no maximum number is required.
237 * This method should be overridden to return a non-negative value if your
238 * layer expects some maximum number of top blobs.
240 virtual inline int MaxTopBlobs() const { return -1; }
242 * @brief Returns true if the layer requires an equal number of bottom and
245 * This method should be overridden to return true if your layer expects an
246 * equal number of bottom and top blobs.
248 virtual inline bool EqualNumBottomTopBlobs() const { return false; }
251 * @brief Return whether "anonymous" top blobs are created automatically
254 * If this method returns true, Net::Init will create enough "anonymous" top
255 * blobs to fulfill the requirement specified by ExactNumTopBlobs() or
258 virtual inline bool AutoTopBlobs() const { return false; }
261 * @brief Return whether to allow force_backward for a given bottom blob
264 * If AllowForceBackward(i) == false, we will ignore the force_backward
265 * setting and backpropagate to blob i only if it needs gradient information
266 * (as is done when force_backward == false).
268 virtual inline bool AllowForceBackward(const int bottom_index) const {
273 * @brief Specifies whether the layer should compute gradients w.r.t. a
274 * parameter at a particular index given by param_id.
276 * You can safely ignore false values and always compute gradients
277 * for all parameters, but possibly with wasteful computation.
279 inline bool param_propagate_down(const int param_id) {
280 return (param_propagate_down_.size() > param_id) ?
281 param_propagate_down_[param_id] : false;
284 * @brief Sets whether the layer should compute gradients w.r.t. a
285 * parameter at a particular index given by param_id.
287 inline void set_param_propagate_down(const int param_id, const bool value) {
288 if (param_propagate_down_.size() <= param_id) {
289 param_propagate_down_.resize(param_id + 1, true);
291 param_propagate_down_[param_id] = value;
296 /** The protobuf that stores the layer parameters */
297 LayerParameter layer_param_;
298 /** The vector that stores the learnable parameters as a set of blobs. */
299 vector<shared_ptr<Blob<Dtype> > > blobs_;
300 /** Vector indicating whether to compute the diff of each param blob. */
301 vector<bool> param_propagate_down_;
303 /** The vector that indicates whether each top blob has a non-zero weight in
304 * the objective function. */
307 /** @brief Using the CPU device, compute the layer output. */
308 virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
309 vector<Blob<Dtype>*>* top) = 0;
311 * @brief Using the GPU device, compute the layer output.
312 * Fall back to Forward_cpu() if unavailable.
314 virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
315 vector<Blob<Dtype>*>* top) {
316 // LOG(WARNING) << "Using CPU code as backup.";
317 return Forward_cpu(bottom, top);
321 * @brief Using the CPU device, compute the gradients for any parameters and
322 * for the bottom blobs if propagate_down is true.
324 virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
325 const vector<bool>& propagate_down,
326 vector<Blob<Dtype>*>* bottom) = 0;
328 * @brief Using the GPU device, compute the gradients for any parameters and
329 * for the bottom blobs if propagate_down is true.
330 * Fall back to Backward_cpu() if unavailable.
332 virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
333 const vector<bool>& propagate_down,
334 vector<Blob<Dtype>*>* bottom) {
335 // LOG(WARNING) << "Using CPU code as backup.";
336 Backward_cpu(top, propagate_down, bottom);
340 * Called by the parent Layer's SetUp to check that the number of bottom
341 * and top Blobs provided as input match the expected numbers specified by
342 * the {ExactNum,Min,Max}{Bottom,Top}Blobs() functions.
344 virtual void CheckBlobCounts(const vector<Blob<Dtype>*>& bottom,
345 const vector<Blob<Dtype>*>& top) {
346 if (ExactNumBottomBlobs() >= 0) {
347 CHECK_EQ(ExactNumBottomBlobs(), bottom.size())
348 << type_name() << " Layer takes " << ExactNumBottomBlobs()
349 << " bottom blob(s) as input.";
351 if (MinBottomBlobs() >= 0) {
352 CHECK_LE(MinBottomBlobs(), bottom.size())
353 << type_name() << " Layer takes at least " << MinBottomBlobs()
354 << " bottom blob(s) as input.";
356 if (MaxBottomBlobs() >= 0) {
357 CHECK_GE(MaxBottomBlobs(), bottom.size())
358 << type_name() << " Layer takes at most " << MaxBottomBlobs()
359 << " bottom blob(s) as input.";
361 if (ExactNumTopBlobs() >= 0) {
362 CHECK_EQ(ExactNumTopBlobs(), top.size())
363 << type_name() << " Layer produces " << ExactNumTopBlobs()
364 << " top blob(s) as output.";
366 if (MinTopBlobs() >= 0) {
367 CHECK_LE(MinTopBlobs(), top.size())
368 << type_name() << " Layer produces at least " << MinTopBlobs()
369 << " top blob(s) as output.";
371 if (MaxTopBlobs() >= 0) {
372 CHECK_GE(MaxTopBlobs(), top.size())
373 << type_name() << " Layer produces at most " << MaxTopBlobs()
374 << " top blob(s) as output.";
376 if (EqualNumBottomTopBlobs()) {
377 CHECK_EQ(bottom.size(), top.size())
378 << type_name() << " Layer produces one top blob as output for each "
379 << "bottom blob input.";
384 * Called by SetUp to initialize the weights associated with any top blobs in
385 * the loss function. Store non-zero loss weights in the diff blob.
387 inline void SetLossWeights(vector<Blob<Dtype>*>* top) {
388 const int num_loss_weights = layer_param_.loss_weight_size();
389 if (num_loss_weights) {
390 CHECK_EQ(top->size(), num_loss_weights) << "loss_weight must be "
391 "unspecified or specified once per top blob.";
392 for (int top_id = 0; top_id < top->size(); ++top_id) {
393 const Dtype loss_weight = layer_param_.loss_weight(top_id);
394 if (loss_weight == Dtype(0)) { continue; }
395 this->set_loss(top_id, loss_weight);
396 const int count = (*top)[top_id]->count();
397 Dtype* loss_multiplier = (*top)[top_id]->mutable_cpu_diff();
398 caffe_set(count, loss_weight, loss_multiplier);
403 DISABLE_COPY_AND_ASSIGN(Layer);
406 // Forward and backward wrappers. You should implement the cpu and
407 // gpu specific implementations instead, and should not change these
409 template <typename Dtype>
410 inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype>*>& bottom,
411 vector<Blob<Dtype>*>* top) {
413 switch (Caffe::mode()) {
415 Forward_cpu(bottom, top);
416 for (int top_id = 0; top_id < top->size(); ++top_id) {
417 if (!this->loss(top_id)) { continue; }
418 const int count = (*top)[top_id]->count();
419 const Dtype* data = (*top)[top_id]->cpu_data();
420 const Dtype* loss_weights = (*top)[top_id]->cpu_diff();
421 loss += caffe_cpu_dot(count, data, loss_weights);
425 Forward_gpu(bottom, top);
427 for (int top_id = 0; top_id < top->size(); ++top_id) {
428 if (!this->loss(top_id)) { continue; }
429 const int count = (*top)[top_id]->count();
430 const Dtype* data = (*top)[top_id]->gpu_data();
431 const Dtype* loss_weights = (*top)[top_id]->gpu_diff();
433 caffe_gpu_dot(count, data, loss_weights, &blob_loss);
439 LOG(FATAL) << "Unknown caffe mode.";
444 template <typename Dtype>
445 inline void Layer<Dtype>::Backward(const vector<Blob<Dtype>*>& top,
446 const vector<bool>& propagate_down,
447 vector<Blob<Dtype>*>* bottom) {
448 switch (Caffe::mode()) {
450 Backward_cpu(top, propagate_down, bottom);
453 Backward_gpu(top, propagate_down, bottom);
456 LOG(FATAL) << "Unknown caffe mode.";
460 // Serialize LayerParameter to protocol buffer
461 template <typename Dtype>
462 void Layer<Dtype>::ToProto(LayerParameter* param, bool write_diff) {
464 param->CopyFrom(layer_param_);
465 param->clear_blobs();
466 for (int i = 0; i < blobs_.size(); ++i) {
467 blobs_[i]->ToProto(param->add_blobs(), write_diff);
471 // The layer factory function
472 template <typename Dtype>
473 Layer<Dtype>* GetLayer(const LayerParameter& param);
477 #endif // CAFFE_LAYER_H_