转载自:http://home.cnblogs.com/louyihang-loves-baiyan/
Layer这个类可以说是里面的一个基本类了,深度网络呢就是一层一层的layer,相互之间通过blob传输数据连接起来。首先layer必须要实现一个forward function,前向传递函数当然功能可以自己定义啦,在forward中呢他会从input也就是Layer的bottom(对了caffe里面网络的前一层是叫bottom的),从bottom中获取blob,并且计算输出到Blob,当然他们也会实现一个反向传播,根据他们的input的blob以及output blob的error gradient 梯度误差计算得到该层的梯度误差。从公式中也可以看到:
\[\delta^l=((w^{l+1})^T\delta^{l+1}) \sigma'(z^l)\]
在 \include\caffe\proto\caffe_pb.h可以看到如下LayerParameter:
class LayerParameter : public ::google::protobuf::Message {
//optional string name = 1;
//optional string type = 2;
//repeated string bottom = 3;
//repeated string top = 4;
…
//optional .caffe.TileParameter tile_param = 138;
//optional .caffe.WindowDataParameter window_data_param = 129;
}
Caffe.proto文件中有相应的结构和上面相对应,存储着layer的大量信息:
message LayerParameter {
optional string name = 1; // the layer name
optional string type = 2; // the layer type
repeated string bottom = 3; // the name of each bottom blob
repeated string top = 4; // the name of each top blob
// The train / test phase for computation.
optional Phase phase = 10;
// The amount of weight to assign each top blob in the objective.
// Each layer assigns a default value, usually of either 0 or 1,
// to each top blob.
repeated float loss_weight = 5;
// Specifies training parameters (multipliers on global learning constants,
// and the name and other settings used for weight sharing).
repeated ParamSpec param = 6;
// The blobs containing the numeric parameters of the layer.
repeated BlobProto blobs = 7;
// Specifies whether to backpropagate to each bottom. If unspecified,
// Caffe will automatically infer whether each input needs backpropagation
// to compute parameter gradients. If set to true for some inputs,
// backpropagation to those inputs is forced; if set false for some inputs,
// backpropagation to those inputs is skipped.
//
// The size must be either 0 or equal to the number of bottoms.
repeated bool propagate_down = 11;
// Rules controlling whether and when a layer is included in the network,
// based on the current NetState. You may specify a non-zero number of rules
// to include OR exclude, but not both. If no include or exclude rules are
// specified, the layer is always included. If the current NetState meets
// ANY (i.e., one or more) of the specified rules, the layer is
// included/excluded.
repeated NetStateRule include = 8;
repeated NetStateRule exclude = 9;
// Parameters for data pre-processing.
optional TransformationParameter transform_param = 100;
// Parameters shared by loss layers.
optional LossParameter loss_param = 101;
// Layer type-specific parameters.
//
// Note: certain layers may have more than one computational engine
// for their implementation. These layers include an Engine type and
// engine parameter for selecting the implementation.
// The default for the engine is set by the ENGINE switch at compile-time.
optional AccuracyParameter accuracy_param = 102;
optional ArgMaxParameter argmax_param = 103;
optional BatchNormParameter batch_norm_param = 139;
optional BiasParameter bias_param = 141;
optional ConcatParameter concat_param = 104;
optional ContrastiveLossParameter contrastive_loss_param = 105;
optional ConvolutionParameter convolution_param = 106;
optional CropParameter crop_param = 144;
optional DataParameter data_param = 107;
optional DropoutParameter dropout_param = 108;
optional DummyDataParameter dummy_data_param = 109;
optional EltwiseParameter eltwise_param = 110;
optional ELUParameter elu_param = 140;
optional EmbedParameter embed_param = 137;
optional ExpParameter exp_param = 111;
optional FlattenParameter flatten_param = 135;
optional HDF5DataParameter hdf5_data_param = 112;
optional HDF5OutputParameter hdf5_output_param = 113;
optional HingeLossParameter hinge_loss_param = 114;
optional ImageDataParameter image_data_param = 115;
optional InfogainLossParameter infogain_loss_param = 116;
optional InnerProductParameter inner_product_param = 117;
optional InputParameter input_param = 143;
optional LogParameter log_param = 134;
optional LRNParameter lrn_param = 118;
optional MemoryDataParameter memory_data_param = 119;
optional MVNParameter mvn_param = 120;
optional ParameterParameter parameter_param = 145;
optional PoolingParameter pooling_param = 121;
optional PowerParameter power_param = 122;
optional PReLUParameter prelu_param = 131;
optional PythonParameter python_param = 130;
optional RecurrentParameter recurrent_param = 146;
optional ReductionParameter reduction_param = 136;
optional ReLUParameter relu_param = 123;
optional ReshapeParameter reshape_param = 133;
optional ScaleParameter scale_param = 142;
optional SigmoidParameter sigmoid_param = 124;
optional SoftmaxParameter softmax_param = 125;
optional SPPParameter spp_param = 132;
optional SliceParameter slice_param = 126;
optional TanHParameter tanh_param = 127;
optional ThresholdParameter threshold_param = 128;
optional TileParameter tile_param = 138;
optional WindowDataParameter window_data_param = 129;
}
如果需要增加一个新的LayerParameter域,一定要记得更新下一个可用ID。
查看 #include/caffe/Layer.hpp
首先来看layer类的构造部分,以及Public部分的函数
template <typename Dtype>
class Layer {
public:
explicit Layer(const LayerParameter& param)
: layer_param_(param), is_shared_(false) {
// Set phase and copy blobs (if there are any).
phase_ = param.phase();
if (layer_param_.blobs_size() > 0) {
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));
}
}
}
virtual ~Layer() {}
首先获得当前网络的Phase,是train还是test,在初始化列表初始化LayerParameter,之后blobs_这里存放的是一个指向blob类的shared_ptr指针的一个vector,在这里是申请空间,然后将传入的layer_param中的blob拷贝过来。
void SetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
InitMutex();
CheckBlobCounts(bottom, top);
LayerSetUp(bottom, top);
Reshape(bottom, top);
SetLossWeights(top);
}
这里是Setup函数,首先check 这个bottom和top的blob是否正确,再调用LayerSetUp对每一具体的层做进一步设置,之后再做Reshape来设置top blobs和internal buffer。最后再设置loss weight multiplier 的blob对每一个非零的loss和weight,一般这个方法被继承之后是不会被重写的。
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top)
virtual inline bool ShareInParallel()
inline bool IsShared() const
inline void SetShared(bool is_shared)
LayerSetup就是对具体某一个layer的setup,被上面的那个Setup函数所调用,ShareInParallel和IsShared和SetShared分别是用来返回并行状态和获得这一layer是否被多个nets所共享,默认是除了data layer都是关闭的。在多个GPU下的Train阶段以及share是true的情况下,is_shared将会被置成true。
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) = 0;
这个Reshape主要是layer用来根据输入的blob调节Internal buffer以及输出的Blob的
注意
接下来是几个最重要的函数,首先是Forward.这其实是一个装饰器,继承之后再调用其相应的forward_cpu或者forward_gpu,根据输入的input data blob计算相应的output data blob,同时会反应这一层layer的total loss.
inline Dtype Forward(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
这里是BackWard,实现的是反向传播,也就是给定top blob的error gradient 计算得到bottom的error gradient。其输入是output blobs ,在Ouput blobs里面的diff存储的就是其相应的error gradients。其中propagate_down这个参数跟Bottom的长度是一样的,每一个Index用来指定是否需要反向传播error gradients 到对应的bottom blob。而bottom 这里面的diff 区域存放的就是BackWard计算出来相应的gradient error.
inline void Backward(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom);
如果自己要实现一个Layer的话,那么Forward_cpu和Backward_cpu 以及gpu(可选),应该要有自己的实现。下面是各种Layer的继承,共有54个:
接下来几个函数比较简单,统一做说明
vector<shared_ptr<Blob<Dtype> > >& blobs() //返回blobs
const LayerParameter& layer_param() //返回layer 的参数parameter
virtual void ToProto(LayerParameter* param, bool write_diff = false) //将层参数写到Protobuffer里
inline Dtype loss(const int top_index) const //给定index返回相应的scalar loss
inline void set_loss(const int top_index, const Dtype value) //给定Index设置loss
virtual inline const char* type() //返回layer的type
以下几个函数主要获得bottom或者top blob的数量状态,比较简单,看名字即可
virtual inline int ExactNumBottomBlobs()
virtual inline int MinBottomBlobs()
virtual inline int MaxBottomBlobs()
virtual inline int ExactNumTopBlobs()
virtual inline int MinTopBlobs()
virtual inline int MaxTopBlobs()
virtual inline bool EqualNumBottomTopBlobs()
virtual inline bool AutoTopBlobs()
AllowforceBackward用来设置是否强制梯度返回,因为有些层其实不需要梯度信息 ,后面两个函数分别查看以及设置是否需要计算梯度。
virtual inline bool AllowForceBackward(const int bottom_index)
inline bool param_propagate_down(const int param_id)
inline void set_param_propagate_down(const int param_id, const bool value)
好,我们再往下面看,几个变量和函数都是保护变量
LayerParameter layer_param_; //保存layer的参数 parameter
Phase phase_; //标定阶段是train还是test
vector<shared_ptr<Blob<Dtype> > > blobs_; //是Blob的一个集合,保存了learnbale参数
vector<bool> param_propagate_down_; //标志位是否要计算param blob的梯度
vector<Dtype> loss_; //用来表明那个top blob 有非零的权重
下面这几个函数,分别是计算cpu和gpu模式下的正向和反向传播
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top)
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& 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)
这个函数被setup调用,主要是check bottom和top 的blob是否match,这里面用了上面提到的ExactBottomBlobs()等函数
virtual void CheckBlobCounts(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top)
SetLoss是非常重要的一个步骤,是被SetUp调用来初始化top bottom的weights,并且存储非零的loss weights 在diff blob里面
inline void SetLossWeights(const vector<Blob<Dtype>*>& top)
私有变量和函数如下,东西比较少,主要是对并行中的锁进行控制
bool is_shared_; //标记该layer是否被其他nets所共享
shared_ptr<boost::mutex> forward_mutex_; //若该layer被shared,则需要这个mutex序列保持forward过程的正常运行
void InitMutex(); //初始化forward 的 mutex
void Lock(); //locak mutex
void Unlock();//unlock mutex