Caffe源码解读1 —— Blob

Caffe源码解读 1 —— Blob

我们首先看Blob这个类,Blob是作为caffe中处理和传递数据的数据封装包,也可以看成是一个N维数组。

1 主要变量

shared_ptr<SyncedMemory> data_; //正向传播使用的数据
shared_ptr<SyncedMemory> diff_; //反向传播的梯度数据
shared_ptr<SyncedMemory> shape_data_;   //Blob的形状
vector<int> shape_;                    //Blob的形状
int count_;                //图像个数*通道数*高度*宽度
int capacity_;             //当前元素个数

其中 shared_ptr 是 boost 库中的智能指针。其他的变量很好理解,其中 count_ 表示元素的总个数,也就是图像个数 * 通道数 * 高度 * 宽度。而 capacity_ 则表示当前元素的个数,也就是说当前 Blob的容纳量,如果count_ > capacity_ ,则Blob要进行reshape。

2 主要函数

 Blob()
 : data_(), diff_(), count_(0), capacity_(0) {}

/// @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);

这三个函数很简单为Blob的构造函数。对于图像数据来说,Blob常规的维数为图像数量num、通道数 channels 、图像高度 height、图像宽度 width。我们也可以用vector < int > 来初始化Blob。

/// @brief Deprecated; use <code>Reshape(const vector<int>& shape)</code>.
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.
*/
void Reshape(const vector<int>& shape);
void Reshape(const BlobShape& shape);

Blob既然是caffe处理数据的基本单元,那么Blob中必定少不了为他分配内存的函数,而reshape函数就实现了分配内存大小的功能。

/**
 * @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中的4个基本变量num,channel,height,width可以直接通过shape(0),shape(1),shape(2),shape(3)来访问。
*/
inline int shape(int index) const {
   return shape_[CanonicalAxisIndex(index)];
}

/**
 * @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.
 */
/**
* 返回 'canonical'版本的axis,允许索引位负值
* 索引 >= 0  则表示从前往后数index个数
* 索引 <  0  则表示从后往前数index个数
*/
  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;
  }

shape函数的作用就是返回Blob中指定维度的大小。其中axis表示Blob的维度。全局变量中定义了最大维度是32。一般正常我们处理图像使用4维就够了,但在caffe里面可以最多使用32维,这使得我们可以处理的数据不局限于图像。
CanonicalAxisIndex函数在检查index的合法性的前提下,允许我们使用负的索引值,其中正索引为从先向后索引,负的为从后向前索引。

 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.
 */
 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.
  */
  inline int count(int start_axis) const {
    return count(start_axis, num_axes());
  }

Blob中有很多count函数,这些函数是为了计算Blob的volume,或者slice,或者从某个axis到某个axis的乘积。

 ///Blob中的4个基本变量num,channel,height,width
 /// @brief Deprecated legacy shape accessor num: use shape(0) instead.
  inline int num() const { return LegacyShape(0); }
 /// @brief Deprecated legacy shape accessor channels: use shape(1) instead.
  inline int channels() const { return LegacyShape(1); }
 /// @brief Deprecated legacy shape accessor height: use shape(2) instead.
  inline int height() const { return LegacyShape(2); }
 /// @brief Deprecated legacy shape accessor width: use shape(3) instead.
  inline int width() const { return LegacyShape(3); }
  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);
  }

上面几个函数是为了分别得到num,channel,height,width这几个基本量。

///获取第n张图第c个通道高为h宽为w的偏移量
///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;
  }

offset函数为了获得第n张图第c个通道高为h宽为w的偏移量,以便于得到指定位置的数据。

///获取第n张图第c个通道高为h宽为w的数据
  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)];
  }
  ///获取第n张图第c个通道高为h宽为w的梯度
  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)];
  }

  inline Dtype data_at(const vector<int>& index) const {
    return cpu_data()[offset(index)];
  }

  inline Dtype diff_at(const vector<int>& index) const {
    return cpu_diff()[offset(index)];
  }

这几个函数就是利用offset函数算出的偏移量来得到Blob中的数据或者梯度

  /**
   * @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
   */
  void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false,
      bool reshape = false);

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

  const Dtype* cpu_data() const;
  void set_cpu_data(Dtype* data);
  const int* gpu_shape() const;
  const Dtype* gpu_data() const;
  const Dtype* cpu_diff() const;
  const Dtype* gpu_diff() const;
  Dtype* mutable_cpu_data();
  Dtype* mutable_gpu_data();
  Dtype* mutable_cpu_diff();
  Dtype* mutable_gpu_diff();

这几个函数看名字就知道是干什么用的了,其中带mutable的函数返回的是可以修改其内容的数据。

template <typename Dtype>
void Blob<Dtype>::Update() {
  // We will perform update based on where the data is located.
  switch (data_->head()) {
  case SyncedMemory::HEAD_AT_CPU:
    // perform computation on CPU
    caffe_axpy<Dtype>(count_, Dtype(-1),
        static_cast<const Dtype*>(diff_->cpu_data()),
        static_cast<Dtype*>(data_->mutable_cpu_data()));
    break;
  case SyncedMemory::HEAD_AT_GPU:
  case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
    // perform computation on GPU
    caffe_gpu_axpy<Dtype>(count_, Dtype(-1),
        static_cast<const Dtype*>(diff_->gpu_data()),
        static_cast<Dtype*>(data_->mutable_gpu_data()));
#else
    NO_GPU;
#endif
    break;
  default:
    LOG(FATAL) << "Syncedmem not initialized.";
  }
}

我们可以看到这个函数里面调用了

void caffe_axpy(const int N, const Dtype alpha, const Dtype* X,
    Dtype* Y);

功能上实现了data - diff

  void FromProto(const BlobProto& proto, bool reshape = true);      //从proto里面读取数据
  void ToProto(BlobProto* proto, bool write_diff = false) const;    //把数据存入proto里面

Caffe中,数据的读取、运算、存储都是采用Google Protocol Buffer来进行的。这两个函数实现了数据的储存和读取。

/// @brief Compute the sum of absolute values (L1 norm) of the data.
  Dtype asum_data() const;      计算data的L1范数
/// @brief Compute the sum of absolute values (L1 norm) of the diff.
  Dtype asum_diff() const;      计算diff的L1范数
/// @brief Compute the sum of squares (L2 norm squared) of the data.
  Dtype sumsq_data() const;     //计算data的L2范数
/// @brief Compute the sum of squares (L2 norm squared) of the diff.
  Dtype sumsq_diff() const;     //计算diff的L2范数

/// @brief Scale the blob data by a constant factor.
  void scale_data(Dtype scale_factor);          //将data部分乘以一个因子
/// @brief Scale the blob diff by a constant factor.
  void scale_diff(Dtype scale_factor);          //将diff部分乘一个因子

/**
 * @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.
 */
void ShareData(const Blob& other);     //data数据的共享
 /**
 * @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.
 */
  void ShareDiff(const Blob& other);       //diff数据共享

以上函数都很简单,注释都写得很清楚了,值得注意的是,当使用sharedata或sharediff函数时,会引起调用这个函数的Blob里面的SyncedMemory被释放。

以上涵盖了几乎所有的Blob函数,如有错误,欢迎指出 ^ - ^。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值