caffe中的layer
layer是神经网络搭建的脚手架,理解了layer,才能盖好神经网络这座摩天大楼。
下图是一张关于layer的思维导图,在功力到达一定程度的时候才可练此功,到时一定会有不一样的收获。
1. Outline
此部分主要概述了与layer有关的方方面面。
1.1 layer.hpp
与layer相关的头文件:
layer.hppcommon_layers.hpp
data_layers.hpp
loss_layers.hpp
neuron_layers.hpp
vision_layers.hp
其中layer.hpp是抽象出来的基类,下面的的五个头文件都是在其基础上的继承,如上图中的五个部分。在layer.hpp头文件里,包含了这几个头文件:
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/device_alternate.hpp"
在device_alternate.hpp中,通过 #ifdef CPU_ONLY定义了一些宏来取消GPU的调用:
#define STUB_GPU(classname)
#define STUB_GPU_FORWARD(classname, funcname)
#define STUB_GPU_BACKWARD(classname, funcname)
layer中有这三个主要参数:
LayerParameter layer_param_; // 这个是protobuf文件中存储的layer参数
vector<share_ptr<Blob<Dtype>>> blobs_; // 这个存储的是layer的参数,在程序中用的
vector<bool> param_propagate_down_; // 这个bool表示是否计算各个blob参数的diff,即传播误差
Layer类的构建函数 explicit Layer(const LayerParameter& param) : layer_param_(param) 会尝试从protobuf文件读取参数。其三个主要接口:
virtual void SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top)
inline Dtype Forward(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top);
inline void Backward(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const <Blob<Dtype>*>* bottom);
SetUp 函数需要根据实际的参数设置进行实现,对各种类型的参数初始化;Forward 和 Backward 对应前向计算和反向更新,输入统一都是 bottom,输出为 top,其中 Backward 里面有个 propagate_down 参数,用来表示该Layer是否反向传播参数。
在 Forward 和 Backward 的具体实现里,会根据 Caffe::mode() 进行对应的操作,即使用cpu或者gpu进行计算,两个都实现了对应的接口 Forward_cpu、Forward_gpu 和 Backward_cpu、Backward_gpu,这些接口都是virtual,具体还是要根据layer的类型进行对应的计算(注意:有些layer并没有GPU计算的实现,所以封装时加入了CPU的计算作为后备)。另外,还实现了ToProto的接口,将Layer的参数写入到protocol buffer文件中。
1.2 data_layers.hpp
data_layers.hpp这个头文件包含了这几个头文件:
#include "boost/scoped_ptr.hpp"
#include "hdf5.h"
#include "leveldb/db.h"
#include "lmdb.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
caffe使用的几个数据库:
LMDB(Lightning Memory-Mapped Database)是一个和levelDB类似的key/value存储库,其常用于单标签数据,像分类等问题。
HDF5(Hierarchical Data Format)是一种为存储和处理大容量科学数据而设计的文件格式及相应的库文件,一般应用于多标签的任务上,比如给定一张猫的图片,它的标签不仅仅只包括它是猫这个标签,还包括它很胖,它很大这种标签,就使用hdf5比较合适。
鉴于目标检测的使用环境,使用最多的是lmdb格式,data_layer作为原始数据的输入层,处于整个网络的最底层,它从数据库lmdb中读取数据,当然也可以直接从内存中读取,还可以从hdf5,甚至是原始的图像读入数据。
caffe/filler.hpp的作用是在网络初始化时,根据layer的定义进行初始参数的填充,根据FillerParameter指定的类型进行对应的参数填充。
// A function to get a specific filler from the specification given in
// FillerParameter. Ideally this would be replaced by a factory pattern,
// but we will leave it this way for now.template <typename Dtype>
Filler<Dtype>* GetFiller(const FillerParameter& param) {const std::string& type = param.type();if (type == "constant") {return new ConstantFiller<Dtype>(param);} else if (type == "gaussian") {return new GaussianFiller<Dtype>(param);} else if (type == "positive_unitball") {return new PositiveUnitballFiller<Dtype>(param);} else if (type == "uniform") {return new UniformFiller<Dtype>(param);} else if (type == "xavier") {return new XavierFiller<Dtype>(param);} else {CHECK(false) << "Unknown filler name: " << param.type();}return (Filler<Dtype>*)(NULL);
}
internal_thread.hpp里面封装了pthread函数,继承的子类可以得到一个单独的线程,主要作用是在计算当前的一批数据时,在后台获取新一批的数据。
1.3 neuron_layers.hpp
输入data,就需进行计算,如常见的sigmoid、tanh,这些计算被抽象成neuron_layers.hpp里的类NeuronLayer,这个层只负责具体的计算,因此明确定义了输入ExactNumBottomBlobs()和ExactNumTopBlobs()都是常量1,即输入一个blob,输出一个blob。
1.4 vision_layers.hpp
主要完成的是图像的卷积操作,像conv、pooling、LRN都在里面,也可输出图像,要看具体实现代码。然后里面有个im2col的实现,按caffe作者的解释,主要是为了加速卷积的。
1.5 loss_layers.hpp
前面的data layer和common layer都是中间计算层,虽然会涉及到反向传播,但传播的源头来自于loss_layer,即网络的最终端。这一层因为要计算误差,所以输入都是2个blob,输出1个blob。
1.6 common_layers.hpp
NeruonLayer仅负责简单的一对一计算,而剩下的那些复杂的计算则通通放在了common_layers.hpp中。像ArgMaxLayer、ConcatLayer、FlattenLayer、SoftmaxLayer、SplitLayer和SliceLayer等各种对blob增减修改的操作。
2.Detail
深入layer的细节中去,对于一些常用的layer,如卷积层,池化层,还给出对应的proto代码。
2.1 数据层(data_layers)
数据通过数据层LMDB进入Caffe,数据层在整个网络的底部。
一些基本的操作,如:mean subtraction, scaling, random cropping, and mirroring均可直接在数据层上进行指定。
2.1.1 Database
类型:Data。
必须参数:
source: 包含数据的目录名称
batch_size: 一次处理的输入的数量
可选参数:
rand_skip: 在开始的时候从输入中跳过这个数值,在异步随机梯度下降(SGD)的时候非常有用
backend [default LEVELDB]: 选择使用 LEVELDB 或者 LMDB
2.1.2 In-Memory
类型: MemoryData
必需参数:
- batch_size, channels, height, width: 指定从内存读取数据的大小
MemoryData层直接从内存中读取数据,而不是拷贝过来。因此,要使用它的话,你必须调用MemoryDataLayer::Reset (from C++)或者Net.set_input_arrays (from Python)以此指定一块连续的数据(通常是一个四维张量)。
2.1.3 Images
类型: ImageData
必要参数:
source: text文件的名字,每一行给出一张图片的文件名和label
batch_size: 一个batch中图片的数量
可选参数:
rand_skip:在开始的时候从输入中跳过这个数值,在异步随机梯度下降(SGD)的时候非常有用
shuffle [default false]
new_height, new_width: 把所有的图像resize到这个大小
2.1.4 Windows
类型:WindowData
2.1.5 Dummy
类型:DummyData
Dummy 层用于development 和debugging。具体参数DummyDataParameter。
2.2 激励层(neuron_layers)
激励层是element-wise的操作,输入和输出的大小相同,一般情况下是一个非线性函数。
2.2.1 ReLU / Rectified-Linear and Leaky-ReLU
类型: ReLU
例子:
layer {name: "relu1"type: "ReLU"bottom: "conv1"top: "conv1"
}
可选参数:
- negative_slope [default 0]: 指定输入值小于零时的输出。
ReLU是目前使用做多的激励函数,主要因为其收敛快,并且能保持同样效果。标准的ReLU函数为max(x, 0),而一般为当x > 0时输出x,但x <= 0时输出negative_slope。RELU层支持in-place计算,这意味着bottom的输出和输入相同以避免内存的消耗。
2.2.2 Sigmoid
类型:Sigmoid
例子:
layer {name: "encode1neuron"bottom: "encode1"top: "encode1neuron"type: "Sigmoid"
}
Sigmoid层通过 sigmoid(x) 计算每一个输入x的输出,函数如下图。
2.2.3 TanH / Hyperbolic Tangent
类型: TanH
例子:
layer {name: "layer"bottom: "in"top: "out"type: "TanH"
}
TanH层通过 tanh(x) 计算每一个输入x的输出,函数如下图。请注意sigmoid函数和TanH函数在纵轴上的区别。sigmoid函数将实数映射到(0,1)。TanH将实数映射到(-1,1)。
2.2.4 Absolute Value
类型: AbsVal
例子:
layer {name: "layer"bottom: "in"top: "out"type: "AbsVal"
}
ABSVAL层通过 abs(x) 计算每一个输入x的输出。
2.2.5 Power
类型: Power
例子:
layer {name: "layer"bottom: "in"top: "out"type: "Power"power_param {power: 1scale: 1shift: 0}
}
可选参数:
power [default 1]
scale [default 1]
shift [default 0]
POWER层通过 (shift + scale * x) ^ power计算每一个输入x的输出。
2.2.6 BNLL
类型: BNLL
例子:
layer {name: "layer"bottom: "in"top: "out"type: BNLL
}
BNLL (binomial normal log likelihood) 层通过 log(1 + exp(x)) 计算每一个输入x的输出。
2.3视觉层(vision_layers)
2.3.1 卷积层(Conv)
类型:Convolution
例子:
layers { name: "conv1" type: CONVOLUTION bottom: "data" top: "conv1" blobs_lr: 1 # learning rate multiplier for the filters blobs_lr: 2 # learning rate multiplier for the biases weight_decay: 1 # weight decay multiplier for the filters weight_decay: 0 # weight decay multiplier for the biases convolution_param { num_output: 96 # learn 96 filters kernel_size: 11 # each filter is 11x11 stride: 4 # step 4 pixels between each filter application weight_filler { type: "gaussian" # initialize the filters from a Gaussian std: 0.01 # distribution with stdev 0.01 (default mean: 0) } bias_filler { type: "constant" # initialize the biases to zero (0) value: 0 } }}
}
blobs_lr: 学习率调整的参数,在上面的例子中设置权重学习率和运行中求解器给出的学习率一样,同时是偏置学习率为权重的两倍。
weight_decay:
卷积层的重要参数
必须参数:
num_output (c_o):过滤器的个数
kernel_size (or kernel_h and kernel_w):过滤器的大小(也就是所谓“核”的大小)。
建议参数:
- weight_filler [default type: ‘constant’ value: 0]:参数的初始化方法
可选参数:
bias_filler:偏置的初始化方法
bias_term [default true]:指定是否是否开启偏置项
pad (or pad_h and pad_w) [default 0]:指定在输入的每一边加上多少个像素
stride (or stride_h and stride_w) [default 1]:指定过滤器的步长
group (g) [default 1]: 如果g>1,那么将每个滤波器都限定只与某个输入的子集有关联。换句话说,将输入分为g组,同时将输出也分为g组。那么第i组输出只与第i组输入有关。
2.3.2 池化层(Pooling)
类型:Pooling
例子:
layers { name: "pool1" type: POOLING bottom: "conv1" top: "pool1" pooling_param { pool: MAX kernel_size: 3 # pool over a 3x3 region stride: 2 # step two pixels (in the bottom blob) between pooling regions }
}
卷积层的重要参数
必需参数:
- kernel_size (or kernel_h and kernel_w):过滤器的大小
可选参数:
pool [default MAX]:pooling的方法,目前有MAX, AVE, 和STOCHASTIC三种方法
pad (or pad_h and pad_w) [default 0]:指定在输入的每一遍加上多少个像素
stride (or stride_h and stride_w) [default 1]:指定过滤器的步长
2.3.3 Local Response Normalization (LRN)
类型:LRN
可选参数:
local_size [default 5]:对于cross channel LRN为需要求和的邻近channel的数量;对于within channel LRN为需要求和的空间区域的边长;
alpha [default 1]:scaling参数;
beta [default 5]:指数;
norm_region [default ACROSS_CHANNELS]: 选择LRN实现的方法:1. ACROSS_CHANNELS ;2. WITHIN_CHANNEL
LRN(Local Response Normalization)对一个局部的输入区域进行的归一化。有两种不同的形式:1. ACCROSS_CHANNEL;2. WITHIN_CHANNEL。其实很好从字面上进行理解。第一种方法综合了不同的channel,而在一个channel里面只取1*1(所以size是localsize×1×1)。而在第二种方法中,不在channel方向上扩展,只在单一channel上进行空间扩展(所以size是1×localsize×localsize)。
计算公式:对每一个输入除以
,其中参数α是scaling参数,参数β是指数。而参数n对应local region的大小。
2.4 损失层(Loss Layers)
深度学习是通过最小化输出和目标的Loss来驱动学习。
2.4.1 Softmax
类型: SoftmaxWithLoss
Softmax Loss层应用于多标签分类。对于输入,计算了multinomial logistic loss。在概念上近似等于一个Softmax层加上一个multinomial logistic loss层,但在梯度的计算上更加稳定。
2.4.2 Sum-of-Squares / Euclidean
类型: EuclideanLoss
Euclidean loss层计算了两个输入差的平方和:
2.4.3 Hinge / Margin
类型: HingeLoss
例子:
L1 Normlayers { name: "loss" type: HINGE_LOSS bottom: "pred" bottom: "label"
}
L2 Normlayers { name: "loss" type: HINGE_LOSS bottom: "pred" bottom: "label" top: "loss" hinge_loss_param { norm: L2 }
}
可选参数:
- norm [default L1]: 选择L1或者L2范数
2.4.4 Sigmoid Cross-Entropy
类型:SigmoidCrossEntropyLoss
2.4.5 Infogain
类型:InfoGainLoss
2.4.6 Accuracy and Top-k
类型:Accuracy
用来计算输出和目标的正确率,事实上这不是一个loss,而且没有backward这一步。
2.5. 一般层(Common Layers)
2.5.1 全连接层 Inner Product
类型:InnerProduct
例子:
layer {name: "fc8"type: "InnerProduct"# learning rate and decay multipliers for the weightsparam { lr_mult: 1 decay_mult: 1 }# learning rate and decay multipliers for the biasesparam { lr_mult: 2 decay_mult: 0 }inner_product_param {num_output: 1000weight_filler {type: "gaussian"std: 0.01}bias_filler {type: "constant"value: 0}}bottom: "fc7"top: "fc8"
}
必要参数:
- num_output (c_o):过滤器的个数
可选参数:
weight_filler [default type: ‘constant’ value: 0]:参数的初始化方法
bias_filler:偏置的初始化方法
bias_term [default true]:指定是否是否开启偏置项
2.5.2 Splitting
类型:Split
Splitting层可以把一个输入blob分离成多个输出blobs。这个用在当需要把一个blob输入到多个输出层的时候。
2.5.3 Flattening
类型:Flatten
Flatten层是把一个输入的大小为n * c * h * w变成一个简单的向量,其大小为 n * (c*h*w) * 1 * 1。
2.5.4 Reshape
类型:Reshape
例子:
layer {name: "reshape"type: "Reshape"bottom: "input"top: "output"reshape_param {shape {dim: 0 # copy the dimension from belowdim: 2dim: 3dim: -1 # infer it from the other dimensions}}}
输入:单独的一个blob,可以是任意维;
输出:同样的blob,但是它的维度已经被我们人为地改变,维度的数据由reshap_param定义。
可选参数:
- shape
Reshape层被用于改变输入的维度,而不改变输入的具体数据。就像Flatten层一样。只是维度被改变而已,这个过程不涉及数据的拷贝。
输出的维度由ReshapeParam proto控制。可以直接使用数字进行指定。设定输入的某一维到输出blob中去。此外,还有两个数字值得说一下:
0 直接从底层复制。例如,如果是底层是一个2在它的第一维,那么顶层在它的第一维也有一个2。
-1 从其他的数据里面推测这一维应该是多少。
2.5.5 Concatenation
类型:Concat
例子:
layer {name: "concat"bottom: "in1"bottom: "in2"top: "out"type: "Concat"concat_param {axis: 1}
}
可选参数:
- axis [default 1]:0代表链接num,1代表链接channels
通过Concatenation层,可以把多个的blobs链接成一个blob。
2.5.6 Slicing
类型:Slice
例子:
layer {name: "slicer_label"type: "Slice"bottom: "label"## Example of label with a shape N x 3 x 1 x 1top: "label1"top: "label2"top: "label3"slice_param {axis: 1slice_point: 1slice_point: 2}
}
Slice层可以将输入层变成多个输出层。这些输出层沿一个给定的维度存在。axis指定了目标的轴,slice_point则指定了选择维度的序号。
2.5.7 Elementwise Operations
类型:Eltwise
2.5.8 Argmax
类型:ArgMax
2.5.9 Softmax
类型:Softmax
2.5.10 Mean-Variance Normalization
类型:MVN
3.综述
每个layer的输入数据来自一些 'bottom' blobs, 输出一些 'top' blobs。Caffe中每种类型layer的参数说明定义在caffe.proto文件中,具体的layer参数值则定义在具体应用的protocals buffer网络结构说明文件中。例如,卷积层(ConvolutionLayer)的参数说明在caffe.proto中是如下定义的,
// in caffe.proto
// Message that stores parameters used by ConvolutionLayer
message ConvolutionParameter { optional uint32 num_output = 1; // The number of outputs for the layer optional bool bias_term = 2 [default = true]; // whether to have bias terms // Pad, kernel size, and stride are all given as a single value for equal // dimensions in height and width or as Y, X pairs. optional uint32 pad = 3 [default = 0]; // The padding size (equal in Y, X) optional uint32 pad_h = 9 [default = 0]; // The padding height optional uint32 pad_w = 10 [default = 0]; // The padding width optional uint32 kernel_size = 4; // The kernel size (square) optional uint32 kernel_h = 11; // The kernel height optional uint32 kernel_w = 12; // The kernel width optional uint32 group = 5 [default = 1]; // The group size for group conv optional uint32 stride = 6 [default = 1]; // The stride (equal in Y, X) optional uint32 stride_h = 13; // The stride height optional uint32 stride_w = 14; // The stride width optional FillerParameter weight_filler = 7; // The filler for the weight optional FillerParameter bias_filler = 8; // The filler for the bias enum Engine { DEFAULT = 0; CAFFE = 1; CUDNN = 2; } optional Engine engine = 15 [default = DEFAULT];
}
其中的参数说明包括卷积核的个数、大小和步长等。在examples\mnist\lenet_train_test.prototxt网络结构说明文件中,具体一个卷积层(ConvolutionLayer)是这样定义的
# in examples\mnist\lenet_train_test.prototxt
layer { name: "conv1" // 层的名字 type: "Convolution" // 层的类型,说明具体执行哪一种计算 bottom: "data" // 层的输入数据Blob的名字 top: "conv1" // 层的输出数据Blob的名字 param { // 层的权值和偏置相关参数 lr_mult: 1 } param { lr_mult: 2 } convolution_param { // 卷积层卷积运算相关的参数 num_output: 20 kernel_size: 5 stride: 1 weight_filler { type: "xavier" } bias_filler { type: "constant" } }
}
每种类型的layer需要定义三种关键操作LayerSetUp, Forward, Backward:
- LayerSetUp: 网络构建时初始化层和层的连接
- Forward: 网络数据前向传递,给定bottom输入数据,计算输出到top
- Backward: 网络误差反向传递,给定top的梯度,计算bottom的梯度并存储到bottom blob
Layer的设计主要就是SetUp、Forward、Backward函数(层一开始的时候的设置、然后就是前传和反传)。
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/device_alternate.hpp" namespace caffe { /** * @brief An interface for the units of computation which can be composed into a * Net. * * Layer%s must implement a Forward function, in which they take their input * (bottom) Blob%s (if any) and compute their output Blob%s (if any). * They may also implement a Backward function, in which they compute the error * gradients with respect to their input Blob%s, given the error gradients with * their output Blob%s. */
template <typename Dtype>
class Layer { public:
/*
首先获得当前网络的Phase,是train还是test,在初始化列表初始化LayerParameter,之后blobs_这里存放的是一个指向blob类的shared_ptr指针的一个vector,在这里是申请空间,然后将传入的layer_param中的blob拷贝过来。
*/
// 显示的构造函数不需要重写,任何初始工作在SetUp()中完成
// 构造方法只复制层参数说明的值,如果层说明参数中提供了权值和偏置参数,也复制 explicit Layer(const LayerParameter& param) : layer_param_(param) { // Set phase and copy blobs (if there are any).
// 训练还是测试?phase phase_ = param.phase(); if (layer_param_.blobs_size() > 0) {
// 将blobs_的大小设置为参数中的大小 blobs_.resize(layer_param_.blobs_size()); for (int i = 0; i < layer_param_.blobs_size(); ++i) {
// 新建若干个Blob blobs_[i].reset(new Blob<Dtype>());
// 从blob文件中获取数据 blobs_[i]->FromProto(layer_param_.blobs(i)); } }//用protobuf 传入的参数对blobs_ 做初始化,blobs_ 是一个vector 存放指向Blob类的智能指针。 #ifdef USE_MPI //If this is a gather layer, all it subsequent layer doesn't need gradient sync. //We will only change itself's property here, //subsequent layers will be inferred in the Net if (is_gathering()){ set_need_sync(false); }else{ set_need_sync(true); } #endif } virtual ~Layer() {}
初始化函数SetUp,每个Layer对象都必须遵循固定的调用模式, /** * @brief Implements common layer setup functionality. * @brief 实现每个layer对象的setup函数 * @param bottom the preshaped input blobs * @param bottom 层的输入数据,blob中的存储空间已申请 * @param top * the allocated but unshaped output blobs, to be shaped by Reshape * @param top 层的输出数据,blob对象以构造但是其中的存储空间未申请, * 具体空间大小需根据bottom blob大小和layer_param_共同决定,具体在Reshape函数现实 * * Checks that the number of bottom and top blobs is correct. * Calls LayerSetUp to do special layer setup for individual layer types, * followed by Reshape to set up sizes of top blobs and internal buffers. * Sets up the loss weight multiplier blobs for any non-zero loss weights. * This method may not be overridden. * 1. 检查输入输出blob个数是否满足要求,每个层能处理的输入输出数据不一样 * 2. 调用LayerSetUp函数初始化特殊的层,每个Layer子类需重写这个函数完成定制的初始化 * 3. 调用Reshape函数为top blob分配合适大小的存储空间 * 4. 为每个top blob设置损失权重乘子,非LossLayer为的top blob其值为零 * * 此方法非虚函数,不用重写,模式固定 */ void SetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { CheckBlobCounts(bottom, top); LayerSetUp(bottom, top); Reshape(bottom, top); SetLossWeights(top); }
/每个子类Layer必须重写的初始化函数LayerSetUp, /** * @brief Does layer-specific setup: your layer should implement this function * as well as Reshape. * @brief 定制初始化,每个子类layer必须实现此虚函数 * * @param bottom * the preshaped input blobs, whose data fields store the input data for * this layer * @param bottom * 输入blob, 数据成员data_和diff_存储了相关数据 * @param top * the allocated but unshaped output blobs * @param top * 输出blob, blob对象已构造但数据成员的空间尚未申请 * * This method should do one-time layer specific setup. This includes reading * and processing relevent parameters from the <code>layer_param_</code>. * Setting up the shapes of top blobs and internal buffers should be done in * <code>Reshape</code>, which will be called before the forward pass to * adjust the top blob sizes. * 此方法执行一次定制化的层初始化,包括从layer_param_读入并处理相关的层权值和偏置参数, * 调用Reshape函数申请top blob的存储空间 */ virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {}
/每个子类Layer必须重写的Reshape函数,完成top blob形状的设置并为其分配存储空间, /** * @brief Adjust the shapes of top blobs and internal buffers to accomodate * the shapes of the bottom blobs. * @brief 根据bottom blob的形状和layer_param_计算top blob的形状并为其分配存储空间 * * @param bottom the input blobs, with the requested input shapes * @param top the top blobs, which should be reshaped as needed * * This method should reshape top blobs as needed according to the shapes * of the bottom (input) blobs, as well as reshaping any internal buffers * and making any other necessary adjustments so that the layer can * accomodate the bottom blobs. */ virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) = 0; /** * @brief Given the bottom blobs, compute the top blobs and the loss. * * @param bottom * the input blobs, whose data fields store the input data for this layer * @param top * the preshaped output blobs, whose data fields will store this layers' * outputs * \return The total loss from the layer. * * The Forward wrapper calls the relevant device wrapper function * (Forward_cpu or Forward_gpu) to compute the top blob values given the * bottom blobs. If the layer has any non-zero loss_weights, the wrapper * then computes and returns the loss. * * Your layer should implement Forward_cpu and (optionally) Forward_gpu. */
//前向传播函数Forward和反向传播函数Backward
/*
首先是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); /** * @brief Given the top blob error gradients, compute the bottom blob error * gradients. * * @param top * the output blobs, whose diff fields store the gradient of the error * with respect to themselves * @param propagate_down * a vector with equal length to bottom, with each index indicating * whether to propagate the error gradients down to the bottom blob at * the corresponding index * @param bottom * the input blobs, whose diff fields will store the gradient of the error * with respect to themselves after Backward is run * * The Backward wrapper calls the relevant device wrapper function * (Backward_cpu or Backward_gpu) to compute the bottom blob diffs given the * top blob diffs. * * Your layer should implement Forward_cpu and (optionally) Forward_gpu. */
/*
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); /** * @brief Returns the vector of learnable parameter blobs. */ vector<shared_ptr<Blob<Dtype> > >& blobs() { return blobs_;//返回vector blobs_ } /** * @brief Returns the layer parameter. */
//返回layer parameter const LayerParameter& layer_param() const { return layer_param_; } /** * @brief Writes the layer parameter to a protocol buffer */
//将layer plarameter 写入protobuf virtual void ToProto(LayerParameter* param, bool write_diff = false); //返回 ,设置一个blob top 在给定 index 的 loss /** * @brief Returns the scalar loss associated with a top blob at a given index. */ inline Dtype loss(const int top_index) const { return (loss_.size() > top_index) ? loss_[top_index] : Dtype(0); } /** * @brief Sets the loss associated with a top blob at a given index. */ 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; }
//一些返回特定参数的函数: /** * 获得bottom或者top blob的数量状态,比较简单,看名字即可 */ // 虚函数,而且还是内联的,返回层类型 virtual inline const char* type() const { return ""; } // 虚函数,获得bottom blob的精确个数 virtual inline int ExactNumBottomBlobs() const { return -1; } // 虚函数,获得bottom blob的最小个数 virtual inline int MinBottomBlobs() const { return -1; } // 虚函数,获得bottom blob的最大个数 virtual inline int MaxBottomBlobs() const { return -1; } // 虚函数,获得top blob的精确个数 virtual inline int ExactNumTopBlobs() const { return -1; } // 虚函数,获得top blob的最小个数 virtual inline int MinTopBlobs() const { return -1; } // 虚函数,获得top blob的最大个数 virtual inline int MaxTopBlobs() const { return -1; } // 虚函数,bottom blob和top blob的个数是否一致 virtual inline bool EqualNumBottomTopBlobs() const { return false; } // 返回当前层是否自动创建匿名top blobs // 如果返回true,表明网络初始化的时候创建了了足够多的匿名top blobs // 来满足ExactNumTopBlobs或者MinTopBlobs所要求的top blobs的个数 virtual inline bool AutoTopBlobs() const { return false; }
/*
AllowforceBackward用来设置是否强制梯度返回,因为有些层其实不需要梯度信息 ,后面两个函数分别查看以及设置是是否需要计算梯度。
*/ // 对于一个给定的bottom blob,返回是否允许强制反传 virtual inline bool AllowForceBackward(const int bottom_index) const { return true; } //set_param_propagate_down,param_propagate_down 函数:设置对于那些bottom 需要反向传播。 /** * @brief Specifies whether the layer should compute gradients w.r.t. a * parameter at a particular index given by param_id. * * You can safely ignore false values and always compute gradients * for all parameters, but possibly with wasteful computation. */ inline bool param_propagate_down(const int param_id) { return (param_propagate_down_.size() > param_id) ? param_propagate_down_[param_id] : false; } /** * @brief Sets whether the layer should compute gradients w.r.t. a * parameter at a particular index given by param_id. */ 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; } #ifdef USE_MPI /** * @brief Checks whether the layer accepts specifed parallel type * * If not supported, will halt the program with hints */ inline virtual bool is_gathering() {return false;} inline virtual bool is_scattering() {return false;} inline bool need_sync(){return need_sync_;} inline void set_need_sync(bool val){need_sync_ = val;} #endif protected: /** The protobuf that stores the layer parameters */ // 层说明参数,从protocal buffers格式的网络结构说明文件中读取 LayerParameter layer_param_; /** The phase: TRAIN or TEST */ // 层状态,参与网络的训练还是测试 Phase phase_; /** The vector that stores the learnable parameters as a set of blobs. */ // 层权值和偏置参数,使用向量是因为权值参数和偏置是分开保存在两个blob中的 vector<shared_ptr<Blob<Dtype> > > blobs_; /** Vector indicating whether to compute the diff of each param blob. */ // 标志每个top blob是否需要计算反向传递的梯度值 vector<bool> param_propagate_down_; /** The vector that indicates whether each top blob has a non-zero weight in * the objective function. */ // 非LossLayer为零,LossLayer中表示每个top blob计算的loss的权重 vector<Dtype> loss_; #ifdef USE_MPI /** * For parallel use */ bool need_sync_; #endif
/这两个函数非虚函数,它们内部会调用如下虚函数完成数据前向传递和
/误差反向传播,根据执行环境的不同每个子类Layer必须重写CPU和GPU版本, /** @brief Using the CPU device, compute the layer output. */ virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) = 0; /** * @brief Using the GPU device, compute the layer output. * Fall back to Forward_cpu() if unavailable. */ virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { // LOG(WARNING) << "Using CPU code as backup."; return Forward_cpu(bottom, top); } /** * @brief Using the CPU device, compute the gradients for any parameters and * for the bottom blobs if propagate_down is true. */ virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) = 0; /** * @brief Using the GPU device, compute the gradients for any parameters and * for the bottom blobs if propagate_down is true. * Fall back to Backward_cpu() if unavailable. */ virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { // LOG(WARNING) << "Using CPU code as backup."; Backward_cpu(top, propagate_down, bottom); } /** * Called by the parent Layer's SetUp to check that the number of bottom * and top Blobs provided as input match the expected numbers specified by * the {ExactNum,Min,Max}{Bottom,Top}Blobs() functions. */ 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."; }// 保证输入bottom 数量和要求的相同 if (MinBottomBlobs() >= 0) { CHECK_LE(MinBottomBlobs(), bottom.size()) << type() << " Layer takes at least " << MinBottomBlobs() << " bottom blob(s) as input."; }//保证输入的bottom数量大于或等于要求的最小数量 if (MaxBottomBlobs() >= 0) { CHECK_GE(MaxBottomBlobs(), bottom.size()) << type() << " Layer takes at most " << MaxBottomBlobs() << " bottom blob(s) as input."; }//保证输入的bottom数量小于或等于要求的最大数量 if (ExactNumTopBlobs() >= 0) { CHECK_EQ(ExactNumTopBlobs(), top.size()) << type() << " Layer produces " << ExactNumTopBlobs() << " top blob(s) as output."; }// 保证输入top数量和要求的相同 if (MinTopBlobs() >= 0) { CHECK_LE(MinTopBlobs(), top.size()) << type() << " Layer produces at least " << MinTopBlobs() << " top blob(s) as output."; }//保证输入的top数量大于或等于要求的最小数量 if (MaxTopBlobs() >= 0) { CHECK_GE(MaxTopBlobs(), top.size()) << type() << " Layer produces at most " << MaxTopBlobs() << " top blob(s) as output."; }//保证输入的top数量小于或等于要求的最大数量 if (EqualNumBottomTopBlobs()) { CHECK_EQ(bottom.size(), top.size()) << type() << " Layer produces one top blob as output for each " << "bottom blob input."; }//保证输入的bottom数量和输出的top数量相同 } /** * Called by SetUp to initialize the weights associated with any top blobs in * the loss function. Store non-zero loss weights in the diff blob. */
/*
SetLoss是非常重要的一个步骤,是被SetUp调用来初始化top bottom的weights,并且存储非零的loss weights 在diff blob里面
*/ 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; }//如果为0不对loss进行操作 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);//将loss_multiplier设为loss_weight } } } DISABLE_COPY_AND_ASSIGN(Layer);
}; // class Layer /*
前传调用对应的Forward_cpu或者Forward_gpu而我们知道Forward_cpu是纯虚函数,必须要实而Forward_gpu是虚函数,如果不实现就调用 Forward_cpu函数了。前传(你必须实现自己的Forward_cpu,实现Forward_gpu是可选的)
*/
// Forward and backward wrappers. You should implement the cpu and
// gpu specific implementations instead, and should not change these
// functions.
template <typename Dtype>
inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { Dtype loss = 0; // 根据bottom设置top的形状 Reshape(bottom, top); // 设置运行模式CPU or GPU switch (Caffe::mode()) { case Caffe::CPU: // 调用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(); // 获取梯度(\frac{\partial Loss}{\partial net}) const Dtype* loss_weights = top[top_id]->cpu_diff(); // data与loss_weight的点积,即得损失函数关于当前层权重的偏导了 // \frac{\partial Loss}{\partial net} * \frac{\partial net}{\frac{W}} // = \frac{\partial Loss}{\partial W} loss += caffe_cpu_dot(count, data, loss_weights); } break; case Caffe::GPU: // GPU前传 Forward_gpu(bottom, top);
#ifndef CPU_ONLY // 同上,只不过这里用GPU来计算点积了 for (int top_id = 0; top_id < top.size(); ++top_id) { if (!this->loss(top_id)) { continue; } const int count = top[top_id]->count(); // 获取GPU上的数据 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."; } return loss;
} 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);
//根据blob top 的error 梯度(diff)计算bottom 的 error 梯度。 propagate_down 是长度
//和bottom 相同的vector ,用于控制是否需要对对应的bottom 元素传播梯度。具体layer具体定义。 break; case Caffe::GPU: Backward_gpu(top, propagate_down, bottom); break; default: LOG(FATAL) << "Unknown caffe mode."; }
}
Layer的序列化函数,将layer的层说明参数layer_param_,层权值和偏置
参数blobs_复制到LayerParameter对象,便于写到磁盘,
// Serialize LayerParameter to protocol buffer
template <typename Dtype>
void Layer<Dtype>::ToProto(LayerParameter* param, bool write_diff) { param->Clear(); param->CopyFrom(layer_param_); // 复制层说明参数layer_param_ param->clear_blobs(); // 复制层权值和偏置参数blobs_ for (int i = 0; i < blobs_.size(); ++i) { blobs_[i]->ToProto(param->add_blobs(), write_diff); }
} } // namespace caffe #endif // CAFFE_LAYER_H_
device_alternate.hpp:
#ifndef CAFFE_UTIL_DEVICE_ALTERNATE_H_
#define CAFFE_UTIL_DEVICE_ALTERNATE_H_ #ifdef CPU_ONLY // CPU-only Caffe. #include <vector> // Stub out GPU calls as unavailable.
//打印出GPU不可以使用
#define NO_GPU LOG(FATAL) << "Cannot use GPU in CPU-only Caffe: check mode."
// 定义给定类的前向和反向(GPU和CPU)传播的函数定义
#define STUB_GPU(classname) \
template <typename Dtype> \
void classname<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, \ const vector<Blob<Dtype>*>& top) { NO_GPU; } \
template <typename Dtype> \
void classname<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, \ const vector<bool>& propagate_down, \ const vector<Blob<Dtype>*>& bottom) { NO_GPU; } \ #define STUB_GPU_FORWARD(classname, funcname) \
template <typename Dtype> \
void classname<Dtype>::funcname##_##gpu(const vector<Blob<Dtype>*>& bottom, \ const vector<Blob<Dtype>*>& top) { NO_GPU; } \ #define STUB_GPU_BACKWARD(classname, funcname) \
template <typename Dtype> \
void classname<Dtype>::funcname##_##gpu(const vector<Blob<Dtype>*>& top, \ const vector<bool>& propagate_down, \ const vector<Blob<Dtype>*>& bottom) { NO_GPU; } \ #else // Normal GPU + CPU Caffe. #include <cublas_v2.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <curand.h>
#include <driver_types.h> // cuda driver types
#ifdef USE_CUDNN // cuDNN acceleration library.
#include "caffe/util/cudnn.hpp"
#endif //
// CUDA macros
// // CUDA: various checks for different function calls.
#define CUDA_CHECK(condition) \ /* Code block avoids redefinition of cudaError_t error */ \ do { \ cudaError_t error = condition; \ CHECK_EQ(error, cudaSuccess) << " " << cudaGetErrorString(error); \ } while (0) #define CUBLAS_CHECK(condition) \ do { \ cublasStatus_t status = condition; \ CHECK_EQ(status, CUBLAS_STATUS_SUCCESS) << " " \ << caffe::cublasGetErrorString(status); \ } while (0) #define CURAND_CHECK(condition) \ do { \ curandStatus_t status = condition; \ CHECK_EQ(status, CURAND_STATUS_SUCCESS) << " " \ << caffe::curandGetErrorString(status); \ } while (0)
//caffe采取的线程格和线程块的维数设计
// blockDim.x* gridDim.x表示的是该线程格所有线程的数量
//n表示核函数总共要处理的元素个数
#define CUDA_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \ i < (n); \ i += blockDim.x * gridDim.x) // CUDA: check for error after kernel execution and exit loudly if there is one.
#define CUDA_POST_KERNEL_CHECK CUDA_CHECK(cudaPeekAtLastError()) namespace caffe { //CUDA的lib错误报告
const char* cublasGetErrorString(cublasStatus_t error);
const char* curandGetErrorString(curandStatus_t error); // CUDA: thread number configuration.
// Use 1024 threads per block, which requires cuda sm_2x or above,
// or fall back to attempt compatibility (best of luck to you).
#if __CUDA_ARCH__ >= 200 const int CAFFE_CUDA_NUM_THREADS = 1024;
#else const int CAFFE_CUDA_NUM_THREADS = 512;
#endif //CUDA线程的块的数量
inline int CAFFE_GET_BLOCKS(const int N) { return (N + CAFFE_CUDA_NUM_THREADS - 1) / CAFFE_CUDA_NUM_THREADS;
} } // namespace caffe #endif // CPU_ONLY #endif // CAFFE_UTIL_DEVICE_ALTERNATE_H_
4. 总结
结合官方文档,再加画图和看代码,终于对整个layer层有了个基本认识:data负责输入,vision负责卷积相关的计算,neuron和common负责中间部分的数据计算,而loss是最后一部分,负责计算反向传播的误差。具体的实现都在src/caffe/layers里面,慢慢再研究研究。
在这些抽象的基类头文件里,看起来挺累,好在各种搜索,也能学到一些技巧,如,巧用宏定义来简写C,C++代码,使用模板方法,将有大量重复接口和参数的类抽象为一个宏定义,达到简化代码的目的。
caffe中的layer相关推荐
- caffe中各层的作用
caffe中各层的作用: 关于caffe中的solver: cafffe中的sover的方法都有: Stochastic Gradient Descent (type: "SGD" ...
- Caffe源码中Pooling Layer文件分析
Caffe源码(caffe version commit: 09868ac , date: 2015.08.15)中有一些重要的头文件,这里介绍下include/caffe/vision_layers ...
- 多线程 python layer_在Caffe中加Python Layer的方法
Author: Zongwei Zhou | 周纵苇 Weibo: @MrGiovanni Email: zongweiz@asu.edu Acknowledgement: Md Rahman Sid ...
- caffe中的softmax layer
在caffe中的lenet实现最后一层是softmax layer,输出分类的结果,下面就简单介绍一下softmax回归. 1,首先,在caffe中,softmax layer输出的是原始的输入在每一 ...
- 在caffe中添加新层 L1 Loss layer
本文地址:http://blog.csdn.net/ismarvellous/article/details/79069661,转载请注明出处. 本文涉及的所有完整文件可在我的github下载. 1. ...
- Caffe中对MNIST执行train操作执行流程解析
之前在 http://blog.csdn.net/fengbingchun/article/details/49849225 中简单介绍过使用Caffe train MNIST的文章,当时只是仿照ca ...
- caffe中权值初始化方法
参考:https://www.cnblogs.com/tianshifu/p/6165809.html 首先说明:在caffe/include/caffe中的 filer.hpp文件中有它的源文件,如 ...
- 怎么在Caffe中配置每一个层的结构
如何在Caffe中配置每一个层的结构 最近刚在电脑上装好Caffe,由于神经网络中有不同的层结构,不同类型的层又有不同的参数,所有就根据Caffe官网的说明文档做了一个简单的总结. 1. Vision ...
- 浅谈caffe中train_val.prototxt和deploy.prototxt文件的区别
浅谈caffe中train_val.prototxt和deploy.prototxt文件的区别 标签: caffe深度学习CaffeNet 2016-11-02 16:10 1203人阅读 评论(1) ...
最新文章
- DreamWeaver文件保存时,提示发生共享违例问题的解决方法
- SyntaxError: invalid syntax的问题原因和解决办法
- 计算机与图像处理论文标题,数字图像处理论文各种题目.doc
- 集成运放组成的电压比较器
- input 不显示边框_不需要使用JavaScript
- setuptools与distutils的区别
- PHP+ExtJS 文件上传示例
- mysql rpm server_记录一次最新版MySQL-server-5.6.20-1.el6.x86_64.rpm的安装
- 蓝桥杯每日真题之直线
- 对电机油冷分析_油冷电驱汇总(Tesla/Nidec/大众MEB/雪佛兰/华为)
- 【图像处理】【去模糊】图像去模糊的原理
- 21世纪八大新兴技术领域对美国战略威慑的影响
- Web安全 Msfconsole攻击技术(成功拿下服务器最高权限.)
- 华为云Web应用防火墙 ——为网络安全打通“第一公里”
- Linux新世纪五笔
- 软件设计的概念与原则
- Charles的安装和注册码破解
- Linux上安装Matlab2020a
- DOM对象的常用属性
- 工资管理系统的需求概述的资料收集与分析:
热门文章
- cocos2d-x Touch触屏事件
- 使用Floyd-Warshall算法求出两点之间的最短路径
- 微信小程序播放背景音乐,关闭背景音乐的操作
- 家庭用电都是交流电,为何会有零线和火线的区别?
- Qt窗口组件实现动态背景功能
- Kafka入门经典教程
- linux上使用openocd的问题
- java 1st 2nd 3rd 4th_为啥第一是1ST,第二是2ND,第三是3RD,第四开始都是TH呢1ST、2ND、...-3rd-英语-耿佬杜同学...
- 安装 Swoole教程
- 在Controller注入Service报错的解决方法