Layer的實現細節

xunan003發表於2017-06-06

原文連結:http://blog.csdn.net/xizero00/article/details/50914471

一、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指標型別的容器。
  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)成員變數

保護性的成員變數:
  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_;  
私有的成員變數:
  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非行內函數:
  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行內函數:
  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類內的函式:
  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虛擬函式(純虛擬函式是必須要實現的!!):
   
  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是可選的)
  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. }  
反傳的道理與前傳的道理很類似
  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是否執行成功的函式、還有就是定義了幾個巨集

下面對其進行介紹:
  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檢查的巨集:
  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的相關知識。

相關文章