您的位置:首页 > Web前端

caffe源码阅读之layer(1)

2017-11-17 21:57 295 查看
Layer为caffe的计算单元,部分Layer带有权值和偏置项,有两个运算方向:前向传播和反向传播;在E:\Caffe\caffe-windows\src\caffe\proto中caffe.proto

message LayerParameter {} 记录了每一个新增的LayerParameter参数,如果自定义了一个卷积等相关的层需要再这定义并修改ID(136之后)

    首先来看layer的定义,这个定义是layer的基类,无论定义什么样的layer需要继承该layer类,接下来具体看看layer是怎么写的。首先在E:\Caffe\caffe-windows\include\caffe下

可以找到layer.hpp和E:\Caffe\caffe-windows\src\caffe下找到layer.cpp文件可以见到layer类的定义和实现。
    接下来看看layer类的成员变量:

LayerParameter layer_param_;//保存layer参数的ProtoBuffer对象,该对象已经在caffe.proto定义
Phase phase_;//Layer当前的阶段,主要有TRAIN和TEST
vector<shared_ptr<Blob<Dtype> > > blobs_;//layer内部的权值或偏置项
vector<bool> param_propagate_down_;//标志是否计算对应的误差和梯度
bool is_shared_;//是否共享

shared_ptr<boost::mutex> forward_mutex_;//互斥锁,如果该层被共享,保证顺序执行前向传播1、构造函数
explicit Layer(const LayerParameter& param): layer_param_(param), is_shared_(false) {
phase_ = param.phase();//设置当前阶段
if (layer_param_.blobs_size() > 0) {
blobs_.resize(layer_param_.blobs_size());//设置Blob个数,并将每一个Blob对象调整为layer_param_中的Blob尺寸
for (int i = 0; i < layer_param_.blobs_size(); ++i) {
blobs_[i].reset(new Blob<Dtype>());
blobs_[i]->FromProto(layer_param_.blobs(i));
}
}
}
//析构函数
virtual ~Layer() {}2、配置函数

实现常用层的配置接口,该层不可被覆盖
void SetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
InitMutex();
CheckBlobCounts(bottom, top);//检测Blob
LayerSetUp(bottom, top);//layer相关的配置
Reshape(bottom, top);//top变形
SetLossWeights(top);//设置损失因子
}
//初始化forward_mutex_
void InitMutex();
//校验输入、输出Blob数目是否满足layer要求
virtual void CheckBlobCounts(const vector<Blob<Dtype>*>& bottom,
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.";
}
}
//做特定类型层的相关配置,需要重写
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) {}
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) = 0;
//初始化输出Blob相关的权重并放到diff
inline void SetLossWeights(const vector<Blob<Dtype>*>& top) {
const int num_loss_weights = layer_param_.loss_weight_size();//从ProtoBuffer对象中获得layer参数
if (num_loss_weights) {
CHECK_EQ(top.size(), num_loss_weights) << "loss_weight must be "
"unspecified or specified once per top blob.";//loss_weight没有或者loss_weight个数与Top Blob数量相同
for (int top_id = 0; top_id < top.size(); ++top_id) {
const Dtype loss_weight = layer_param_.loss_weight(top_id);//从protoBuffer中获取参数(1或0)
if (loss_weight == Dtype(0)) { continue; }//若果==0:表示当前层不参与loss计算,跳过
this->set_loss(top_id, loss_weight);//若果不为0:表示当前层参与loss计算,对网络做相关计算
const int count = top[top_id]->count();
Dtype* loss_multiplier = top[top_id]->mutable_cpu_diff();
caffe_set(count, loss_weight, loss_multiplier);//将loss_weight值写入到diff中,传递到其他需要使用的地方,实现远程同步
}
}
}3、前向传播和反向传播
//给定输入Blob输出输出Blob和loss
inline Dtype Forward(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top);

template <typename Dtype>
inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
// Lock during forward to ensure sequential forward(枷锁防止其他层使用)
Lock();
Dtype loss = 0;
Reshape(bottom, top);
switch (Caffe::mode()) {//判断计算机的训练模式
case Caffe::CPU:
Forward_cpu(bottom, top);//调用CPU版本的Forward
for (int top_id = 0; top_id < top.size(); ++top_id) {
if (!this->loss(top_id)) { continue; }
const int count = top[top_id]->count();//若为lossLayer计算的全局损失函数放到data域中
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);//计算加权后的loss的到一个标量
}
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;
}
//反向传播,给定输出blob层的diff,该层的diff由该函数计算得到
inline void Backward(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down,const vector<Blob<Dtype>*>& bottom);

template <typename Dtype>
inline void Layer<Dtype>::Backward(const vector<Blob<Dtype>*>& top,
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.";
}
}
上面的函数不需要重写,接下来的四个函数需要在创建特有的layer时需要重写
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) = 0;
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) {
return Forward_cpu(bottom, top);
}
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down,const vector<Blob<Dtype>*>& bottom) = 0;
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down,const vector<Blob<Dtype>*>& bottom) {
Backward_cpu(top, propagate_down, bottom);
}
4、其他

(1)判断和设置layer层是否被共享
virtual inline bool ShareInParallel() const { return false; }//在数据并行时是否会被其他Net共享,默认只能用于数据读取层(Datalayer)
inline bool IsShared() const { return is_shared_; }//该层是否会被其他层共享,ShareInParallel()返回true且被多个GPU使用,网络处于训练阶段时返回true
inline void SetShared(bool is_shared) {//设置该层是否被共享
CHECK(ShareInParallel() || !is_shared)
<< type() << "Layer does not support sharing.";
is_shared_ = is_shared;
}(2)Blob参数相关操作
vector<shared_ptr<Blob<Dtype> > >& blobs() {//返回layer内部可训练的权重和偏置项Blob
return blobs_;
}
const LayerParameter& layer_param() const { return layer_param_; }//返回ProtoBuffer中的layer初始化参数
virtual void ToProto(LayerParameter* param, bool write_diff = false);//将layer初始化参数写入到ProtoBuffer中
inline Dtype loss(const int top_index) const {//返回某个Blob标量loss值
return (loss_.size() > top_index) ? loss_[top_index] : Dtype(0);
}
inline void set_loss(const int top_index, const Dtype value) {//设置某个Blob标量loss值
if (loss_.size() <= top_index) {
loss_.resize(top_index + 1, Dtype(0));
}
loss_[top_index] = value;
}
virtual inline const char* type() const { return ""; }//返回层类型字符串
//返回该Layer需要输入的Blob数目
virtual inline int ExactNumBottomBlobs() const { return -1; }
virtual inline int MinBottomBlobs() const { return -1; }
virtual inline int MaxBottomBlobs() const { return -1; }
//返回该层需要输出的Blob数目
virtual inline int ExactNumTopBlobs() const { return -1; }
virtual inline int MinTopBlobs() const { return -1; }
virtual inline int MaxTopBlobs() const { return -1; }
//输入和输出Blob是否相等
virtual inline bool EqualNumBottomTopBlobs() const { return false; }
//返回匿名输出Blob,该Blob由layer自动创建
virtual inline bool AutoTopBlobs() const { return false; }
//Blob是否强制反向传播
virtual inline bool AllowForceBackward(const int bottom_index) const {
return true;
}
//指定layer
inline bool param_propagate_down(const int param_id) {
return (param_propagate_down_.size() > param_id) ?
param_propagate_down_[param_id] : false;
}
//设置该layer是否计算相对权值或偏置项梯度
inline void set_param_
9203
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: