Merge pull request #1837 from shelhamer/image-fail-die
[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.
183    */
184   virtual inline const char* type() const { return ""; }
185
186   /**
187    * @brief Returns the exact number of bottom blobs required by the layer,
188    *        or -1 if no exact number is required.
189    *
190    * This method should be overridden to return a non-negative value if your
191    * layer expects some exact number of bottom blobs.
192    */
193   virtual inline int ExactNumBottomBlobs() const { return -1; }
194   /**
195    * @brief Returns the minimum number of bottom blobs required by the layer,
196    *        or -1 if no minimum number is required.
197    *
198    * This method should be overridden to return a non-negative value if your
199    * layer expects some minimum number of bottom blobs.
200    */
201   virtual inline int MinBottomBlobs() const { return -1; }
202   /**
203    * @brief Returns the maximum number of bottom blobs required by the layer,
204    *        or -1 if no maximum number is required.
205    *
206    * This method should be overridden to return a non-negative value if your
207    * layer expects some maximum number of bottom blobs.
208    */
209   virtual inline int MaxBottomBlobs() const { return -1; }
210   /**
211    * @brief Returns the exact number of top blobs required by the layer,
212    *        or -1 if no exact number is required.
213    *
214    * This method should be overridden to return a non-negative value if your
215    * layer expects some exact number of top blobs.
216    */
217   virtual inline int ExactNumTopBlobs() const { return -1; }
218   /**
219    * @brief Returns the minimum number of top blobs required by the layer,
220    *        or -1 if no minimum number is required.
221    *
222    * This method should be overridden to return a non-negative value if your
223    * layer expects some minimum number of top blobs.
224    */
225   virtual inline int MinTopBlobs() const { return -1; }
226   /**
227    * @brief Returns the maximum number of top blobs required by the layer,
228    *        or -1 if no maximum number is required.
229    *
230    * This method should be overridden to return a non-negative value if your
231    * layer expects some maximum number of top blobs.
232    */
233   virtual inline int MaxTopBlobs() const { return -1; }
234   /**
235    * @brief Returns true if the layer requires an equal number of bottom and
236    *        top blobs.
237    *
238    * This method should be overridden to return true if your layer expects an
239    * equal number of bottom and top blobs.
240    */
241   virtual inline bool EqualNumBottomTopBlobs() const { return false; }
242
243   /**
244    * @brief Return whether "anonymous" top blobs are created automatically
245    *        by the layer.
246    *
247    * If this method returns true, Net::Init will create enough "anonymous" top
248    * blobs to fulfill the requirement specified by ExactNumTopBlobs() or
249    * MinTopBlobs().
250    */
251   virtual inline bool AutoTopBlobs() const { return false; }
252
253   /**
254    * @brief Return whether to allow force_backward for a given bottom blob
255    *        index.
256    *
257    * If AllowForceBackward(i) == false, we will ignore the force_backward
258    * setting and backpropagate to blob i only if it needs gradient information
259    * (as is done when force_backward == false).
260    */
261   virtual inline bool AllowForceBackward(const int bottom_index) const {
262     return true;
263   }
264
265   /**
266    * @brief Specifies whether the layer should compute gradients w.r.t. a
267    *        parameter at a particular index given by param_id.
268    *
269    * You can safely ignore false values and always compute gradients
270    * for all parameters, but possibly with wasteful computation.
271    */
272   inline bool param_propagate_down(const int param_id) {
273     return (param_propagate_down_.size() > param_id) ?
274         param_propagate_down_[param_id] : false;
275   }
276   /**
277    * @brief Sets whether the layer should compute gradients w.r.t. a
278    *        parameter at a particular index given by param_id.
279    */
280   inline void set_param_propagate_down(const int param_id, const bool value) {
281     if (param_propagate_down_.size() <= param_id) {
282       param_propagate_down_.resize(param_id + 1, true);
283     }
284     param_propagate_down_[param_id] = value;
285   }
286
287
288  protected:
289   /** The protobuf that stores the layer parameters */
290   LayerParameter layer_param_;
291   /** The vector that stores the learnable parameters as a set of blobs. */
292   vector<shared_ptr<Blob<Dtype> > > blobs_;
293   /** Vector indicating whether to compute the diff of each param blob. */
294   vector<bool> param_propagate_down_;
295
296   /** The vector that indicates whether each top blob has a non-zero weight in
297    *  the objective function. */
298   vector<Dtype> loss_;
299
300   /** @brief Using the CPU device, compute the layer output. */
301   virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
302       const vector<Blob<Dtype>*>& top) = 0;
303   /**
304    * @brief Using the GPU device, compute the layer output.
305    *        Fall back to Forward_cpu() if unavailable.
306    */
307   virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
308       const vector<Blob<Dtype>*>& top) {
309     // LOG(WARNING) << "Using CPU code as backup.";
310     return Forward_cpu(bottom, top);
311   }
312
313   /**
314    * @brief Using the CPU device, compute the gradients for any parameters and
315    *        for the bottom blobs if propagate_down is true.
316    */
317   virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
318       const vector<bool>& propagate_down,
319       const vector<Blob<Dtype>*>& bottom) = 0;
320   /**
321    * @brief Using the GPU device, compute the gradients for any parameters and
322    *        for the bottom blobs if propagate_down is true.
323    *        Fall back to Backward_cpu() if unavailable.
324    */
325   virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
326       const vector<bool>& propagate_down,
327       const vector<Blob<Dtype>*>& bottom) {
328     // LOG(WARNING) << "Using CPU code as backup.";
329     Backward_cpu(top, propagate_down, bottom);
330   }
331
332   /**
333    * Called by the parent Layer's SetUp to check that the number of bottom
334    * and top Blobs provided as input match the expected numbers specified by
335    * the {ExactNum,Min,Max}{Bottom,Top}Blobs() functions.
336    */
337   virtual void CheckBlobCounts(const vector<Blob<Dtype>*>& bottom,
338                                const vector<Blob<Dtype>*>& top) {
339     if (ExactNumBottomBlobs() >= 0) {
340       CHECK_EQ(ExactNumBottomBlobs(), bottom.size())
341           << type() << " Layer takes " << ExactNumBottomBlobs()
342           << " bottom blob(s) as input.";
343     }
344     if (MinBottomBlobs() >= 0) {
345       CHECK_LE(MinBottomBlobs(), bottom.size())
346           << type() << " Layer takes at least " << MinBottomBlobs()
347           << " bottom blob(s) as input.";
348     }
349     if (MaxBottomBlobs() >= 0) {
350       CHECK_GE(MaxBottomBlobs(), bottom.size())
351           << type() << " Layer takes at most " << MaxBottomBlobs()
352           << " bottom blob(s) as input.";
353     }
354     if (ExactNumTopBlobs() >= 0) {
355       CHECK_EQ(ExactNumTopBlobs(), top.size())
356           << type() << " Layer produces " << ExactNumTopBlobs()
357           << " top blob(s) as output.";
358     }
359     if (MinTopBlobs() >= 0) {
360       CHECK_LE(MinTopBlobs(), top.size())
361           << type() << " Layer produces at least " << MinTopBlobs()
362           << " top blob(s) as output.";
363     }
364     if (MaxTopBlobs() >= 0) {
365       CHECK_GE(MaxTopBlobs(), top.size())
366           << type() << " Layer produces at most " << MaxTopBlobs()
367           << " top blob(s) as output.";
368     }
369     if (EqualNumBottomTopBlobs()) {
370       CHECK_EQ(bottom.size(), top.size())
371           << type() << " Layer produces one top blob as output for each "
372           << "bottom blob input.";
373     }
374   }
375
376   /**
377    * Called by SetUp to initialize the weights associated with any top blobs in
378    * the loss function. Store non-zero loss weights in the diff blob.
379    */
380   inline void SetLossWeights(const vector<Blob<Dtype>*>& top) {
381     const int num_loss_weights = layer_param_.loss_weight_size();
382     if (num_loss_weights) {
383       CHECK_EQ(top.size(), num_loss_weights) << "loss_weight must be "
384           "unspecified or specified once per top blob.";
385       for (int top_id = 0; top_id < top.size(); ++top_id) {
386         const Dtype loss_weight = layer_param_.loss_weight(top_id);
387         if (loss_weight == Dtype(0)) { continue; }
388         this->set_loss(top_id, loss_weight);
389         const int count = top[top_id]->count();
390         Dtype* loss_multiplier = top[top_id]->mutable_cpu_diff();
391         caffe_set(count, loss_weight, loss_multiplier);
392       }
393     }
394   }
395
396   DISABLE_COPY_AND_ASSIGN(Layer);
397 };  // class Layer
398
399 // Forward and backward wrappers. You should implement the cpu and
400 // gpu specific implementations instead, and should not change these
401 // functions.
402 template <typename Dtype>
403 inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype>*>& bottom,
404     const vector<Blob<Dtype>*>& top) {
405   Dtype loss = 0;
406   switch (Caffe::mode()) {
407   case Caffe::CPU:
408     Forward_cpu(bottom, top);
409     for (int top_id = 0; top_id < top.size(); ++top_id) {
410       if (!this->loss(top_id)) { continue; }
411       const int count = top[top_id]->count();
412       const Dtype* data = top[top_id]->cpu_data();
413       const Dtype* loss_weights = top[top_id]->cpu_diff();
414       loss += caffe_cpu_dot(count, data, loss_weights);
415     }
416     break;
417   case Caffe::GPU:
418     Forward_gpu(bottom, top);
419 #ifndef CPU_ONLY
420     for (int top_id = 0; top_id < top.size(); ++top_id) {
421       if (!this->loss(top_id)) { continue; }
422       const int count = top[top_id]->count();
423       const Dtype* data = top[top_id]->gpu_data();
424       const Dtype* loss_weights = top[top_id]->gpu_diff();
425       Dtype blob_loss = 0;
426       caffe_gpu_dot(count, data, loss_weights, &blob_loss);
427       loss += blob_loss;
428     }
429 #endif
430     break;
431   default:
432     LOG(FATAL) << "Unknown caffe mode.";
433   }
434   return loss;
435 }
436
437 template <typename Dtype>
438 inline void Layer<Dtype>::Backward(const vector<Blob<Dtype>*>& top,
439     const vector<bool>& propagate_down,
440     const vector<Blob<Dtype>*>& bottom) {
441   switch (Caffe::mode()) {
442   case Caffe::CPU:
443     Backward_cpu(top, propagate_down, bottom);
444     break;
445   case Caffe::GPU:
446     Backward_gpu(top, propagate_down, bottom);
447     break;
448   default:
449     LOG(FATAL) << "Unknown caffe mode.";
450   }
451 }
452
453 // Serialize LayerParameter to protocol buffer
454 template <typename Dtype>
455 void Layer<Dtype>::ToProto(LayerParameter* param, bool write_diff) {
456   param->Clear();
457   param->CopyFrom(layer_param_);
458   param->clear_blobs();
459   for (int i = 0; i < blobs_.size(); ++i) {
460     blobs_[i]->ToProto(param->add_blobs(), write_diff);
461   }
462 }
463
464 }  // namespace caffe
465
466 #endif  // CAFFE_LAYER_H_