caffe代码阅读5:Layer的实现细节-2016.3.17

caffe代码阅读5:Layer的实现细节-2016.3.17

一、Layer的作用简介

Layer实际上定义了Layer的基本操作,即初始化层、前向传播和反向传播。在前向传播中根据bottom blob得到top blob,反向传播则根据top反传到bottom。而且在前传的时候还可以计算loss,一般来说只有最后一层才会计算loss,虽然每个层都有计算loss的功能。Layer类在没有实现GPU前传和反传的时候会自动使用CPU的实现。下面给出Layer类的具体介绍。
下面给出生成的一幅图,感性地了解一下Layer的层次。
类的层次

二、Layer类的详细介绍

1)构造函数

构造函数初始化层的参数,并且设置当前层是否可以共享(如果是数据层则可以共享数据给多个网络)
这里的blobs_的定义是 vector<shared_ptr<Blob<Dtype> > > blobs_;也就是说它是是blob指针类型的容器。
[cpp] view plain copy
 
  1. explicit Layer(const LayerParameter& param)  
  2.     : layer_param_(param), is_shared_(false) {  
  3.       // Set phase and copy blobs (if there are any).  
  4.       // 训练还是测试?phase  
  5.       phase_ = param.phase();  
  6.       if (layer_param_.blobs_size() > 0) {  
  7.         // 将blobs_的大小设置为参数中的大小  
  8.         blobs_.resize(layer_param_.blobs_size());  
  9.         for (int i = 0; i < layer_param_.blobs_size(); ++i) {  
  10.           // 新建若干个Blob  
  11.           blobs_[i].reset(new Blob<Dtype>());  
  12.           // 从blob文件中获取数据  
  13.           blobs_[i]->FromProto(layer_param_.blobs(i));  
  14.         }  
  15.       }  
  16.     }  

2)成员变量

保护性的成员变量:
[cpp] view plain copy
 
  1. /** The protobuf that stores the layer parameters */  
  2. // 层的参数  
  3. LayerParameter layer_param_;  
  4. /** The phase: TRAIN or TEST */  
  5. // 训练还是测试  
  6. Phase phase_;  
  7. /** The vector that stores the learnable parameters as a set of blobs. */  
  8. // blobs_的是blob指针容器  
  9. vector<shared_ptr<Blob<Dtype> > > blobs_;  
  10. /** Vector indicating whether to compute the diff of each param blob. */  
  11. // 是否需要计算梯度,也即是否需要往下传播  
  12. vector<bool> param_propagate_down_;  
  13.   
  14. /** The vector that indicates whether each top blob has a non-zero weight in 
  15.  *  the objective function. */  
  16. // 每个top blob在目标函数中有非零的权重  
  17. vector<Dtype> loss_;  
私有的成员变量:
[cpp] view plain copy
 
  1. /** Whether this layer is actually shared by other nets*/  
  2. // 判断该层是否被其他层所共享  
  3. // 这个内部变量实际是判断该层是不是数据层、数据层才可以被其他的网络共享  
  4. bool is_shared_;  
  5.   
  6. /** The mutex for sequential forward if this layer is shared */  
  7. // 前向传播的时候所使用的互斥量的指针  
  8. shared_ptr<boost::mutex> forward_mutex_;  

3)成员函数

3-1非内联函数:
[cpp] view plain copy
 
  1. /** Initialize forward_mutex_ */  
  2. void InitMutex();  
  3. /** Lock forward_mutex_ if this layer is shared */  
  4. // 如果该层是共享的,则需要锁住互斥量  
  5. void Lock();  
  6. /** Unlock forward_mutex_ if this layer is shared */  
  7. // 如果该层是共享的,则需要解锁互斥量  
  8. void Unlock();  
