Back-merge to include #1198
[platform/upstream/caffeonacl.git] / include / caffe / layer.hpp
1 #ifndef CAFFE_LAYER_H_
2 #define CAFFE_LAYER_H_
3
4 #include <algorithm>
5 #include <string>
6 #include <vector>
7
8 #include "caffe/blob.hpp"
9 #include "caffe/common.hpp"
10 #include "caffe/layer_factory.hpp"
11 #include "caffe/proto/caffe.pb.h"
12 #include "caffe/util/device_alternate.hpp"
13
14 namespace caffe {
15
16 /**
17  * @brief An interface for the units of computation which can be composed into a
18  *        Net.
19  *
20  * Layer&s must implement a Forward function, in which they take their input
21  * (bottom) Blob&s (if any) and compute their output Blob&s (if any).
22  * They may also implement a Backward function, in which they compute the error
23  * gradients with respect to their input Blob&s, given the error gradients with
24  * their output Blob&s.
25  */
26 template <typename Dtype>
27 class Layer {
28  public:
29   /**
30    * You should not implement your own constructor. Any set up code should go
31    * to SetUp(), where the dimensions of the bottom blobs are provided to the
32    * layer.
33    */
34   explicit Layer(const LayerParameter& param)
35     : layer_param_(param) {
36       // The only thing we do is to copy blobs if there are any.
37       if (layer_param_.blobs_size() > 0) {
38         blobs_.resize(layer_param_.blobs_size());
39         for (int i = 0; i < layer_param_.blobs_size(); ++i) {
40           blobs_[i].reset(new Blob<Dtype>());
41           blobs_[i]->FromProto(layer_param_.blobs(i));
42         }
43       }
44     }
45   virtual ~Layer() {}
46
47   /**
48    * @brief Implements common layer setup functionality.
49    *
50    * @param bottom the preshaped input blobs
51    * @param top
52    *     the allocated but unshaped output blobs, to be shaped by Reshape
53    *
54    * Checks that the number of bottom and top blobs is correct.
55    * Calls LayerSetUp to do special layer setup for individual layer types,
56    * followed by Reshape to set up sizes of top blobs and internal buffers.
57    * Sets up the loss weight multiplier blobs for any non-zero loss weights.
58    * This method may not be overridden.
59    */
60   void SetUp(const vector<Blob<Dtype>*>& bottom,
61       const vector<Blob<Dtype>*>& top) {
62     CheckBlobCounts(bottom, top);
63     LayerSetUp(bottom, top);
64     Reshape(bottom, top);
65     SetLossWeights(top);
66   }
67
68   /**
69    * @brief Does layer-specific setup: your layer should implement this function
70    *        as well as Reshape.
71    *
72    * @param bottom
73    *     the preshaped input blobs, whose data fields store the input data for
74    *     this layer
75    * @param top
76    *     the allocated but unshaped output blobs
77    *
78    * This method should do one-time layer specific setup. This includes reading
79    * and processing relevent parameters from the <code>layer_param_</code>.
80    * Setting up the shapes of top blobs and internal buffers should be done in
81    * <code>Reshape</code>, which will be called before the forward pass to
82    * adjust the top blob sizes.
83    */
84   virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
85       const vector<Blob<Dtype>*>& top) {}
86
87   /**
88    * @brief Adjust the shapes of top blobs and internal buffers to accomodate
89    *        the shapes of the bottom blobs.
90    *
91    * @param bottom the input blobs, with the requested input shapes
92    * @param top the top blobs, which should be reshaped as needed
93    *
94    * This method should reshape top blobs as needed according to the shapes
95    * of the bottom (input) blobs, as well as reshaping any internal buffers
96    * and making any other necessary adjustments so that the layer can
97    * accomodate the bottom blobs.
98    */
99   virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
100       const vector<Blob<Dtype>*>& top) = 0;
101
102   /**
103    * @brief Given the bottom blobs, compute the top blobs and the loss.
104    *
105    * @param bottom
106    *     the input blobs, whose data fields store the input data for this layer
107    * @param top
108    *     the preshaped output blobs, whose data fields will store this layers'
109    *     outputs
110    * \return The total loss from the layer.
111    *
112    * The Forward wrapper calls the relevant device wrapper function
113    * (Forward_cpu or Forward_gpu) to compute the top blob values given the
114    * bottom blobs.  If the layer has any non-zero loss_weights, the wrapper
115    * then computes and returns the loss.
116    *
117    * Your layer should implement Forward_cpu and (optionally) Forward_gpu.
118    */
119   inline Dtype Forward(const vector<Blob<Dtype>*>& bottom,
120       const vector<Blob<Dtype>*>& top);
121
122   /**
123    * @brief Given the top blob error gradients, compute the bottom blob error
124    *        gradients.
125    *
126    * @param top
127    *     the output blobs, whose diff fields store the gradient of the error
128    *     with respect to themselves
129    * @param propagate_down
130    *     a vector with equal length to bottom, with each index indicating
131    *     whether to propagate the error gradients down to the bottom blob at
132    *     the corresponding index
133    * @param bottom
134    *     the input blobs, whose diff fields will store the gradient of the error
135    *     with respect to themselves after Backward is run
136    *
137    * The Backward wrapper calls the relevant device wrapper function
138    * (Backward_cpu or Backward_gpu) to compute the bottom blob diffs given the
139    * top blob diffs.
140    *
141    * Your layer should implement Forward_cpu and (optionally) Forward_gpu.
142    */
143   inline void Backward(const vector<Blob<Dtype>*>& top,
144       const vector<bool>& propagate_down,
145       const vector<Blob<Dtype>*>& bottom);
146
147   /**
148    * @brief Returns the vector of learnable parameter blobs.
149    */
150   vector<shared_ptr<Blob<Dtype> > >& blobs() {
151     return blobs_;
152   }
153
154   /**
155    * @brief Returns the layer parameter.
156    */
157   const LayerParameter& layer_param() const { return layer_param_; }
158
159   /**
160    * @brief Writes the layer parameter to a protocol buffer
161    */
162   virtual void ToProto(LayerParameter* param, bool write_diff = false);
163
164   /**
165    * @brief Returns the scalar loss associated with a top blob at a given index.
166    */
167   inline Dtype loss(const int top_index) const {
168     return (loss_.size() > top_index) ? loss_[top_index] : Dtype(0);
169   }
170
171   /**
172    * @brief Sets the loss associated with a top blob at a given index.
173    */
174   inline void set_loss(const int top_index, const Dtype value) {
175     if (loss_.size() <= top_index) {
176       loss_.resize(top_index + 1, Dtype(0));
177     }
178     loss_[top_index] = value;
179   }
180
181   /**
182    * @brief Returns the layer type as an enum value.
183    */
184   virtual inline LayerParameter_LayerType type() const {
185     return LayerParameter_LayerType_NONE;
186   }
187
188   /**
189    * @brief Returns the layer type name.
190    */
191   virtual inline const string& type_name() const {
192     return LayerParameter_LayerType_Name(type());
193   }
194
195   /**
196    * @brief Returns the exact number of bottom blobs required by the layer,
197    *        or -1 if no exact number is required.
198    *
199    * This method should be overridden to return a non-negative value if your
200    * layer expects some exact number of bottom blobs.
201    */
202   virtual inline int ExactNumBottomBlobs() const { return -1; }
203   /**
204    * @brief Returns the minimum number of bottom blobs required by the layer,
205    *        or -1 if no minimum number is required.
206    *
207    * This method should be overridden to return a non-negative value if your
208    * layer expects some minimum number of bottom blobs.
209    */
210   virtual inline int MinBottomBlobs() const { return -1; }
211   /**
212    * @brief Returns the maximum number of bottom blobs required by the layer,
213    *        or -1 if no maximum number is required.
214    *
215    * This method should be overridden to return a non-negative value if your
216    * layer expects some maximum number of bottom blobs.
217    */
218   virtual inline int MaxBottomBlobs() const { return -1; }
219   /**
220    * @brief Returns the exact number of top blobs required by the layer,
221    *        or -1 if no exact number is required.
222    *
223    * This method should be overridden to return a non-negative value if your
224    * layer expects some exact number of top blobs.
225    */
226   virtual inline int ExactNumTopBlobs() const { return -1; }
227   /**
228    * @brief Returns the minimum number of top blobs required by the layer,
229    *        or -1 if no minimum number is required.
230    *
231    * This method should be overridden to return a non-negative value if your
232    * layer expects some minimum number of top blobs.
233    */
234   virtual inline int MinTopBlobs() const { return -1; }
235   /**
236    * @brief Returns the maximum number of top blobs required by the layer,
237    *        or -1 if no maximum number is required.
238    *
239    * This method should be overridden to return a non-negative value if your
240    * layer expects some maximum number of top blobs.
241    */
242   virtual inline int MaxTopBlobs() const { return -1; }
243   /**
244    * @brief Returns true if the layer requires an equal number of bottom and
245    *        top blobs.
246    *
247    * This method should be overridden to return true if your layer expects an
248    * equal number of bottom and top blobs.
249    */
250   virtual inline bool EqualNumBottomTopBlobs() const { return false; }
251
252   /**
253    * @brief Return whether "anonymous" top blobs are created automatically
254    *        by the layer.
255    *
256    * If this method returns true, Net::Init will create enough "anonymous" top
257    * blobs to fulfill the requirement specified by ExactNumTopBlobs() or
258    * MinTopBlobs().
259    */
260   virtual inline bool AutoTopBlobs() const { return false; }
261
262   /**
263    * @brief Return whether to allow force_backward for a given bottom blob
264    *        index.
265    *
266    * If AllowForceBackward(i) == false, we will ignore the force_backward
267    * setting and backpropagate to blob i only if it needs gradient information
268    * (as is done when force_backward == false).
269    */
270   virtual inline bool AllowForceBackward(const int bottom_index) const {
271     return true;
272   }
273
274   /**
275    * @brief Specifies whether the layer should compute gradients w.r.t. a
276    *        parameter at a particular index given by param_id.
277    *
278    * You can safely ignore false values and always compute gradients
279    * for all parameters, but possibly with wasteful computation.
280    */
281   inline bool param_propagate_down(const int param_id) {
282     return (param_propagate_down_.size() > param_id) ?
283         param_propagate_down_[param_id] : false;
284   }
285   /**
286    * @brief Sets whether the layer should compute gradients w.r.t. a
287    *        parameter at a particular index given by param_id.
288    */
289   inline void set_param_propagate_down(const int param_id, const bool value) {
290     if (param_propagate_down_.size() <= param_id) {
291       param_propagate_down_.resize(param_id + 1, true);
292     }
293     param_propagate_down_[param_id] = value;
294   }
295
296
297  protected:
298   /** The protobuf that stores the layer parameters */
299   LayerParameter layer_param_;
300   /** The vector that stores the learnable parameters as a set of blobs. */
301   vector<shared_ptr<Blob<Dtype> > > blobs_;
302   /** Vector indicating whether to compute the diff of each param blob. */
303   vector<bool> param_propagate_down_;
304
305   /** The vector that indicates whether each top blob has a non-zero weight in
306    *  the objective function. */
307   vector<Dtype> loss_;
308
309   /** @brief Using the CPU device, compute the layer output. */
310   virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
311       const vector<Blob<Dtype>*>& top) = 0;
312   /**
313    * @brief Using the GPU device, compute the layer output.
314    *        Fall back to Forward_cpu() if unavailable.
315    */
316   virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
317       const vector<Blob<Dtype>*>& top) {
318     // LOG(WARNING) << "Using CPU code as backup.";
319     return Forward_cpu(bottom, top);
320   }
321
322   /**
323    * @brief Using the CPU device, compute the gradients for any parameters and
324    *        for the bottom blobs if propagate_down is true.
325    */
326   virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
327       const vector<bool>& propagate_down,
328       const vector<Blob<Dtype>*>& bottom) = 0;
329   /**
330    * @brief Using the GPU device, compute the gradients for any parameters and
331    *        for the bottom blobs if propagate_down is true.
332    *        Fall back to Backward_cpu() if unavailable.
333    */
334   virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
335       const vector<bool>& propagate_down,
336       const vector<Blob<Dtype>*>& bottom) {
337     // LOG(WARNING) << "Using CPU code as backup.";
338     Backward_cpu(top, propagate_down, bottom);
339   }
340
341   /**
342    * Called by the parent Layer's SetUp to check that the number of bottom
343    * and top Blobs provided as input match the expected numbers specified by
344    * the {ExactNum,Min,Max}{Bottom,Top}Blobs() functions.
345    */
346   virtual void CheckBlobCounts(const vector<Blob<Dtype>*>& bottom,
347                                const vector<Blob<Dtype>*>& top) {
348     if (ExactNumBottomBlobs() >= 0) {
349       CHECK_EQ(ExactNumBottomBlobs(), bottom.size())
350           << type_name() << " Layer takes " << ExactNumBottomBlobs()
351           << " bottom blob(s) as input.";
352     }
353     if (MinBottomBlobs() >= 0) {
354       CHECK_LE(MinBottomBlobs(), bottom.size())
355           << type_name() << " Layer takes at least " << MinBottomBlobs()
356           << " bottom blob(s) as input.";
357     }
358     if (MaxBottomBlobs() >= 0) {
359       CHECK_GE(MaxBottomBlobs(), bottom.size())
360           << type_name() << " Layer takes at most " << MaxBottomBlobs()
361           << " bottom blob(s) as input.";
362     }
363     if (ExactNumTopBlobs() >= 0) {
364       CHECK_EQ(ExactNumTopBlobs(), top.size())
365           << type_name() << " Layer produces " << ExactNumTopBlobs()
366           << " top blob(s) as output.";
367     }
368     if (MinTopBlobs() >= 0) {
369       CHECK_LE(MinTopBlobs(), top.size())
370           << type_name() << " Layer produces at least " << MinTopBlobs()
371           << " top blob(s) as output.";
372     }
373     if (MaxTopBlobs() >= 0) {
374       CHECK_GE(MaxTopBlobs(), top.size())
375           << type_name() << " Layer produces at most " << MaxTopBlobs()
376           << " top blob(s) as output.";
377     }
378     if (EqualNumBottomTopBlobs()) {
379       CHECK_EQ(bottom.size(), top.size())
380           << type_name() << " Layer produces one top blob as output for each "
381           << "bottom blob input.";
382     }
383   }
384
385   /**
386    * Called by SetUp to initialize the weights associated with any top blobs in
387    * the loss function. Store non-zero loss weights in the diff blob.
388    */
389   inline void SetLossWeights(const vector<Blob<Dtype>*>& top) {
390     const int num_loss_weights = layer_param_.loss_weight_size();
391     if (num_loss_weights) {
392       CHECK_EQ(top.size(), num_loss_weights) << "loss_weight must be "
393           "unspecified or specified once per top blob.";
394       for (int top_id = 0; top_id < top.size(); ++top_id) {
395         const Dtype loss_weight = layer_param_.loss_weight(top_id);
396         if (loss_weight == Dtype(0)) { continue; }
397         this->set_loss(top_id, loss_weight);
398         const int count = top[top_id]->count();
399         Dtype* loss_multiplier = top[top_id]->mutable_cpu_diff();
400         caffe_set(count, loss_weight, loss_multiplier);
401       }
402     }
403   }
404
405   DISABLE_COPY_AND_ASSIGN(Layer);
406 };  // class Layer
407
408 // Forward and backward wrappers. You should implement the cpu and
409 // gpu specific implementations instead, and should not change these
410 // functions.
411 template <typename Dtype>
412 inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype>*>& bottom,
413     const vector<Blob<Dtype>*>& top) {
414   Dtype loss = 0;
415   switch (Caffe::mode()) {
416   case Caffe::CPU:
417     Forward_cpu(bottom, top);
418     for (int top_id = 0; top_id < top.size(); ++top_id) {
419       if (!this->loss(top_id)) { continue; }
420       const int count = top[top_id]->count();
421       const Dtype* data = top[top_id]->cpu_data();
422       const Dtype* loss_weights = top[top_id]->cpu_diff();
423       loss += caffe_cpu_dot(count, data, loss_weights);
424     }
425     break;
426   case Caffe::GPU:
427     Forward_gpu(bottom, top);
428 #ifndef CPU_ONLY
429     for (int top_id = 0; top_id < top.size(); ++top_id) {
430       if (!this->loss(top_id)) { continue; }
431       const int count = top[top_id]->count();
432       const Dtype* data = top[top_id]->gpu_data();
433       const Dtype* loss_weights = top[top_id]->gpu_diff();
434       Dtype blob_loss = 0;
435       caffe_gpu_dot(count, data, loss_weights, &blob_loss);
436       loss += blob_loss;
437     }
438 #endif
439     break;
440   default:
441     LOG(FATAL) << "Unknown caffe mode.";
442   }
443   return loss;
444 }
445
446 template <typename Dtype>
447 inline void Layer<Dtype>::Backward(const vector<Blob<Dtype>*>& top,
448     const vector<bool>& propagate_down,
449     const vector<Blob<Dtype>*>& bottom) {
450   switch (Caffe::mode()) {
451   case Caffe::CPU:
452     Backward_cpu(top, propagate_down, bottom);
453     break;
454   case Caffe::GPU:
455     Backward_gpu(top, propagate_down, bottom);
456     break;
457   default:
458     LOG(FATAL) << "Unknown caffe mode.";
459   }
460 }
461
462 // Serialize LayerParameter to protocol buffer
463 template <typename Dtype>
464 void Layer<Dtype>::ToProto(LayerParameter* param, bool write_diff) {
465   param->Clear();
466   param->CopyFrom(layer_param_);
467   param->clear_blobs();
468   for (int i = 0; i < blobs_.size(); ++i) {
469     blobs_[i]->ToProto(param->add_blobs(), write_diff);
470   }
471 }
472
473 }  // namespace caffe
474
475 #endif  // CAFFE_LAYER_H_