Caffe源码-Blob类
Blob类简介
Blob是caffe中的数据传递的一个基本类,网络各层的输入输出数据以及网络层中的可学习参数(learnable parameters,如卷积层的权重和偏置参数)都是Blob类型。Blob内部包含SyncedMemory类型的 data_ (数据,用于前向计算)和 diff_ (梯度,用于反向传播),以及表示数据形状的 shape_data_ (旧版本)和 shape_ (新版本)。Blob中还有表示有效数据的个数的变量 count_ 和表示当前数据的最大容量的变量 capacity_ 。剩余的为一些用于访问、修改data_或diff_数据的值、形状的一些函数。
blob.cpp源码
//调整blob中数据的形状,与openv中的Mat::Reshape()一样,只修改与数据的形状相关的变量,没有拷贝数据的操作
template <typename Dtype>
void Blob<Dtype>::Reshape(const int num, const int channels, const int height,
const int width) {
vector<int> shape(4);
shape[0] = num;
shape[1] = channels;
shape[2] = height;
shape[3] = width; //设置n,c,h,w
Reshape(shape);
}
//修改blob数据的形状,但不会改变data_中的值(除非重新创建)
template <typename Dtype>
void Blob<Dtype>::Reshape(const vector<int>& shape) {
CHECK_LE(shape.size(), kMaxBlobAxes); //检查shape的维度不能超过kMaxBlobAxes
count_ = 1; //新的总大小,count_ = shape[0] * shape[1] * ... * shape[shape.size() - 1]
shape_.resize(shape.size()); //修改shape_变量的大小
if (!shape_data_ || shape_data_->size() < shape.size() * sizeof(int)) { //shape_data_不为空,且大小比新的小
shape_data_.reset(new SyncedMemory(shape.size() * sizeof(int))); //shape_ptr::reset,清除之前的数据指针,重新申请
}
int* shape_data = static_cast<int*>(shape_data_->mutable_cpu_data()); //shape_data_的数据指针
for (int i = 0; i < shape.size(); ++i) {
CHECK_GE(shape[i], 0); //检查 shape[i] >= 0 (注意,reshape()允许shape[i]为0)
if (count_ != 0) { //检查数据的总体大小是否可能会超出INT_MAX(int类型的最大值)
CHECK_LE(shape[i], INT_MAX / count_) << "blob size exceeds INT_MAX";
}
count_ *= shape[i]; //新shape的各个维度之积
shape_[i] = shape[i]; //设置shape_(新版本使用)和shape_data_(旧版本使用)中的值
shape_data[i] = shape[i];
}
if (count_ > capacity_) { //如果新的形状的总大小超出之前容纳范围,则创建新的SyncedMemory对象
capacity_ = count_; //设置为新的
data_.reset(new SyncedMemory(capacity_ * sizeof(Dtype))); //此处只是创建了SyncedMemory对象,但是并未真正的分配内存或显存
diff_.reset(new SyncedMemory(capacity_ * sizeof(Dtype))); //在第一次访问内部的数据的时候才会分配(参见SyncedMemory.cpp)
}
}
//根据shape的值修改blob中数据的形状 //BlobShape定义在caffe.pb.h文件中,caffe.pb.h和caffe.pb.cc由caffe.proto生成
template <typename Dtype>
void Blob<Dtype>::Reshape(const BlobShape& shape) {
CHECK_LE(shape.dim_size(), kMaxBlobAxes); //同样检查维度数不能超过kMaxBlobAxes
vector<int> shape_vec(shape.dim_size());
for (int i = 0; i < shape.dim_size(); ++i) {
shape_vec[i] = shape.dim(i); //设置
}
Reshape(shape_vec);
}
//调整当前blob的形状,使其与other的数据的形状一致
template <typename Dtype>
void Blob<Dtype>::ReshapeLike(const Blob<Dtype>& other) {
Reshape(other.shape());
}
//blob的构造函数,创建对应形状的blob数据
template <typename Dtype>
Blob<Dtype>::Blob(const int num, const int channels, const int height,
const int width)
// capacity_ must be initialized before calling Reshape
: capacity_(0) { //初始必须先将容量capacity_设置为0,保证reshape时一定会给data_和diff_创建新的SyncedMemory对象
Reshape(num, channels, height, width);
}
template <typename Dtype>
Blob<Dtype>::Blob(const vector<int>& shape) //blob的构造函数
// capacity_ must be initialized before calling Reshape
: capacity_(0) {
Reshape(shape);
}
template <typename Dtype>
const int* Blob<Dtype>::gpu_shape() const { //返回blob中gpu数据的形状
CHECK(shape_data_);
return (const int*)shape_data_->gpu_data();
}
template <typename Dtype>
const Dtype* Blob<Dtype>::cpu_data() const { //返回blob中数据在cpu上的指针
CHECK(data_);
return (const Dtype*)data_->cpu_data();
}
template <typename Dtype>
void Blob<Dtype>::set_cpu_data(Dtype* data) { //修改blob中数据在cpu上的指针
CHECK(data);
// Make sure CPU and GPU sizes remain equal
size_t size = count_ * sizeof(Dtype); //当前blob中的数据的大小
if (data_->size() != size) { //data_->size()/sizeof(Dtype)即为capacity_,与count_不一定相等
data_.reset(new SyncedMemory(size)); //创建新的SyncedMemory对象,data_和diff_中cpu和gpu数据大小一致
diff_.reset(new SyncedMemory(size));
}
data_->set_cpu_data(data); //调用SyncedMemory类中的set_cpu_data(),设置cpu数据的指针和数据的状态HEAD_AT_CPU等
}
template <typename Dtype>
const Dtype* Blob<Dtype>::gpu_data() const { //返回blob中数据在gpu上的指针
CHECK(data_);
return (const Dtype*)data_->gpu_data();
}
template <typename Dtype>
void Blob<Dtype>::set_gpu_data(Dtype* data) { //修改blob中数据在gpu上的指针,与set_cpu_data操作类似
CHECK(data);
// Make sure CPU and GPU sizes remain equal
size_t size = count_ * sizeof(Dtype);
if (data_->size() != size) {
data_.reset(new SyncedMemory(size));
diff_.reset(new SyncedMemory(size));
}
data_->set_gpu_data(data);
}
template <typename Dtype>
const Dtype* Blob<Dtype>::cpu_diff() const { //修改blob中梯度在cpu上的指针
CHECK(diff_);
return (const Dtype*)diff_->cpu_data();
}
template <typename Dtype>
const Dtype* Blob<Dtype>::gpu_diff() const { //修改blob中梯度在gpu上的指针
CHECK(diff_);
return (const Dtype*)diff_->gpu_data();
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_cpu_data() { //返回blob中数据在cpu上的指针(数据可修改)
CHECK(data_);
return static_cast<Dtype*>(data_->mutable_cpu_data());
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_gpu_data() { //返回blob中数据在gpu上的指针(数据可修改)
CHECK(data_);
return static_cast<Dtype*>(data_->mutable_gpu_data());
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_cpu_diff() { //返回blob中梯度在cpu上的指针(数据可修改)
CHECK(diff_);
return static_cast<Dtype*>(diff_->mutable_cpu_data());
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_gpu_diff() { //返回blob中梯度在gpu上的指针(数据可修改)
CHECK(diff_);
return static_cast<Dtype*>(diff_->mutable_gpu_data());
}
template <typename Dtype>
void Blob<Dtype>::ShareData(const Blob& other) { //共享数据,将当前blob的数据指针指向other中的数据
CHECK_EQ(count_, other.count()); //检查当前blob中数据大小与other中数据的大小是否一致
data_ = other.data();
}
template <typename Dtype>
void Blob<Dtype>::ShareDiff(const Blob& other) { //共享梯度,将当前blob的梯度指针指向other中的梯度
CHECK_EQ(count_, other.count());
diff_ = other.diff();
}
// The "update" method is used for parameter blobs in a Net, which are stored
// as Blob<float> or Blob<double> -- hence we do not define it for
// Blob<int> or Blob<unsigned int>.
template <> void Blob<unsigned int>::Update() { NOT_IMPLEMENTED; }
template <> void Blob<int>::Update() { NOT_IMPLEMENTED; }
//使用梯度更新当前的数据
//caffe_axpy()和caffe_gpu_axpy()分别为cpu和gpu上的计算函数,使用了BLAS库
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: //在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())); //运用梯度,data_ = Dtype(-1) * diff_ + 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())); //gpu上的操作,data_ = Dtype(-1) * diff_ + data_
#else
NO_GPU;
#endif
break;
default:
LOG(FATAL) << "Syncedmem not initialized.";
}
}
template <> unsigned int Blob<unsigned int>::asum_data() const {
NOT_IMPLEMENTED;
return 0;
}
template <> int Blob<int>::asum_data() const {
NOT_IMPLEMENTED;
return 0;
}
template <typename Dtype>
Dtype Blob<Dtype>::asum_data() const { //计算data_中元素的绝对值之和
if (!data_) { return 0; }
switch (data_->head()) {
case SyncedMemory::HEAD_AT_CPU:
return caffe_cpu_asum(count_, cpu_data()); //数据在cpu中,计算绝对值之和
case SyncedMemory::HEAD_AT_GPU:
case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
{
Dtype asum;
caffe_gpu_asum(count_, gpu_data(), &asum); //数据在gpu中
return asum;
}
#else
NO_GPU;
#endif
case SyncedMemory::UNINITIALIZED: //未初始化,返回0
return 0;
default:
LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
}
return 0;
}
template <> unsigned int Blob<unsigned int>::asum_diff() const {
NOT_IMPLEMENTED;
return 0;
}
template <> int Blob<int>::asum_diff() const {
NOT_IMPLEMENTED;
return 0;
}
template <typename Dtype>
Dtype Blob<Dtype>::asum_diff() const { //与asum_data类似,计算diff_中元素的绝对值之和
if (!diff_) { return 0; }
switch (diff_->head()) {
case SyncedMemory::HEAD_AT_CPU:
return caffe_cpu_asum(count_, cpu_diff()); //cpu
case SyncedMemory::HEAD_AT_GPU:
case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
{
Dtype asum;
caffe_gpu_asum(count_, gpu_diff(), &asum);
return asum;
}
#else
NO_GPU;
#endif
case SyncedMemory::UNINITIALIZED:
return 0;
default:
LOG(FATAL) << "Unknown SyncedMemory head state: " << diff_->head();
}
return 0;
}
template <> unsigned int Blob<unsigned int>::sumsq_data() const {
NOT_IMPLEMENTED;
return 0;
}
template <> int Blob<int>::sumsq_data() const {
NOT_IMPLEMENTED;
return 0;
}
template <typename Dtype>
Dtype Blob<Dtype>::sumsq_data() const { //与asum_data()类似,计算data_中元素的平方和
Dtype sumsq;
const Dtype* data;
if (!data_) { return 0; }
switch (data_->head()) {
case SyncedMemory::HEAD_AT_CPU:
data = cpu_data();
sumsq = caffe_cpu_dot(count_, data, data); //向量data与data的内积
break;
case SyncedMemory::HEAD_AT_GPU:
case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
data = gpu_data();
caffe_gpu_dot(count_, data, data, &sumsq); //gpu上计算
#else
NO_GPU;
#endif
break;
case SyncedMemory::UNINITIALIZED:
return 0;
default:
LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
}
return sumsq;
}
template <> unsigned int Blob<unsigned int>::sumsq_diff() const {
NOT_IMPLEMENTED;
return 0;
}
template <> int Blob<int>::sumsq_diff() const {
NOT_IMPLEMENTED;
return 0;
}
template <typename Dtype>
Dtype Blob<Dtype>::sumsq_diff() const { //与sumsq_data()类似,计算diff_中元素的平方和
Dtype sumsq;
const Dtype* diff;
if (!diff_) { return 0; }
switch (diff_->head()) {
case SyncedMemory::HEAD_AT_CPU:
diff = cpu_diff();
sumsq = caffe_cpu_dot(count_, diff, diff); //内积
break;
case SyncedMemory::HEAD_AT_GPU:
case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
diff = gpu_diff();
caffe_gpu_dot(count_, diff, diff, &sumsq);
break;
#else
NO_GPU;
#endif
case SyncedMemory::UNINITIALIZED:
return 0;
default:
LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
}
return sumsq;
}
template <> void Blob<unsigned int>::scale_data(unsigned int scale_factor) {
NOT_IMPLEMENTED;
}
template <> void Blob<int>::scale_data(int scale_factor) {
NOT_IMPLEMENTED;
}
template <typename Dtype>
void Blob<Dtype>::scale_data(Dtype scale_factor) { //给data_数据乘上一个系数
Dtype* data;
if (!data_) { return; }
switch (data_->head()) {
case SyncedMemory::HEAD_AT_CPU: //在cpu中
data = mutable_cpu_data(); //数据在cpu上的指针
caffe_scal(count_, scale_factor, data); //data = data * scale_factor (data中每个元素乘上scale_factor)
return;
case SyncedMemory::HEAD_AT_GPU:
case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
data = mutable_gpu_data();
caffe_gpu_scal(count_, scale_factor, data); //gpu操作
return;
#else
NO_GPU;
#endif
case SyncedMemory::UNINITIALIZED:
return;
default:
LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
}
}
template <> void Blob<unsigned int>::scale_diff(unsigned int scale_factor) {
NOT_IMPLEMENTED;
}
template <> void Blob<int>::scale_diff(int scale_factor) {
NOT_IMPLEMENTED;
}
template <typename Dtype>
void Blob<Dtype>::scale_diff(Dtype scale_factor) { //与scale_data类似,给diff_中的元素乘上一个系数
Dtype* diff;
if (!diff_) { return; }
switch (diff_->head()) {
case SyncedMemory::HEAD_AT_CPU:
diff = mutable_cpu_diff();
caffe_scal(count_, scale_factor, diff); //diff = scale_factor * diff
return;
case SyncedMemory::HEAD_AT_GPU:
case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
diff = mutable_gpu_diff();
caffe_gpu_scal(count_, scale_factor, diff);
return;
#else
NO_GPU;
#endif
case SyncedMemory::UNINITIALIZED:
return;
default:
LOG(FATAL) << "Unknown SyncedMemory head state: " << diff_->head();
}
}
//判断当前blob的形状与BlobProto类型的other表示的形状是否一致
//TODO BlobProto类定义在caffe.pb.h中,包含data和diff数据,但是暂时不了解它与blob的关系以及如何使用?
template <typename Dtype>
bool Blob<Dtype>::ShapeEquals(const BlobProto& other) {
if (other.has_num() || other.has_channels() ||
other.has_height() || other.has_width()) { //如果other中设置了num/channels/height/width的等属性
// Using deprecated 4D Blob dimensions --
// shape is (num, channels, height, width).
// Note: we do not use the normal Blob::num(), Blob::channels(), etc.
// methods as these index from the beginning of the blob shape, where legacy
// parameter blobs were indexed from the end of the blob shape (e.g., bias
// Blob shape (1 x 1 x 1 x N), IP layer weight Blob shape (1 x 1 x M x N)).
return shape_.size() <= 4 &&
LegacyShape(-4) == other.num() &&
LegacyShape(-3) == other.channels() && //LegacyShape(-3)表示shape_中的倒数第3个维度的大小
LegacyShape(-2) == other.height() &&
LegacyShape(-1) == other.width(); //shape的维度必须小于等于4,且n,c,h,w均与other的相等
}
vector<int> other_shape(other.shape().dim_size()); //创建vector变量,将other中的各个维度的大小存入
for (int i = 0; i < other.shape().dim_size(); ++i) {
other_shape[i] = other.shape().dim(i); //第i个维度
}
return shape_ == other_shape; //返回两者是否相等
}
//从source中拷贝数据至当前的blob中,copy_diff表示拷贝的是data_数据还是diff_数据
//reshape表示当前blob是否需要进行reshape操作
template <typename Dtype>
void Blob<Dtype>::CopyFrom(const Blob& source, bool copy_diff, bool reshape) {
if (source.count() != count_ || source.shape() != shape_) { //source中数据的大小和形状与当前blob的不一致
if (reshape) { //允许修改
ReshapeLike(source); //修改当前blob的形状
} else {
LOG(FATAL) << "Trying to copy blobs of different sizes."; //形状不一致还不允许reshape,返回错误
}
}
switch (Caffe::mode()) { //当前运行的模式,cpu还是gpu模式
case Caffe::GPU:
if (copy_diff) { //拷贝梯度diff_数据
caffe_copy(count_, source.gpu_diff(),
static_cast<Dtype*>(diff_->mutable_gpu_data())); //将source的diff在gpu上的数据拷贝至当前blob的diff在gpu的显存中,拷贝大小为count_
} else {
caffe_copy(count_, source.gpu_data(),
static_cast<Dtype*>(data_->mutable_gpu_data())); //将source的data在gpu上的数据拷贝至当前blob的data在gpu的显存中,拷贝大小为count_
}
break;
case Caffe::CPU: //cpu模式
if (copy_diff) {
caffe_copy(count_, source.cpu_diff(),
static_cast<Dtype*>(diff_->mutable_cpu_data())); //将source的diff在cpu上的数据拷贝至当前blob的diff在cpu的内存中,拷贝大小为count_
} else {
caffe_copy(count_, source.cpu_data(),
static_cast<Dtype*>(data_->mutable_cpu_data())); //将source的data在cpu上的数据拷贝至当前blob的data在cpu的内存中,拷贝大小为count_
}
break;
default:
LOG(FATAL) << "Unknown caffe mode."; //未知模式返回错误
}
}
//从BlobProto类型的变量中拷贝data和diff数据
//如果reshape为true,需要保证当前blob与proto的总体数据大小一致,
//如果reshape为false,需要保证当前blob与proto的中数据的各个维度的大小一致
template <typename Dtype>
void Blob<Dtype>::FromProto(const BlobProto& proto, bool reshape) {
if (reshape) { //需要reshape
vector<int> shape; //将proto的各个维度保存在shape中
if (proto.has_num() || proto.has_channels() ||
proto.has_height() || proto.has_width()) {
// Using deprecated 4D Blob dimensions --
// shape is (num, channels, height, width).
shape.resize(4); //只有4个维度
shape[0] = proto.num();
shape[1] = proto.channels();
shape[2] = proto.height();
shape[3] = proto.width();
} else {
shape.resize(proto.shape().dim_size()); //保存所有维度的大小
for (int i = 0; i < proto.shape().dim_size(); ++i) {
shape[i] = proto.shape().dim(i);
}
}
Reshape(shape); //修改当前blob的形状
} else {
CHECK(ShapeEquals(proto)) << "shape mismatch (reshape not set)"; //不需reshape,检查各个维度大小是否一致
}
// copy data
Dtype* data_vec = mutable_cpu_data(); //当前blob中data的指针
if (proto.double_data_size() > 0) { //如果是双精度数据,double类型
CHECK_EQ(count_, proto.double_data_size()); //检查数据大小是否一致
for (int i = 0; i < count_; ++i) {
data_vec[i] = proto.double_data(i); //拷贝
}
} else { //单精度数据,float类型
CHECK_EQ(count_, proto.data_size()); //检查大小
for (int i = 0; i < count_; ++i) {
data_vec[i] = proto.data(i); //复制
}
}
if (proto.double_diff_size() > 0) { //操作与data_的类似,拷贝diff数据至当前blob的diff_中
CHECK_EQ(count_, proto.double_diff_size());
Dtype* diff_vec = mutable_cpu_diff();
for (int i = 0; i < count_; ++i) {
diff_vec[i] = proto.double_diff(i);
}
} else if (proto.diff_size() > 0) {
CHECK_EQ(count_, proto.diff_size());
Dtype* diff_vec = mutable_cpu_diff();
for (int i = 0; i < count_; ++i) {
diff_vec[i] = proto.diff(i);
}
}
}
//将当前blob的data数据保存在BlobProto类型的变量中(双精度数据区),write_diff表示是否需要保存diff数据
template <>
void Blob<double>::ToProto(BlobProto* proto, bool write_diff) const {
proto->clear_shape(); //清空proto中的shape数据
for (int i = 0; i < shape_.size(); ++i) {
proto->mutable_shape()->add_dim(shape_[i]); //将当前blob数据的形状保存在proto中
}
proto->clear_double_data(); //清空之前的data和diff数据(双精度类型)
proto->clear_double_diff();
const double* data_vec = cpu_data(); //当前blob的data在cpu上的数据
for (int i = 0; i < count_; ++i) {
proto->add_double_data(data_vec[i]); //添加进proto
}
if (write_diff) { //需要保存diff数据
const double* diff_vec = cpu_diff();
for (int i = 0; i < count_; ++i) {
proto->add_double_diff(diff_vec[i]); //写入proto中
}
}
}
//与上面的Blob<double>::ToProto()类似,此处是将blob中的数据写入proto的单精度数据区
template <>
void Blob<float>::ToProto(BlobProto* proto, bool write_diff) const {
proto->clear_shape();
for (int i = 0; i < shape_.size(); ++i) {
proto->mutable_shape()->add_dim(shape_[i]);
}
proto->clear_data();
proto->clear_diff();
const float* data_vec = cpu_data();
for (int i = 0; i < count_; ++i) {
proto->add_data(data_vec[i]); //存入float类型的数据区
}
if (write_diff) {
const float* diff_vec = cpu_diff();
for (int i = 0; i < count_; ++i) {
proto->add_diff(diff_vec[i]);
}
}
}
blob.hpp源码
const int kMaxBlobAxes = 32; //数据维度个数的最大值,shape_.size()不能超过改值
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 <typename Dtype>
class Blob {
public:
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);
/// @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);
void ReshapeLike(const Blob& other);
inline string shape_string() const { //输出包含各维度信息的字符串,"n c h w (count_)"
ostringstream stream;
for (int i = 0; i < shape_.size(); ++i) {
stream << shape_[i] << " ";
}
stream << "(" << count_ << ")";
return stream.str();
}
inline const vector<int>& shape() const { return shape_; } //返回blob数据的形状
/**
* @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.
*/
inline int shape(int index) const {
return shape_[CanonicalAxisIndex(index)]; //返回blob数据的第index维的大小
}
inline int num_axes() const { return shape_.size(); } //返回数据的维度的个数
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 { //返回第start_axis维到第end_axis维之间的数据的大小
CHECK_LE(start_axis, end_axis); //检查 start_axis <= end_axis
CHECK_GE(start_axis, 0); //检查 start_axis >= 0
CHECK_GE(end_axis, 0); //检查 end_axis >= 0
CHECK_LE(start_axis, num_axes()); //检查 start_axis <= shape_.size()
CHECK_LE(end_axis, num_axes()); //检查 end_axis <= shape_.size()
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 { //返回第start_axis维到最后维之间的数据的大小
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.
*/
inline int CanonicalAxisIndex(int axis_index) const { //输入axis_index(可正可负),返回axis_index在shape_对应的实际索引
CHECK_GE(axis_index, -num_axes())
<< "axis " << axis_index << " out of range for " << num_axes()
<< "-D Blob with shape " << shape_string(); //检查 axis_index >= -num_axes()
CHECK_LT(axis_index, num_axes())
<< "axis " << axis_index << " out of range for " << num_axes()
<< "-D Blob with shape " << shape_string(); //检查 axis_index < num_axes()
if (axis_index < 0) {
return axis_index + num_axes(); //为负数时,表示倒数第-axis_index个,计算对应的正向时的索引
}
return axis_index; //正数不处理,直接返回
}
/// @brief Deprecated legacy shape accessor num: use shape(0) instead.
inline int num() const { return LegacyShape(0); } //num()/channels()/height()/width()这四个函数已不建议使用,使用shape(i)替代
/// @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 { //返回shape_中的第index个维度的大小,index可以为负数
CHECK_LE(num_axes(), 4)
<< "Cannot use legacy accessors on Blobs with > 4 axes."; //blob中数据的维度超过4时,不能使用这种方式
CHECK_LT(index, 4); //检查index的范围
CHECK_GE(index, -4);
//对于小于4维的数据,如果给出的索引超过数据的维度范围但是在4范围内,那么返回1.相当于将数据缺少的维度大小用1填充
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);
}
inline int offset(const int n, const int c = 0, const int h = 0, const int w = 0) const { //返回第(n,c,h,w)个数据的偏移位置
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 { //同理,返回indices中指示的数据的偏移位置
CHECK_LE(indices.size(), num_axes()); //检查indices的长度是否与shape_匹配
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
*/
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, //返回data中(n,c,h,w)处的数据值
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, //返回diff中(n,c,h,w)处的数据值
const int w) const {
return cpu_diff()[offset(n, c, h, w)];
}
inline Dtype data_at(const vector<int>& index) const { //返回data中index处的数据值
return cpu_data()[offset(index)];
}
inline Dtype diff_at(const vector<int>& index) const { //返回diff中index处的数据值
return cpu_diff()[offset(index)];
}
inline const shared_ptr<SyncedMemory>& data() const { //返回存放data在cpu上的数据指针
CHECK(data_);
return data_;
}
inline const shared_ptr<SyncedMemory>& diff() const { //返回存放diff在cpu上的数据指针
CHECK(diff_);
return diff_;
}
const Dtype* cpu_data() const;
void set_cpu_data(Dtype* data);
const int* gpu_shape() const;
const Dtype* gpu_data() const;
void set_gpu_data(Dtype* data);
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();
void Update();
void FromProto(const BlobProto& proto, bool reshape = true);
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;
/// @brief Compute the sum of absolute values (L1 norm) of the diff.
Dtype asum_diff() const;
/// @brief Compute the sum of squares (L2 norm squared) of the data.
Dtype sumsq_data() const;
/// @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);
/// @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.
*/
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);
protected:
shared_ptr<SyncedMemory> data_; //存放数据,用于前向计算
shared_ptr<SyncedMemory> diff_; //存放梯度数据,用于反向传播
shared_ptr<SyncedMemory> shape_data_; //数据的各维度大小
vector<int> shape_; //数据的各维度大小,值与shape_data_中的各个值一致
//capacity_表示data.size()/sizeof(Dtype), 表示data_或diff_中能存放的数据的最大个数
//count_表示当前data_或diff_中有效的数据的个数,总有 count_ <= capacity_
int count_; //当前数据的总个数(各个维度的相乘)
int capacity_; //data_或diff_中能容纳的数据的大小
DISABLE_COPY_AND_ASSIGN(Blob);
}; // class Blob
} // namespace caffe
小结
- 网络上关于count_和capacity_的说明比较模糊,但是查看blob的Reshape()函数便可发现,两者一般情况下是相等的,但是出现reshape操作时,count_的值一定被修改,count_ = new_shape[0] * new_shape[1] * ... * new_shape[new_shape.size() - 1],而capacity_只有在capacity_ <= count_的时候才会修改,同时data_和diff_会重新申请内存/显存。因此他们的实际关系始终为capacity_ >= count_,并且始终有**capacity_ = data.size() / sizeof(Dtype) ,表示SyncedMemory类型的data_/diff_中能存放的最大数据个数(容量)。以及count_ = shape(0) * shape(1) * ... * shape(shape_.size()-1) **,表示data_中实际有效的数据的个数。
- 代码中有部分内容(如BlobProto类的作用和与Blob的关系)笔者还不太了解,待后续更新。
Caffe的源码笔者是第一次阅读,一边阅读一边记录,对代码的理解和分析可能会存在错误或遗漏,希望各位读者批评指正,谢谢支持!