Blob类简介

Blob是caffe中的数据传递的一个基本类,网络各层的输入输出数据以及网络层中的可学习参数(learnable parameters,如卷积层的权重和偏置参数)都是Blob类型。Blob内部包含SyncedMemory类型的 data_ (数据,用于前向计算)和 diff_ (梯度,用于反向传播),以及表示数据形状的 shape_data_ (旧版本)和 shape_ (新版本)。Blob中还有表示有效数据的个数的变量 count_ 和表示当前数据的最大容量的变量 capacity_ 。剩余的为一些用于访问、修改data_或diff_数据的值、形状的一些函数。

blob.cpp源码

  1. //调整blob中数据的形状,与openv中的Mat::Reshape()一样,只修改与数据的形状相关的变量,没有拷贝数据的操作
  2. template <typename Dtype>
  3. void Blob<Dtype>::Reshape(const int num, const int channels, const int height,
  4. const int width) {
  5. vector<int> shape(4);
  6. shape[0] = num;
  7. shape[1] = channels;
  8. shape[2] = height;
  9. shape[3] = width; //设置n,c,h,w
  10. Reshape(shape);
  11. }
  12. //修改blob数据的形状,但不会改变data_中的值(除非重新创建)
  13. template <typename Dtype>
  14. void Blob<Dtype>::Reshape(const vector<int>& shape) {
  15. CHECK_LE(shape.size(), kMaxBlobAxes); //检查shape的维度不能超过kMaxBlobAxes
  16. count_ = 1; //新的总大小,count_ = shape[0] * shape[1] * ... * shape[shape.size() - 1]
  17. shape_.resize(shape.size()); //修改shape_变量的大小
  18. if (!shape_data_ || shape_data_->size() < shape.size() * sizeof(int)) { //shape_data_不为空,且大小比新的小
  19. shape_data_.reset(new SyncedMemory(shape.size() * sizeof(int))); //shape_ptr::reset,清除之前的数据指针,重新申请
  20. }
  21. int* shape_data = static_cast<int*>(shape_data_->mutable_cpu_data()); //shape_data_的数据指针
  22. for (int i = 0; i < shape.size(); ++i) {
  23. CHECK_GE(shape[i], 0); //检查 shape[i] >= 0 (注意,reshape()允许shape[i]为0)
  24. if (count_ != 0) { //检查数据的总体大小是否可能会超出INT_MAX(int类型的最大值)
  25. CHECK_LE(shape[i], INT_MAX / count_) << "blob size exceeds INT_MAX";
  26. }
  27. count_ *= shape[i]; //新shape的各个维度之积
  28. shape_[i] = shape[i]; //设置shape_(新版本使用)和shape_data_(旧版本使用)中的值
  29. shape_data[i] = shape[i];
  30. }
  31. if (count_ > capacity_) { //如果新的形状的总大小超出之前容纳范围,则创建新的SyncedMemory对象
  32. capacity_ = count_; //设置为新的
  33. data_.reset(new SyncedMemory(capacity_ * sizeof(Dtype))); //此处只是创建了SyncedMemory对象,但是并未真正的分配内存或显存
  34. diff_.reset(new SyncedMemory(capacity_ * sizeof(Dtype))); //在第一次访问内部的数据的时候才会分配(参见SyncedMemory.cpp)
  35. }
  36. }
  37. //根据shape的值修改blob中数据的形状 //BlobShape定义在caffe.pb.h文件中,caffe.pb.h和caffe.pb.cc由caffe.proto生成
  38. template <typename Dtype>
  39. void Blob<Dtype>::Reshape(const BlobShape& shape) {
  40. CHECK_LE(shape.dim_size(), kMaxBlobAxes); //同样检查维度数不能超过kMaxBlobAxes
  41. vector<int> shape_vec(shape.dim_size());
  42. for (int i = 0; i < shape.dim_size(); ++i) {
  43. shape_vec[i] = shape.dim(i); //设置
  44. }
  45. Reshape(shape_vec);
  46. }
  47. //调整当前blob的形状,使其与other的数据的形状一致
  48. template <typename Dtype>
  49. void Blob<Dtype>::ReshapeLike(const Blob<Dtype>& other) {
  50. Reshape(other.shape());
  51. }
  52. //blob的构造函数,创建对应形状的blob数据
  53. template <typename Dtype>
  54. Blob<Dtype>::Blob(const int num, const int channels, const int height,
  55. const int width)
  56. // capacity_ must be initialized before calling Reshape
  57. : capacity_(0) { //初始必须先将容量capacity_设置为0,保证reshape时一定会给data_和diff_创建新的SyncedMemory对象
  58. Reshape(num, channels, height, width);
  59. }
  60. template <typename Dtype>
  61. Blob<Dtype>::Blob(const vector<int>& shape) //blob的构造函数
  62. // capacity_ must be initialized before calling Reshape
  63. : capacity_(0) {
  64. Reshape(shape);
  65. }
  66. template <typename Dtype>
  67. const int* Blob<Dtype>::gpu_shape() const { //返回blob中gpu数据的形状
  68. CHECK(shape_data_);
  69. return (const int*)shape_data_->gpu_data();
  70. }
  71. template <typename Dtype>
  72. const Dtype* Blob<Dtype>::cpu_data() const { //返回blob中数据在cpu上的指针
  73. CHECK(data_);
  74. return (const Dtype*)data_->cpu_data();
  75. }
  76. template <typename Dtype>
  77. void Blob<Dtype>::set_cpu_data(Dtype* data) { //修改blob中数据在cpu上的指针
  78. CHECK(data);
  79. // Make sure CPU and GPU sizes remain equal
  80. size_t size = count_ * sizeof(Dtype); //当前blob中的数据的大小
  81. if (data_->size() != size) { //data_->size()/sizeof(Dtype)即为capacity_,与count_不一定相等
  82. data_.reset(new SyncedMemory(size)); //创建新的SyncedMemory对象,data_和diff_中cpu和gpu数据大小一致
  83. diff_.reset(new SyncedMemory(size));
  84. }
  85. data_->set_cpu_data(data); //调用SyncedMemory类中的set_cpu_data(),设置cpu数据的指针和数据的状态HEAD_AT_CPU等
  86. }
  87. template <typename Dtype>
  88. const Dtype* Blob<Dtype>::gpu_data() const { //返回blob中数据在gpu上的指针
  89. CHECK(data_);
  90. return (const Dtype*)data_->gpu_data();
  91. }
  92. template <typename Dtype>
  93. void Blob<Dtype>::set_gpu_data(Dtype* data) { //修改blob中数据在gpu上的指针,与set_cpu_data操作类似
  94. CHECK(data);
  95. // Make sure CPU and GPU sizes remain equal
  96. size_t size = count_ * sizeof(Dtype);
  97. if (data_->size() != size) {
  98. data_.reset(new SyncedMemory(size));
  99. diff_.reset(new SyncedMemory(size));
  100. }
  101. data_->set_gpu_data(data);
  102. }
  103. template <typename Dtype>
  104. const Dtype* Blob<Dtype>::cpu_diff() const { //修改blob中梯度在cpu上的指针
  105. CHECK(diff_);
  106. return (const Dtype*)diff_->cpu_data();
  107. }
  108. template <typename Dtype>
  109. const Dtype* Blob<Dtype>::gpu_diff() const { //修改blob中梯度在gpu上的指针
  110. CHECK(diff_);
  111. return (const Dtype*)diff_->gpu_data();
  112. }
  113. template <typename Dtype>
  114. Dtype* Blob<Dtype>::mutable_cpu_data() { //返回blob中数据在cpu上的指针(数据可修改)
  115. CHECK(data_);
  116. return static_cast<Dtype*>(data_->mutable_cpu_data());
  117. }
  118. template <typename Dtype>
  119. Dtype* Blob<Dtype>::mutable_gpu_data() { //返回blob中数据在gpu上的指针(数据可修改)
  120. CHECK(data_);
  121. return static_cast<Dtype*>(data_->mutable_gpu_data());
  122. }
  123. template <typename Dtype>
  124. Dtype* Blob<Dtype>::mutable_cpu_diff() { //返回blob中梯度在cpu上的指针(数据可修改)
  125. CHECK(diff_);
  126. return static_cast<Dtype*>(diff_->mutable_cpu_data());
  127. }
  128. template <typename Dtype>
  129. Dtype* Blob<Dtype>::mutable_gpu_diff() { //返回blob中梯度在gpu上的指针(数据可修改)
  130. CHECK(diff_);
  131. return static_cast<Dtype*>(diff_->mutable_gpu_data());
  132. }
  133. template <typename Dtype>
  134. void Blob<Dtype>::ShareData(const Blob& other) { //共享数据,将当前blob的数据指针指向other中的数据
  135. CHECK_EQ(count_, other.count()); //检查当前blob中数据大小与other中数据的大小是否一致
  136. data_ = other.data();
  137. }
  138. template <typename Dtype>
  139. void Blob<Dtype>::ShareDiff(const Blob& other) { //共享梯度,将当前blob的梯度指针指向other中的梯度
  140. CHECK_EQ(count_, other.count());
  141. diff_ = other.diff();
  142. }
  143. // The "update" method is used for parameter blobs in a Net, which are stored
  144. // as Blob<float> or Blob<double> -- hence we do not define it for
  145. // Blob<int> or Blob<unsigned int>.
  146. template <> void Blob<unsigned int>::Update() { NOT_IMPLEMENTED; }
  147. template <> void Blob<int>::Update() { NOT_IMPLEMENTED; }
  148. //使用梯度更新当前的数据
  149. //caffe_axpy()和caffe_gpu_axpy()分别为cpu和gpu上的计算函数,使用了BLAS库
  150. template <typename Dtype>
  151. void Blob<Dtype>::Update() {
  152. // We will perform update based on where the data is located.
  153. switch (data_->head()) { //当前数据的状态
  154. case SyncedMemory::HEAD_AT_CPU: //在cpu中
  155. // perform computation on CPU
  156. caffe_axpy<Dtype>(count_, Dtype(-1),
  157. static_cast<const Dtype*>(diff_->cpu_data()),
  158. static_cast<Dtype*>(data_->mutable_cpu_data())); //运用梯度,data_ = Dtype(-1) * diff_ + data_
  159. break;
  160. case SyncedMemory::HEAD_AT_GPU:
  161. case SyncedMemory::SYNCED:
  162. #ifndef CPU_ONLY
  163. // perform computation on GPU
  164. caffe_gpu_axpy<Dtype>(count_, Dtype(-1),
  165. static_cast<const Dtype*>(diff_->gpu_data()),
  166. static_cast<Dtype*>(data_->mutable_gpu_data())); //gpu上的操作,data_ = Dtype(-1) * diff_ + data_
  167. #else
  168. NO_GPU;
  169. #endif
  170. break;
  171. default:
  172. LOG(FATAL) << "Syncedmem not initialized.";
  173. }
  174. }
  175. template <> unsigned int Blob<unsigned int>::asum_data() const {
  176. NOT_IMPLEMENTED;
  177. return 0;
  178. }
  179. template <> int Blob<int>::asum_data() const {
  180. NOT_IMPLEMENTED;
  181. return 0;
  182. }
  183. template <typename Dtype>
  184. Dtype Blob<Dtype>::asum_data() const { //计算data_中元素的绝对值之和
  185. if (!data_) { return 0; }
  186. switch (data_->head()) {
  187. case SyncedMemory::HEAD_AT_CPU:
  188. return caffe_cpu_asum(count_, cpu_data()); //数据在cpu中,计算绝对值之和
  189. case SyncedMemory::HEAD_AT_GPU:
  190. case SyncedMemory::SYNCED:
  191. #ifndef CPU_ONLY
  192. {
  193. Dtype asum;
  194. caffe_gpu_asum(count_, gpu_data(), &asum); //数据在gpu中
  195. return asum;
  196. }
  197. #else
  198. NO_GPU;
  199. #endif
  200. case SyncedMemory::UNINITIALIZED: //未初始化,返回0
  201. return 0;
  202. default:
  203. LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
  204. }
  205. return 0;
  206. }
  207. template <> unsigned int Blob<unsigned int>::asum_diff() const {
  208. NOT_IMPLEMENTED;
  209. return 0;
  210. }
  211. template <> int Blob<int>::asum_diff() const {
  212. NOT_IMPLEMENTED;
  213. return 0;
  214. }
  215. template <typename Dtype>
  216. Dtype Blob<Dtype>::asum_diff() const { //与asum_data类似,计算diff_中元素的绝对值之和
  217. if (!diff_) { return 0; }
  218. switch (diff_->head()) {
  219. case SyncedMemory::HEAD_AT_CPU:
  220. return caffe_cpu_asum(count_, cpu_diff()); //cpu
  221. case SyncedMemory::HEAD_AT_GPU:
  222. case SyncedMemory::SYNCED:
  223. #ifndef CPU_ONLY
  224. {
  225. Dtype asum;
  226. caffe_gpu_asum(count_, gpu_diff(), &asum);
  227. return asum;
  228. }
  229. #else
  230. NO_GPU;
  231. #endif
  232. case SyncedMemory::UNINITIALIZED:
  233. return 0;
  234. default:
  235. LOG(FATAL) << "Unknown SyncedMemory head state: " << diff_->head();
  236. }
  237. return 0;
  238. }
  239. template <> unsigned int Blob<unsigned int>::sumsq_data() const {
  240. NOT_IMPLEMENTED;
  241. return 0;
  242. }
  243. template <> int Blob<int>::sumsq_data() const {
  244. NOT_IMPLEMENTED;
  245. return 0;
  246. }
  247. template <typename Dtype>
  248. Dtype Blob<Dtype>::sumsq_data() const { //与asum_data()类似,计算data_中元素的平方和
  249. Dtype sumsq;
  250. const Dtype* data;
  251. if (!data_) { return 0; }
  252. switch (data_->head()) {
  253. case SyncedMemory::HEAD_AT_CPU:
  254. data = cpu_data();
  255. sumsq = caffe_cpu_dot(count_, data, data); //向量data与data的内积
  256. break;
  257. case SyncedMemory::HEAD_AT_GPU:
  258. case SyncedMemory::SYNCED:
  259. #ifndef CPU_ONLY
  260. data = gpu_data();
  261. caffe_gpu_dot(count_, data, data, &sumsq); //gpu上计算
  262. #else
  263. NO_GPU;
  264. #endif
  265. break;
  266. case SyncedMemory::UNINITIALIZED:
  267. return 0;
  268. default:
  269. LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
  270. }
  271. return sumsq;
  272. }
  273. template <> unsigned int Blob<unsigned int>::sumsq_diff() const {
  274. NOT_IMPLEMENTED;
  275. return 0;
  276. }
  277. template <> int Blob<int>::sumsq_diff() const {
  278. NOT_IMPLEMENTED;
  279. return 0;
  280. }
  281. template <typename Dtype>
  282. Dtype Blob<Dtype>::sumsq_diff() const { //与sumsq_data()类似,计算diff_中元素的平方和
  283. Dtype sumsq;
  284. const Dtype* diff;
  285. if (!diff_) { return 0; }
  286. switch (diff_->head()) {
  287. case SyncedMemory::HEAD_AT_CPU:
  288. diff = cpu_diff();
  289. sumsq = caffe_cpu_dot(count_, diff, diff); //内积
  290. break;
  291. case SyncedMemory::HEAD_AT_GPU:
  292. case SyncedMemory::SYNCED:
  293. #ifndef CPU_ONLY
  294. diff = gpu_diff();
  295. caffe_gpu_dot(count_, diff, diff, &sumsq);
  296. break;
  297. #else
  298. NO_GPU;
  299. #endif
  300. case SyncedMemory::UNINITIALIZED:
  301. return 0;
  302. default:
  303. LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
  304. }
  305. return sumsq;
  306. }
  307. template <> void Blob<unsigned int>::scale_data(unsigned int scale_factor) {
  308. NOT_IMPLEMENTED;
  309. }
  310. template <> void Blob<int>::scale_data(int scale_factor) {
  311. NOT_IMPLEMENTED;
  312. }
  313. template <typename Dtype>
  314. void Blob<Dtype>::scale_data(Dtype scale_factor) { //给data_数据乘上一个系数
  315. Dtype* data;
  316. if (!data_) { return; }
  317. switch (data_->head()) {
  318. case SyncedMemory::HEAD_AT_CPU: //在cpu中
  319. data = mutable_cpu_data(); //数据在cpu上的指针
  320. caffe_scal(count_, scale_factor, data); //data = data * scale_factor (data中每个元素乘上scale_factor)
  321. return;
  322. case SyncedMemory::HEAD_AT_GPU:
  323. case SyncedMemory::SYNCED:
  324. #ifndef CPU_ONLY
  325. data = mutable_gpu_data();
  326. caffe_gpu_scal(count_, scale_factor, data); //gpu操作
  327. return;
  328. #else
  329. NO_GPU;
  330. #endif
  331. case SyncedMemory::UNINITIALIZED:
  332. return;
  333. default:
  334. LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
  335. }
  336. }
  337. template <> void Blob<unsigned int>::scale_diff(unsigned int scale_factor) {
  338. NOT_IMPLEMENTED;
  339. }
  340. template <> void Blob<int>::scale_diff(int scale_factor) {
  341. NOT_IMPLEMENTED;
  342. }
  343. template <typename Dtype>
  344. void Blob<Dtype>::scale_diff(Dtype scale_factor) { //与scale_data类似,给diff_中的元素乘上一个系数
  345. Dtype* diff;
  346. if (!diff_) { return; }
  347. switch (diff_->head()) {
  348. case SyncedMemory::HEAD_AT_CPU:
  349. diff = mutable_cpu_diff();
  350. caffe_scal(count_, scale_factor, diff); //diff = scale_factor * diff
  351. return;
  352. case SyncedMemory::HEAD_AT_GPU:
  353. case SyncedMemory::SYNCED:
  354. #ifndef CPU_ONLY
  355. diff = mutable_gpu_diff();
  356. caffe_gpu_scal(count_, scale_factor, diff);
  357. return;
  358. #else
  359. NO_GPU;
  360. #endif
  361. case SyncedMemory::UNINITIALIZED:
  362. return;
  363. default:
  364. LOG(FATAL) << "Unknown SyncedMemory head state: " << diff_->head();
  365. }
  366. }
  367. //判断当前blob的形状与BlobProto类型的other表示的形状是否一致
  368. //TODO BlobProto类定义在caffe.pb.h中,包含data和diff数据,但是暂时不了解它与blob的关系以及如何使用?
  369. template <typename Dtype>
  370. bool Blob<Dtype>::ShapeEquals(const BlobProto& other) {
  371. if (other.has_num() || other.has_channels() ||
  372. other.has_height() || other.has_width()) { //如果other中设置了num/channels/height/width的等属性
  373. // Using deprecated 4D Blob dimensions --
  374. // shape is (num, channels, height, width).
  375. // Note: we do not use the normal Blob::num(), Blob::channels(), etc.
  376. // methods as these index from the beginning of the blob shape, where legacy
  377. // parameter blobs were indexed from the end of the blob shape (e.g., bias
  378. // Blob shape (1 x 1 x 1 x N), IP layer weight Blob shape (1 x 1 x M x N)).
  379. return shape_.size() <= 4 &&
  380. LegacyShape(-4) == other.num() &&
  381. LegacyShape(-3) == other.channels() && //LegacyShape(-3)表示shape_中的倒数第3个维度的大小
  382. LegacyShape(-2) == other.height() &&
  383. LegacyShape(-1) == other.width(); //shape的维度必须小于等于4,且n,c,h,w均与other的相等
  384. }
  385. vector<int> other_shape(other.shape().dim_size()); //创建vector变量,将other中的各个维度的大小存入
  386. for (int i = 0; i < other.shape().dim_size(); ++i) {
  387. other_shape[i] = other.shape().dim(i); //第i个维度
  388. }
  389. return shape_ == other_shape; //返回两者是否相等
  390. }
  391. //从source中拷贝数据至当前的blob中,copy_diff表示拷贝的是data_数据还是diff_数据
  392. //reshape表示当前blob是否需要进行reshape操作
  393. template <typename Dtype>
  394. void Blob<Dtype>::CopyFrom(const Blob& source, bool copy_diff, bool reshape) {
  395. if (source.count() != count_ || source.shape() != shape_) { //source中数据的大小和形状与当前blob的不一致
  396. if (reshape) { //允许修改
  397. ReshapeLike(source); //修改当前blob的形状
  398. } else {
  399. LOG(FATAL) << "Trying to copy blobs of different sizes."; //形状不一致还不允许reshape,返回错误
  400. }
  401. }
  402. switch (Caffe::mode()) { //当前运行的模式,cpu还是gpu模式
  403. case Caffe::GPU:
  404. if (copy_diff) { //拷贝梯度diff_数据
  405. caffe_copy(count_, source.gpu_diff(),
  406. static_cast<Dtype*>(diff_->mutable_gpu_data())); //将source的diff在gpu上的数据拷贝至当前blob的diff在gpu的显存中,拷贝大小为count_
  407. } else {
  408. caffe_copy(count_, source.gpu_data(),
  409. static_cast<Dtype*>(data_->mutable_gpu_data())); //将source的data在gpu上的数据拷贝至当前blob的data在gpu的显存中,拷贝大小为count_
  410. }
  411. break;
  412. case Caffe::CPU: //cpu模式
  413. if (copy_diff) {
  414. caffe_copy(count_, source.cpu_diff(),
  415. static_cast<Dtype*>(diff_->mutable_cpu_data())); //将source的diff在cpu上的数据拷贝至当前blob的diff在cpu的内存中,拷贝大小为count_
  416. } else {
  417. caffe_copy(count_, source.cpu_data(),
  418. static_cast<Dtype*>(data_->mutable_cpu_data())); //将source的data在cpu上的数据拷贝至当前blob的data在cpu的内存中,拷贝大小为count_
  419. }
  420. break;
  421. default:
  422. LOG(FATAL) << "Unknown caffe mode."; //未知模式返回错误
  423. }
  424. }
  425. //从BlobProto类型的变量中拷贝data和diff数据
  426. //如果reshape为true,需要保证当前blob与proto的总体数据大小一致,
  427. //如果reshape为false,需要保证当前blob与proto的中数据的各个维度的大小一致
  428. template <typename Dtype>
  429. void Blob<Dtype>::FromProto(const BlobProto& proto, bool reshape) {
  430. if (reshape) { //需要reshape
  431. vector<int> shape; //将proto的各个维度保存在shape中
  432. if (proto.has_num() || proto.has_channels() ||
  433. proto.has_height() || proto.has_width()) {
  434. // Using deprecated 4D Blob dimensions --
  435. // shape is (num, channels, height, width).
  436. shape.resize(4); //只有4个维度
  437. shape[0] = proto.num();
  438. shape[1] = proto.channels();
  439. shape[2] = proto.height();
  440. shape[3] = proto.width();
  441. } else {
  442. shape.resize(proto.shape().dim_size()); //保存所有维度的大小
  443. for (int i = 0; i < proto.shape().dim_size(); ++i) {
  444. shape[i] = proto.shape().dim(i);
  445. }
  446. }
  447. Reshape(shape); //修改当前blob的形状
  448. } else {
  449. CHECK(ShapeEquals(proto)) << "shape mismatch (reshape not set)"; //不需reshape,检查各个维度大小是否一致
  450. }
  451. // copy data
  452. Dtype* data_vec = mutable_cpu_data(); //当前blob中data的指针
  453. if (proto.double_data_size() > 0) { //如果是双精度数据,double类型
  454. CHECK_EQ(count_, proto.double_data_size()); //检查数据大小是否一致
  455. for (int i = 0; i < count_; ++i) {
  456. data_vec[i] = proto.double_data(i); //拷贝
  457. }
  458. } else { //单精度数据,float类型
  459. CHECK_EQ(count_, proto.data_size()); //检查大小
  460. for (int i = 0; i < count_; ++i) {
  461. data_vec[i] = proto.data(i); //复制
  462. }
  463. }
  464. if (proto.double_diff_size() > 0) { //操作与data_的类似,拷贝diff数据至当前blob的diff_中
  465. CHECK_EQ(count_, proto.double_diff_size());
  466. Dtype* diff_vec = mutable_cpu_diff();
  467. for (int i = 0; i < count_; ++i) {
  468. diff_vec[i] = proto.double_diff(i);
  469. }
  470. } else if (proto.diff_size() > 0) {
  471. CHECK_EQ(count_, proto.diff_size());
  472. Dtype* diff_vec = mutable_cpu_diff();
  473. for (int i = 0; i < count_; ++i) {
  474. diff_vec[i] = proto.diff(i);
  475. }
  476. }
  477. }
  478. //将当前blob的data数据保存在BlobProto类型的变量中(双精度数据区),write_diff表示是否需要保存diff数据
  479. template <>
  480. void Blob<double>::ToProto(BlobProto* proto, bool write_diff) const {
  481. proto->clear_shape(); //清空proto中的shape数据
  482. for (int i = 0; i < shape_.size(); ++i) {
  483. proto->mutable_shape()->add_dim(shape_[i]); //将当前blob数据的形状保存在proto中
  484. }
  485. proto->clear_double_data(); //清空之前的data和diff数据(双精度类型)
  486. proto->clear_double_diff();
  487. const double* data_vec = cpu_data(); //当前blob的data在cpu上的数据
  488. for (int i = 0; i < count_; ++i) {
  489. proto->add_double_data(data_vec[i]); //添加进proto
  490. }
  491. if (write_diff) { //需要保存diff数据
  492. const double* diff_vec = cpu_diff();
  493. for (int i = 0; i < count_; ++i) {
  494. proto->add_double_diff(diff_vec[i]); //写入proto中
  495. }
  496. }
  497. }
  498. //与上面的Blob<double>::ToProto()类似,此处是将blob中的数据写入proto的单精度数据区
  499. template <>
  500. void Blob<float>::ToProto(BlobProto* proto, bool write_diff) const {
  501. proto->clear_shape();
  502. for (int i = 0; i < shape_.size(); ++i) {
  503. proto->mutable_shape()->add_dim(shape_[i]);
  504. }
  505. proto->clear_data();
  506. proto->clear_diff();
  507. const float* data_vec = cpu_data();
  508. for (int i = 0; i < count_; ++i) {
  509. proto->add_data(data_vec[i]); //存入float类型的数据区
  510. }
  511. if (write_diff) {
  512. const float* diff_vec = cpu_diff();
  513. for (int i = 0; i < count_; ++i) {
  514. proto->add_diff(diff_vec[i]);
  515. }
  516. }
  517. }

blob.hpp源码

  1. const int kMaxBlobAxes = 32; //数据维度个数的最大值,shape_.size()不能超过改值
  2. namespace caffe {
  3. /**
  4. * @brief A wrapper around SyncedMemory holders serving as the basic
  5. * computational unit through which Layer%s, Net%s, and Solver%s
  6. * interact.
  7. *
  8. * TODO(dox): more thorough description.
  9. */
  10. template <typename Dtype>
  11. class Blob {
  12. public:
  13. Blob()
  14. : data_(), diff_(), count_(0), capacity_(0) {}
  15. /// @brief Deprecated; use <code>Blob(const vector<int>& shape)</code>.
  16. explicit Blob(const int num, const int channels, const int height,
  17. const int width);
  18. explicit Blob(const vector<int>& shape);
  19. /// @brief Deprecated; use <code>Reshape(const vector<int>& shape)</code>.
  20. void Reshape(const int num, const int channels, const int height,
  21. const int width);
  22. /**
  23. * @brief Change the dimensions of the blob, allocating new memory if
  24. * necessary.
  25. *
  26. * This function can be called both to create an initial allocation
  27. * of memory, and to adjust the dimensions of a top blob during Layer::Reshape
  28. * or Layer::Forward. When changing the size of blob, memory will only be
  29. * reallocated if sufficient memory does not already exist, and excess memory
  30. * will never be freed.
  31. *
  32. * Note that reshaping an input blob and immediately calling Net::Backward is
  33. * an error; either Net::Forward or Net::Reshape need to be called to
  34. * propagate the new input shape to higher layers.
  35. */
  36. void Reshape(const vector<int>& shape);
  37. void Reshape(const BlobShape& shape);
  38. void ReshapeLike(const Blob& other);
  39. inline string shape_string() const { //输出包含各维度信息的字符串,"n c h w (count_)"
  40. ostringstream stream;
  41. for (int i = 0; i < shape_.size(); ++i) {
  42. stream << shape_[i] << " ";
  43. }
  44. stream << "(" << count_ << ")";
  45. return stream.str();
  46. }
  47. inline const vector<int>& shape() const { return shape_; } //返回blob数据的形状
  48. /**
  49. * @brief Returns the dimension of the index-th axis (or the negative index-th
  50. * axis from the end, if index is negative).
  51. *
  52. * @param index the axis index, which may be negative as it will be
  53. * "canonicalized" using CanonicalAxisIndex.
  54. * Dies on out of range index.
  55. */
  56. inline int shape(int index) const {
  57. return shape_[CanonicalAxisIndex(index)]; //返回blob数据的第index维的大小
  58. }
  59. inline int num_axes() const { return shape_.size(); } //返回数据的维度的个数
  60. inline int count() const { return count_; } //返回数据的总体大小
  61. /**
  62. * @brief Compute the volume of a slice; i.e., the product of dimensions
  63. * among a range of axes.
  64. *
  65. * @param start_axis The first axis to include in the slice.
  66. *
  67. * @param end_axis The first axis to exclude from the slice.
  68. */
  69. inline int count(int start_axis, int end_axis) const { //返回第start_axis维到第end_axis维之间的数据的大小
  70. CHECK_LE(start_axis, end_axis); //检查 start_axis <= end_axis
  71. CHECK_GE(start_axis, 0); //检查 start_axis >= 0
  72. CHECK_GE(end_axis, 0); //检查 end_axis >= 0
  73. CHECK_LE(start_axis, num_axes()); //检查 start_axis <= shape_.size()
  74. CHECK_LE(end_axis, num_axes()); //检查 end_axis <= shape_.size()
  75. int count = 1;
  76. for (int i = start_axis; i < end_axis; ++i) {
  77. count *= shape(i); //积
  78. }
  79. return count;
  80. }
  81. /**
  82. * @brief Compute the volume of a slice spanning from a particular first
  83. * axis to the final axis.
  84. *
  85. * @param start_axis The first axis to include in the slice.
  86. */
  87. inline int count(int start_axis) const { //返回第start_axis维到最后维之间的数据的大小
  88. return count(start_axis, num_axes());
  89. }
  90. /**
  91. * @brief Returns the 'canonical' version of a (usually) user-specified axis,
  92. * allowing for negative indexing (e.g., -1 for the last axis).
  93. *
  94. * @param axis_index the axis index.
  95. * If 0 <= index < num_axes(), return index.
  96. * If -num_axes <= index <= -1, return (num_axes() - (-index)),
  97. * e.g., the last axis index (num_axes() - 1) if index == -1,
  98. * the second to last if index == -2, etc.
  99. * Dies on out of range index.
  100. */
  101. inline int CanonicalAxisIndex(int axis_index) const { //输入axis_index(可正可负),返回axis_index在shape_对应的实际索引
  102. CHECK_GE(axis_index, -num_axes())
  103. << "axis " << axis_index << " out of range for " << num_axes()
  104. << "-D Blob with shape " << shape_string(); //检查 axis_index >= -num_axes()
  105. CHECK_LT(axis_index, num_axes())
  106. << "axis " << axis_index << " out of range for " << num_axes()
  107. << "-D Blob with shape " << shape_string(); //检查 axis_index < num_axes()
  108. if (axis_index < 0) {
  109. return axis_index + num_axes(); //为负数时,表示倒数第-axis_index个,计算对应的正向时的索引
  110. }
  111. return axis_index; //正数不处理,直接返回
  112. }
  113. /// @brief Deprecated legacy shape accessor num: use shape(0) instead.
  114. inline int num() const { return LegacyShape(0); } //num()/channels()/height()/width()这四个函数已不建议使用,使用shape(i)替代
  115. /// @brief Deprecated legacy shape accessor channels: use shape(1) instead.
  116. inline int channels() const { return LegacyShape(1); }
  117. /// @brief Deprecated legacy shape accessor height: use shape(2) instead.
  118. inline int height() const { return LegacyShape(2); }
  119. /// @brief Deprecated legacy shape accessor width: use shape(3) instead.
  120. inline int width() const { return LegacyShape(3); }
  121. inline int LegacyShape(int index) const { //返回shape_中的第index个维度的大小,index可以为负数
  122. CHECK_LE(num_axes(), 4)
  123. << "Cannot use legacy accessors on Blobs with > 4 axes."; //blob中数据的维度超过4时,不能使用这种方式
  124. CHECK_LT(index, 4); //检查index的范围
  125. CHECK_GE(index, -4);
  126. //对于小于4维的数据,如果给出的索引超过数据的维度范围但是在4范围内,那么返回1.相当于将数据缺少的维度大小用1填充
  127. if (index >= num_axes() || index < -num_axes()) {
  128. // Axis is out of range, but still in [0, 3] (or [-4, -1] for reverse
  129. // indexing) -- this special case simulates the one-padding used to fill
  130. // extraneous axes of legacy blobs.
  131. return 1;
  132. }
  133. return shape(index);
  134. }
  135. inline int offset(const int n, const int c = 0, const int h = 0, const int w = 0) const { //返回第(n,c,h,w)个数据的偏移位置
  136. CHECK_GE(n, 0); //对输入参数进行检查
  137. CHECK_LE(n, num());
  138. CHECK_GE(channels(), 0);
  139. CHECK_LE(c, channels());
  140. CHECK_GE(height(), 0);
  141. CHECK_LE(h, height());
  142. CHECK_GE(width(), 0);
  143. CHECK_LE(w, width());
  144. return ((n * channels() + c) * height() + h) * width() + w;
  145. }
  146. inline int offset(const vector<int>& indices) const { //同理,返回indices中指示的数据的偏移位置
  147. CHECK_LE(indices.size(), num_axes()); //检查indices的长度是否与shape_匹配
  148. int offset = 0;
  149. for (int i = 0; i < num_axes(); ++i) {
  150. offset *= shape(i);
  151. if (indices.size() > i) {
  152. CHECK_GE(indices[i], 0);
  153. CHECK_LT(indices[i], shape(i));
  154. offset += indices[i]; //从高维开始,累加得到其偏移位置
  155. }
  156. }
  157. return offset;
  158. }
  159. /**
  160. * @brief Copy from a source Blob.
  161. *
  162. * @param source the Blob to copy from
  163. * @param copy_diff if false, copy the data; if true, copy the diff
  164. * @param reshape if false, require this Blob to be pre-shaped to the shape
  165. * of other (and die otherwise); if true, Reshape this Blob to other's
  166. * shape if necessary
  167. */
  168. void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false,
  169. bool reshape = false);
  170. inline Dtype data_at(const int n, const int c, const int h, //返回data中(n,c,h,w)处的数据值
  171. const int w) const {
  172. return cpu_data()[offset(n, c, h, w)];
  173. }
  174. inline Dtype diff_at(const int n, const int c, const int h, //返回diff中(n,c,h,w)处的数据值
  175. const int w) const {
  176. return cpu_diff()[offset(n, c, h, w)];
  177. }
  178. inline Dtype data_at(const vector<int>& index) const { //返回data中index处的数据值
  179. return cpu_data()[offset(index)];
  180. }
  181. inline Dtype diff_at(const vector<int>& index) const { //返回diff中index处的数据值
  182. return cpu_diff()[offset(index)];
  183. }
  184. inline const shared_ptr<SyncedMemory>& data() const { //返回存放data在cpu上的数据指针
  185. CHECK(data_);
  186. return data_;
  187. }
  188. inline const shared_ptr<SyncedMemory>& diff() const { //返回存放diff在cpu上的数据指针
  189. CHECK(diff_);
  190. return diff_;
  191. }
  192. const Dtype* cpu_data() const;
  193. void set_cpu_data(Dtype* data);
  194. const int* gpu_shape() const;
  195. const Dtype* gpu_data() const;
  196. void set_gpu_data(Dtype* data);
  197. const Dtype* cpu_diff() const;
  198. const Dtype* gpu_diff() const;
  199. Dtype* mutable_cpu_data();
  200. Dtype* mutable_gpu_data();
  201. Dtype* mutable_cpu_diff();
  202. Dtype* mutable_gpu_diff();
  203. void Update();
  204. void FromProto(const BlobProto& proto, bool reshape = true);
  205. void ToProto(BlobProto* proto, bool write_diff = false) const;
  206. /// @brief Compute the sum of absolute values (L1 norm) of the data.
  207. Dtype asum_data() const;
  208. /// @brief Compute the sum of absolute values (L1 norm) of the diff.
  209. Dtype asum_diff() const;
  210. /// @brief Compute the sum of squares (L2 norm squared) of the data.
  211. Dtype sumsq_data() const;
  212. /// @brief Compute the sum of squares (L2 norm squared) of the diff.
  213. Dtype sumsq_diff() const;
  214. /// @brief Scale the blob data by a constant factor.
  215. void scale_data(Dtype scale_factor);
  216. /// @brief Scale the blob diff by a constant factor.
  217. void scale_diff(Dtype scale_factor);
  218. /**
  219. * @brief Set the data_ shared_ptr to point to the SyncedMemory holding the
  220. * data_ of Blob other -- useful in Layer%s which simply perform a copy
  221. * in their Forward pass.
  222. *
  223. * This deallocates the SyncedMemory holding this Blob's data_, as
  224. * shared_ptr calls its destructor when reset with the "=" operator.
  225. */
  226. void ShareData(const Blob& other);
  227. /**
  228. * @brief Set the diff_ shared_ptr to point to the SyncedMemory holding the
  229. * diff_ of Blob other -- useful in Layer%s which simply perform a copy
  230. * in their Forward pass.
  231. *
  232. * This deallocates the SyncedMemory holding this Blob's diff_, as
  233. * shared_ptr calls its destructor when reset with the "=" operator.
  234. */
  235. void ShareDiff(const Blob& other);
  236. bool ShapeEquals(const BlobProto& other);
  237. protected:
  238. shared_ptr<SyncedMemory> data_; //存放数据,用于前向计算
  239. shared_ptr<SyncedMemory> diff_; //存放梯度数据,用于反向传播
  240. shared_ptr<SyncedMemory> shape_data_; //数据的各维度大小
  241. vector<int> shape_; //数据的各维度大小,值与shape_data_中的各个值一致
  242. //capacity_表示data.size()/sizeof(Dtype), 表示data_或diff_中能存放的数据的最大个数
  243. //count_表示当前data_或diff_中有效的数据的个数,总有 count_ <= capacity_
  244. int count_; //当前数据的总个数(各个维度的相乘)
  245. int capacity_; //data_或diff_中能容纳的数据的大小
  246. DISABLE_COPY_AND_ASSIGN(Blob);
  247. }; // class Blob
  248. } // namespace caffe

小结

  1. 网络上关于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_中实际有效的数据的个数。
  2. 代码中有部分内容(如BlobProto类的作用和与Blob的关系)笔者还不太了解,待后续更新。

Caffe的源码笔者是第一次阅读,一边阅读一边记录,对代码的理解和分析可能会存在错误或遗漏,希望各位读者批评指正,谢谢支持!

Caffe源码-Blob类的更多相关文章

  1. Caffe源码-SyncedMemory类

    SyncedMemory类简介 最近在阅读caffe源码,代码来自BVLC/caffe,基本是参照网络上比较推荐的 Blob-->Layer-->Net-->Solver 的顺序来分 ...

  2. Caffe源码-Solver类

    Solver类简介 Net类中实现了网络的前向/反向计算和参数更新,而Solver类中则是对此进行进一步封装,包含可用于逐次训练网络的Step()函数,和用于求解网络的优化解的Solve()函数,同时 ...

  3. Caffe源码-SGDSolver类

    SGDSolver类简介 Solver类用于网络参数的更新,而SGDSolver类实现了优化方法中的随机梯度下降法(stochastic gradient descent),此外还具备缩放.正则化梯度 ...

  4. Caffe源码-Net类(下)

    net.cpp部分源码 // 接着上一篇博客的介绍,此部分为Net类中前向反向计算函数,以及一些与HDF5文件或proto文件相互转换的函数. template <typename Dtype& ...

  5. Caffe源码-Net类(上)

    Net类简介 Net类主要处理各个Layer之间的输入输出数据和参数数据共享等的关系.由于Net类的代码较多,本次主要介绍网络初始化部分的代码.Net类在初始化的时候将各个Layer的输出blob都统 ...

  6. Caffe源码-Layer类

    Layer类简介 Layer是caffe中搭建网络的基本单元,caffe代码中包含大量Layer基类派生出来的各种各样的层,各自通过虚函数 Forward() 和 Backward() 实现自己的功能 ...

  7. caffe源码整个训练过程

    Caffe源码 Blob protected: shared_ptr<SyncedMemory> data_; shared_ptr<SyncedMemory> diff_; ...

  8. Caffe源码-几种优化算法

    SGD简介 caffe中的SGDSolver类中实现了带动量的梯度下降法,其原理如下,\(lr\)为学习率,\(m\)为动量参数. 计算新的动量:history_data = local_rate * ...

  9. Caffe源码理解2:SyncedMemory CPU和GPU间的数据同步

    目录 写在前面 成员变量的含义及作用 构造与析构 内存同步管理 参考 博客:blog.shinelee.me | 博客园 | CSDN 写在前面 在Caffe源码理解1中介绍了Blob类,其中的数据成 ...

