CudnnBatchNormLayer.cpp 6.2 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 24 25 26 27 28 29 30 31 32 33 34 35 36 37

namespace paddle {

REGISTER_LAYER(cudnn_batch_norm, CudnnBatchNormLayer);

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 已提交
38
  hl_tensor_reshape(ioDesc_, batchSize, channels_, imageH_ * imageD_, imageW_);
Z
zhangjinchao01 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
}

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();

P
peterzhang2029 已提交
62 63
  // cuDNN does not allow an epsilon value less than CUDNN_BN_MIN_EPSILON.
  eps_ = std::max(CUDNN_BN_MIN_EPSILON, static_cast<double>(epsilon_));
Z
zhangjinchao01 已提交
64 65 66 67 68

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

  /* 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();

P
peterzhang2029 已提交
132 133
  // cuDNN does not allow an epsilon value less than CUDNN_BN_MIN_EPSILON.
  eps_ = std::max(CUDNN_BN_MIN_EPSILON, static_cast<double>(epsilon_));
Z
zhangjinchao01 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

  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);
  }
153

154 155 156 157 158 159 160 161 162 163
  hl_batch_norm_backward(ioDesc_,
                         input,
                         ioDesc_,
                         outGrad,
                         ioDesc_,
                         inGrad,
                         bnParamDesc_,
                         gamma,
                         gammaGrad,
                         betaGrad,
164
                         eps_,
165 166
                         savedMean,
                         savedInvVar);
Z
zhangjinchao01 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180

  {
    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