caffe源码解读之Blob

来源:互联网 发布:mac绘画录制软件 编辑:程序博客网 时间:2024/05/16 02:38

Blob:数据传输的媒介
Blob 主要用来表示网络中的数据,包括训练数据,网络各层自身的参数(包括权值、偏置以及它们的梯度),网络之间传递的数据都是通过 Blob 来实现的,同时 Blob 数据也支持在 CPU 与 GPU 上存储,能够在两者之间做同步。
Blob中的主要变量包括:

    shared_ptr<SyncedMemory> data_;//存储前向传播数据    shared_ptr<SyncedMemory> diff_;//存储反向传播数据    shared_ptr<SyncedMemory> shape_data_;//存储blob形状数据    vector<int> shape_;    int count_; //blob中元素个数    int capacity_;//当前元素个数,数据容量

BLob只是一个基本的数据结构,因此内部的变量相对较少,首先是data_指针,指针类型是shared_ptr,属于boost库的一个智能指针,这一部分主要用来申请内存存储data,data主要是正向传播的时候用的。同理,diff_主要用来存储偏差,update data,shape_data和shape_都是存储Blob的形状,一个是老版本一个是新版本。count表示Blob中的元素个数,也就是个数通道数高度*宽度, capacity表示当前的元素个数,因为Blob可能会reshape。

Blob中的主要函数包括:

1.构造函数:开辟内存空间存储数据

     Blob() //默认构造函数       : data_(), diff_(), count_(0), capacity_(0) {}    //explicit关键字的作用是禁止单参数构造函数的隐式转换     explicit Blob(const int num, const int channels,const int height,const int width);     explicit Blob(const vector<int>& shape);

2.reshape相关函数:在Layer中的reshape或者forward操作中来调整维度。

    //Reshape函数将num,channels,height,width传递给vector shape_     void Reshape(const int num, const int channels, const int height,const int width);    //根据shape来初始化shape_,以及为data_ 和diff_ 分配空间。    void Reshape(const vector<int>& shape);    void Reshape(const BlobShape& shape);    //用已知的Blob的shape来对shape_ 进行reshape     void ReshapeLike(const Blob& other);

当改变Blob大小时,如果内存大小不够了,内存将会重新分配,此时额外的内存将不会被释放。对input的blob进行reshape,如果立马调用Net::Backward是会出错的,因为reshape之后,要么Net::forward或者Net::Reshape就会被调用来将新的input shape传播到高层

3.shape相关函数:获取shape_的相关信息。

    inline const vector<int>& shape() const { return shape_; }    //获取index维的大小,返回某一维的尺寸    inline int shape(int index) const {    return shape_[CanonicalAxisIndex(index)];    }    //获取维的个数    inline int num_axes() const { return shape_.size(); }

4.count相关函数:统计Blob的容量(volume),或者是某一片(slice),从某个axis到具体某个axis的shape乘积。

    inline int count() const { return count_; }    //获取某几维数据的大小    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;    }    //获取某一维到结束数据的大小     inline int count(int start_axis) const {    return count(start_axis, num_axes());    }

5.CanonicalAxisIndex函数:Blob的Index是可以从负坐标开始读的,标准化索引,对参数索引进行标准化,以满足要求,转换坐标轴索引[-N,N]为[0,N];

    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;    }

6.4个基本变量num,channel,height,width的访问

     inline int num() const { return LegacyShape(0); }     inline int channels() const { return LegacyShape(1);}     inline int height() const { return LegacyShape(2); }     inline int width() const { return LegacyShape(3); }     //data_维数不大于4时才能使用,功能同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);// 检查维度索引是不是小于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);    }

7.计算offset

/*计算offset,offset计算的方式也支持两种方式,一种直接指定n,c,h,w或者放到一个vector中进行计算偏移量是根据对应的n,c,h,w,返回的offset是((n*channels() +c)*height()+h)*width()+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;    }    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;    }

8.CopyFrom函数:从一个blob中copy数据 ,通过开关控制是否copy_diff,如果是False则copy data。reshape控制是否需要reshape

void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false,bool reshape = false);

9.获取数据相关函数

     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)];      }      // 同步内存shared_ptr(不明白share_ptr的可以自行百度,引用计数管理机制),获取data_      inline const shared_ptr<SyncedMemory>& data() const {    CHECK(data_);    return data_;      }      //获取diff_      inline const shared_ptr<SyncedMemory>& diff() const {    CHECK(diff_);    return diff_;      }    /*这里有data和diff两类数据,而这个diff就是我们所熟知的偏差,前者主要存储前向传递的数据,而后者存储的是反向传播中的梯度*/    const Dtype* cpu_data() const;//只读获取data_ cpu指针     void set_cpu_data(Dtype* data);//设置data_的cpu指针,只是修改了指针    const int* gpu_shape() const;    const Dtype* gpu_data() const;//获取diff_的gpu指针    const Dtype* cpu_diff() const;    const Dtype* gpu_diff() const;    Dtype* mutable_cpu_data();//见SyncedMemory的mutable_cpu_data(),mutable是可读写访问    Dtype* mutable_gpu_data();    Dtype* mutable_cpu_diff();    Dtype* mutable_gpu_diff();

10.updata函数:更新data_的数据,减去diff_的数据,就是合并data和diff

    void Update();

11.序列化和反序列化函数

    //从proto序列化文件读取blob对象    void FromProto(const BlobProto& proto, bool reshape = true);    /*由BlobProto对Blob进行赋值操作。reshape代表是否允许修改shape_的大小。需要注意的是再这里有double和float两种类型的数据 ,将blob序列化为protobuf文件,在代码中可以看到具体的体现*/    void ToProto(BlobProto* proto, bool write_diff = false) const;

12.相关计算函数

    Dtype asum_data() const;//计算data的L1范数    Dtype asum_diff() const;//计算diff的L1范数    Dtype sumsq_data() const;//计算data的L2范数    Dtype sumsq_diff() const;//计算diff的L2范数    void scale_data(Dtype scale_factor);//将data部分乘以一个因子    void scale_diff(Dtype scale_factor);//将diff部分乘一个因子

13.共享函数

    /* 这两个函数看名字就知道了一个是共享data,一个是共享diff,具体就是将别的blob的data和响应的diff指针给这个Blob,实现数据的共享。同时需要注意的是这个操作会引起这个Blob里面的SyncedMemory被释放,因为shared_ptr指针被用 = 重置的时候回调用响应的析构器。*/    void ShareData(const Blob& other);    void ShareDiff(const Blob& other);

14.Blob形状比较函数

    //比较两个Blob形状是否相同    bool ShapeEquals(const BlobProto& other);