3-2内联函数:
[cpp] view plain copy
 
  1. // 判断该层是否开启共享模式(即是否数据并行化了)  
  2. inline bool IsShared() const { return is_shared_; }  
  3.  // 设置是否共享  
  4. inline void SetShared(bool is_shared) {  
  5.   CHECK(ShareInParallel() || !is_shared)  
  6.       << type() << "Layer does not support sharing.";  
  7.   is_shared_ = is_shared;  
  8. }  
  9.   
  10. // 前向传播函数  
  11. // 输入bottom,计算出top  
  12. inline Dtype Forward(const vector<Blob<Dtype>*>& bottom,  
  13.     const vector<Blob<Dtype>*>& top);  
  14.   
  15.  // 反向传播函数  
  16.  // 输入top和propagate_down  
  17.  // 输出bottom  
  18. inline void Backward(const vector<Blob<Dtype>*>& top,  
  19.     const vector<bool>& propagate_down,  
  20.     const vector<Blob<Dtype>*>& bottom);  
  21.   
  22.  // 返回标量的损失(该损失与top blob相关联,给定索引就可获得该损失)  
  23. inline Dtype loss(const int top_index) const {  
  24.   return (loss_.size() > top_index) ? loss_[top_index] : Dtype(0);  
  25. }  
  26.   
  27.  // 给定索引,设置top blob相关联的损失  
  28. inline void set_loss(const int top_index, const Dtype value) {  
  29.   if (loss_.size() <= top_index) {  
  30.     loss_.resize(top_index + 1, Dtype(0));  
  31.   }  
  32.   loss_[top_index] = value;  
  33. }  
  34.   
  35.  // 给定param_id返回是否应该计算梯度  
  36. inline bool param_propagate_down(const int param_id) {  
  37.   return (param_propagate_down_.size() > param_id) ?  
  38.       param_propagate_down_[param_id] : false;  
  39. }  
  40.   
  41.  // 给定param_id设置是否应该计算梯度  
  42. inline void set_param_propagate_down(const int param_id, const bool value) {  
  43.   if (param_propagate_down_.size() <= param_id) {  
  44.     param_propagate_down_.resize(param_id + 1, true);  
  45.   }  
  46.   param_propagate_down_[param_id] = value;  
  47. }  
  48.   
  49.  // 设置损失权重??暂时还不懂  
  50. inline void SetLossWeights(const vector<Blob<Dtype>*>& top) {  
  51.   const int num_loss_weights = layer_param_.loss_weight_size();  
  52.   if (num_loss_weights) {  
  53.     CHECK_EQ(top.size(), num_loss_weights) << "loss_weight must be "  
  54.         "unspecified or specified once per top blob.";  
  55.     for (int top_id = 0; top_id < top.size(); ++top_id) {  
  56.        // the amount of weight to assign each top blob in the objective.  
  57.        // Each layer assigns a default value, usually of either 0 or 1,  
  58.     // to each top blob. loss_weight要么为0,要么为1  
  59.       const Dtype loss_weight = layer_param_.loss_weight(top_id);  
  60.       if (loss_weight == Dtype(0)) { continue; }// 为0则调过  
  61.       // loss_weigth为1则  
  62.       this->set_loss(top_id, loss_weight);  
  63.       const int count = top[top_id]->count();  
  64.       Dtype* loss_multiplier = top[top_id]->mutable_cpu_diff();  
  65.       caffe_set(count, loss_weight, loss_multiplier);  
  66.     }  
  67.   }  
  68. }  
3-3类内的函数:
[cpp] view plain copy
 
  1. // SetUp设置层的互斥量、检查BLOB的参数、调用LayerSetUp进行初始化  
  2. // LayerSetUp是一个虚函数,用户可以去重载它。  
  3. // 然后再设置topblob的形状以及设置损失权重。  
  4. void SetUp(const vector<Blob<Dtype>*>& bottom,  
  5.       const vector<Blob<Dtype>*>& top) {  
  6.     // 初始化互斥量  
  7.     InitMutex();  
  8.     // 检查Blob  
  9.     CheckBlobCounts(bottom, top);  
  10.     // 层的初始化(虚函数,需用户去实现如何初始化层)  
  11.     LayerSetUp(bottom, top);  
  12.     // 改变top的形状(虚函数,需用户去实现如何根据bottomblob改变topblob的形状)  
  13.     Reshape(bottom, top);  
  14.     // 设置损失权重  
  15.     SetLossWeights(top);  
  16.   }  
  17.   
  18.    // 返回blob指针的容器  
  19.   vector<shared_ptr<Blob<Dtype> > >& blobs() {  
  20.     return blobs_;  
  21.   }  
  22.   
  23.    // 返回层的参数  
  24.   const LayerParameter& layer_param() const { return layer_param_; }  
3-4虚函数(纯虚函数是必须要实现的!!):
   
[cpp] view plain copy
 
  1. // 虚函数,必须自己去实现  
  2.   virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,  
  3.       const vector<Blob<Dtype>*>& top) {}  
  4.   
  5.    // 在数据并行化的时候,层是否可以在多个网络之间共享  
  6.    // 默认是只有数据层才能在多个网络之间共享,其他层则不行  
  7.    // 数据层应该在数据并行化的时候确保每个solver能够顺序地访问数据  
  8.   virtual inline bool ShareInParallel() const { return false; }  
  9.   
  10.   // 纯虚函数(Reshape必须要实现)  
  11.   virtual void Reshape(const vector<Blob<Dtype>*>& bottom,  
  12.       const vector<Blob<Dtype>*>& top) = 0;  
  13.   
  14.   // 把层参数写入到proto文件  
  15.   virtual void ToProto(LayerParameter* param, bool write_diff = false);  
  16.   
  17.    // 虚函数,而且还是内联的,返回层类型  
  18.   virtual inline const char* type() const { return ""; }  
  19.   
  20.    // 虚函数,获得bottom blob的精确个数  
  21.   virtual inline int ExactNumBottomBlobs() const { return -1; }  
  22.   
  23.    // 虚函数,获得bottom blob的最小个数  
  24.   virtual inline int MinBottomBlobs() const { return -1; }  
  25.   
  26.    // 虚函数,获得bottom blob的最大个数  
  27.   virtual inline int MaxBottomBlobs() const { return -1; }  
  28.   
  29.    // 虚函数,获得top blob的精确个数  
  30.   virtual inline int ExactNumTopBlobs() const { return -1; }  
  31.   
  32.    // 虚函数,获得top blob的最小个数  
  33.   virtual inline int MinTopBlobs() const { return -1; }  
  34.   
  35.    // 虚函数,获得top blob的最大个数  
  36.   virtual inline int MaxTopBlobs() const { return -1; }  
  37.   
  38.    // 虚函数,bottom blob和top blob的个数是否一致  
  39.   virtual inline bool EqualNumBottomTopBlobs() const { return false; }  
  40.   
  41.    // 返回当前层是否自动创建匿名top blobs  
  42.    // 如果返回true,表明网络初始化的时候创建了了足够多的匿名top blobs  
  43.    // 来满足ExactNumTopBlobs或者MinTopBlobs所要求的top blobs的个数  
  44.   virtual inline bool AutoTopBlobs() const { return false; }  
  45.   
  46.    // 对于一个给定的bottom blob,返回是否允许强制反传  
  47.   virtual inline bool AllowForceBackward(const int bottom_index) const {  
  48.     return true;  
  49.   }  
  50.   
  51.   // 纯虚函数,必须要实现前向的CPU计算,需要用户去实现全向传播CPU,也就是说必须要实现CPU的前向传播  
  52.   virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,  
  53.       const vector<Blob<Dtype>*>& top) = 0;  
  54.   
  55.   // 虚函数,需要用户去实现全向传播GPU,如果实现GPU则运行GPU的代码  
  56.   // 如果没有实现则调用默认的CPU的代码  
  57.   virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,  
  58.       const vector<Blob<Dtype>*>& top) {  
  59.     // LOG(WARNING) << "Using CPU code as backup.";  
  60.     return Forward_cpu(bottom, top);  
  61.   }  
  62.   
  63.    // 纯虚函数,反传CPU ,必须要实现!!  
  64.   virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,  
  65.       const vector<bool>& propagate_down,  
  66.       const vector<Blob<Dtype>*>& bottom) = 0;  
  67.   
  68.    // 虚函数,反传GPU,如果没有则用CPU的反传  
  69.   virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,  
  70.       const vector<bool>& propagate_down,  
  71.       const vector<Blob<Dtype>*>& bottom) {  
  72.     // LOG(WARNING) << "Using CPU code as backup.";  
  73.     Backward_cpu(top, propagate_down, bottom);  
  74.   }  
  75.   
  76.    // 该函数在SetUp中被调用  
  77.    // 检查Blob的一些参数是否正确  
  78.    // 比如:  
  79.    // 精确的底层blob数目  
  80.    // 最小的底层blob数目  
  81.    // 最大的底层blob数目  
  82.    // 精确的顶层blob数目  
  83.    // 最小的顶层blob数目  
  84.    // 最大的顶层blob数目  
  85.    // 此外还检查顶层和底层是否一致  
  86.   virtual void CheckBlobCounts(const vector<Blob<Dtype>*>& bottom,  
  87.                                const vector<Blob<Dtype>*>& top) {  
  88.     if (ExactNumBottomBlobs() >= 0) {  
  89.       CHECK_EQ(ExactNumBottomBlobs(), bottom.size())  
  90.           << type() << " Layer takes " << ExactNumBottomBlobs()  
  91.           << " bottom blob(s) as input.";  
  92.     }  
  93.     if (MinBottomBlobs() >= 0) {  
  94.       CHECK_LE(MinBottomBlobs(), bottom.size())  
  95.           << type() << " Layer takes at least " << MinBottomBlobs()  
  96.           << " bottom blob(s) as input.";  
  97.     }  
  98.     if (MaxBottomBlobs() >= 0) {  
  99.       CHECK_GE(MaxBottomBlobs(), bottom.size())  
  100.           << type() << " Layer takes at most " << MaxBottomBlobs()  
  101.           << " bottom blob(s) as input.";  
  102.     }  
  103.     if (ExactNumTopBlobs() >= 0) {  
  104.       CHECK_EQ(ExactNumTopBlobs(), top.size())  
  105.           << type() << " Layer produces " << ExactNumTopBlobs()  
  106.           << " top blob(s) as output.";  
  107.     }  
  108.     if (MinTopBlobs() >= 0) {  
  109.       CHECK_LE(MinTopBlobs(), top.size())  
  110.           << type() << " Layer produces at least " << MinTopBlobs()  
  111.           << " top blob(s) as output.";  
  112.     }  
  113.     if (MaxTopBlobs() >= 0) {  
  114.       CHECK_GE(MaxTopBlobs(), top.size())  
  115.           << type() << " Layer produces at most " << MaxTopBlobs()  
  116.           << " top blob(s) as output.";  
  117.     }  
  118.     if (EqualNumBottomTopBlobs()) {  
  119.       CHECK_EQ(bottom.size(), top.size())  
  120.           << type() << " Layer produces one top blob as output for each "  
  121.           << "bottom blob input.";  
  122.     }  
  123.   }  
