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"
15 Forward declare boost::thread instead of including boost/thread.hpp
16 to avoid a boost/NVCC issues (#1009, #1010) on OSX.
18 namespace boost { class mutex; }
23 * @brief An interface for the units of computation which can be composed into a
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.
32 template <typename Dtype>
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
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));
55 * @brief Implements common layer setup functionality.
57 * @param bottom the preshaped input blobs
59 * the allocated but unshaped output blobs, to be shaped by Reshape
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.
67 void SetUp(const vector<Blob<Dtype>*>& bottom,
68 const vector<Blob<Dtype>*>& top) {
70 CheckBlobCounts(bottom, top);
71 LayerSetUp(bottom, top);
77 * @brief Does layer-specific setup: your layer should implement this function
81 * the preshaped input blobs, whose data fields store the input data for
84 * the allocated but unshaped output blobs
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.
92 virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
93 const vector<Blob<Dtype>*>& top) {}
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.
101 virtual inline bool ShareInParallel() const { return false; }
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.
107 inline bool IsShared() const { return is_shared_; }
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.
113 inline void SetShared(bool is_shared) {
114 CHECK(ShareInParallel() || !is_shared)
115 << type() << "Layer does not support sharing.";
116 is_shared_ = is_shared;
120 * @brief Adjust the shapes of top blobs and internal buffers to accommodate
121 * the shapes of the bottom blobs.
123 * @param bottom the input blobs, with the requested input shapes
124 * @param top the top blobs, which should be reshaped as needed
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.
131 virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
132 const vector<Blob<Dtype>*>& top) = 0;
135 * @brief Given the bottom blobs, compute the top blobs and the loss.
138 * the input blobs, whose data fields store the input data for this layer
140 * the preshaped output blobs, whose data fields will store this layers'
142 * \return The total loss from the layer.
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.
149 * Your layer should implement Forward_cpu and (optionally) Forward_gpu.
151 inline Dtype Forward(const vector<Blob<Dtype>*>& bottom,
152 const vector<Blob<Dtype>*>& top);
155 * @brief Given the top blob error gradients, compute the bottom blob error
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
166 * the input blobs, whose diff fields will store the gradient of the error
167 * with respect to themselves after Backward is run
169 * The Backward wrapper calls the relevant device wrapper function
170 * (Backward_cpu or Backward_gpu) to compute the bottom blob diffs given the
173 * Your layer should implement Backward_cpu and (optionally) Backward_gpu.
175 inline void Backward(const vector<Blob<Dtype>*>& top,
176 const vector<bool>& propagate_down,
177 const vector<Blob<Dtype>*>& bottom);
180 * @brief Returns the vector of learnable parameter blobs.
182 vector<shared_ptr<Blob<Dtype> > >& blobs() {
187 * @brief Returns the layer parameter.
189 const LayerParameter& layer_param() const { return layer_param_; }
192 * @brief Writes the layer parameter to a protocol buffer
194 virtual void ToProto(LayerParameter* param, bool write_diff = false);
197 * @brief Returns the scalar loss associated with a top blob at a given index.
199 inline Dtype loss(const int top_index) const {
200 return (loss_.size() > top_index) ? loss_[top_index] : Dtype(0);
204 * @brief Sets the loss associated with a top blob at a given index.
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));
210 loss_[top_index] = value;
214 * @brief Returns the layer type.
216 virtual inline const char* type() const { return ""; }
219 * @brief Returns the exact number of bottom blobs required by the layer,
220 * or -1 if no exact number is required.
222 * This method should be overridden to return a non-negative value if your
223 * layer expects some exact number of bottom blobs.
225 virtual inline int ExactNumBottomBlobs() const { return -1; }
227 * @brief Returns the minimum number of bottom blobs required by the layer,
228 * or -1 if no minimum number is required.
230 * This method should be overridden to return a non-negative value if your
231 * layer expects some minimum number of bottom blobs.
233 virtual inline int MinBottomBlobs() const { return -1; }
235 * @brief Returns the maximum number of bottom blobs required by the layer,
236 * or -1 if no maximum number is required.
238 * This method should be overridden to return a non-negative value if your
239 * layer expects some maximum number of bottom blobs.
241 virtual inline int MaxBottomBlobs() const { return -1; }
243 * @brief Returns the exact number of top blobs required by the layer,
244 * or -1 if no exact number is required.
246 * This method should be overridden to return a non-negative value if your
247 * layer expects some exact number of top blobs.
249 virtual inline int ExactNumTopBlobs() const { return -1; }
251 * @brief Returns the minimum number of top blobs required by the layer,
252 * or -1 if no minimum number is required.
254 * This method should be overridden to return a non-negative value if your
255 * layer expects some minimum number of top blobs.
257 virtual inline int MinTopBlobs() const { return -1; }
259 * @brief Returns the maximum number of top blobs required by the layer,
260 * or -1 if no maximum number is required.
262 * This method should be overridden to return a non-negative value if your
263 * layer expects some maximum number of top blobs.
265 virtual inline int MaxTopBlobs() const { return -1; }
267 * @brief Returns true if the layer requires an equal number of bottom and
270 * This method should be overridden to return true if your layer expects an
271 * equal number of bottom and top blobs.
273 virtual inline bool EqualNumBottomTopBlobs() const { return false; }
276 * @brief Return whether "anonymous" top blobs are created automatically
279 * If this method returns true, Net::Init will create enough "anonymous" top
280 * blobs to fulfill the requirement specified by ExactNumTopBlobs() or
283 virtual inline bool AutoTopBlobs() const { return false; }
286 * @brief Return whether to allow force_backward for a given bottom blob
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).
293 virtual inline bool AllowForceBackward(const int bottom_index) const {
298 * @brief Specifies whether the layer should compute gradients w.r.t. a
299 * parameter at a particular index given by param_id.
301 * You can safely ignore false values and always compute gradients
302 * for all parameters, but possibly with wasteful computation.
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;
309 * @brief Sets whether the layer should compute gradients w.r.t. a
310 * parameter at a particular index given by param_id.
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);
316 param_propagate_down_[param_id] = value;
321 /** The protobuf that stores the layer parameters */
322 LayerParameter layer_param_;
323 /** The phase: TRAIN or TEST */
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_;
330 /** The vector that indicates whether each top blob has a non-zero weight in
331 * the objective function. */
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;
338 * @brief Using the GPU device, compute the layer output.
339 * Fall back to Forward_cpu() if unavailable.
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);
348 * @brief Using the CPU device, compute the gradients for any parameters and
349 * for the bottom blobs if propagate_down is true.
351 virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
352 const vector<bool>& propagate_down,
353 const vector<Blob<Dtype>*>& bottom) = 0;
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.
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);
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.
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.";
378 if (MinBottomBlobs() >= 0) {
379 CHECK_LE(MinBottomBlobs(), bottom.size())
380 << type() << " Layer takes at least " << MinBottomBlobs()
381 << " bottom blob(s) as input.";
383 if (MaxBottomBlobs() >= 0) {
384 CHECK_GE(MaxBottomBlobs(), bottom.size())
385 << type() << " Layer takes at most " << MaxBottomBlobs()
386 << " bottom blob(s) as input.";
388 if (ExactNumTopBlobs() >= 0) {
389 CHECK_EQ(ExactNumTopBlobs(), top.size())
390 << type() << " Layer produces " << ExactNumTopBlobs()
391 << " top blob(s) as output.";
393 if (MinTopBlobs() >= 0) {
394 CHECK_LE(MinTopBlobs(), top.size())
395 << type() << " Layer produces at least " << MinTopBlobs()
396 << " top blob(s) as output.";
398 if (MaxTopBlobs() >= 0) {
399 CHECK_GE(MaxTopBlobs(), top.size())
400 << type() << " Layer produces at most " << MaxTopBlobs()
401 << " top blob(s) as output.";
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.";
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.
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);
431 /** Whether this layer is actually shared by other nets*/
434 /** The mutex for sequential forward if this layer is shared */
435 shared_ptr<boost::mutex> forward_mutex_;
437 /** Initialize forward_mutex_ */
439 /** Lock forward_mutex_ if this layer is shared */
441 /** Unlock forward_mutex_ if this layer is shared */
444 DISABLE_COPY_AND_ASSIGN(Layer);
447 // Forward and backward wrappers. You should implement the cpu and
448 // gpu specific implementations instead, and should not change these
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
456 Reshape(bottom, top);
457 switch (Caffe::mode()) {
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);
469 Forward_gpu(bottom, top);
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();
477 caffe_gpu_dot(count, data, loss_weights, &blob_loss);
483 LOG(FATAL) << "Unknown caffe mode.";
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()) {
495 Backward_cpu(top, propagate_down, bottom);
498 Backward_gpu(top, propagate_down, bottom);
501 LOG(FATAL) << "Unknown caffe mode.";
505 // Serialize LayerParameter to protocol buffer
506 template <typename Dtype>
507 void Layer<Dtype>::ToProto(LayerParameter* param, bool write_diff) {
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);
518 #endif // CAFFE_LAYER_H_