Caffe最优化求解过程

将前面几天讲述的不同Layer组合起来就可以构建起完整的CNN/DNN。今天将从Caffe的Solver类入手,对Caffe训练时的流程做深入分析,也就是看Caffe实际是如何“动”起来的。

求解器是什么

从前两天内容我们学习到,Net己经完成部分学习任务(数据前向传播、误差反向传播),而CNN剩下有监督的优化过程、利用每层的梯度生成权值增量则由求解器(Solver)负责.

求解器负责对模型优化,它的KPI(Key Performance Indicator,关键绩效指你,某公司常用的一种员工绩效评定方式)就是让损失函数达到全局最小。

求解器的特性如下:

  • 负责记录优化过程,创建用于学习的训练网络和用于评估学习效果的测试网络。
  • 调用Forward\(\rightarrow\)调用Backward\(\rightarrow\)更新权值,反复迭代优化模型。
  • 周期性的评估测试网络
  • 在优化过程中为模型,求解器状态打快照.

为了让权值从初始化状态向着更好的模型前进,求解器在每次迭代中做了如下事情:

  • 调用Net的前向传播函数来计算输出和损失函数。
  • 调用Net的反向传播函数来计算梯度。
  • 根据求解器方法,将梯度转换为权值增量
  • 根据学习速率、历史权值、所用方法更新求解器状态。

求解器是如何实现的

在卷积神经网络中,有两种类型的层需要学习:卷积层和全连接层(统称权值层,因为它们都有weight参数)。在设计求解器时,学习速率参数的设置也是针对这两个层的

在caffe中我们要适当把握度,控制收敛的参数---学习速率.

我们来具体看一下Caffe是如何对权值学习做到“不偏不倚”的。

算法描述

Caffe中的求解器有以下几种:

  • 随机梯度下降法(Stochastic Gradient Descent, SGD),最常用的一种
  • AdaDelta
  • 自适应梯度法(Adaptive Gradient, ADAGRAD)
  • Adam
  • Nesterov加速梯度法(Nesterov’s Accelerated Gradient, NAG)
  • RMSprop

求解器方法重点是最小化损失函数的全局优化问题,对于数据集D,优化目标是在全数据集D上损失函数平均值:
\[
L(W)=\frac{1}{|{D}|}\sum^{|D|}_{i}{f_w(X^{(i)}) + \lambda{r}(W)}
\]