其中的一些函数的具体实现如下:
主要就是前传和反传,前传调用对应的Forward_cpu或者Forward_gpu
而我们知道Forward_cpu是纯虚函数,必须要实现而Forward_gpu是虚函数,如果不实现就调用 Forward_cpu函数了。
前传(你必须实现自己的Forward_cpu,实现Forward_gpu是可选的)
[cpp] view plain copy
 
  1. template <typename Dtype>  
  2. inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype>*>& bottom,  
  3.     const vector<Blob<Dtype>*>& top) {  
  4.   // Lock during forward to ensure sequential forward  
  5.   // 前传的时候需要上锁,按照顺序执行才行,否则就乱了  
  6.   Lock();  
  7.   Dtype loss = 0;  
  8.   // 根据bottom设置top的形状  
  9.   Reshape(bottom, top);  
  10.   // 设置运行模式CPU or GPU  
  11.   switch (Caffe::mode()) {  
  12.   case Caffe::CPU:  
  13.     // 调用CPU的前传  
  14.     Forward_cpu(bottom, top);  
  15.     // 前传计算完之后计算损失(只有最后一层才进行计算,其余层都不用)  
  16.     for (int top_id = 0; top_id < top.size(); ++top_id) {  
  17.       if (!this->loss(top_id)) { continue; }  
  18.       const int count = top[top_id]->count();  
  19.       // 获取前传的数据  
  20.       const Dtype* data = top[top_id]->cpu_data();  
  21.       // 获取梯度(\frac{\partial Loss}{\partial net})  
  22.       const Dtype* loss_weights = top[top_id]->cpu_diff();  
  23.       // data与loss_weight的点积,即得损失函数关于当前层权重的偏导了  
  24.     // \frac{\partial Loss}{\partial net} * \frac{\partial net}{\frac{W}}  
  25.     // = \frac{\partial Loss}{\partial W}  
  26.       loss += caffe_cpu_dot(count, data, loss_weights);  
  27.     }  
  28.     break;  
  29.   case Caffe::GPU:  
  30.     // GPU前传  
  31.     Forward_gpu(bottom, top);  
  32. #ifndef CPU_ONLY  
  33.     // 同上,只不过这里用GPU来计算点积了  
  34.     for (int top_id = 0; top_id < top.size(); ++top_id) {  
  35.       if (!this->loss(top_id)) { continue; }  
  36.       const int count = top[top_id]->count();  
  37.       // 获取GPU上的数据  
  38.       const Dtype* data = top[top_id]->gpu_data();  
  39.       const Dtype* loss_weights = top[top_id]->gpu_diff();  
  40.       Dtype blob_loss = 0;  
  41.       caffe_gpu_dot(count, data, loss_weights, &blob_loss);  
  42.       loss += blob_loss;  
  43.     }  
  44. #endif  
  45.     break;  
  46.   default:  
  47.     LOG(FATAL) << "Unknown caffe mode.";  
  48.   }  
  49.   Unlock();  
  50.   return loss;  
  51. }  
