博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Caffe源码中blob文件分析
阅读量:2111 次
发布时间:2019-04-29

本文共 17744 字,大约阅读时间需要 59 分钟。

Caffe源码(caffe version commit: 09868ac , date: 2015.08.15)中有一些重要的头文件,这里介绍下include/caffe/blob.hpp文件的内容:

1.      Include文件:

(1)、<caffe/common.hpp>:此文件的介绍可以参考:

(2)、<caffe/proto/caffe.pb.h>:此文件的介绍可以参考:

(3)、<caffe/syncedmem.hpp>:此文件的介绍可以参考:

(4)、<caffe/util/math_functinons.hpp>:此文件的介绍可以参考:

2.        全局常量kMaxBlobAxes:

由const声明的全局常量kMaxBlobAxes表示Blob可以支持的最高维数,目前设置的支持的最高维数为32。

3.        类Blob:

Blob是Caffe中处理和传递实际数据的数据封装包,并且在CPU与GPU之间具有数据同步处理能力。从数学意义上说,blob是按C风格连续存储的N维数组,即在内部所存储的数据是一块连续的内存。

Blob是用来存储图像数据、网络参数(包括权值、偏置以及它们的梯度)、模型参数、学习到的参数、网络传输过程中产生的数据、网络中间的处理结果、优化过程的偏导数等各种数据。

Blob可以动态改变数组的尺寸,当拓展数组导致原有内存空间不足以存放下数据时(count_>capacity_),就会通过Reshape函数实现重新确定空间大小。

Blob数据可以通过Protobuf来做相应的序列化操作,ToProto和FromProto两个函数完成相应的序列化、反序列化(数据解析)操作。

Caffe基于blobs存储和交换数据。网络各层之间的数据都是通过Blob来传递的。为了便于优化,blobs提供统一的内存接口来存储某种类型的数据,例如批量图像数据、模型参数以及用来进行优化的导数。

blobs可根据CPU主机与GPU设备的同步需要,屏蔽CPU/GPU混合运算在计算上的开销。主机和设备上的内存按需分配,以提高内存的使用效率。

对于批量图像数据来说,blob常规的维数为图像数量N*通道数K*图像高度H*图像宽度W。blob按行为主(row-major)进行存储,所以一个4维blob中,坐标为(n,k,h,w)的值的物理位置为((n*K+k)*H+h)*W+w,这也使得最后面/最右边的维度更新最快,其中:

(1)、Number/N是每个批次处理的数据量。批量处理信息有利于提供设备处理和交换的数据的吞吐率。在ImageNet上每个训练批量为256张图像,则N=256;

(2)、Channel/K是特征维度,例如对RGB图像来说,可以理解为通道数量,K=3;如果是网络中间结果,就是feature map的数量;

(3)、H、W:如果是图像数据,可以理解为图像的高度和宽度;如果是参数数据,可以理解为滤波核的高度和宽度。

虽然Caffe的图像应用例子中很多blobs都是4维坐标,但是对于非图像应用任务,blobs也完全可以照常使用。

参数Blob的维度是根据层的类型和配置而变化的。

对于blob中的数据,我们关心的是values(值)和gradients(梯度),所以一个blob单元存储了两块数据------data_和diff_。前者是我们在网络中传送的普通数据,后者是通过网络计算得到的梯度。而且,由于数据既可存储在CPU上,又可存储在GPU上,因而有两种数据访问方式,如在CPU上的data_:静态方式,不改变数值(const Dtype* cpu_data() const;);动态方式,改变数值(Dtype*mutable_cpu_data();)。GPU和diff_的操作与在CPU上的data_类似。

之所以这么设计是因为blob使用了一个SyncedMemory类来同步CPU和GPU上的数据,以隐藏同步的细节和最小化传送数据。一个经验准则是,如果不想改变数据,就一直使用常量调用,而且决不要在自定义类中存储指针。每次操作blob时,调用相应的函数来获取它的指针,因为SyncedMemory需要用这种方式来确定何时需要复制数据。