其中,\(f_w(X^{(i)})\)是在数据实例\(X^{(i)\)上的损失函数,\(r(W)\)为规整项,\(\lambda\)为规整项的权重。数据集\(D\)可能非常大,工程上一般在每次迭代中使用这个目标函数的随机逼近,即小批量数据\(N<<|D|\)个数据实例:

2017/7/6 posted in  Caffe最优化求解过程

SoftmaxWithLossLayer的实现

我们找到SoftmaxWithLossLayer.hpp文件查看声明,如下:


//将实数预测向量通过Softmax计算获得每个类别的概率分布
//这个类比单独SoftmaxLayer + MultinomialLogisticLossLayer在梯度数值计算上更加稳定
//Test阶段,这个层可以直接用SoftmaxLayer代替
/**
 *输入Blob 1为预测结果,形状为N x K x 1 x 1,K为总类别数目,N为批量数。取值范围为(-Inf, Inf),
 *表示每个类别获得的分类score,值越大说明输入图像与该类别越接近
 *输入Blob 2为真实标签,形状为N x 1 x 1 x 1
 *输出Blob为计算得到的交叉熵分类损失E,形状为1 x 1 x 1 x 1
**/
template <typename Dtype>
class SoftmaxWithLossLayer : public LossLayer<Dtype> {
 public:
   /**
    * @param param provides LossParameter loss_param, with options:
    *  - ignore_label (optional)
    *    Specify a label value that should be ignored when computing the loss.
    *  - normalize (optional, default true)
    *    If true, the loss is normalized by the number of (nonignored) labels
    *    present; otherwise the loss is simply summed over spatial locations.
    */
    explicit SoftmaxWithLossLayer(const LayerParameter& param)
      : LossLayer<Dtype>(param) {}
  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual inline const char* type() const { return "SoftmaxWithLoss"; }
  virtual inline int ExactNumTopBlobs() const { return -1; }
  virtual inline int MinTopBlobs() const { return 1; }
  virtual inline int MaxTopBlobs() const { return 2; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
      
/**
   * @brief Computes the softmax loss error gradient w.r.t. the predictions.
   *
   * Gradients cannot be computed with respect to the label inputs (bottom[1]),
   * so this method ignores bottom[1] and requires !propagate_down[1], crashing
   * if propagate_down[1] is set.
   *
   * @param top output Blob vector (length 1), providing the error gradient with
   *      respect to the outputs
   *   -# @f$ (1 \times 1 \times 1 \times 1) @f$
   *      This Blob's diff will simply contain the loss_weight* @f$ \lambda @f$,
   *      as @f$ \lambda @f$ is the coefficient of this layer's output
   *      @f$\ell_i@f$ in the overall Net loss
   *      @f$ E = \lambda_i \ell_i + \mbox{other loss terms}@f$; hence
   *      @f$ \frac{\partial E}{\partial \ell_i} = \lambda_i @f$.
   *      (*Assuming that this top Blob is not used as a bottom (input) by any
   *      other layer of the Net.)
   * @param propagate_down see Layer::Backward.
   *      propagate_down[1] must be false as we can't compute gradients with
   *      respect to the labels.
   * @param bottom input Blob vector (length 2)
   *   -# @f$ (N \times C \times H \times W) @f$
   *      the predictions @f$ x @f$; Backward computes diff
   *      @f$ \frac{\partial E}{\partial x} @f$
   *   -# @f$ (N \times 1 \times 1 \times 1) @f$
   *      the labels -- ignored as we can't compute their error gradients
   */
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
      
/// Read the normalization mode parameter and compute the normalizer based
  /// on the blob size.  If normalization_mode is VALID, the count of valid
  /// outputs will be read from valid_count, unless it is -1 in which case
  /// all outputs are assumed to be valid.
  virtual Dtype get_normalizer(
      LossParameter_NormalizationMode normalization_mode, int valid_count);

  /// The internal SoftmaxLayer used to map predictions to a distribution.(内置一个SoftmaxLayer对象)
  shared_ptr<Layer<Dtype> > softmax_layer_;
  /// prob stores the output probability predictions from the SoftmaxLayer.
  Blob<Dtype> prob_;
  /// bottom vector holder used in call to the underlying SoftmaxLayer::Forward
  vector<Blob<Dtype>*> softmax_bottom_vec_;
  /// top vector holder used in call to the underlying SoftmaxLayer::Forward
  vector<Blob<Dtype>*> softmax_top_vec_;
  /// Whether to ignore instances with a certain label.
  bool has_ignore_label_;
  /// The label indicating that an instance should be ignored.
  int ignore_label_;
  /// How to normalize the output loss.
  LossParameter_NormalizationMode normalization_;

  int softmax_axis_, outer_num_, inner_num_;
};

之后我们来看实现的.cpp文件:

第一个是SetUp函数.
```c++

template
void SoftmaxWithLossLayer::LayerSetUp(
const vector>& bottom, const vector>& top) {
LossLayer::LayerSetUp(bottom, top);
//创建时动态修改本层的LayerParameter参数,适应SoftmaxLayer
LayerParameter softmax_param(this->layer_param_);
softmax_param.set_type("Softmax");
softmax_layer_ = LayerRegistry::CreateLayer(softmax_param);
softmax_bottom_vec_.clear();
softmax_bottom_vec_.push_back(bottom[0]);
softmax_top_vec_.clear();
softmax_top_vec_.push_back(&prob_);
softmax_layer_->SetUp(softmax_bottom_vec_, softmax_top_vec_);

has_ignore_label_ =
this->layer_param_.loss_param().has_ignore_label();
if (has_ignore_label_) {
ignore_label_ = this->layer_param_.loss_param().ignore_label();
}
if (!this->layer_param_.loss_param().has_normalization() &&
this->layer_param_.loss_param().has_normalize()) {
normalization_ = this->layer_param_.loss_param().normalize() ?
LossParameter_NormalizationMode_VALID :
LossParameter_NormalizationMode_BATCH_SIZE;
} else {
normalization_ = this->layer_param_.loss_param().normalization();
}
}

可见,在SetUp阶段,创建了内部SoftmaxLayer对象并配置了其输入/输出Blob,然后调用该对象的SetUp函数。


下面看看`SoftmaxWithLossLayer`的前向传播函数:

```c++

template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::Forward_cpu(
    const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
  // The forward pass computes the softmax prob values.(内部SoftmaxLayer的前向传播计算)
  softmax_layer_->Forward(softmax_bottom_vec_, softmax_top_vec_);
  //获得概率密度
  const Dtype* prob_data = prob_.cpu_data();
  //获得标签值
  const Dtype* label = bottom[1]->cpu_data();
  int dim = prob_.count() / outer_num_;
  int count = 0;
  Dtype loss = 0;
  for (int i = 0; i < outer_num_; ++i) {
    for (int j = 0; j < inner_num_; j++) {
      const int label_value = static_cast<int>(label[i * inner_num_ + j]);
      if (has_ignore_label_ && label_value == ignore_label_) {
        continue;
      }
      DCHECK_GE(label_value, 0);
      DCHECK_LT(label_value, prob_.shape(softmax_axis_));
      //计算损失函数-log(prob[label])
      loss -= log(std::max(prob_data[i * dim + label_value * inner_num_ + j],
                           Dtype(FLT_MIN)));
      ++count;
    }
  }
  //设置输出Blob值
  top[0]->mutable_cpu_data()[0] = loss / get_normalizer(normalization_, count);
  if (top.size() == 2) {
    top[1]->ShareData(prob_);
  }
}


可见通过内部SoftmaxLayer对象非常简洁。我们再看一下 Backward计算:


template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
  if (propagate_down[1]) {
   //label输入Blob不做反向传播
    LOG(FATAL) << this->type()
               << " Layer cannot backpropagate to label inputs.";
  }
  if (propagate_down[0]) {
    Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
    const Dtype* prob_data = prob_.cpu_data();
    //将概率密度拷贝输入Blob的diff域
    caffe_copy(prob_.count(), prob_data, bottom_diff);
    const Dtype* label = bottom[1]->cpu_data();
    int dim = prob_.count() / outer_num_;
    int count = 0;
    for (int i = 0; i < outer_num_; ++i) {
      for (int j = 0; j < inner_num_; ++j) {
        const int label_value = static_cast<int>(label[i * inner_num_ + j]);
        if (has_ignore_label_ && label_value == ignore_label_) {
          for (int c = 0; c < bottom[0]->shape(softmax_axis_); ++c) {
            bottom_diff[i * dim + c * inner_num_ + j] = 0;
          }
        } else {
        //在输入Blob的diff域,计算当前槪率密度与理想概率密度(label 对应类别概率为1,其他类别 概肀为0)之差,实现误差反向传播
          bottom_diff[i * dim + label_value * inner_num_ + j] -= 1;
          ++count;
        }
      }
    }
    // Scale gradient(适当的缩放)
    Dtype loss_weight = top[0]->cpu_diff()[0] /
                        get_normalizer(normalization_, count);
    caffe_scal(prob_.count(), loss_weight, bottom_diff);
  }
}

通过对Caffe损失层的研究,我们了解到,前向传播阶段数据逐层传播,到损失层计算预测概率密度和损失函数;而反向传播阶段则从损失层开始,由预测概率密度与理想概率密度(这就是有监督学习的佐证)差值得到误差(diff),然后将由下一节内容逐层反向传播。我们已经知道一个Blob是由data和diff两部分构成的,如果说数据读取层是data之源,那么损失层就是diff之源。

反向传播的实现

Caffe Net数据结构中的'Backward函数具体的声明和实现文件为net.hppnet.cpp:

//从第start层反向传播到达第end层
template <typename Dtype>
void Net<Dtype>::BackwardFromTo(int start, int end) {
  CHECK_GE(end, 0);
  CHECK_LT(start, layers_.size());
  for (int i = start; i >= end; --i) {
    for (int c = 0; c < before_backward_.size(); ++c) {
      before_backward_[c]->run(i);
    }
    if (layer_need_backward_[i]) {
    //遍历每个居,调用相应的Backward函数
      layers_[i]->Backward(
          top_vecs_[i], bottom_need_backward_[i], bottom_vecs_[i]);
      if (debug_info_) { BackwardDebugInfo(i); }
    }
    for (int c = 0; c < after_backward_.size(); ++c) {
      after_backward_[c]->run(i);
    }
  }
}

//从第start层幵始到第一层的反向传播过程
template <typename Dtype>
void Net<Dtype>::BackwardFrom(int start) {
  BackwardFromTo(start, 0);
}

//从最后一层开始到第end层的反向传播过程
template <typename Dtype>
void Net<Dtype>::BackwardTo(int end) {
  BackwardFromTo(layers_.size() - 1, end);
}

//整个网络的反向传播过程
template <typename Dtype>
void Net<Dtype>::Backward() {
  BackwardFromTo(layers_.size() - 1, 0);
  if (debug_info_) {
  //如果打幵了调试信息开关(在prototxt中设定),则计算所有权值的data/diff的L1、L2范数,监控其变化情况,避免发散
    Dtype asum_data = 0, asum_diff = 0, sumsq_data = 0, sumsq_diff = 0;
    for (int i = 0; i < learnable_params_.size(); ++i) {
      asum_data += learnable_params_[i]->asum_data();
      asum_diff += learnable_params_[i]->asum_diff();
      sumsq_data += learnable_params_[i]->sumsq_data();
      sumsq_diff += learnable_params_[i]->sumsq_diff();
    }
    const Dtype l2norm_data = std::sqrt(sumsq_data);
    const Dtype l2norm_diff = std::sqrt(sumsq_diff);
    LOG(ERROR) << "    [Backward] All net params (data, diff): "
               << "L1 norm = (" << asum_data << ", " << asum_diff << "); "
               << "L2 norm = (" << l2norm_data << ", " << l2norm_diff << ")";
  }
}

//更新权值函数,在反向传播结束后调用
template <typename Dtype>
void Net<Dtype>::Update() {
  for (int i = 0; i < learnable_params_.size(); ++i) {
  //调用内部Blob的Update()函数,具体计算为data = data - diff
    learnable_params_[i]->Update();
  }
}

//权值diff清零
template <typename Dtype>
void Net<Dtype>::ClearParamDiffs() {
  for (int i = 0; i < learnable_params_.size(); ++i) {
    Blob<Dtype>* blob = learnable_params_[i];
    switch (Caffe::mode()) {
    case Caffe::CPU:
      caffe_set(blob->count(), static_cast<Dtype>(0),
                blob->mutable_cpu_diff());
      break;
    case Caffe::GPU:
#ifndef CPU_ONLY
      caffe_gpu_set(blob->count(), static_cast<Dtype>(0),
                    blob->mutable_gpu_diff());
#else
      NO_GPU;
#endif
      break;
    }
  }
}

到此,caffe基本的backward反向传播过程就清楚了,这样对于设计更复杂的有监督学习算法具有指导意义。

2017/7/5 posted in  Caffe反向传播计算

Caffe反向传播计算

反向传播对电脑的计算能力要求很高,所以反向传播过程只有在训练环境下才需要计算,由于消耗时间较长,对计算资源要求较高,一般为离线服务.

反向传播的特点

CNN进行前向传播阶段,依次调用每个LayerForward函数,得到逐层的输出,最后一层与目标函数比较得到损失函数,计算误差更新值,通过反向传播路径逐层到达第一层所有权值层在反向传播结束后一起更新

损失函数

损失层(Loss Layer)是CNN的终点,接受两个Blob作为输入,其中一个为CNN的预测值;另一个是真实标签。损失层则将这两个输入进行一系列运算,得到当前网络的损失函数(Loss Function), —般记为\(L(\theta)\),其中\(\theta\)表示当前网络权值构成的向量空间。机器学习的目的是在权值空间中找到让损失函数\(L(\theta)\)最小的权值\(\theta_{opt}\),可以采用一系列最优化方法(如后面将会介绍的SGD方法)逼近权值\(\theta_{opt}\)

损失函数是在前向传播计算中得到的,同时也是反向传播的起点.

算法描述

Caffe中实现了多种损失层,分别用于不同场合。其中SoftmaxWithLossLayer实现了Softmax+交叉熵损失函数计算过程,适用于单label的分类问题:另外还有欧式损失函数(用于回归问题)、Hinge损失函数(最大间隔分类,SVM)、Sigmoid+交叉熵损失函数(用于多属性/多分类问题)等。今天我们只关注最基本的SoftmaxWithLossLayer,其他损失层的算法可以直接看Caffe相应源码。

假设有K个类别,Softmax计算过程为:

\[
Softmax(a_i) = \frac{exp(a_i)}{\sum_j{exp(a_i)}} ,i=0,1,2,...K-1
\]

Softmax的结果相当于输入图像被分到每个标签的概率分布。根据高等数学知识,该函数是单调增函数,即输入值越大,输出也越大,输入图像属于该标签的概率就越大。

对Softmax的结果计算交叉熵分类损失函数为:

\[
L(\theta) = -{\frac{1}{N}}\sum_ilog[Softmax(a_k)], i=0,1,2,...N-1
\]

其中,k为真实标签值,N为一个批量的大小.

理想的分类器应当是除了真实标签的概率为1,其余标签概率均为0,这样计算得到其损失函数为-ln(1) =0损失函数越大,说明该分类器在真实标签上分类概率越小,性能也就越差,一个非常差的分类器,可能在真实标签上的分类概率接近于0,那么损失函数就接近于正无穷,我们称为训练发散,需要调小学习速率,在ImageNet-1000分类问题中,初始状态为均匀分布,每个类别的分类概率均为0.001,故此时计算损失函数值为-ln(O.OO1) = ln(1000) = 6.907755... 经常有同学问,“我的loss为什么总是在6.9左右(该现象被称为6.9高原反应),训练了好久都不下降呢?”说明还都没有训练收敛的迹象,尝试调大学习速率,或者修改权值初始化方式.

参数描述

先看一下caffe.proto,找到有关Softmax的消息定义:


// Message that stores parameters used by SoftmaxLayer, SoftmaxWithLossLayer
message SoftmaxParameter {
  enum Engine {
    DEFAULT = 0;
    CAFFE = 1;
    CUDNN = 2;  //使用cudnn引擎计算
  }
  optional Engine engine = 1 [default = DEFAULT]; // 默认为 0 

  // The axis along which to perform the softmax -- may be negative to index
  // from the end (e.g., -1 for the last axis).
  // Any other axes will be evaluated as independent softmaxes.
  // axis为可选参数,指定沿哪个维度计算Softmax,可以是负数,表示从后向前索引
  optional int32 axis = 2 [default = 1];
}

源码分析

损失层的基类声明于include/caffe/layers/loss_layers.hpp中:

/**
 * @brief An interface for Layer%s that take two Blob%s as input -- usually
 *        (1) predictions and (2) ground-truth labels -- and output a
 *        singleton Blob representing the loss.
 *
 * LossLayers are typically only capable of backpropagating to their first input
 * -- the predictions.
 */
 
 
 //损失层的鼻祖类,派生于Layer
template <typename Dtype>
class LossLayer : public Layer<Dtype> {
 public:
 //显式抅造函数
  explicit LossLayer(const LayerParameter& param)
     : Layer<Dtype>(param) {}
//层配置函数
  virtual void LayerSetUp(
      const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top);
//变形函数
  virtual void Reshape(
      const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top);
//接受沔个Blob作为输入
  virtual inline int ExactNumBottomBlobs() const { return 2; }

  /**
   * @brief For convenience and backwards compatibility, instruct the Net to
   *        automatically allocate a single top Blob for LossLayers, into which
   *        they output their singleton loss, (even if the user didn't specify
   *        one in the prototxt, etc.).
   */
   //为了方便和后向兼容,指导Net为损失层自动分配单个输出Blob.损失层则会将计算结果L(θ)保存在这里
  virtual inline bool AutoTopBlobs() const { return true; }
  //只有一个输出Blob
  virtual inline int ExactNumTopBlobs() const { return 1; }
  /**
   * We usually cannot backpropagate to the labels; ignore force_backward for
   * these inputs.
   */
  virtual inline bool AllowForceBackward(const int bottom_index) const {
    return bottom_index != 1;
  }
};

用来计算 Softmax 损失函数的层 SoftmaxLayer 声明在 include/caffe/layers/softmaxlayer.hpp中:

/**
 * @brief Computes the softmax function.
 *
 * TODO(dox): thorough documentation for Forward, Backward, and proto params.
 */
 
 //SoftmaxLayer直接派生于Layer
template <typename Dtype>
class SoftmaxLayer : public Layer<Dtype> {
 public:
 //显示构造函数
  explicit SoftmaxLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {}
//变形函数
  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
//返回类名字符串
  virtual inline const char* type() const { return "Softmax"; }
  //该层接受一个输入BLOB,传生一个输出Blob
  virtual inline int ExactNumBottomBlobs() const { return 1; }
  virtual inline int ExactNumTopBlobs() const { return 1; }

 protected:
 //前向传播函数
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  //反向传播函数
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
     const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
//计算参数
  int outer_num_;
  int inner_num_;
  int softmax_axis_;
  /// sum_multiplier is used to carry out sum using BLAS(利用BLAS计算求和)
  Blob<Dtype> sum_multiplier_;
  /// scale is an intermediate Blob to hold temporary results.(用来临时存放中间结果的Blob)
  Blob<Dtype> scale_;
};

SoftmaxLayer实现在src/caffe/layers/softmax_layer.cpp中,我们深入内部来看一下具体实现:

//变形函数
template <typename Dtype>
void SoftmaxLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
//获得正确的维度索引
  softmax_axis_ =
      bottom[0]->CanonicalAxisIndex(this->layer_param_.softmax_param().axis());
//是输出blob与输入blob形状相同
  top[0]->ReshapeLike(*bottom[0]);
  //sum_multiplier_这里都是1,用于辅助计算,可以看作一个行向量,或者行数为1的矩阵 类似于sum_multiplier_.Reshape(1, bottom[0]->channels(),bottom[0]->height(), bottom[0]->width());  
  vector<int> mult_dims(1, bottom[0]->shape(softmax_axis_));
  sum_multiplier_.Reshape(mult_dims);
  Dtype* multiplier_data = sum_multiplier_.mutable_cpu_data();
  //乘子初始化为1
  caffe_set(sum_multiplier_.count(), Dtype(1), multiplier_data);
  outer_num_ = bottom[0]->count(0, softmax_axis_);
  inner_num_ = bottom[0]->count(softmax_axis_ + 1);
  vector<int> scale_dims = bottom[0]->shape();
  scale_dims[softmax_axis_] = 1;
  //初始化scale_的形状
  scale_.Reshape(scale_dims);
}