反传的道理与前传的道理很类似
[cpp] view plain copy
 
  1. // 反传 ,必须实现CPU,但是GPU是可选的  
  2. template <typename Dtype>  
  3. inline void Layer<Dtype>::Backward(const vector<Blob<Dtype>*>& top,  
  4.     const vector<bool>& propagate_down,  
  5.     const vector<Blob<Dtype>*>& bottom) {  
  6.   switch (Caffe::mode()) {  
  7.   case Caffe::CPU:// CPU反传  
  8.     Backward_cpu(top, propagate_down, bottom);  
  9.     break;  
  10.   case Caffe::GPU:// GPU反传  
  11.     Backward_gpu(top, propagate_down, bottom);  
  12.     break;  
  13.   default:  
  14.     LOG(FATAL) << "Unknown caffe mode.";  
  15.   }  
  16. }  
  17.   
  18. // 将LayerParameter转换为ProtoBuf  
  19. template <typename Dtype>  
  20. void Layer<Dtype>::ToProto(LayerParameter* param, bool write_diff) {  
  21.   param->Clear();  
  22.   param->CopyFrom(layer_param_);  
  23.   param->clear_blobs();  
  24.   for (int i = 0; i < blobs_.size(); ++i) {  
  25.     blobs_[i]->ToProto(param->add_blobs(), write_diff);  
  26.   }  
  27. }  
  28.   
  29.   
  30. 其他部分的实现:  
  31. // 初始化互斥量  
  32. template <typename Dtype>  
  33. void Layer<Dtype>::InitMutex() {  
  34.   forward_mutex_.reset(new boost::mutex());  
  35. }  
  36.   
  37. // Lock  
  38. template <typename Dtype>  
  39. void Layer<Dtype>::Lock() {  
  40.   if (IsShared()) {  
  41.     forward_mutex_->lock();  
  42.   }  
  43. }  
  44.   
  45. // UnLock  
  46. template <typename Dtype>  
  47. void Layer<Dtype>::Unlock() {  
  48.   if (IsShared()) {  
  49.     forward_mutex_->unlock();  
  50.   }  
  51. }  

