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"
17 * @brief An interface for the units of computation which can be composed into a
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.
26 template <typename Dtype>
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
34 explicit Layer(const LayerParameter& param)
35 : layer_param_(param) {
36 // Set phase and copy blobs (if there are any).
37 phase_ = param.phase();
38 if (layer_param_.blobs_size() > 0) {
39 blobs_.resize(layer_param_.blobs_size());
40 for (int i = 0; i < layer_param_.blobs_size(); ++i) {
41 blobs_[i].reset(new Blob<Dtype>());
42 blobs_[i]->FromProto(layer_param_.blobs(i));
49 * @brief Implements common layer setup functionality.
51 * @param bottom the preshaped input blobs
53 * the allocated but unshaped output blobs, to be shaped by Reshape
55 * Checks that the number of bottom and top blobs is correct.
56 * Calls LayerSetUp to do special layer setup for individual layer types,
57 * followed by Reshape to set up sizes of top blobs and internal buffers.
58 * Sets up the loss weight multiplier blobs for any non-zero loss weights.
59 * This method may not be overridden.
61 void SetUp(const vector<Blob<Dtype>*>& bottom,
62 const vector<Blob<Dtype>*>& top) {
63 CheckBlobCounts(bottom, top);
64 LayerSetUp(bottom, top);
70 * @brief Does layer-specific setup: your layer should implement this function
74 * the preshaped input blobs, whose data fields store the input data for
77 * the allocated but unshaped output blobs
79 * This method should do one-time layer specific setup. This includes reading
80 * and processing relevent parameters from the <code>layer_param_</code>.
81 * Setting up the shapes of top blobs and internal buffers should be done in
82 * <code>Reshape</code>, which will be called before the forward pass to
83 * adjust the top blob sizes.
85 virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
86 const vector<Blob<Dtype>*>& top) {}
89 * @brief Adjust the shapes of top blobs and internal buffers to accomodate
90 * the shapes of the bottom blobs.
92 * @param bottom the input blobs, with the requested input shapes
93 * @param top the top blobs, which should be reshaped as needed
95 * This method should reshape top blobs as needed according to the shapes
96 * of the bottom (input) blobs, as well as reshaping any internal buffers
97 * and making any other necessary adjustments so that the layer can
98 * accomodate the bottom blobs.
100 virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
101 const vector<Blob<Dtype>*>& top) = 0;
104 * @brief Given the bottom blobs, compute the top blobs and the loss.
107 * the input blobs, whose data fields store the input data for this layer
109 * the preshaped output blobs, whose data fields will store this layers'
111 * \return The total loss from the layer.
113 * The Forward wrapper calls the relevant device wrapper function
114 * (Forward_cpu or Forward_gpu) to compute the top blob values given the
115 * bottom blobs. If the layer has any non-zero loss_weights, the wrapper
116 * then computes and returns the loss.
118 * Your layer should implement Forward_cpu and (optionally) Forward_gpu.
120 inline Dtype Forward(const vector<Blob<Dtype>*>& bottom,
121 const vector<Blob<Dtype>*>& top);
124 * @brief Given the top blob error gradients, compute the bottom blob error
128 * the output blobs, whose diff fields store the gradient of the error
129 * with respect to themselves
130 * @param propagate_down
131 * a vector with equal length to bottom, with each index indicating
132 * whether to propagate the error gradients down to the bottom blob at
133 * the corresponding index
135 * the input blobs, whose diff fields will store the gradient of the error
136 * with respect to themselves after Backward is run
138 * The Backward wrapper calls the relevant device wrapper function
139 * (Backward_cpu or Backward_gpu) to compute the bottom blob diffs given the
142 * Your layer should implement Backward_cpu and (optionally) Backward_gpu.
144 inline void Backward(const vector<Blob<Dtype>*>& top,
145 const vector<bool>& propagate_down,
146 const vector<Blob<Dtype>*>& bottom);
149 * @brief Returns the vector of learnable parameter blobs.
151 vector<shared_ptr<Blob<Dtype> > >& blobs() {
156 * @brief Returns the layer parameter.
158 const LayerParameter& layer_param() const { return layer_param_; }
161 * @brief Writes the layer parameter to a protocol buffer
163 virtual void ToProto(LayerParameter* param, bool write_diff = false);
166 * @brief Returns the scalar loss associated with a top blob at a given index.
168 inline Dtype loss(const int top_index) const {
169 return (loss_.size() > top_index) ? loss_[top_index] : Dtype(0);
173 * @brief Sets the loss associated with a top blob at a given index.
175 inline void set_loss(const int top_index, const Dtype value) {
176 if (loss_.size() <= top_index) {
177 loss_.resize(top_index + 1, Dtype(0));
179 loss_[top_index] = value;
183 * @brief Returns the layer type.
185 virtual inline const char* type() const { return ""; }
188 * @brief Returns the exact number of bottom blobs required by the layer,
189 * or -1 if no exact number is required.
191 * This method should be overridden to return a non-negative value if your
192 * layer expects some exact number of bottom blobs.
194 virtual inline int ExactNumBottomBlobs() const { return -1; }
196 * @brief Returns the minimum number of bottom blobs required by the layer,
197 * or -1 if no minimum number is required.
199 * This method should be overridden to return a non-negative value if your
200 * layer expects some minimum number of bottom blobs.
202 virtual inline int MinBottomBlobs() const { return -1; }
204 * @brief Returns the maximum number of bottom blobs required by the layer,
205 * or -1 if no maximum number is required.
207 * This method should be overridden to return a non-negative value if your
208 * layer expects some maximum number of bottom blobs.
210 virtual inline int MaxBottomBlobs() const { return -1; }
212 * @brief Returns the exact number of top blobs required by the layer,
213 * or -1 if no exact number is required.
215 * This method should be overridden to return a non-negative value if your
216 * layer expects some exact number of top blobs.
218 virtual inline int ExactNumTopBlobs() const { return -1; }
220 * @brief Returns the minimum number of top blobs required by the layer,
221 * or -1 if no minimum number is required.
223 * This method should be overridden to return a non-negative value if your
224 * layer expects some minimum number of top blobs.
226 virtual inline int MinTopBlobs() const { return -1; }
228 * @brief Returns the maximum number of top blobs required by the layer,
229 * or -1 if no maximum number is required.
231 * This method should be overridden to return a non-negative value if your
232 * layer expects some maximum number of top blobs.
234 virtual inline int MaxTopBlobs() const { return -1; }
236 * @brief Returns true if the layer requires an equal number of bottom and
239 * This method should be overridden to return true if your layer expects an
240 * equal number of bottom and top blobs.
242 virtual inline bool EqualNumBottomTopBlobs() const { return false; }
245 * @brief Return whether "anonymous" top blobs are created automatically
248 * If this method returns true, Net::Init will create enough "anonymous" top
249 * blobs to fulfill the requirement specified by ExactNumTopBlobs() or
252 virtual inline bool AutoTopBlobs() const { return false; }
255 * @brief Return whether to allow force_backward for a given bottom blob
258 * If AllowForceBackward(i) == false, we will ignore the force_backward
259 * setting and backpropagate to blob i only if it needs gradient information
260 * (as is done when force_backward == false).
262 virtual inline bool AllowForceBackward(const int bottom_index) const {
267 * @brief Specifies whether the layer should compute gradients w.r.t. a
268 * parameter at a particular index given by param_id.
270 * You can safely ignore false values and always compute gradients
271 * for all parameters, but possibly with wasteful computation.
273 inline bool param_propagate_down(const int param_id) {
274 return (param_propagate_down_.size() > param_id) ?
275 param_propagate_down_[param_id] : false;
278 * @brief Sets whether the layer should compute gradients w.r.t. a
279 * parameter at a particular index given by param_id.
281 inline void set_param_propagate_down(const int param_id, const bool value) {
282 if (param_propagate_down_.size() <= param_id) {
283 param_propagate_down_.resize(param_id + 1, true);
285 param_propagate_down_[param_id] = value;
290 /** The protobuf that stores the layer parameters */
291 LayerParameter layer_param_;
292 /** The phase: TRAIN or TEST */
294 /** The vector that stores the learnable parameters as a set of blobs. */
295 vector<shared_ptr<Blob<Dtype> > > blobs_;
296 /** Vector indicating whether to compute the diff of each param blob. */
297 vector<bool> param_propagate_down_;
299 /** The vector that indicates whether each top blob has a non-zero weight in
300 * the objective function. */
303 /** @brief Using the CPU device, compute the layer output. */
304 virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
305 const vector<Blob<Dtype>*>& top) = 0;
307 * @brief Using the GPU device, compute the layer output.
308 * Fall back to Forward_cpu() if unavailable.
310 virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
311 const vector<Blob<Dtype>*>& top) {
312 // LOG(WARNING) << "Using CPU code as backup.";
313 return Forward_cpu(bottom, top);
317 * @brief Using the CPU device, compute the gradients for any parameters and
318 * for the bottom blobs if propagate_down is true.
320 virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
321 const vector<bool>& propagate_down,
322 const vector<Blob<Dtype>*>& bottom) = 0;
324 * @brief Using the GPU device, compute the gradients for any parameters and
325 * for the bottom blobs if propagate_down is true.
326 * Fall back to Backward_cpu() if unavailable.
328 virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
329 const vector<bool>& propagate_down,
330 const vector<Blob<Dtype>*>& bottom) {
331 // LOG(WARNING) << "Using CPU code as backup.";
332 Backward_cpu(top, propagate_down, bottom);
336 * Called by the parent Layer's SetUp to check that the number of bottom
337 * and top Blobs provided as input match the expected numbers specified by
338 * the {ExactNum,Min,Max}{Bottom,Top}Blobs() functions.
340 virtual void CheckBlobCounts(const vector<Blob<Dtype>*>& bottom,
341 const vector<Blob<Dtype>*>& top) {
342 if (ExactNumBottomBlobs() >= 0) {
343 CHECK_EQ(ExactNumBottomBlobs(), bottom.size())
344 << type() << " Layer takes " << ExactNumBottomBlobs()
345 << " bottom blob(s) as input.";
347 if (MinBottomBlobs() >= 0) {
348 CHECK_LE(MinBottomBlobs(), bottom.size())
349 << type() << " Layer takes at least " << MinBottomBlobs()
350 << " bottom blob(s) as input.";
352 if (MaxBottomBlobs() >= 0) {
353 CHECK_GE(MaxBottomBlobs(), bottom.size())
354 << type() << " Layer takes at most " << MaxBottomBlobs()
355 << " bottom blob(s) as input.";
357 if (ExactNumTopBlobs() >= 0) {
358 CHECK_EQ(ExactNumTopBlobs(), top.size())
359 << type() << " Layer produces " << ExactNumTopBlobs()
360 << " top blob(s) as output.";
362 if (MinTopBlobs() >= 0) {
363 CHECK_LE(MinTopBlobs(), top.size())
364 << type() << " Layer produces at least " << MinTopBlobs()
365 << " top blob(s) as output.";
367 if (MaxTopBlobs() >= 0) {
368 CHECK_GE(MaxTopBlobs(), top.size())
369 << type() << " Layer produces at most " << MaxTopBlobs()
370 << " top blob(s) as output.";
372 if (EqualNumBottomTopBlobs()) {
373 CHECK_EQ(bottom.size(), top.size())
374 << type() << " Layer produces one top blob as output for each "
375 << "bottom blob input.";
380 * Called by SetUp to initialize the weights associated with any top blobs in
381 * the loss function. Store non-zero loss weights in the diff blob.
383 inline void SetLossWeights(const vector<Blob<Dtype>*>& top) {
384 const int num_loss_weights = layer_param_.loss_weight_size();
385 if (num_loss_weights) {
386 CHECK_EQ(top.size(), num_loss_weights) << "loss_weight must be "
387 "unspecified or specified once per top blob.";
388 for (int top_id = 0; top_id < top.size(); ++top_id) {
389 const Dtype loss_weight = layer_param_.loss_weight(top_id);
390 if (loss_weight == Dtype(0)) { continue; }
391 this->set_loss(top_id, loss_weight);
392 const int count = top[top_id]->count();
393 Dtype* loss_multiplier = top[top_id]->mutable_cpu_diff();
394 caffe_set(count, loss_weight, loss_multiplier);
399 DISABLE_COPY_AND_ASSIGN(Layer);
402 // Forward and backward wrappers. You should implement the cpu and
403 // gpu specific implementations instead, and should not change these
405 template <typename Dtype>
406 inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype>*>& bottom,
407 const vector<Blob<Dtype>*>& top) {
409 Reshape(bottom, top);
410 switch (Caffe::mode()) {
412 Forward_cpu(bottom, top);
413 for (int top_id = 0; top_id < top.size(); ++top_id) {
414 if (!this->loss(top_id)) { continue; }
415 const int count = top[top_id]->count();
416 const Dtype* data = top[top_id]->cpu_data();
417 const Dtype* loss_weights = top[top_id]->cpu_diff();
418 loss += caffe_cpu_dot(count, data, loss_weights);
422 Forward_gpu(bottom, top);
424 for (int top_id = 0; top_id < top.size(); ++top_id) {
425 if (!this->loss(top_id)) { continue; }
426 const int count = top[top_id]->count();
427 const Dtype* data = top[top_id]->gpu_data();
428 const Dtype* loss_weights = top[top_id]->gpu_diff();
430 caffe_gpu_dot(count, data, loss_weights, &blob_loss);
436 LOG(FATAL) << "Unknown caffe mode.";
441 template <typename Dtype>
442 inline void Layer<Dtype>::Backward(const vector<Blob<Dtype>*>& top,
443 const vector<bool>& propagate_down,
444 const vector<Blob<Dtype>*>& bottom) {
445 switch (Caffe::mode()) {
447 Backward_cpu(top, propagate_down, bottom);
450 Backward_gpu(top, propagate_down, bottom);
453 LOG(FATAL) << "Unknown caffe mode.";
457 // Serialize LayerParameter to protocol buffer
458 template <typename Dtype>
459 void Layer<Dtype>::ToProto(LayerParameter* param, bool write_diff) {
461 param->CopyFrom(layer_param_);
462 param->clear_blobs();
463 for (int i = 0; i < blobs_.size(); ++i) {
464 blobs_[i]->ToProto(param->add_blobs(), write_diff);
470 #endif // CAFFE_LAYER_H_