//前向计算,得到Softmax(a_k}值
template <typename Dtype>
void SoftmaxLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
    const vector<Blob<Dtype>*>& top) {
    
//获得输入/输出Blob数据指针
  const Dtype* bottom_data = bottom[0]->cpu_data();
  Dtype* top_data = top[0]->mutable_cpu_data();
  //中间临时值数据指针
  Dtype* scale_data = scale_.mutable_cpu_data();
  int channels = bottom[0]->shape(softmax_axis_);
  int dim = bottom[0]->count() / outer_num_; //总的类别数目
  caffe_copy(bottom[0]->count(), bottom_data, top_data); //将输入拷贝到输出缓冲区
  // We need to subtract the max to avoid numerical issues, compute the exp,
  // and then normalize.(遍历bottom_data查找最大值,存入scale_data)
  for (int i = 0; i < outer_num_; ++i) {
    // initialize scale_data to the first plane(初始化scale_data为bottom_data首元素)
    caffe_copy(inner_num_, bottom_data + i * dim, scale_data);
    for (int j = 0; j < channels; j++) {
      for (int k = 0; k < inner_num_; k++) {
        scale_data[k] = std::max(scale_data[k],
            bottom_data[i * dim + j * inner_num_ + k]);
      }
    }
    // subtraction(输出缓冲区减去最大值a_k = a_k- max(a_i))
    caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, channels, inner_num_,
        1, -1., sum_multiplier_.cpu_data(), scale_data, 1., top_data);
    // exponentiation(求指数项exp(a_k))
    caffe_exp<Dtype>(dim, top_data, top_data);
    // sum after exp(累加求和1 + exp(a_k),存放在scale_data中)
    caffe_cpu_gemv<Dtype>(CblasTrans, channels, inner_num_, 1.,
        top_data, sum_multiplier_.cpu_data(), 0., scale_data);
    // division 求Softmax值,即exp(a_k)/(1 + exp(a_k))
    for (int j = 0; j < channels; j++) {
    // top_data = top_data / scale_data
      caffe_div(inner_num_, top_data, scale_data, top_data);
      // 加偏移跳转指针
      top_data += inner_num_;
    }
  }
}
//反向传播,与求导有关
template <typename Dtype>
void SoftmaxLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const vector<bool>& propagate_down,
    const vector<Blob<Dtype>*>& bottom) {
//获得data,diff指针
  const Dtype* top_diff = top[0]->cpu_diff();
  const Dtype* top_data = top[0]->cpu_data();
  Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
  Dtype* scale_data = scale_.mutable_cpu_data();
  int channels = top[0]->shape(softmax_axis_);
  int dim = top[0]->count() / outer_num_;
  caffe_copy(top[0]->count(), top_diff, bottom_diff);
  for (int i = 0; i < outer_num_; ++i) {
    // compute dot(top_diff, top_data) and subtract them from the bottom diff
    for (int k = 0; k < inner_num_; ++k) {
      scale_data[k] = caffe_cpu_strided_dot<Dtype>(channels,
          bottom_diff + i * dim + k, inner_num_,
          top_data + i * dim + k, inner_num_);
    }
    // subtraction
    caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, channels, inner_num_, 1,
        -1., sum_multiplier_.cpu_data(), scale_data, 1., bottom_diff + i * dim);
  }
  // elementwise multiplication(逐点相乘)
  caffe_mul(top[0]->count(), bottom_diff, top_data, bottom_diff);
}


