Blob类是caffe中对处理和传递的实际数据的封装,是caffe中基本的数据存储单元,包括前向传播中的图像数据,反向传播中的梯度数据以及网络层间的中间数据变量(包括权值,偏置等),训练模型的参数等等,能够说在caffe中,无数据不blob。api
blob能够认为是按C风格连续存储的N维数组,在硬件上能够认为是在内存中的一块连续的内存块。数组
补充一点智能指针的知识:网络
C++中的动态内存管理是经过new和delete运算符完成的,没有及时delete释放内存或者提早释放内存均可能形成内存异常,致使内存泄漏,或者是引用了非法的内存指针。app
C++ 11 标准库提供了智能指针(smart pointer)来管理动态内存对象,这种智能指针的智能之处在于能够自动释放内存对象。智能指针分为两种,一种是shared_ptr,容许多了个指针同时指向同一个对象,另外一种是unique_ptr,同时只能有一个指针指向内存对象。 智能指针是模板类而不是指针,建立一个智能指针时,必须指出智能指针的对象能够指向的类型。函数
blob.hpp文件注释:ui
#ifndef CAFFE_BLOB_HPP_ #define CAFFE_BLOB_HPP_ #include <algorithm> #include <string> #include <vector> #include "caffe/common.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/syncedmem.hpp" //const类型的整形kMaxBlobAxes定义了Blob最大的维度,Blob的通常维度是4,图像数量*图像通道*图像宽度*图像高度 const int kMaxBlobAxes = 32; namespace caffe { //Blob类也定义在caffe命名空间下 /** * @brief A wrapper around SyncedMemory holders serving as the basic * computational unit through which Layer%s, Net%s, and Solver%s * interact. * * TODO(dox): more thorough description. */ template <typename Dtype> //类模板 class Blob { public: Blob() //无参构造函数 : data_(), diff_(), count_(0), capacity_(0) {} //explicit关键字的做用是防止单参数构造函数的隐式转换, 对于含有多个未初始化值的构造函数无效 //shape是一个int型的向量,包含一个blob的维度,图像深度,高,宽信息 //这两个构造函数都会在内部调用Reshape函数,用来设置或者修改当前blob的shape_,count_和capacity_属性 /// @brief Deprecated; use <code>Blob(const vector<int>& shape)</code>. explicit Blob(const int num, const int channels, const int height, const int width); explicit Blob(const vector<int>& shape); /// @brief Deprecated; use <code>Reshape(const vector<int>& shape)</code>. //Reshape函数的做用是建立或调整blob的shape_,count_和capacity_属性 void Reshape(const int num, const int channels, const int height, const int width); /* * @brief Change the dimensions of the blob, allocating new memory if * necessary. *Reshape函数能够用来建立一个初始化的内存分配信息,也能够调整前向传播过程当中网络层的数据输出尺度 * This function can be called both to create an initial allocation * of memory, and to adjust the dimensions of a top blob during Layer::Reshape blob的大小改变后,只有在已分配的内存不够的状况下才会从新分配内存, 而且新增的内存将不会被释放 * or Layer::Forward.When changing the size of blob, memory will only be * reallocated if sufficient memory does not already exist, and excess memory * will never be freed. *须要注意的是直接改变输入blob的大小是错误的,它们应该在数据从低层向高层的传播中数据量增长的时候被调用 * Note that reshaping an input blob and immediately calling Net::Backward is * an error; either Net::Forward or Net::Reshape need to be called to * propagate the new input shape to higher layers. */ //经过类型为vector<int>类型的shape设置shape_,count_和capacity_ 的大小 void Reshape(const vector<int>& shape); //经过类型为BlobShape类对象shape设置shape_,count_和capacity_ 的大小 //BlobShape是在caffe.pb.h中定义的类,含有维度信息,继承自protobuf::Message void Reshape(const BlobShape& shape); //经过其余的blob对象类设置bolb的shape_,count_和capacity_ 的大小 void ReshapeLike(const Blob& other); //inline定义的是内联函数,做用是将代码直接复制到调用处,节省函数调用开销,代价是增长了代码量 //shape_string 函数用于获取bolb的打印信息(shape_和count_值) inline string shape_string() const { ostringstream stream; for (int i = 0; i < shape_.size(); ++i) { stream << shape_[i] << " "; } stream << "(" << count_ << ")"; return stream.str(); } //获取当前blob的shape_信息 inline const vector<int>& shape() const { return shape_; } /** * @brief Returns the dimension of the index-th axis (or the negative index-th * axis from the end, if index is negative). * * @param index the axis index, which may be negative as it will be * "canonicalized" using CanonicalAxisIndex. * Dies on out of range index. */ //获取当前指定blob指定索引的维度值 inline int shape(int index) const { return shape_[CanonicalAxisIndex(index)]; } //获取blob的维数 inline int num_axes() const { return shape_.size(); } //获取blob的元素个数 inline int count() const { return count_; } /** * @brief Compute the volume of a slice; i.e., the product of dimensions * among a range of axes. * * @param start_axis The first axis to include in the slice. * * @param end_axis The first axis to exclude from the slice. */ //根据指定的开始维度和结束维度计算blob元素的个数 inline int count(int start_axis, int end_axis) const { CHECK_LE(start_axis, end_axis); CHECK_GE(start_axis, 0); CHECK_GE(end_axis, 0); CHECK_LE(start_axis, num_axes()); CHECK_LE(end_axis, num_axes()); int count = 1; for (int i = start_axis; i < end_axis; ++i) { count *= shape(i); } return count; } /** * @brief Compute the volume of a slice spanning from a particular first * axis to the final axis. * * @param start_axis The first axis to include in the slice. */ //根据指定的开始维度计算剩下的blob元素个数,内部是经过调用上边定义的count函数实现的 inline int count(int start_axis) const { return count(start_axis, num_axes()); } /** * @brief Returns the 'canonical' version of a (usually) user-specified axis, * allowing for negative indexing (e.g., -1 for the last axis). * * @param axis_index the axis index. * If 0 <= index < num_axes(), return index. * If -num_axes <= index <= -1, return (num_axes() - (-index)), * e.g., the last axis index (num_axes() - 1) if index == -1, * the second to last if index == -2, etc. * Dies on out of range index. */ //CanonicalAxisIndex是用于对blob的axis_index进行转化,容许axis_index的值是负值,经过 //CanonicalAxisIndex函数内定义的规则,转换成正值 inline int CanonicalAxisIndex(int axis_index) const { CHECK_GE(axis_index, -num_axes()) << "axis " << axis_index << " out of range for " << num_axes() << "-D Blob with shape " << shape_string(); CHECK_LT(axis_index, num_axes()) << "axis " << axis_index << " out of range for " << num_axes() << "-D Blob with shape " << shape_string(); if (axis_index < 0) { return axis_index + num_axes(); } return axis_index; } //获取当前blob的维度,推荐直接使用shape(0)获取 /// @brief Deprecated legacy shape accessor num: use shape(0) instead. inline int num() const { return LegacyShape(0); } //获取当前blob的通道数(深度),推荐直接使用shape(1)获取 /// @brief Deprecated legacy shape accessor channels: use shape(1) instead. inline int channels() const { return LegacyShape(1); } //获取当前blob的图像高度信息,推荐直接使用shape(2)获取 /// @brief Deprecated legacy shape accessor height: use shape(2) instead. inline int height() const { return LegacyShape(2); } //获取当前blob的图像宽度信息,推荐直接使用shape(3)获取 /// @brief Deprecated legacy shape accessor width: use shape(3) instead. inline int width() const { return LegacyShape(3); } //获取某一维度index下的信息,index要求在[0,3]或[-4,-1]区间内,貌似是对shape函数的封装,只是增长了形参的断定 inline int LegacyShape(int index) const { CHECK_LE(num_axes(), 4) << "Cannot use legacy accessors on Blobs with > 4 axes."; CHECK_LT(index, 4); CHECK_GE(index, -4); if (index >= num_axes() || index < -num_axes()) { // Axis is out of range, but still in [0, 3] (or [-4, -1] for reverse // indexing) -- this special case simulates the one-padding used to fill // extraneous axes of legacy blobs. return 1; } return shape(index); } //经过blob的维度n,通道(图像深度)c,图像高度h和图像宽度w计算偏移量,由该偏移量能够 //惟必定位到bolb内的一张图像上的一个像素上 inline int offset(const int n, const int c = 0, const int h = 0, const int w = 0) const { CHECK_GE(n, 0); CHECK_LE(n, num()); CHECK_GE(channels(), 0); CHECK_LE(c, channels()); CHECK_GE(height(), 0); CHECK_LE(h, height()); CHECK_GE(width(), 0); CHECK_LE(w, width()); return ((n * channels() + c) * height() + h) * width() + w; } //根据vector<int>类型的indices计算偏移量 inline int offset(const vector<int>& indices) const { CHECK_LE(indices.size(), num_axes()); int offset = 0; for (int i = 0; i < num_axes(); ++i) { offset *= shape(i); if (indices.size() > i) { CHECK_GE(indices[i], 0); CHECK_LT(indices[i], shape(i)); offset += indices[i]; } } return offset; } /** * @brief Copy from a source Blob. * * @param source the Blob to copy from * @param copy_diff if false, copy the data; if true, copy the diff * @param reshape if false, require this Blob to be pre-shaped to the shape * of other (and die otherwise); if true, Reshape this Blob to other's * shape if necessary */ //复制外部的blob数据到本blob,根据状况拷贝data_数据仍是diff_数据,以及是否从新分配大小 void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false, bool reshape = false); //根据给定的维度,深度,宽高位置信息获取前向传播数据的一个元素的值 inline Dtype data_at(const int n, const int c, const int h, const int w) const { return cpu_data()[offset(n, c, h, w)]; } //根据给定的维度,深度,宽高位置信息获取反向传播梯度diff_的一个元素的值 inline Dtype diff_at(const int n, const int c, const int h, const int w) const { return cpu_diff()[offset(n, c, h, w)]; } //获取前向传播数据data_的指针 inline Dtype data_at(const vector<int>& index) const { return cpu_data()[offset(index)]; } //获取反向传播梯度diff_的指针 inline Dtype diff_at(const vector<int>& index) const { return cpu_diff()[offset(index)]; } //获取前向传播数据对象 inline const shared_ptr<SyncedMemory>& data() const { CHECK(data_); return data_; } //获取反向传播梯度对象 inline const shared_ptr<SyncedMemory>& diff() const { CHECK(diff_); return diff_; } const Dtype* cpu_data() const; //定义的获取cpu数据指针函数 void set_cpu_data(Dtype* data); //设置cpu数据 const int* gpu_shape() const; //返回GPU shape_数据指针 const Dtype* gpu_data() const; //返回GPU 数据指针 const Dtype* cpu_diff() const; //返回CPU上反向传播的梯度数据指针 const Dtype* gpu_diff() const; //返回GPU上反向传播的梯度数据指针 Dtype* mutable_cpu_data(); //如下加上mutable表明能够修改获取到的数据 Dtype* mutable_gpu_data(); Dtype* mutable_cpu_diff(); Dtype* mutable_gpu_diff(); //梯度降低过程当中训练参数更新 void Update(); //从BlobProto中导入数据到当前blob,完成数据解析(反序列化) void FromProto(const BlobProto& proto, bool reshape = true); //把blob数据导入BlobProto,完成数据序列化 void ToProto(BlobProto* proto, bool write_diff = false) const; //计算data_的L1范式:向量中各个元素绝对值之和 /// @brief Compute the sum of absolute values (L1 norm) of the data. Dtype asum_data() const; //计算diff_的L1范式:向量中各个元素绝对值之和 /// @brief Compute the sum of absolute values (L1 norm) of the diff. Dtype asum_diff() const; //计算data_的L2范式:向量中各个元素的平方和 /// @brief Compute the sum of squares (L2 norm squared) of the data. Dtype sumsq_data() const; //计算diff_的L2范式:向量中各个元素的平方和 /// @brief Compute the sum of squares (L2 norm squared) of the diff. Dtype sumsq_diff() const; //将data_数据乘以一个系数scale_factor /// @brief Scale the blob data by a constant factor. void scale_data(Dtype scale_factor); //将diff _数据乘以一个系数scale_factor /// @brief Scale the blob diff by a constant factor. void scale_diff(Dtype scale_factor); /** * @brief Set the data_ shared_ptr to point to the SyncedMemory holding the * data_ of Blob other -- useful in Layer%s which simply perform a copy * in their Forward pass. * * This deallocates the SyncedMemory holding this Blob's data_, as * shared_ptr calls its destructor when reset with the "=" operator. */ //将外部一个Blob对象的数据指针指向当前的blob的数据data_,从而实现数据共享 void ShareData(const Blob& other); /** * @brief Set the diff_ shared_ptr to point to the SyncedMemory holding the * diff_ of Blob other -- useful in Layer%s which simply perform a copy * in their Forward pass. * * This deallocates the SyncedMemory holding this Blob's diff_, as * shared_ptr calls its destructor when reset with the "=" operator. */ //将外部一个Blob对象的梯度指针指向当前的blob的数据diff_,从而实现数据共享 void ShareDiff(const Blob& other); //判断当前blob的shape_和BlobProto中的shape_是否相同 bool ShapeEquals(const BlobProto& other); protected: //后缀加上_表示是Blob的成员变量 shared_ptr<SyncedMemory> data_; //前向传播数据 shared_ptr<SyncedMemory> diff_; //反向传播梯度(误差)数据 shared_ptr<SyncedMemory> shape_data_; //blob的训练数据 vector<int> shape_; //blob的训练数据的组织维度 int count_; //blob中全部元素的个数,值为shape_中4个参数的乘积 int capacity_; //blob的容积量 //禁用Blob类的拷贝和赋值操做 DISABLE_COPY_AND_ASSIGN(Blob); }; // class Blob } // namespace caffe #endif // CAFFE_BLOB_HPP_