Caffe源码解读:Blob类
2017-07-23 本文已影响246人
Mordekaiser
Caffe里面有几个基本的类:Blob,Net,Layer,Solver。其中Blob类是caffe最基本的数据结构,是一个多维数组,且自动在CPU和GPU之间实现数据同步。对于图像数据而言,维度为4,从低到高表示为:width_, height_, channels_, num_。有点像Tensorflow里面的tensor一样。一层层的Layer组成了Net,Blob在Layer之间传播(反向,前向传播)。利用Solver求解优化。
首先介绍下ProtoBuffer,它是一种高效的结构化存储格式。其实其主要的有点就是解决了数据的序列化,反序列化问题,不用程序员去操心,而且相比其他工具而言,速度快。总之就是方便数据存储。
- 序列化: 将数据结构或对象转换成二进制串的过程
- 反序列化:将在序列化过程中所生成的二进制串转换成数据结构或者对象的过程
目录
- Blob的ProtoBuffer描述
- Blob类声明文件详解
- Blob类定义文件详解
Blob的ProtoBuffer描述
首先看看./src/caffe/proto/caffe.proto文件关于BlobProto部分的描述(下面部分描述实际上是说明了Blob在磁盘中的存储方式,因为数据为了存储到磁盘,需要进行序列化,序列化哪些东西需要做一个约定,下面就是约定的内容):
// BlobShape类的定义
message BlobShape {
// 指定了Blob的维度信息,packed表示在内存中精密排布,没有空洞
repeated int64 dim = 1 [packed = true];
}
// BlobProto类的定义:Blob在磁盘中序列化后的形态
message BlobProto {
optional BlobShape shape = 7; // 可选,包括一个BlobShape对象
repeated float data = 5 [packed = true]; // 包含若干浮点元素,在内存中紧密排布,用于存储数据或权值
repeated float diff = 6 [packed = true]; // 包含若干浮点元素,在内存中紧密排布,用于梯度
repeated double double_data = 8 [packed = true];// 同上,类型为double而已
repeated double double_diff = 9 [packed = true];
// 可选维度信息,新版本推荐使用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];
}
Blob类声明文件详解
接下来看看./include/caffe/blob.hpp文件,里面有Blob类的定义:
#ifndef CAFFE_BLOB_HPP_
#define CAFFE_BLOB_HPP_
#include <algorithm>
#include <string>
#include <vector>
#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h" // 包含了遵循caffe.proto描述的BlobProto,BlobShape类
#include "caffe/syncedmem.hpp" // 共享内存类,用于CPU,GPU数据的同步
const int kMaxBlobAxes = 32; // Blob最大维度为32维,通常为4维
// Blob类声明位于caffe名字空间内,其成员带有下划线,如: shape_
namespace caffe {
template <typename Dtype>
class Blob {
protected:
shared_ptr<SyncedMemory> data_; // 存储图像数据
shared_ptr<SyncedMemory> diff_; // 存储反向传播中的梯度,和data_大小一致
shared_ptr<SyncedMemory> shape_data_; // 共享内存类对象,存储着shape_需要的字节数
vector<int> shape_; // 数据的shape
int count_; // 存储Blob所有元素数量
int capacity_; // 存储Blob的容量信息,count_ <= capacity的,如果超过了(比如Reshape时),就要重新new内存
// 为了实现单例模式,禁用拷贝和析构
DISABLE_COPY_AND_ASSIGN(Blob);
public:
Blob() // 默认构造函数
: data_(), diff_(), count_(0), capacity_(0) {}
// 显式构造函数,新版caffe推荐使用第二种
explicit Blob(const int num, const int channels, const int height,
const int width);
explicit Blob(const vector<int>& shape);
// Reshape函数,必要时可以重新分配内存
void Reshape(const int num, const int channels, const int height,
const int width);
void Reshape(const vector<int>& shape);
void Reshape(const BlobShape& shape);
void ReshapeLike(const Blob& other);
// 打印shape信息,如:1 2 3 4 (24)
inline string shape_string() const {
ostringstream stream;
for (int i = 0; i < shape_.size(); ++i) {
stream << shape_[i] << " ";
}
stream << "(" << count_ << ")";
return stream.str();
}
// 返回shape信息
inline const vector<int>& shape() const { return shape_; }
// 返回第index维度的大小,index可以为负值,像python一样
inline int shape(int index) const {
return shape_[CanonicalAxisIndex(index)];
}
// 返回维度数
inline int num_axes() const { return shape_.size(); }
// 返回Blob里面的元素数量:所有维度大小相乘
inline int count() const { return count_; }
// 返回[start_axis, end_axis)维度里面的元素数量
inline int count(int start_axis, int end_axis) const {
// 下面是一系列宏定义,校验输入是否正确
// L表示less, E表示equal, G表示great
// 下面不允许[-1, -2)这种输入,可以优化
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());
}
// 负数索引转换函数
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(0),下面其他类似
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); }
// 求某一维度的大小,老版本的接口
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()) {
return 1;
}
return shape(index);
}
// 下面函数是计算偏移量的,
//比如大小为(2, 3, 5, 5)的Blob,(1, 0, 0, 0)其在内存中的存储位置是75:(1, 0, 0, 0)表示的是第二张图片的第0个通道的第0行0列
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;
}
/**
* @brief 从某一Blob拷贝数据
*
* @param source:拷贝源
* @param copy_diff:是否拷贝梯度信息
* @param reshape :是否调整大小为source的大小,如果不调整,需要保证拷贝的数据之间大小是一致的,否则会报错
*/
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)]; // 猜想此处cpu_data()应该是返回指针
}
// 访问某个元素的梯度
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)];
}
// 返回指向数据的指针,注意此处用了shared_ptr。并且使用共享内存类,实现了CPU和GPU数据同步,不管数据在CPU还是GPU都可以取出来。下面类似
inline const shared_ptr<SyncedMemory>& data() const {
CHECK(data_);
return data_;
}
inline const shared_ptr<SyncedMemory>& diff() const {
CHECK(diff_);
return diff_;
}
// 只读访问cpu数据
const Dtype* cpu_data() const;
// 设置cpu数据
void set_cpu_data(Dtype* data);
// 返回gpu数据的shape?这块没懂,看对应的.cpp感觉好奇怪
const int* gpu_shape() const;
// 下面就是读写访问cpu,gpu里面的数据以及梯度
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();
// 根据梯度更新data_: x = x - learning_rate * tidu(x)
void Update();
// 反序列化,从BlobProto中恢复Blob
void FromProto(const BlobProto& proto, bool reshape = true);
// 序列化,将内存中的Blob对象保存到BlobProto中
void ToProto(BlobProto* proto, bool write_diff = false) const;
// 计算data_,diff_的L1,L2范数
Dtype asum_data() const;
Dtype asum_diff() const;
Dtype sumsq_data() const;
Dtype sumsq_diff() const;
// data_, diff_乘以一个倍数
void scale_data(Dtype scale_factor);
void scale_diff(Dtype scale_factor);
// 共享另一个Blob的data_, diff_
void ShareData(const Blob& other);
void ShareDiff(const Blob& other);
// 判断Blob的大小是否相等
bool ShapeEquals(const BlobProto& other);
}; // class Blob
} // namespace caffe
#endif // CAFFE_BLOB_HPP_
Blob类定义文件详解
阅读caffe源码三部曲,先proto文件,然后.hpp,然后.cpp。下面就来看看./src/caffe/blob.cpp,很多函数其实已经在类声明里面实现了~:
#include <climits>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/syncedmem.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
// Reshape函数,将维度信息转为vector<int>,然后调用另一个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;
Reshape(shape);
}
template <typename Dtype>
void Blob<Dtype>::Reshape(const vector<int>& shape) {
CHECK_LE(shape.size(), kMaxBlobAxes);
count_ = 1;
shape_.resize(shape.size());
// 重新分配shape_data_的内存
if (!shape_data_ || shape_data_->size() < shape.size() * sizeof(int)) {
shape_data_.reset(new SyncedMemory(shape.size() * sizeof(int)));
}
int* shape_data = static_cast<int*>(shape_data_->mutable_cpu_data());
for (int i = 0; i < shape.size(); ++i) {
CHECK_GE(shape[i], 0);
if (count_ != 0) {
// 保证cout_不超过INT_MAX,否则到后面数据溢出就麻烦了
CHECK_LE(shape[i], INT_MAX / count_) << "blob size exceeds INT_MAX";
}
count_ *= shape[i];
shape_[i] = shape[i];
shape_data[i] = shape[i];
}
if (count_ > capacity_) { // 如果count_超出当前容量,则扩容
capacity_ = count_;
data_.reset(new SyncedMemory(capacity_ * sizeof(Dtype)));
diff_.reset(new SyncedMemory(capacity_ * sizeof(Dtype)));
}
}
// 同上
template <typename Dtype>
void Blob<Dtype>::Reshape(const BlobShape& shape) {
CHECK_LE(shape.dim_size(), 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);
}
template <typename Dtype>
void Blob<Dtype>::ReshapeLike(const Blob<Dtype>& other) {
Reshape(other.shape());
}
// 构造函数
template <typename Dtype>
Blob<Dtype>::Blob(const int num, const int channels, const int height,
const int width)
// 在调用Reshape之前,capacity_ 必须被初始化,下同
: capacity_(0) {
Reshape(num, channels, height, width);
}
template <typename Dtype>
Blob<Dtype>::Blob(const vector<int>& shape)
: capacity_(0) {
Reshape(shape);
}
// 返回gpu里面的shape信息,之所以用(const int*)是因为返回值是const void*,且shape信息是int型的数组
template <typename Dtype>
const int* Blob<Dtype>::gpu_shape() const {
CHECK(shape_data_);
return (const int*)shape_data_->gpu_data();
}
// 下面这些函数的功能已经在.hpp文件中有所介绍,此处不再赘述
// 关键要注意data_, diff_, shape_data_都是智能指针,其指向SyncedMemory类
template <typename Dtype>
const Dtype* Blob<Dtype>::cpu_data() const {
CHECK(data_); // 保证data_不为NULL
return (const Dtype*)data_->cpu_data();
}
template <typename Dtype>
void Blob<Dtype>::set_cpu_data(Dtype* data) {
CHECK(data); // 检验数据的合法性,类似的宏都是这种功能
data_->set_cpu_data(data);
}
template <typename Dtype>
const Dtype* Blob<Dtype>::gpu_data() const {
CHECK(data_);
return (const Dtype*)data_->gpu_data();
}
template <typename Dtype>
const Dtype* Blob<Dtype>::cpu_diff() const {
CHECK(diff_);
return (const Dtype*)diff_->cpu_data();
}
template <typename Dtype>
const Dtype* Blob<Dtype>::gpu_diff() const {
CHECK(diff_);
return (const Dtype*)diff_->gpu_data();
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_cpu_data() {
CHECK(data_);
return static_cast<Dtype*>(data_->mutable_cpu_data());
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_gpu_data() {
CHECK(data_);
return static_cast<Dtype*>(data_->mutable_gpu_data());
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_cpu_diff() {
CHECK(diff_);
return static_cast<Dtype*>(diff_->mutable_cpu_data());
}
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_gpu_diff() {
CHECK(diff_);
return static_cast<Dtype*>(diff_->mutable_gpu_data());
}
template <typename Dtype>
void Blob<Dtype>::ShareData(const Blob& other) {
CHECK_EQ(count_, other.count());
data_ = other.data(); // 智能指针赋值,引用计数+1
}
template <typename Dtype>
void Blob<Dtype>::ShareDiff(const Blob& other) {
CHECK_EQ(count_, other.count());
diff_ = other.diff();
}
// Updata为模型参数更新函数,由于模型参数必然是float或者double的,所以没有定义unsigned和int的模板
template <> void Blob<unsigned int>::Update() { NOT_IMPLEMENTED; }
template <> void Blob<int>::Update() { NOT_IMPLEMENTED; }
template <typename Dtype>
void Blob<Dtype>::Update() {
// 根据数据在cpu,还是gpu,决定在哪更新
switch (data_->head()) {
case SyncedMemory::HEAD_AT_CPU:
// 在CPU进行参数更新
// 命令行输入:grep -n -H -R "caffe_axpy" *, 可以知道caffe_axpy是一个模板函数
// 定义在include/caffe/util/math_functions.hpp文件第29行,查看其对应的.cpp文件(如果是GPU上计算,则查看对应的.cu文件)其调用了cblas_saxpy(cublasSaxpy)函数(假如模板参数是float),这个函数MKL库里面的一个函数。这样做只是为了加速。
// 总之其原理就是: x = x - tidu(x)。学习速率在Back_Forward函数里面作为梯度的一部分算在diff_里面了,所以这个caffe_axpy第二个参数是-1。后面会提到,这个要注意。
caffe_axpy<Dtype>(count_, Dtype(-1),
static_cast<const Dtype*>(diff_->cpu_data()),
static_cast<Dtype*>(data_->mutable_cpu_data()));
break;
// 数据在GPU端,或者CPU/GPU数据已经同步
case SyncedMemory::HEAD_AT_GPU:
case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
// 在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.";
}
}
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 {
if (!data_) { return 0; }
switch (data_->head()) {
case SyncedMemory::HEAD_AT_CPU:
// 同样的,该函数定义在include/caffe/util/math_functions.hpp文件中106行,之后调用MKL里面的cblas_sasum函数。下同,不在赘述
return caffe_cpu_asum(count_, cpu_data());
case SyncedMemory::HEAD_AT_GPU:
case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
{
Dtype asum;
caffe_gpu_asum(count_, gpu_data(), &asum);
return asum;
}
#else
NO_GPU;
#endif
case SyncedMemory::UNINITIALIZED:
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 {
if (!diff_) { return 0; }
switch (diff_->head()) {
case SyncedMemory::HEAD_AT_CPU:
return caffe_cpu_asum(count_, cpu_diff());
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 {
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);
break;
case SyncedMemory::HEAD_AT_GPU:
case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
data = gpu_data();
caffe_gpu_dot(count_, data, data, &sumsq);
#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 {
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) {
Dtype* data;
if (!data_) { return; }
switch (data_->head()) {
case SyncedMemory::HEAD_AT_CPU:
data = mutable_cpu_data();
caffe_scal(count_, scale_factor, data);
return;
case SyncedMemory::HEAD_AT_GPU:
case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
data = mutable_gpu_data();
caffe_gpu_scal(count_, scale_factor, data);
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) {
Dtype* diff;
if (!diff_) { return; }
switch (diff_->head()) {
case SyncedMemory::HEAD_AT_CPU:
diff = mutable_cpu_diff();
caffe_scal(count_, 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();
}
}
// 上面的代码实现都是一个套路,不在详说
template <typename Dtype>
bool Blob<Dtype>::ShapeEquals(const BlobProto& other) {
if (other.has_num() || other.has_channels() ||
other.has_height() || other.has_width()) {
// 从末尾开始索引比较看似快,可还要把负数索引转换为正数,用意何在?
return shape_.size() <= 4 &&
LegacyShape(-4) == other.num() &&
LegacyShape(-3) == other.channels() &&
LegacyShape(-2) == other.height() &&
LegacyShape(-1) == other.width();
}
vector<int> other_shape(other.shape().dim_size());
for (int i = 0; i < other.shape().dim_size(); ++i) {
other_shape[i] = other.shape().dim(i);
}
return shape_ == other_shape;
}
template <typename Dtype>
void Blob<Dtype>::CopyFrom(const Blob& source, bool copy_diff, bool reshape) {
if (source.count() != count_ || source.shape() != shape_) {
if (reshape) { // 如果有必要就Reshape
ReshapeLike(source);
} else {
LOG(FATAL) << "Trying to copy blobs of different sizes.";
}
}
switch (Caffe::mode()) {
case Caffe::GPU:
if (copy_diff) {
// 同样的套路,输入: grep -n -H -R "caffe_copy"
// 发现在*math_functions.hpp:37行有函数定义,查看对应的.cpp文件,发现调用了cudaMemcpy函数(cpu中调用的是memcpy函数)。
// 此处用case多此一举,因为caffe_copy函数还会做一次判断
caffe_copy(count_, source.gpu_diff(),
static_cast<Dtype*>(diff_->mutable_gpu_data()));
} else {
caffe_copy(count_, source.gpu_data(),
static_cast<Dtype*>(data_->mutable_gpu_data()));
}
break;
case Caffe::CPU:
if (copy_diff) {
caffe_copy(count_, source.cpu_diff(),
static_cast<Dtype*>(diff_->mutable_cpu_data()));
} else {
caffe_copy(count_, source.cpu_data(),
static_cast<Dtype*>(data_->mutable_cpu_data()));
}
break;
default:
LOG(FATAL) << "Unknown caffe mode.";
}
}
// 数据反序列化到Blob
template <typename Dtype>
void Blob<Dtype>::FromProto(const BlobProto& proto, bool reshape) {
if (reshape) {
vector<int> shape;
if (proto.has_num() || proto.has_channels() ||
proto.has_height() || proto.has_width()) {
// 老版本的方法
shape.resize(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);
} else {
CHECK(ShapeEquals(proto)) << "shape mismatch (reshape not set)";
}
// copy data
Dtype* data_vec = mutable_cpu_data();
if (proto.double_data_size() > 0) { // 如果proto里面的是double类型的data
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) { // 如果proto里面的是double类型的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) { // 若为float
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);
}
}
}
template <>
void Blob<double>::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_double_data();
proto->clear_double_diff();
const double* data_vec = cpu_data();
for (int i = 0; i < count_; ++i) {
proto->add_double_data(data_vec[i]);
}
if (write_diff) {
const double* diff_vec = cpu_diff();
for (int i = 0; i < count_; ++i) {
proto->add_double_diff(diff_vec[i]);
}
}
}
template <>
void Blob<float>::ToProto(BlobProto* proto, bool write_diff) const {
proto->clear_shape(); // 重置proto的维度,保证与Blob的相同
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]); // data赋值
}
if (write_diff) {
const float* diff_vec = cpu_diff();
for (int i = 0; i < count_; ++i) {
proto->add_diff(diff_vec[i]); // 如果有必要,diff赋值
}
}
}
INSTANTIATE_CLASS(Blob); // 实例化类模板,减少编译时间?
template class Blob<int>; // 实例化模板,下同,不提供int, unsigned实现
template class Blob<unsigned int>;
} // namespace caffe
Blob总算读完啦~其实也没多复杂,关键是得静下来,几个小时也就完事儿了
参考资料
- 《21天实战Caffe》