到这里我们就已经了解了Softmax函数的计算过程,后面我们在来看SoftmaxWithLossLayer的实现.

2017/7/4 posted in  Caffe反向传播计算

Net Forward实现

掌握了上次Net的初始化代码以及方法,我们下面来看一下他的Forward代码:


template <typename Dtype>
Dtype Net<Dtype>::ForwardFromTo(int start, int end) {
//计算从第start到end层的前向传播过程
  CHECK_GE(start, 0);
  CHECK_LT(end, layers_.size());
  Dtype loss = 0;
  for (int i = start; i <= end; ++i) {
    for (int c = 0; c < before_forward_.size(); ++c) {
      before_forward_[c]->run(i);
    }
// LOG(ERROR) << "Forwarding " <<layer_names_[i];
// 调用每个Layer的Forward()函数,得到每层loss
    Dtype layer_loss = layers_[i]->Forward(bottom_vecs_[i], top_vecs_[i]);
    loss += layer_loss;
    if (debug_info_) { ForwardDebugInfo(i); }
    for (int c = 0; c < after_forward_.size(); ++c) {
      after_forward_[c]->run(i);
    }
  }
  //返回loss值
  return loss;
}

template <typename Dtype>
Dtype Net<Dtype>::ForwardFrom(int start) {
//计算从start开始到最后一层的前向传播过程
  return ForwardFromTo(start, layers_.size() - 1);
}