三、与Layer类相关类的介绍

(1)用到了device_alternate.hpp

这其中只是定义了一些检查CUDA是否运行成功的函数、还有就是定义了几个宏
 
下面对其进行介绍:
[cpp] view plain copy
 
  1. // 定义给定类的前向和反向(GPU和CPU)传播的函数定义  
  2. #define STUB_GPU(classname) \  
  3. template <typename Dtype> \  
  4. void classname<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, \  
  5.     const vector<Blob<Dtype>*>& top) { NO_GPU; } \  
  6. template <typename Dtype> \  
  7. void classname<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, \  
  8.     const vector<bool>& propagate_down, \  
  9.     const vector<Blob<Dtype>*>& bottom) { NO_GPU; } \  
  10.   
  11. #define STUB_GPU_FORWARD(classname, funcname) \  
  12. template <typename Dtype> \  
  13. void classname<Dtype>::funcname##_##gpu(const vector<Blob<Dtype>*>& bottom, \  
  14.     const vector<Blob<Dtype>*>& top) { NO_GPU; } \  
  15.   
  16. #define STUB_GPU_BACKWARD(classname, funcname) \  
  17. template <typename Dtype> \  
  18. void classname<Dtype>::funcname##_##gpu(const vector<Blob<Dtype>*>& top, \  
  19.     const vector<bool>& propagate_down, \  
  20.     const vector<Blob<Dtype>*>& bottom) { NO_GPU; } \  
CUDA检查的宏:
[cpp] view plain copy
 
  1. // CUDA: various checks for different function calls.  
  2. #define CUDA_CHECK(condition) \  
  3.   /* Code block avoids redefinition of cudaError_t error */ \  
  4.   do { \  
  5.     cudaError_t error = condition; \  
  6.     CHECK_EQ(error, cudaSuccess) << " " << cudaGetErrorString(error); \  
  7.   } while (0)  
  8.   
  9. #define CUBLAS_CHECK(condition) \  
  10.   do { \  
  11.     cublasStatus_t status = condition; \  
  12.     CHECK_EQ(status, CUBLAS_STATUS_SUCCESS) << " " \  
  13.       << caffe::cublasGetErrorString(status); \  
  14.   } while (0)  
  15.   
  16. #define CURAND_CHECK(condition) \  
  17.   do { \  
  18.     curandStatus_t status = condition; \  
  19.     CHECK_EQ(status, CURAND_STATUS_SUCCESS) << " " \  
  20.       << caffe::curandGetErrorString(status); \  
  21.   } while (0)  
  22.   
  23. // CUDA: grid stride looping  
  24. #define CUDA_KERNEL_LOOP(i, n) \  
  25.   for (int i = blockIdx.x * blockDim.x + threadIdx.x; \  
  26.        i < (n); \  
  27.        i += blockDim.x * gridDim.x)  

四、总结

Layer的设计主要就是SetUp、Forward、Backward函数(层一开始的时候的设置、然后就是前传和反传)
这其中的SetUp的实现又依赖于CheckBlobCounts、LayerSetUp、Reshape等的实现。这其中Reshape又是必须要实现的,因为它是纯虚函数
这其中的Forward中又依赖于Forward_cpu、Forward_gpu,这其中Forward_cpu又是必须要实现的。
这其中的Backward中又依赖于Backward_cpu、Backward_gpu,这其中Backward_cpu 又是必须要实现的。
 

参考:

你可能需要了解一下多层感知机的前向传播和反向传播。
具体可以参考UFLDL的相关知识。
posted @ 2016-04-07 10:57  菜鸡一枚  阅读(1125)  评论(0编辑  收藏  举报