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