template <typename Dtype>
Dtype Net<Dtype>::ForwardTo(int end) {
//计算从第1层到第end层的前向传播过程
  return ForwardFromTo(0, end);
}

template <typename Dtype>
const vector<Blob<Dtype>*>& Net<Dtype>::Forward(Dtype* loss) {
//计算整个网络前向传播过程,返回损失值(可选)和网络输出Blob
  if (loss != NULL) {
    *loss = ForwardFromTo(0, layers_.size() - 1);
  } else {
    ForwardFromTo(0, layers_.size() - 1);
  }
  return net_output_blobs_;
}

template <typename Dtype>
const vector<Blob<Dtype>*>& Net<Dtype>::Forward(
    const vector<Blob<Dtype>*> & bottom, Dtype* loss) {
    //接受输入Blob作为Net输入,计算前向传播,得到损失值(可选)和网络输出Blob
  LOG_EVERY_N(WARNING, 1000) << "DEPRECATED: Forward(bottom, loss) "
      << "will be removed in a future version. Use Forward(loss).";
  // Copy bottom to net bottoms(直接将输入Blob拷贝到net_input_blobs_中)
  for (int i = 0; i < bottom.size(); ++i) {
    net_input_blobs_[i]->CopyFrom(*bottom[i]);
  }
  return Forward(loss);
}

到这里 我们就初步了解了所有的前向传波函数,应该能够在脑海中形成DAG数据流动图,后面学习反向传播过程.

2017/7/3 posted in  Caffe前向传播计算

Net初始化时的三个登记注册函数

我们已经知道Init()函数完成了非常关键的网络初始化和层初始化操作.虽然代码很长.但是只要抓住几个核心对象,了解其功能并密切关注其动态,即可掌握Init()函数的执行流程和具体意义.

Init()中调用了三个登记注册函数:

AppendTop:


// Helper for Net::Init: add a new top blob to the net.
//登记每层输出Blob
template <typename Dtype>
void Net<Dtype>::AppendTop(const NetParameter& param, const int layer_id,
                           const int top_id, set<string>* available_blobs,
                           map<string, int>* blob_name_to_idx) {
  shared_ptr<LayerParameter> layer_param(
      new LayerParameter(param.layer(layer_id)));
  const string& blob_name = (layer_param->top_size() > top_id) ?
      layer_param->top(top_id) : "(automatic)";
  // Check if we are doing in-place computation(检查是否为原位计算)
  if (blob_name_to_idx && layer_param->bottom_size() > top_id &&
      blob_name == layer_param->bottom(top_id)) {
    // In-place computation(是原位计算)
    LOG_IF(INFO, Caffe::root_solver())
        << layer_param->name() << " -> " << blob_name << " (in-place)";
    top_vecs_[layer_id].push_back(blobs_[(*blob_name_to_idx)[blob_name]].get());
    top_id_vecs_[layer_id].push_back((*blob_name_to_idx)[blob_name]);
  } else if (blob_name_to_idx &&
             blob_name_to_idx->find(blob_name) != blob_name_to_idx->end()) {
    // If we are not doing in-place computation but have duplicated blobs,
    // raise an error.
    LOG(FATAL) << "Top blob '" << blob_name
               << "' produced by multiple sources.";
  } else {
    // Normal output.(正常输出)
    if (Caffe::root_solver()) {
      LOG(INFO) << layer_param->name() << " -> " << blob_name;
    }
    shared_ptr<Blob<Dtype> > blob_pointer(new Blob<Dtype>());
    //新建一个Blob,插入到Net::blobs_最后
    const int blob_id = blobs_.size();
    blobs_.push_back(blob_pointer);
    blob_names_.push_back(blob_name);
    blob_need_backward_.push_back(false);
    if (blob_name_to_idx) { (*blob_name_to_idx)[blob_name] = blob_id; }
    top_id_vecs_[layer_id].push_back(blob_id);
    top_vecs_[layer_id].push_back(blob_pointer.get());
  }
  if (available_blobs) { available_blobs->insert(blob_name); }
}

AppendBottom:


// Helper for Net::Init: add a new bottom blob to the net.
//登记每层输入Blob
template <typename Dtype>
int Net<Dtype>::AppendBottom(const NetParameter& param, const int layer_id,
    const int bottom_id, set<string>* available_blobs,
    map<string, int>* blob_name_to_idx) {
  const LayerParameter& layer_param = param.layer(layer_id);
  const string& blob_name = layer_param.bottom(bottom_id);
  if (available_blobs->find(blob_name) == available_blobs->end()) {
    LOG(FATAL) << "Unknown bottom blob '" << blob_name << "' (layer '"
               << layer_param.name() << "', bottom index " << bottom_id << ")";
  }
  const int blob_id = (*blob_name_to_idx)[blob_name];
  LOG_IF(INFO, Caffe::root_solver())
      << layer_names_[layer_id] << " <- " << blob_name;
  bottom_vecs_[layer_id].push_back(blobs_[blob_id].get());
  bottom_id_vecs_[layer_id].push_back(blob_id);
  available_blobs->erase(blob_name);
  bool need_backward = blob_need_backward_[blob_id];
  // Check if the backpropagation on bottom_id should be skipped(检查是否可以跳过反向传播)
  if (layer_param.propagate_down_size() > 0) {
    need_backward = layer_param.propagate_down(bottom_id);
  }
  bottom_need_backward_[layer_id].push_back(need_backward);
  return blob_id;
}

