caffe源码导读(三)Blob.hpp头文件解析

caffe中的Blob.hpp头文件源码解析

#ifndef CAFFE_BLOB_HPP_
#define CAFFE_BLOB_HPP_

#include <algorithm>
#include <string>
#include <vector>

#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
// 由protoc生成的头文件,声明了BlobProto,BlobShape等 caffe.proto协议的数据结构
#include "caffe/syncedmem.hpp" //CPU/GPU共享内存,用于数据同步

const int kMaxBlobAxes = 32; //Blob最大维数目, Blob的一般维度是4, n*c*h*w

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) {}
  /// @brief Deprecated; use <code>Blob(const vector<int>& shape)</code>.
  // 关键字 explicit,这里表示不能通过隐式变换来调用这个函数,也就是避免隐式数据类型转换,注意只防止单参数
  // 构造函数的隐式转换,对含有多个未初始化的值的构造函数无效
  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>.
  // 变形函数,根据输入参数的形状重新设置当前Blob的形状,必要时,重新分配内存
  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.
   * 这个函数可以用用来创建一个初始化的内存分配信息,也可以调整前向传播过程中网络的数据输出尺度
   * 当blob的大小改变后,只有在已经分配的内存不够的情况下才会重新分配内存,并且新增的内存不会释放
   * 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.
   * 注意,直接改变输入的blob并立即调用反向传播是错误的, 他们需要前向传播或reshape时被调用,也就是
   * 从底层到高层
   * 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); // BlobShaoe是 caffe.pb.h中定义的,含有维度信息
  void ReshapeLike(const Blob& other); // 通过其他Blob对象设置
  // 得到Blob的形状字符串用于打印log,类似如 100 1 28 28 (78400)
  // inline关键字,内联函数,作用是将代码直接复制到调用处,节省函数调用开销,(快)
  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<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索引的维度值,比如shape(0) = n, shape(1) = c
  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中某几维子集的元素总数,意思就是根据指定的开始维度和结束维度计算blob元素的个数
  inline int count(int start_axis, int end_axis) const {
    CHECK_LE(start_axis, end_axis); // 保证start_axis <= end_axis
    CHECK_GE(start_axis, 0); // 保证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()); //调用上面的count函数
  }

  /**
   * @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的axix_index进行转化,允许axis_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;
  }

  /// @brief Deprecated legacy shape accessor num: use shape(0) instead.
  // 获取当前blob某一维度的尺寸,推荐直接使用 n,c,h,w 对应shape(0),shape(1)..
  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); }
  // 获取某一维度index下的信息,index要求在[0,3]或[-4,-1]区间内,
  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);
  }

  // 计算偏移量,根据 n c h w计算偏移量们可以唯一定位到blob内的一张图像的一张像素上
  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类型计算,vector里 存放着 nchw
  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) { // num_axes返回blob的维度数目
      offset *= shape(i); // shape(i)指的是当前i的维度值,比如shape(0) = n, shape(1) = c
      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)];
  }
  // 根据指定位置信息,获取反向传播梯度的一个元素的值
  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)];
  }

  // 如果参数是vector形式,获取值,和以上的是一样的,只不过将nchw放入到了vector里
  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)];
  }

  // 获取前向传播的数据对象
  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数据指针,只读访问cpu_data
  void set_cpu_data(Dtype* data); // 设置cpu_data
  const int* gpu_shape() const; // 返回gpu shape_数据指针
  const Dtype* gpu_data() const; // 返回gpu_data的指针,只读访问
  void set_gpu_data(Dtype* data); //设置gpu_data
  const Dtype* cpu_diff() const; //获取diff的数据指针,只读访问
  const Dtype* gpu_diff() const; // 获取gpu_diff数据指针,只读访问
  Dtype* mutable_cpu_data(); //加上mutable表示可以修改获取到的数据,即读写访问
  Dtype* mutable_gpu_data();
  Dtype* mutable_cpu_diff();
  Dtype* mutable_gpu_diff();
  void Update(); // blob更新计算,即梯度下降过程中训练参数的更新
  //序列化函数,从blobProto中导入数据到当前的blob,完成数据解析
  void FromProto(const BlobProto& proto, bool reshape = true);
  //序列化函数,将blob数据,导入blobProto
  void ToProto(BlobProto* proto, bool write_diff = false) const;

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

  /// @brief Scale the blob data by a constant factor.
  void scale_data(Dtype scale_factor);// 将data_ 数据乘以一个系数 scale_factor
  /// @brief Scale the blob diff by a constant factor.
  void scale_diff(Dtype scale_factor); // 将diff_ 数据乘以一个系数 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.
   */
  void ShareDiff(const Blob& other);

  bool ShapeEquals(const BlobProto& other);//判断当前blob的shape_和blobProto中的shape_是否相同

 protected: // 后缀加上_表示blob的成员变量
  shared_ptr<SyncedMemory> data_; //前向传播数据,指针
  shared_ptr<SyncedMemory> diff_; //反向传播梯度数据,指针
  shared_ptr<SyncedMemory> shape_data_; // blob的训练数据
  vector<int> shape_; // blob训练数据的维度
  int count_; //blob中所有元素的个数,值为shaoe_中四个参数的乘积
  int capacity_; //blob的容积量

  DISABLE_COPY_AND_ASSIGN(Blob); //禁止拷贝构造函数,赋值 运算符重载
};  // class Blob

}  // namespace caffe

#endif  // CAFFE_BLOB_HPP_

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值