实际上,使用GPU时,Caffe中CPU代码先从磁盘中加载数据到blob,同时请求分配一个GPU设备核(devicekernel)以使用GPU进行计算,再将计算好的blob数据送入下一层,这样既实现了高效运算,又忽略了底层细节。只要所有layers均有GPU实现,这种情况下所有的中间数据和梯度都会保留在GPU 上。

注:以上关于Blob内容的介绍主要摘自由CaffeCN社区翻译的《Caffe官方教程中译本》。

<caffe/blob.hpp>文件的详细介绍如下:

#ifndef CAFFE_BLOB_HPP_#define CAFFE_BLOB_HPP_#include 
#include
#include
#include "caffe/common.hpp"#include "caffe/proto/caffe.pb.h"#include "caffe/syncedmem.hpp"#include "caffe/util/math_functions.hpp"// 全局常量,用来表示Blob可以支持的最高维数const int kMaxBlobAxes = 32;namespace 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
class Blob { public:// 默认不带参数的构造函数,初始化count_=0,capacity_=0 Blob() : data_(), diff_(), count_(0), capacity_(0) {} /// @brief Deprecated; use
Blob(const vector
& shape)
.// 带参数的显示构造函数,推荐使用带vector
参数的构造函数// 这两个构造函数内部会均会调用Reshape(const vector
)函数// 注:执行这两个构造函数后,并不会真正分配内存空间,只是用来设置当前blob的shape_、count_和capacity_大小 explicit Blob(const int num, const int channels, const int height, const int width); explicit Blob(const vector
& shape); /// @brief Deprecated; use
Reshape(const vector
& shape)
.// Reshape系列函数通过输入参数用来设置或重新设置当前blob的shape_、count_和capacity_大小// 推荐使用带vector
参数的Reshape函数// 内部会调用SyncedMemory的构造函数,但不会真正分配内存空间// 通过num/channes/height/width参数设置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. * * 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 * 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. * * 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
参数设置shape_、count_和capacity_大小 void Reshape(const vector
& shape);// 通过类BlobShape参数设置shape_、count_和capacity_大小// BlobShape是定义在caffe.proto中的一个message,其字段有dim void Reshape(const BlobShape& shape);// 通过外部的blob参数来设置shape_、count_和capacity_大小 void ReshapeLike(const Blob& other);// 以string类型获得当前blob的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的所有维度值 inline const vector
& 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. */// 根据指定的start axis和end axis(部分blob)计算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. */// 根据指定的start axis(部分blob)计算blob元素个数 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 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. */// Blob的index可以是负值,对参数axis_index进行判断,结果返回一个正的索引值// 如果axis_index是负值,则要求axis_index>=-shape_.size(),则返回axis_index+shape_.size()// 如果axis_index是正值,则要求axis_index
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); }// 根据num、channels、height、width计算偏移量:((n*K+k)*H+h)*W+w 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
index计算偏移量:((n*K+k)*H+h)*W+w inline int offset(const vector
& 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// 若reshape参数为true,如果两边blob的reshape不相同,则会重新reshape// 若copy_diff为false,则拷贝data_数据;若copy_diff为true,则拷贝diff_数据 void CopyFrom(const Blob
& source, bool copy_diff = false, bool reshape = false);// 根据给定的位置访问数据// 根据指定的偏移量获得前向传播数据data_的一个元素的值 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
& index) const { return cpu_data()[offset(index)]; }// 根据指定的偏移量获得反向传播梯度diff_的一个元素的值 inline Dtype diff_at(const vector
& index) const { return cpu_diff()[offset(index)]; }// 获得前向传播数据data_的指针 inline const shared_ptr
& data() const { CHECK(data_); return data_; }// 获得反向传播梯度diff_的指针 inline const shared_ptr
& diff() const { CHECK(diff_); return diff_; }// Blob的数据访问函数,包括CPU和GPU// 带mutable_前缀的函数是可以对Blob数据进行改写的;其它不带的是只读的,不允许改写数据 const Dtype* cpu_data() const; // 调用SyncedMemory::cpu_data()函数 const Dtype* gpu_data() const; // 调用SyncedMemory::gpu_data()函数 const Dtype* cpu_diff() const; // 调用SyncedMemory::cpu_data()函数 const Dtype* gpu_diff() const; // 调用SyncedMemory::gpu_data()函数 Dtype* mutable_cpu_data(); // 调用SyncedMemory::mutable_cpu_data()函数 Dtype* mutable_gpu_data(); // 调用SyncedMemory::mutable_gpu_data()函数 Dtype* mutable_cpu_diff(); // 调用SyncedMemory::mutable_cpu_data()函数 Dtype* mutable_gpu_diff(); // 调用SyncedMemory::mutable_gpu_data()函数 void set_cpu_data(Dtype* data); // 调用SyncedMemory::set_cpu_data(void*)函数// 它会被网络中存储参数的Blob调用,完成梯度下降过程中的参数更新// 调用caffe_axpy函数重新计算data_(weight,bias 等减去对应的导数): data_ = -1 * diff_ + data_ void Update();// Blob的数据持久化函数,通过Protobuf来做相应的序列化/反序列化操作// BlobProto是定义在caffe.proto中的一个message,其字段有shape(BlobShape)、data、diff、num、channels、height、width// 将BlobProto的shape/data/diff分别copy给当前blob的shape_/data_/diff_完成数据解析(反序列化)// 若reshape参数为true,则会对当前的blob重新进行reshape void FromProto(const BlobProto& proto, bool reshape = true);// 将Blob的shape_/data_/diff_(如果write_diff为true)分别copy给BlobProto的shape/data/diff完成序列化 void ToProto(BlobProto* proto, bool write_diff = false) const; /// @brief Compute the sum of absolute values (L1 norm) of the data.// 计算data_的L1范式:向量中各个元素绝对值之和 Dtype asum_data() const; /// @brief Compute the sum of absolute values (L1 norm) of the diff.// 计算diff_的L1范式:向量中各个元素绝对值之和 Dtype asum_diff() const; /// @brief Compute the sum of squares (L2 norm squared) of the data.// 计算data_的L2范式平方:向量中各元素的平方和 Dtype sumsq_data() const; /// @brief Compute the sum of squares (L2 norm squared) of the diff.// // 计算diff_的L2范式平方:向量中各元素的平方和 Dtype sumsq_diff() const; /// @brief Scale the blob data by a constant factor.// 将data_数据乘以一个因子:X = alpha*X void scale_data(Dtype scale_factor); /// @brief Scale the blob diff by a constant factor.// 将diff_数据乘以一个因子:X = alpha*X 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的data_指针指向给当前blob的data_,以实现共享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的diff_指针指向给当前blob的diff_,以实现共享diff_ void ShareDiff(const Blob& other);// 比较两个blob的shape是否相同// BlobProto是定义在caffe.proto中的一个message,其字段有shape(BlobShape)、data、diff、num、channels、height、width bool ShapeEquals(const BlobProto& other); protected:// Caffe中类的成员变量名都带有后缀"_",这样就容易区分临时变量和类成员变量 shared_ptr
data_; // 存储前向传播的数据 shared_ptr
diff_; // 存储反向传播的导数、梯度、偏差 vector
shape_; // Blob的维度值,通过Reshape函数的shape参数获得相应值,若为4维,则依次为num、channels、height、width int count_; // 表示Blob中的元素个数,shape_所有元素的乘积 int capacity_; // 表示当前Blob的元素个数(控制动态分配),因为Blob可能会reshape// 禁止使用Blob类的拷贝和赋值操作 DISABLE_COPY_AND_ASSIGN(Blob);}; // class Blob} // namespace caffe#endif // CAFFE_BLOB_HPP_
在caffe.proto文件中,有3个message是与blob有关的,如下:

// 可选package声明符,用来防止不同的消息类型有命名冲突package caffe; // 以下所有生成的信息将会在命名空间caffe内: namespace caffe { ... }// 说明:带"deprecated"关键字的信息可以不用看,过时的,后面有可能是被废弃的// 以下三个是关于blob的三个类:BlobShape、BlobProto、BlobProtoVector// Specifies the shape (dimensions) of a Blob.message BlobShape { // 数据块形状(Blob的维度),若为4维,则为num、channel、height、width  repeated int64 dim = 1 [packed = true]; // blob shape数组}message BlobProto { // blob属性类  optional BlobShape shape = 7; // BlobShappe类对象  repeated float data = 5 [packed = true]; // float类型的data,前向  repeated float diff = 6 [packed = true]; // float类型的diff,后向  repeated double double_data = 8 [packed = true]; // double类型的data,前向  repeated double double_diff = 9 [packed = true]; // double类型的diff,后向  // 4D dimensions -- deprecated.  Use "shape" instead.  // 已使用BlobShape shape替代  optional int32 num = 1 [default = 0];  optional int32 channels = 2 [default = 0];  optional int32 height = 3 [default = 0];  optional int32 width = 4 [default = 0];}// The BlobProtoVector is simply a way to pass multiple blobproto instances// around.message BlobProtoVector { // 存放多个BlobProto实例  repeated BlobProto blobs = 1;}
blob的测试代码如下:

#include "funset.hpp"#include 
#include
#include "common.hpp"int test_caffe_blob(){ caffe::Blob
blob1; std::vector
shape{ 2, 3, 4, 5 }; caffe::Blob
blob2(shape); std::vector
blob_shape = blob2.shape(); fprintf(stderr, "blob shape: "); for (auto index : blob_shape) { fprintf(stderr, "%d ", index); } std::vector
shape_{ 6, 7, 8, 9 }; blob2.Reshape(shape_); std::vector
blob_shape_ = blob2.shape(); fprintf(stderr, "\nnew blob shape: "); for (auto index : blob_shape_) { fprintf(stderr, "%d ", index); } fprintf(stderr, "\n"); int value = blob2.shape(-1); fprintf(stdout, "blob index -1: %d\n", value); int num_axes = blob2.num_axes(); fprintf(stderr, "blob num axes(dimension): %d\n", num_axes); int count = blob2.count(); fprintf(stderr, "blob count sum: %d\n", count); count = blob2.count(2, 4); fprintf(stderr, "blob count(start_axis(2), end_axis(4)): %d\n", count); count = blob2.count(1); fprintf(stderr, "blob count(start_axis(1)): %d\n", count); int canonical_axis_index = blob2.CanonicalAxisIndex(-2); fprintf(stderr, "blob canonical axis index: %d\n", canonical_axis_index); int num = blob2.num(); int channels = blob2.channels(); int height = blob2.height(); int width = blob2.width(); int legacy_shape = blob2.LegacyShape(-2); fprintf(stderr, "blob num: %d, channels: %d, height: %d, width: %d, legacy shape(-2): %d\n", num, channels, height, width, legacy_shape); std::vector
indices{ 2, 3, 7, 6 }; int offset1 = blob2.offset(indices); int offset2 = blob2.offset(indices[0], indices[1], indices[2], indices[3]); fprintf(stderr, "blob offset1: %d, offset2: %d\n", offset1, offset2); std::string shape_string = blob2.shape_string(); fprintf(stderr, "shape string: %s\n", shape_string.c_str()); caffe::BlobProto blob_proto; blob_proto.set_num(6); blob_proto.set_channels(7); blob_proto.set_height(8); blob_proto.set_width(9); bool flag = blob2.ShapeEquals(blob_proto); fprintf(stderr, "blob2's shape and blob_proto's shape are equal: %d\n", flag); int blob_proto_data_size_float = blob_proto.data_size(); int blob_proto_data_size_double = blob_proto.double_data_size(); int blob_proto_diff_size_float = blob_proto.diff_size(); int blob_proto_diff_size_double = blob_proto.double_diff_size(); fprintf(stderr, "blob_proto data/diff size: %d, %d, %d, %d\n", blob_proto_data_size_float, blob_proto_data_size_double, blob_proto_diff_size_float, blob_proto_diff_size_double); caffe::BlobShape blob_proto_shape; for (int i = 0; i < 4; ++i) { blob_proto_shape.add_dim(i + 10); } blob2.Reshape(blob_proto_shape); blob_shape_ = blob2.shape(); fprintf(stderr, "new blob shape: "); for (auto index : blob_shape_) { fprintf(stderr, "%d ", index); } fprintf(stderr, "\n"); fprintf(stderr, "blob proto shape: "); for (int i = 0; i < blob_proto_shape.dim_size(); ++i) { fprintf(stderr, "%d ", blob_proto_shape.dim(i)); } fprintf(stderr, "\n"); // 注:以上进行的所有操作均不会申请分配任何内存 // cv::Mat -> Blob std::string image_name = "E:/GitCode/Caffe_Test/test_data/images/a.jpg"; cv::Mat mat = cv::imread(image_name, 1); if (!mat.data) { fprintf(stderr, "read image fail: %s\n", image_name.c_str()); return -1; } cv::Mat mat2; mat.convertTo(mat2, CV_32FC3); std::vector
mat_reshape{ 1, mat2.channels(), mat2.rows, mat2.cols }; blob2.Reshape(mat_reshape); float sum1 = blob2.asum_data(); blob2.set_cpu_data((float*)mat2.data); float sum2 = blob2.asum_data(); blob2.scale_data(0.5); float sum3 = blob2.asum_data(); float sum4 = blob2.sumsq_data(); fprintf(stderr, "sum1: %f, sum2: %f, sum3: %f, sum4: %f\n", sum1, sum2, sum3, sum4); float value2 = blob2.data_at(0, 2, 100, 200); fprintf(stderr, "data at value: %f\n", value2); const float* data = blob2.cpu_data(); fprintf(stderr, "data at 0: %f\n", data[0]); cv::Mat mat3; mat2.convertTo(mat3, CV_8UC3); image_name = "E:/GitCode/Caffe_Test/test_data/images/a_ret.jpg"; cv::imwrite(image_name, mat3); return 0;}
测试结果如下:

GitHub

你可能感兴趣的文章
Leetcode C++《每日一题》20200626 338. 比特位计数
查看>>
Leetcode C++ 《拓扑排序-1》20200626 207.课程表
查看>>
Go语言学习Part1:包、变量和函数
查看>>
Go语言学习Part2:流程控制语句:for、if、else、switch 和 defer
查看>>
Go语言学习Part3:struct、slice和映射
查看>>
Go语言学习Part4-1:方法和接口
查看>>
Leetcode Go 《精选TOP面试题》20200628 69.x的平方根
查看>>
Leetcode C++ 剑指 Offer 09. 用两个栈实现队列
查看>>
Leetcode C++《每日一题》20200707 112. 路径总和
查看>>
云原生 第十一章 应用健康
查看>>
Leetcode C++ 《第202场周赛》
查看>>
云原生 第十二章 可观测性:监控与日志
查看>>
Leetcode C++ 《第203场周赛》
查看>>
云原生 第十三章 Kubernetes网络概念及策略控制
查看>>
《redis设计与实现》 第一部分:数据结构与对象 || 读书笔记
查看>>
《redis设计与实现》 第二部分(第9-11章):单机数据库的实现
查看>>
算法工程师 面经2019年5月
查看>>
搜索架构师 一面面经2019年6月
查看>>
稻草人手记
查看>>
第一次kaggle比赛 回顾篇
查看>>