AppendParam:


//登记每层权值Blob
template <typename Dtype>
void Net<Dtype>::AppendParam(const NetParameter& param, const int layer_id,
                             const int param_id) {
  const LayerParameter& layer_param = layers_[layer_id]->layer_param();
  const int param_size = layer_param.param_size();
  string param_name =
      (param_size > param_id) ? layer_param.param(param_id).name() : "";
  if (param_name.size()) {
    param_display_names_.push_back(param_name);
  } else {
    ostringstream param_display_name;
    param_display_name << param_id;
    param_display_names_.push_back(param_display_name.str());
  }
  const int net_param_id = params_.size();
  params_.push_back(layers_[layer_id]->blobs()[param_id]);
  param_id_vecs_[layer_id].push_back(net_param_id);
  param_layer_indices_.push_back(make_pair(layer_id, param_id));
  ParamSpec default_param_spec;
  const ParamSpec* param_spec = (layer_param.param_size() > param_id) ?
      &layer_param.param(param_id) : &default_param_spec;
  if (!param_size || !param_name.size() || (param_name.size() &&
      param_names_index_.find(param_name) == param_names_index_.end())) {
    // This layer "owns" this parameter blob -- it is either anonymous
    // (i.e., not given a param_name) or explicitly given a name that we
    // haven't already seen.
    //该层拥有权值Blob
    param_owners_.push_back(-1);
    if (param_name.size()) {
      param_names_index_[param_name] = net_param_id;
    }
    const int learnable_param_id = learnable_params_.size();
    learnable_params_.push_back(params_[net_param_id].get());
    learnable_param_ids_.push_back(learnable_param_id);
    has_params_lr_.push_back(param_spec->has_lr_mult());
    has_params_decay_.push_back(param_spec->has_decay_mult());
    params_lr_.push_back(param_spec->lr_mult());
    params_weight_decay_.push_back(param_spec->decay_mult());
  } else {
    // Named param blob with name we've seen before: share params(该层共享权值Blob)
    const int owner_net_param_id = param_names_index_[param_name];
    param_owners_.push_back(owner_net_param_id);
    const pair<int, int>& owner_index =
        param_layer_indices_[owner_net_param_id];
    const int owner_layer_id = owner_index.first;
    const int owner_param_id = owner_index.second;
    LOG_IF(INFO, Caffe::root_solver()) << "Sharing parameters '" << param_name
        << "' owned by "
        << "layer '" << layer_names_[owner_layer_id] << "', param "
        << "index " << owner_param_id;
    Blob<Dtype>* this_blob = layers_[layer_id]->blobs()[param_id].get();
    Blob<Dtype>* owner_blob =
        layers_[owner_layer_id]->blobs()[owner_param_id].get();
    const int param_size = layer_param.param_size();
    if (param_size > param_id && (layer_param.param(param_id).share_mode() ==
                                  ParamSpec_DimCheckMode_PERMISSIVE)) {
      // Permissive dimension checking -- only check counts are the same.
      CHECK_EQ(this_blob->count(), owner_blob->count())
          << "Cannot share param '" << param_name << "' owned by layer '"
          << layer_names_[owner_layer_id] << "' with layer '"
          << layer_names_[layer_id] << "'; count mismatch.  Owner layer param "
          << "shape is " << owner_blob->shape_string() << "; sharing layer "
          << "shape is " << this_blob->shape_string();
    } else {
      // Strict dimension checking -- all dims must be the same.(严格检查)
      CHECK(this_blob->shape() == owner_blob->shape())
          << "Cannot share param '" << param_name << "' owned by layer '"
          << layer_names_[owner_layer_id] << "' with layer '"
          << layer_names_[layer_id] << "'; shape mismatch.  Owner layer param "
          << "shape is " << owner_blob->shape_string() << "; sharing layer "
          << "expects shape " << this_blob->shape_string();
    }
    const int learnable_param_id = learnable_param_ids_[owner_net_param_id];
    learnable_param_ids_.push_back(learnable_param_id);
    if (param_spec->has_lr_mult()) {
      if (has_params_lr_[learnable_param_id]) {
        CHECK_EQ(param_spec->lr_mult(), params_lr_[learnable_param_id])
            << "Shared param '" << param_name << "' has mismatched lr_mult.";
      } else {
        has_params_lr_[learnable_param_id] = true;
        params_lr_[learnable_param_id] = param_spec->lr_mult();
      }
    }
    if (param_spec->has_decay_mult()) {
      if (has_params_decay_[learnable_param_id]) {
        CHECK_EQ(param_spec->decay_mult(),
                 params_weight_decay_[learnable_param_id])
            << "Shared param '" << param_name << "' has mismatched decay_mult.";
      } else {
        has_params_decay_[learnable_param_id] = true;
        params_weight_decay_[learnable_param_id] = param_spec->decay_mult();
      }
    }
  }
}

2017/7/1 posted in  Caffe前向传播计算

Caffe前向传播计算

使用传统的BP算法进行CNN训练时包括两个阶段:前向传播计算(Forward)和反向传播计算(Backward)。今天我们将注意力放在前向传播阶段。

前向传播阶段在实际应用中最常见,比如大量的在线系统(语音识别、文字识别、图像分类和检索等)都是仅前向传播阶段的应用;一些嵌入式系统(视觉机器人、无人机、智能语音 机器人)受限于计算资源,仅实现前向传播阶段,而反向传播计算则由计算性能更强大的服务器完成.

前向传播的特点

在前向传播阶段,数据源起于数据读取层,经过若干处理层,到达最后一层(可能是损失 层或特征层)。

网络中的权值在前向传播阶段不发生变化,可以看作常量。

网络路径是一个有向无环图(DirectedAcyclineGraph,DAG)。从最初的节点出发,经历若干处理层,不存在循环结构,因此数据流会直向前推进到达终点。

我们可以使用数据流分析方法对前向传播过程进行研究:

从输入数据集中取一个样本\((X,Y)\),其中X为数据,Y为标签。将X送入网络,逐层计算,得到相应的网络处理输出\(O\)。网络执行的计算可以用公式表达为:
\[
O = F_n(...(F_2(F_1(XW_1)W_2)...)W_n)
\]

其中,\(F_i ,i=1,2,...n\)表示非线性变换,而\(W_i=1,2,…n\),表示各个权值层权值。

得到网络输出\(O\)后,可以用\((Y,O)\)评估网络质量。理想的网络满足\(Y==O\)。

前向传播的实现

在Caffe中CNN前向传播过程由Net + Layer组合完成,中间结果和最终结果则使用Blob承载。下面我们深入代码来观察这一过程。

DAG(有向无环图)构造过程

首先我们从Net构造函数开始.