随机推荐

  1. webpack-dev-middleware 和 webpack-hot-middleware 配置开发环境和生产环境;webpack脚手架;仿vue-cli

    webpack-dev-server更新后自带express服务器,已经不需要自己搭建.vue-cli从17年底左右也换成了最新的webpack-dev-server,而不是用webpack-dev- ...

  2. python变量、输入输出-xdd

    1.注释 #输入身高,计算BMI 注释1,单行注释... 注释2,多行注释xiedong.. 2.中文编码声明,UTF-8编码声明 # coding=编码 # coding=utf-8 3.建议每行不 ...

  3. SpringMVC请求参数接收总结(一)

    前提 在日常使用SpringMVC进行开发的时候,有可能遇到前端各种类型的请求参数,这里做一次相对全面的总结.SpringMVC中处理控制器参数的接口是HandlerMethodArgumentRes ...

  4. cbv请求分析

    CBV源码分析 DRF中中所有视图都是基于CBV形式完成, 所以分析其cbv源码, 了解drf的基本请求流程就比较有必要了. urls.py """下面是一个通用的url ...

  5. Linux的ftp安装及使用

    FTP服务器的安装与配置(Ubuntu)1.查询是否安装vsftpd:  rpm -qa |grep vsftpd (rpm的安装:apt-get install rpm) 或者查询当前ftp进程:p ...

  6. Python实现简单框架及三大框架对比

    手撸web框架 简单的请求响应实现 要实现最简单的web框架,首先要对网络熟悉,首先HTTP协议是应用层的协议,只要我们给数据加上HTTP格式的响应报头,我们的数据就能基于socket进行实现了 im ...

  7. 网络层 IP

    网络层 -- 数据包 网络层作用 解决什么问题? 在讲网络层之前,其实基于广播的这种通信就可以实现全世界通信了,你吼一声,如果全世界是一个局域网,全世界的计算机肯定可以听得见,从理论上似乎行得通,如果 ...

  8. maven中的setting文件

      localRepository默认jar包下载到本地哪个目录下 pluginGroups 把自己的插件放在这里进行管理 这样不用写groupId和artifactId     一个生命周期包含很多 ...

  9. 重写系统自带tabbar出现的 代理错误

  10. Python-车牌识别

    一.车牌识别系统的用途与技术车牌识别系统(Vehicle License Plate Recognition,VLPR) 是计算机视频图像识别技术在车辆牌照识别中的一种应用.车牌识别在高速公路车辆管理 ...