caffe源码追踪--layer

首先来看看caffe/include/caffe/layer.hpp

#ifndef CAFFE_LAYER_H_
#define CAFFE_LAYER_H_

#include <algorithm>
#include <string>
#include <vector>

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/layer_factory.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/math_functions.hpp"
namespace boost { class mutex; }
namespace caffe {
template <typename Dtype>
class Layer {
 public:
  explicit Layer(const LayerParameter& param)
    : layer_param_(param), is_shared_(false) {
      phase_ = param.phase();//train 还是test
      if (layer_param_.blobs_size() > 0) {//如果有参数,则开辟空间并从protobuf中拷贝过来,blobs向量装的是指向blob的智能指针,存放每一层的可学习参数
        blobs_.resize(layer_param_.blobs_size());
        for (int i = 0; i < layer_param_.blobs_size(); ++i) {
          blobs_[i].reset(new Blob<Dtype>());
          blobs_[i]->FromProto(layer_param_.blobs(i));//blob中的函数,用来从protobuf中读取数据
        }
      }
    }
  virtual ~Layer() {}//虚析构函数,是为了在多态时能析构掉继承类资源
  void SetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {//setup函数,具体的setup是通过LayerSetUp实现
    InitMutex();
    CheckBlobCounts(bottom, top);//检查输入输出blob数目是否正确
    LayerSetUp(bottom, top);//setup
    Reshape(bottom, top);//根据输入,对输出blob进行塑形
    SetLossWeights(top);//,设置一些损失和权重相关的blob,这个方法一般不会被子类重写
  }
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {}//setup函数
  virtual inline bool ShareInParallel() const { return false; }//接下来的三个函数是为了获取并行状态和该layer是否被允许被多个nets共享,默认情况下,除了数据层都是关闭的。在多GPU时的训练阶段以及share是true的情况下,is_shared将会被置成true。
  inline bool IsShared() const { return is_shared_; }
  inline void SetShared(bool is_shared) {
    CHECK(ShareInParallel() || !is_shared)
        << type() << "Layer does not support sharing.";
    is_shared_ = is_shared;
  }
  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,//根据需要对输出blob塑形
      const vector<Blob<Dtype>*>& top) = 0;
  inline Dtype Forward(const vector<Blob<Dtype>*>& bottom,//根据输入数据,计算输出数据,返回损失
      const vector<Blob<Dtype>*>& top);
  inline void Backward(const vector<Blob<Dtype>*>& top,//根据输出blob的diff数据计算输入的梯度存在diff里面
      const vector<bool>& propagate_down,
      const vector<Blob<Dtype>*>& bottom);
  vector<shared_ptr<Blob<Dtype> > >& blobs() {//获取可学习参数
    return blobs_;
  }
  const LayerParameter& layer_param() const { return layer_param_; }//获取层参数
  virtual void ToProto(LayerParameter* param, bool write_diff = false);//将层参数写到protobuf
  inline Dtype loss(const int top_index) const {//获取指定输出索引处的损失值
    return (loss_.size() > top_index) ? loss_[top_index] : Dtype(0);
  }
  inline void set_loss(const int top_index, const Dtype value) {//设置指定输出索引处的损失值
    if (loss_.size() <= top_index) {
      loss_.resize(top_index + 1, Dtype(0));
    }
    loss_[top_index] = value;
  }
  virtual inline const char* type() const { return ""; }//获取层类型
  virtual inline int ExactNumBottomBlobs() const { return -1; }//获取输入个数
  virtual inline int MinBottomBlobs() const { return -1; }//最小输入个数
  virtual inline int MaxBottomBlobs() const { return -1; }//最大输入个数
  virtual inline int ExactNumTopBlobs() const { return -1; }//获取输出个数
  virtual inline int MinTopBlobs() const { return -1; }//最小输出个数
  virtual inline int MaxTopBlobs() const { return -1; }//最大输出个数
  virtual inline bool EqualNumBottomTopBlobs() const { return false; }//输入输出个数是否相等
  virtual inline bool AutoTopBlobs() const { return false; }//若为真,则 Net::Init将自动创建输出blob
  virtual inline bool AllowForceBackward(const int bottom_index) const {//是否强制梯度返回
    return true;
  }
  inline bool param_propagate_down(const int param_id) {//查看是否需要计算梯度
    return (param_propagate_down_.size() > param_id) ?
        param_propagate_down_[param_id] : false;
  }
  inline void set_param_propagate_down(const int param_id, const bool value) {//设置是否需要计算梯度
    if (param_propagate_down_.size() <= param_id) {
      param_propagate_down_.resize(param_id + 1, true);
    }
    param_propagate_down_[param_id] = value;
  }
 protected:
  LayerParameter layer_param_;//层参数
  Phase phase_;//train 还是test
  vector<shared_ptr<Blob<Dtype> > > blobs_;//层的可学习参数
  vector<bool> param_propagate_down_;//是否需要计算梯度
  vector<Dtype> loss_;//每一层都有个损失
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,//在CPU上进行前向传播
      const vector<Blob<Dtype>*>& top) = 0;
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,//在gpu上进行前向传播
      const vector<Blob<Dtype>*>& top) {
    // LOG(WARNING) << "Using CPU code as backup.";
    return Forward_cpu(bottom, top);
  }
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,//在CPU上进行反向传播
      const vector<bool>& propagate_down,
      const vector<Blob<Dtype>*>& bottom) = 0;
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,//在gpu上进行前向传播
      const vector<bool>& propagate_down,
      const vector<Blob<Dtype>*>& bottom) {
    // LOG(WARNING) << "Using CPU code as backup.";
    Backward_cpu(top, propagate_down, bottom);
  }
  virtual void CheckBlobCounts(const vector<Blob<Dtype>*>& bottom,//由父类SETUP函数调用,查看输入输出个数是否满足要求
                               const vector<Blob<Dtype>*>& top) {
    if (ExactNumBottomBlobs() >= 0) {
      CHECK_EQ(ExactNumBottomBlobs(), bottom.size())
          << type() << " Layer takes " << ExactNumBottomBlobs()
          << " bottom blob(s) as input.";
    }
    if (MinBottomBlobs() >= 0) {
      CHECK_LE(MinBottomBlobs(), bottom.size())
          << type() << " Layer takes at least " << MinBottomBlobs()
          << " bottom blob(s) as input.";
    }
    if (MaxBottomBlobs() >= 0) {
      CHECK_GE(MaxBottomBlobs(), bottom.size())
          << type() << " Layer takes at most " << MaxBottomBlobs()
          << " bottom blob(s) as input.";
    }
    if (ExactNumTopBlobs() >= 0) {
      CHECK_EQ(ExactNumTopBlobs(), top.size())
          << type() << " Layer produces " << ExactNumTopBlobs()
          << " top blob(s) as output.";
    }
    if (MinTopBlobs() >= 0) {
      CHECK_LE(MinTopBlobs(), top.size())
          << type() << " Layer produces at least " << MinTopBlobs()
          << " top blob(s) as output.";
    }
    if (MaxTopBlobs() >= 0) {
      CHECK_GE(MaxTopBlobs(), top.size())
          << type() << " Layer produces at most " << MaxTopBlobs()
          << " top blob(s) as output.";
    }
    if (EqualNumBottomTopBlobs()) {
      CHECK_EQ(bottom.size(), top.size())
          << type() << " Layer produces one top blob as output for each "
          << "bottom blob input.";
    }
  }
  inline void SetLossWeights(const vector<Blob<Dtype>*>& top) {//也是被父类调用初始化梯度值
    const int num_loss_weights = layer_param_.loss_weight_size();
    if (num_loss_weights) {
      CHECK_EQ(top.size(), num_loss_weights) << "loss_weight must be "
          "unspecified or specified once per top blob.";
      for (int top_id = 0; top_id < top.size(); ++top_id) {
        const Dtype loss_weight = layer_param_.loss_weight(top_id);
        if (loss_weight == Dtype(0)) { continue; }
        this->set_loss(top_id, loss_weight);
        const int count = top[top_id]->count();
        Dtype* loss_multiplier = top[top_id]->mutable_cpu_diff();
        caffe_set(count, loss_weight, loss_multiplier);
      }
    }
  }
 private:
  bool is_shared_;
  shared_ptr<boost::mutex> forward_mutex_;
  void InitMutex();
  void Lock();
  void Unlock();
  DISABLE_COPY_AND_ASSIGN(Layer);
};  // class Layer
template <typename Dtype>
inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype>*>& bottom,//前向传播,具体实现是Forward_cpu和Forward_gpu函数,子类负责实现
    const vector<Blob<Dtype>*>& top) {
  Lock();
  Dtype loss = 0;
  Reshape(bottom, top);
  switch (Caffe::mode()) {
  case Caffe::CPU:
    Forward_cpu(bottom, top);
    for (int top_id = 0; top_id < top.size(); ++top_id) {
      if (!this->loss(top_id)) { continue; }
      const int count = top[top_id]->count();
      const Dtype* data = top[top_id]->cpu_data();
      const Dtype* loss_weights = top[top_id]->cpu_diff();
      loss += caffe_cpu_dot(count, data, loss_weights);
    }
    break;
  case Caffe::GPU:
    Forward_gpu(bottom, top);
#ifndef CPU_ONLY
    for (int top_id = 0; top_id < top.size(); ++top_id) {
      if (!this->loss(top_id)) { continue; }
      const int count = top[top_id]->count();
      const Dtype* data = top[top_id]->gpu_data();
      const Dtype* loss_weights = top[top_id]->gpu_diff();
      Dtype blob_loss = 0;
      caffe_gpu_dot(count, data, loss_weights, &blob_loss);
      loss += blob_loss;
    }
#endif
    break;
  default:
    LOG(FATAL) << "Unknown caffe mode.";
  }
  Unlock();
  return loss;
}
template <typename Dtype>
inline void Layer<Dtype>::Backward(const vector<Blob<Dtype>*>& top,//反向传播借口,具体在Backward_cpu和Backward_gpu函数中实现,子类负责实现子类负责实现子类负责实现
    const vector<bool>& propagate_down,
    const vector<Blob<Dtype>*>& bottom) {
  switch (Caffe::mode()) {
  case Caffe::CPU:
    Backward_cpu(top, propagate_down, bottom);
    break;
  case Caffe::GPU:
    Backward_gpu(top, propagate_down, bottom);
    break;
  default:
    LOG(FATAL) << "Unknown caffe mode.";
  }
}
template <typename Dtype>
void Layer<Dtype>::ToProto(LayerParameter* param, bool write_diff) {//序列化层参数到protobuf
  param->Clear();
  param->CopyFrom(layer_param_);
  param->clear_blobs();
  for (int i = 0; i < blobs_.size(); ++i) {
    blobs_[i]->ToProto(param->add_blobs(), write_diff);
  }
}

}  // namespace caffe

#endif  // CAFFE_LAYER_H_

这里有很多层参数的使用,层参数都在这个文件里面有定义caffe/src/caffe/proto/caffe.proto
layer.cpp文件里面是一些线程处理相关的

#include <boost/thread.hpp>
#include "caffe/layer.hpp"

namespace caffe {

template <typename Dtype>
void Layer<Dtype>::InitMutex() {
  forward_mutex_.reset(new boost::mutex());
}
template <typename Dtype>
void Layer<Dtype>::Lock() {
  if (IsShared()) {
    forward_mutex_->lock();
  }
}
template <typename Dtype>
void Layer<Dtype>::Unlock() {
  if (IsShared()) {
    forward_mutex_->unlock();
  }
}
INSTANTIATE_CLASS(Layer);
}  // namespace caffe
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值