//从NetParameter对象构造
template <typename Dtype>
Net<Dtype>::Net(const NetParameter& param) {
  Init(param);
}

//从net.prototxt文件构造
template <typename Dtype>
Net<Dtype>::Net(const string& param_file, Phase phase,
    const int level, const vector<string>* stages) {
  NetParameter param;
  ReadNetParamsFromTextFileOrDie(param_file, &param);
  // Set phase, stages and level
  param.mutable_state()->set_phase(phase);
  if (stages != NULL) {
    for (int i = 0; i < stages->size(); i++) {
      param.mutable_state()->add_stage((*stages)[i]);
    }
  }
  param.mutable_state()->set_level(level);
  Init(param);
}

从上面的构造函数看到,二者都调用了Init()函数。传递给该函数的参数param是 NetParameter对象,我们已经之前的例程中使用过,了解过其数据结构描述(caffe.proto)。 我们可以从net.prototxt文件读取到内存中,初始化一个NetParameter对象,然后传递给Init()函数.

接着追踪Init()函数:

//这个函数很长
template <typename Dtype>
void Net<Dtype>::Init(const NetParameter& in_param) {
  // Set phase from the state.
  phase_ = in_param.state().phase();
  // Filter layers based on their include/exclude rules and
  // the current NetState.
  NetParameter filtered_param;
  //过滤一些参数,仅仅保留当前阶段参数.
  FilterNet(in_param, &filtered_param);
  LOG_IF(INFO, Caffe::root_solver())
      << "Initializing net from parameters: " << std::endl
      << filtered_param.DebugString();
  // Create a copy of filtered_param with splits added where necessary.(创建一个拷贝,之后就用这个拷贝)
  NetParameter param;
  InsertSplits(filtered_param, &param);
  // Basically, build all the layers and set up their connections.(构建所有Layer并将它们连接)
  name_ = param.name(); //网络名
  map<string, int> blob_name_to_idx;    //Blob名与索引的映射
  set<string> available_blobs;  //已有Blob名集合
  memory_used_ = 0;     //统计内存占用
  // For each layer, set up its input and output
  //对每个 Layer 设置输入 Blob (BottomBlob)和输出 Blob (TopBlob)
  bottom_vecs_.resize(param.layer_size()); //有多少层,就有多少个输入 Blob 
  top_vecs_.resize(param.layer_size()); //有多少层,就有多少个输出Blob 
  bottom_id_vecs_.resize(param.layer_size()); //记录每个层的输入Blob索引
  param_id_vecs_.resize(param.layer_size());    // 记录每个层的权值Blob索引
  top_id_vecs_.resize(param.layer_size());  // 记录每个层的输出Blob索引
  bottom_need_backward_.resize(param.layer_size()); //记录每个Blob是否需要反向传播过程
  
  //遍历每个层
  for (int layer_id = 0; layer_id < param.layer_size(); ++layer_id) {
    // Inherit phase from net if unset.(每个层的阶段标记.如果在层描述中未指定阶段,就使用Net的阶段)
    if (!param.layer(layer_id).has_phase()) {
      param.mutable_layer(layer_id)->set_phase(phase_);
    }
    // Setup layer.
    //获取层参数
    const LayerParameter& layer_param = param.layer(layer_id);
    if (layer_param.propagate_down_size() > 0) {
      CHECK_EQ(layer_param.propagate_down_size(),
          layer_param.bottom_size())
          << "propagate_down param must be specified "
          << "either 0 or bottom_size times ";
    }
    // Layer工厂,专业制造各种Layer,然后添加到Net类的layers_对象中 
    // 注意到这Layer的LayerParameter都继承自NetParameter
NetParameterlayers_.push_back(LayerRegistry<Dtype>::CreateLayer(layer_param));
    layer_names_.push_back(layer_param.name());
    LOG_IF(INFO, Caffe::root_solver())
        << "Creating Layer " << layer_param.name();
    bool need_backward = false;     //判断该层是否需要反向传播

    // Figure out this layer's input and output(确定该Layer的输入Blob和输出Blob)
    for (int bottom_id = 0; bottom_id < layer_param.bottom_size();
         ++bottom_id) {
         //遍历所有输入Blob,记录到Blob名集合、Blob名到索引映射中
      const int blob_id = AppendBottom(param, layer_id, bottom_id, &available_blobs, &blob_name_to_idx);
      // If a blob needs backward, this layer should provide it.
      need_backward |= blob_need_backward_[blob_id];
    }
    //输出Blob做同样的事
    int num_top = layer_param.top_size();
    for (int top_id = 0; top_id < num_top; ++top_id) {
      AppendTop(param, layer_id, top_id, &available_blobs, &blob_name_to_idx);
      // Collect Input layer tops as Net inputs.(收集输入层(InputLayer)信息,如果有,其输出blob将作为整个Net的输入)
      if (layer_param.type() == "Input") {
        const int blob_id = blobs_.size() - 1;
        net_input_blob_indices_.push_back(blob_id);
        net_input_blobs_.push_back(blobs_[blob_id].get());
      }
    }
    // If the layer specifies that AutoTopBlobs() -> true and the LayerParameter
    // specified fewer than the required number (as specified by
    // ExactNumTopBlobs() or MinTopBlobs()), allocate them here.
    Layer<Dtype>* layer = layers_[layer_id].get();
    if (layer->AutoTopBlobs()) {
      const int needed_num_top =
          std::max(layer->MinTopBlobs(), layer->ExactNumTopBlobs());
      for (; num_top < needed_num_top; ++num_top) {
        // Add "anonymous" top blobs -- do not modify available_blobs or
        // blob_name_to_idx as we don't want these blobs to be usable as input
        // to other layers.
        AppendTop(param, layer_id, num_top, NULL, NULL);
      }
    }
    
    
    // After this layer is connected, set it up.(Layer连接设置完毕,调用各个Layer的SetUp()函数)
    layers_[layer_id]->SetUp(bottom_vecs_[layer_id], top_vecs_[layer_id]);
    LOG_IF(INFO, Caffe::root_solver())
        << "Setting up " << layer_names_[layer_id];
        //设置输出Blob对损失函数的投票因子
    for (int top_id = 0; top_id < top_vecs_[layer_id].size(); ++top_id) {
      if (blob_loss_weights_.size() <= top_id_vecs_[layer_id][top_id]) {
        blob_loss_weights_.resize(top_id_vecs_[layer_id][top_id] + 1, Dtype(0));
      }
      blob_loss_weights_[top_id_vecs_[layer_id][top_id]] = layer->loss(top_id);
      //打印每层输出Blob尺寸信息
      LOG_IF(INFO, Caffe::root_solver())
          << "Top shape: " << top_vecs_[layer_id][top_id]->shape_string();
      if (layer->loss(top_id)) {
        LOG_IF(INFO, Caffe::root_solver())
            << "    with loss weight " << layer->loss(top_id);      //除了损失层的loss_weight为1,其它层都是0
      }
      //统计每个输出Blob内存占用量
      memory_used_ += top_vecs_[layer_id][top_id]->count();
    }
    //打印所有输出Blob内存占用量
    LOG_IF(INFO, Caffe::root_solver())
        << "Memory required for data: " << memory_used_ * sizeof(Dtype);
        
    //下面开始初始化各层权值Blob
    const int param_size = layer_param.param_size();
    const int num_param_blobs = layers_[layer_id]->blobs().size();
    //保证参数配置需要的权值Blob数目不大于实际对象的权值Blob数
    CHECK_LE(param_size, num_param_blobs)
        << "Too many params specified for layer " << layer_param.name();
    ParamSpec default_param_spec;
    //每个权值层(卷基层,全连接层)都要经历下面的过程
    for (int param_id = 0; param_id < num_param_blobs; ++param_id) {
      const ParamSpec* param_spec = (param_id < param_size) ?
          &layer_param.param(param_id) : &default_param_spec;
      const bool param_need_backward = param_spec->lr_mult() != 0;
      //设置权值层param(lr_mult:0)可以禁止其反向传播过程,即冻结权值
      need_backward |= param_need_backward;
      layers_[layer_id]->set_param_propagate_down(param_id,
                                                  param_need_backward);
    }
    for (int param_id = 0; param_id < num_param_blobs; ++param_id) {
    //记录权值Blob到Net后台数据库
      AppendParam(param, layer_id, param_id);
    }
    // Finally, set the backward flag
    layer_need_backward_.push_back(need_backward);
    if (need_backward) {
      for (int top_id = 0; top_id < top_id_vecs_[layer_id].size(); ++top_id) {
        blob_need_backward_[top_id_vecs_[layer_id][top_id]] = true;
      }
    }
  }
  // Go through the net backwards to determine which blobs contribute to the
  // loss.  We can skip backward computation for blobs that don't contribute
  // to the loss.
  // Also checks if all bottom blobs don't need backward computation (possible
  // because the skip_propagate_down param) and so we can skip bacward
  // computation for the entire layer
  set<string> blobs_under_loss;
  set<string> blobs_skip_backp;
  for (int layer_id = layers_.size() - 1; layer_id >= 0; --layer_id) {
    bool layer_contributes_loss = false;
    bool layer_skip_propagate_down = true;
    for (int top_id = 0; top_id < top_vecs_[layer_id].size(); ++top_id) {
      const string& blob_name = blob_names_[top_id_vecs_[layer_id][top_id]];
      if (layers_[layer_id]->loss(top_id) ||
          (blobs_under_loss.find(blob_name) != blobs_under_loss.end())) {
        layer_contributes_loss = true;
      }
      if (blobs_skip_backp.find(blob_name) == blobs_skip_backp.end()) {
        layer_skip_propagate_down = false;
      }
      if (layer_contributes_loss && !layer_skip_propagate_down)
        break;
    }
    // If this layer can skip backward computation, also all his bottom blobs
    // don't need backpropagation
    if (layer_need_backward_[layer_id] && layer_skip_propagate_down) {
      layer_need_backward_[layer_id] = false;
      for (int bottom_id = 0; bottom_id < bottom_vecs_[layer_id].size();
               ++bottom_id) {
        bottom_need_backward_[layer_id][bottom_id] = false;
      }
    }
    if (!layer_contributes_loss) { layer_need_backward_[layer_id] = false; }
    if (Caffe::root_solver()) {
      if (layer_need_backward_[layer_id]) {
        LOG(INFO) << layer_names_[layer_id] << " needs backward computation.";
      } else {
        LOG(INFO) << layer_names_[layer_id]
            << " does not need backward computation.";
      }
    }
    for (int bottom_id = 0; bottom_id < bottom_vecs_[layer_id].size();
         ++bottom_id) {
      if (layer_contributes_loss) {
        const string& blob_name =
            blob_names_[bottom_id_vecs_[layer_id][bottom_id]];
        blobs_under_loss.insert(blob_name);
      } else {
        bottom_need_backward_[layer_id][bottom_id] = false;
      }
      if (!bottom_need_backward_[layer_id][bottom_id]) {
        const string& blob_name =
                   blob_names_[bottom_id_vecs_[layer_id][bottom_id]];
        blobs_skip_backp.insert(blob_name);
      }
    }
  }
  // Handle force_backward if needed.
  if (param.force_backward()) {
    for (int layer_id = 0; layer_id < layers_.size(); ++layer_id) {
      layer_need_backward_[layer_id] = true;
      for (int bottom_id = 0;
           bottom_id < bottom_need_backward_[layer_id].size(); ++bottom_id) {
        bottom_need_backward_[layer_id][bottom_id] =
            bottom_need_backward_[layer_id][bottom_id] ||
            layers_[layer_id]->AllowForceBackward(bottom_id);
        blob_need_backward_[bottom_id_vecs_[layer_id][bottom_id]] =
            blob_need_backward_[bottom_id_vecs_[layer_id][bottom_id]] ||
            bottom_need_backward_[layer_id][bottom_id];
      }
      for (int param_id = 0; param_id < layers_[layer_id]->blobs().size();
           ++param_id) {
        layers_[layer_id]->set_param_propagate_down(param_id, true);
      }
    }
  }
  // In the end, all remaining blobs are considered output blobs.(所有剩下的Blob都被看作输出Blob)
  for (set<string>::iterator it = available_blobs.begin();
      it != available_blobs.end(); ++it) {
    LOG_IF(INFO, Caffe::root_solver())
        << "This network produces output " << *it;
    net_output_blobs_.push_back(blobs_[blob_name_to_idx[*it]].get());
    net_output_blob_indices_.push_back(blob_name_to_idx[*it]);
  }
  //将Blob名称与Blob id对应关系登记到Net后台数据库
  for (size_t blob_id = 0; blob_id < blob_names_.size(); ++blob_id) {
    blob_names_index_[blob_names_[blob_id]] = blob_id;
  }
  //将Layer名称与Layer id对应关系登记到Net后台数据库
  for (size_t layer_id = 0; layer_id < layer_names_.size(); ++layer_id) {
    layer_names_index_[layer_names_[layer_id]] = layer_id;
  }
  ShareWeights();
  debug_info_ = param.debug_info();
  LOG_IF(INFO, Caffe::root_solver()) << "Network initialization done.";
}


到这里我们大概了解了一个Net初始化的过程,关于其中三个登记注册函数,后面继续学习.

2017/6/30 posted in  Caffe前向传播计算