CudnnBatchNormLayer.cpp 6.6 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "CudnnBatchNormLayer.h"
Y
Yu Yang 已提交
16
#include "Layer.h"
17
#include "paddle/cuda/include/hl_batch_norm.h"
Y
Yu Yang 已提交
18
#include "paddle/utils/Stat.h"
Z
zhangjinchao01 已提交
19 20 21 22 23

namespace paddle {

REGISTER_LAYER(cudnn_batch_norm, CudnnBatchNormLayer);

P
peterzhang2029 已提交
24
const double CudnnBatchNormLayer::MIN_EPS = 1E-5;
Z
zhangjinchao01 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

bool CudnnBatchNormLayer::init(const LayerMap& layerMap,
                               const ParameterMap& parameterMap) {
  /* Initialize the basic parent class */
  if (!BatchNormBaseLayer::init(layerMap, parameterMap)) return false;
  CHECK(useGpu_) << "CudnnBatchNorm only support GPU";

  hl_create_tensor_descriptor(&ioDesc_);
  hl_create_tensor_descriptor(&bnParamDesc_);
  hl_tensor_reshape(bnParamDesc_, 1, channels_, 1, 1);

  return true;
}

void CudnnBatchNormLayer::reshape(int batchSize) {
C
chengduoZH 已提交
40
  hl_tensor_reshape(ioDesc_, batchSize, channels_, imageH_ * imageD_, imageW_);
Z
zhangjinchao01 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
}

void CudnnBatchNormLayer::forward(PassType passType) {
  Layer::forward(passType);

  int batchSize = getInputValue(0)->getHeight();
  calFeatureMapSize();
  reshape(batchSize);
  resetOutput(batchSize, getInputValue(0)->getWidth());

  // for testing in training peroid.
  useGlobalStats_ = (passType == PASS_TEST);
  if (passType == PASS_TEST && config_.has_use_global_stats()) {
    useGlobalStats_ = config_.use_global_stats();
  }

  real* input = getInputValue(0)->getData();
  real* output = getOutputValue()->getData();
  real* gamma = weight_->getW()->getData();
  real* beta = biases_->getW()->getData();
  real* movingMean = movingMean_->getW()->getData();
  real* movingVar = movingVar_->getW()->getData();

64 65 66 67 68 69 70 71
  /**
  * If epsilon_ equals to 1e-5 and eps_ is assigned the value of
  * static_cast<double>(epsilon_), The CUDNN_STATUS_BAD_PARAM error
  * will occur due to eps_ value is less than
  * CUDNN_BN_MIN_EPSILON.
  * The following code is to ensure that the eps_ meets requirement.
  */
  eps_ = std::max(MIN_EPS, static_cast<double>(epsilon_));
Z
zhangjinchao01 已提交
72 73 74 75 76

  if (!useGlobalStats_) {
    REGISTER_TIMER_INFO("CudnnBatchFwTimer", getName().c_str());
    real* savedMean = savedMean_->getData();
    real* savedInvVar = savedInvVar_->getData();
77 78 79 80
    hl_batch_norm_forward_training(ioDesc_,
                                   input,
                                   ioDesc_,
                                   output,
Z
zhangjinchao01 已提交
81
                                   bnParamDesc_,
82 83 84 85 86
                                   gamma,
                                   beta,
                                   1.0 - movingAvgFraction_,
                                   movingMean,
                                   movingVar,
87
                                   eps_,
88 89
                                   savedMean,
                                   savedInvVar);
Z
zhangjinchao01 已提交
90 91
  } else {
    // used movingMean and movingVar in testing
D
dangqingqing 已提交
92 93 94 95 96 97 98 99 100 101
    if (batchSize <= 1024) {
      hl_batch_norm_forward_inference(ioDesc_,
                                      input,
                                      ioDesc_,
                                      output,
                                      bnParamDesc_,
                                      gamma,
                                      beta,
                                      movingMean,
                                      movingVar,
102
                                      eps_);
D
dangqingqing 已提交
103 104 105 106
    } else {
      // There is a limitation in cudnn library.
      // When the batch size is larger than 1024 in cuDNN v5.1,
      // the cudnnBatchNormalizationForwardInference will fail.
107 108 109 110 111 112
      hl_batch_norm_cuda_inference(input,
                                   output,
                                   gamma,
                                   beta,
                                   movingMean,
                                   movingVar,
113
                                   eps_,
114 115
                                   batchSize,
                                   channels_,
C
chengduoZH 已提交
116
                                   imageH_ * imageD_,
117 118
                                   imageW_);
    }
Z
zhangjinchao01 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
  }

  /* activation */ {
    REGISTER_TIMER_INFO("FwAtvTimer", getName().c_str());
    forwardActivation();
  }
}

void CudnnBatchNormLayer::backward(const UpdateCallback& callback) {
  /* Do derivation */ {
    REGISTER_TIMER_INFO("BpAvtTimer", getName().c_str());
    backwardActivation();
  }

  real* input = getInputValue(0)->getData();
  real* outGrad = getOutputGrad()->getData();
  real* inGrad = getInputGrad(0)->getData();
  real* gamma = weight_->getW()->getData();
  real* savedMean = savedMean_->getData();
  real* savedInvVar = savedInvVar_->getData();

140 141 142 143 144 145 146 147
  /**
  * If epsilon_ equals to 1e-5 and eps_ is assigned the value of
  * static_cast<double>(epsilon_), The CUDNN_STATUS_BAD_PARAM error
  * will occur due to eps_ value is less than
  * CUDNN_BN_MIN_EPSILON.
  * The following code is to ensure that the eps_ meets requirement.
  */
  eps_ = std::max(MIN_EPS, static_cast<double>(epsilon_));
Z
zhangjinchao01 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

  auto create = [](MatrixPtr& m, size_t h, size_t w, real** p) {
    Matrix::resizeOrCreate(m, h, w, false, true);
    m->zeroMem();
    *p = m->getData();
  };

  real* gammaGrad = nullptr;
  real* betaGrad = nullptr;
  if (weight_->getWGrad()) {
    gammaGrad = weight_->getWGrad()->getData();
  } else {
    create(tmpWGrad_, 1, channels_, &gammaGrad);
  }
  if (biases_ && biases_->getWGrad()) {
    betaGrad = biases_->getWGrad()->getData();
  } else {
    create(tmpBiasGrad_, 1, channels_, &betaGrad);
  }
167

168 169 170 171 172 173 174 175 176 177
  hl_batch_norm_backward(ioDesc_,
                         input,
                         ioDesc_,
                         outGrad,
                         ioDesc_,
                         inGrad,
                         bnParamDesc_,
                         gamma,
                         gammaGrad,
                         betaGrad,
178
                         eps_,
179 180
                         savedMean,
                         savedInvVar);
Z
zhangjinchao01 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194

  {
    REGISTER_TIMER_INFO("WeightUpdate", getName().c_str());
    biases_->getParameterPtr()->incUpdate(callback);
    weight_->getParameterPtr()->incUpdate(callback);
  }
}

CudnnBatchNormLayer::~CudnnBatchNormLayer() {
  hl_destroy_tensor_descriptor(ioDesc_);
  hl_destroy_tensor_descriptor(bnParamDesc_);
}

}  // namespace paddle