CudnnConvLayer.cpp 10.1 KB
Newer Older
Z
zhangjinchao01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
/* Copyright (c) 2016 Baidu, Inc. All Rights Reserve.

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 "paddle/utils/Logging.h"
#include "paddle/utils/Stat.h"
#include "CudnnConvLayer.h"

namespace paddle {

REGISTER_LAYER(cudnn_conv, CudnnConvLayer);

bool CudnnConvLayer::init(const LayerMap &layerMap,
                          const ParameterMap &parameterMap) {
  ConvBaseLayer::init(layerMap, parameterMap);
  CHECK(useGpu_) << "CudnnConvLayer only support gpu";

  maxGroups_ = 0;
  for (size_t i = 0; i < inputLayers_.size(); i++) {
    CHECK_EQ(channels_[i] % groups_[i], 0);
    CHECK_EQ(numFilters_ % groups_[i], 0);

    hl_filter_descriptor filter;
    hl_create_filter_descriptor(&filter, channels_[i] / groups_[i],
                                numFilters_ / groups_[i], filterSizeY_[i],
                                filterSize_[i]);
    filterDesc_.push_back(filter);

    hl_tensor_descriptor input;
    hl_create_tensor_descriptor(&input);
    inputDesc_.push_back(input);

    hl_tensor_descriptor output;
    int outputX =
        outputSize(imgSize_[i], filterSize_[i], padding_[i], stride_[i]);
    CHECK_EQ(outputX, outputX_[i]);
    hl_create_tensor_descriptor(&output);
    outputDesc_.push_back(output);

    hl_convolution_descriptor conv;
    hl_create_convolution_descriptor(&conv, input, filter, paddingY_[i],
                                     padding_[i], strideY_[i], stride_[i]);
    convDesc_.push_back(conv);

    weightOffset_.push_back((numFilters_ / groups_[i]) *
                            (channels_[i] / groups_[i]) * filterPixels_[i]);
    inputOffset_.push_back((channels_[i] / groups_[i]) * imgSize_[i] *
                           imgSize_[i]);
    outputOffset_.push_back((numFilters_ / groups_[i]) * outputX_[i] *
                            outputX_[i]);

    // initialize all to default algorithms
    fwdAlgo_.push_back(0);
    bwdFilterAlgo_.push_back(0);
    bwdDataAlgo_.push_back(0);
    fwdLimitBytes_.push_back(0);
    bwdFilterLimitBytes_.push_back(0);
    bwdDataLimitBytes_.push_back(0);

    // cudnn streams per group equal to 1
    if (groups_[i] > maxGroups_) {
      maxGroups_ = groups_[i];
    }
  }

  workSpaceInBytes_ = 0;
  workSpaceData_ = NULL;
  for (int i = 0; i < maxGroups_; ++i) {
    workSpace_.push_back(NULL);
  }

  if (biases_.get() && sharedBiases_) {
    hl_create_tensor_descriptor(&biasDesc_);
    hl_tensor_reshape(biasDesc_, 1, numFilters_ / groups_[0], 1, 1);
    biasOffset_ = numFilters_ / groups_[0];
  }

88
  batchNum_ = 0;
Z
zhangjinchao01 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
  isSelectAlgo_ = false;
  return true;
}

void CudnnConvLayer::allocConvWorkSpace(size_t maxWorkSpace) {
  size_t totalWorkSpace = maxWorkSpace * maxGroups_;

  if (totalWorkSpace  > workSpaceInBytes_) {
      if (workSpaceInBytes_ != 0) {
          hl_free_mem_device(workSpaceData_);
      }
      // total amount of storage needed over all groups
      workSpaceData_ = hl_malloc_device(totalWorkSpace);

      // update work space address for each group
      for (int i = 0; i < maxGroups_; ++i) {
            workSpace_[i] = reinterpret_cast<char *>(workSpaceData_)
                                  + i * maxWorkSpace;
      }
      workSpaceInBytes_ = totalWorkSpace;
  }
}

void CudnnConvLayer::reshape(int batchSize) {
  CHECK_NE(inputLayers_.size(), 0UL);
  imageH_ = inputLayers_[0]->getOutput().getFrameHeight();
  imageW_ = inputLayers_[0]->getOutput().getFrameWidth();
  if (imageH_ == 0) imageH_ = imgSize_[0];
  if (imageW_ == 0) imageW_ = imgSize_[0];

  for (size_t i = 1; i < inputLayers_.size(); i++) {
    int imageH = inputLayers_[i]->getOutput().getFrameHeight();
    int imageW = inputLayers_[i]->getOutput().getFrameWidth();
    if (imageH) {
      CHECK_EQ(imageH_, imageH) << "Inputs must have same height.";
    }
    if (imageW) {
      CHECK_EQ(imageW_, imageW) << "Inputs must have same width.";
    }
  }

  outputH_ = outputSize(imageH_, filterSizeY_[0], paddingY_[0], strideY_[0]);
  outputW_ = outputSize(imageW_, filterSize_[0], padding_[0], stride_[0]);
  // check outputH & outputW
  getOutput().setFrameHeight(outputH_);
  getOutput().setFrameWidth(outputW_);

Q
qingqing01 已提交
136 137
  // if the batchSize remains the same, set isSelectAlgo_ true.
  // Otherwise, set isSelectAlgo_ false and select algo again.
138 139 140
  isSelectAlgo_ = (batchSize == batchNum_);
  batchNum_ = batchSize;

Z
zhangjinchao01 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  size_t maxWorkSpace = 0;
  for (size_t i = 0; i < inputLayers_.size(); i++) {
    CHECK_EQ(inputLayers_[i]->getOutput().value->getWidth(),
             (size_t)(channels_[i] * imageH_ * imageW_));

    hl_tensor_reshape(inputDesc_[i], batchSize, channels_[i] / groups_[i],
                      imageH_, imageW_, channels_[i] * imageH_ * imageW_,
                      imageH_ * imageW_, imageW_, 1);

    hl_tensor_reshape(outputDesc_[i], batchSize, numFilters_ / groups_[i],
                      outputH_, outputW_, numFilters_ * outputH_ * outputW_,
                      outputH_ * outputW_, outputW_, 1);

    hl_reset_convolution_descriptor(convDesc_[i], inputDesc_[i],
                                    filterDesc_[i], paddingY_[i],
                                    padding_[i], strideY_[i], stride_[i]);

    inputOffset_[i] = (channels_[i] / groups_[i]) * imageH_ * imageW_;
    outputOffset_[i] = (numFilters_ / groups_[i]) * outputH_ * outputW_;

    if (!isSelectAlgo_) {
      hl_conv_workspace(inputDesc_[i], outputDesc_[i], filterDesc_[i],
                        convDesc_[i], &fwdAlgo_[i], &fwdLimitBytes_[i],
                        &bwdDataAlgo_[i], &bwdDataLimitBytes_[i],
                        &bwdFilterAlgo_[i], &bwdFilterLimitBytes_[i]);

      maxWorkSpace = std::max(fwdLimitBytes_[i], bwdDataLimitBytes_[i]);
      maxWorkSpace = std::max(maxWorkSpace, bwdFilterLimitBytes_[i]);
169 170 171 172

      VLOG(3) << getName() << " Fwd / BwdData / BwdFilter algo: " << fwdAlgo_[i]
                           << " / " << bwdDataAlgo_[i]
                           << " / " << bwdFilterAlgo_[i];
Z
zhangjinchao01 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    }
  }

  if (!isSelectAlgo_) {
    allocConvWorkSpace(maxWorkSpace);
  }

  isSelectAlgo_ = true;
}

void CudnnConvLayer::forward(PassType passType) {
  Layer::forward(passType);
  int batchSize = inputLayers_[0]->getOutputValue()->getHeight();
  reshape(batchSize);
  resetOutput(batchSize, outputH_ * outputW_ * numFilters_);

  for (size_t i = 0; i != inputLayers_.size(); ++i) {
    REGISTER_TIMER_INFO("CudnnConvFwTimer", getName().c_str());
    for (int g = 0; g < groups_[i]; ++g) {
      real *inputData = getInputValue(i)->getData() + inputOffset_[i] * g;
      real *wgtData = weights_[i]->getW()->getData() + weightOffset_[i] * g;
      real *outData = getOutputValue()->getData() + outputOffset_[i] * g;
      hl_convolution_forward(inputDesc_[i], inputData, outputDesc_[i],
                             outData, filterDesc_[i], wgtData,
                             convDesc_[i], workSpace_[g],
                             fwdLimitBytes_[i], fwdAlgo_[i]);
    }
  }

  if (biases_) {
    REGISTER_TIMER_INFO("CudnnConvBiasTimer", getName().c_str());
    addBiases();
  }

  forwardActivation();
}

void CudnnConvLayer::addBiases() {
  if (sharedBiases_) {
    for (int g = 0; g < groups_[0]; ++g) {
      real *biasData = biases_->getW()->getData() + biasOffset_ * g;
      real *outData = getOutputValue()->getData() + outputOffset_[0] * g;
      hl_convolution_forward_add_bias(biasDesc_, biasData,
                                      outputDesc_[0], outData);
    }
  } else {
    LOG(FATAL) << "Not supported";
  }
}

void CudnnConvLayer::bpropBiases() {
  if (sharedBiases_) {
    for (int g = 0; g < groups_[0]; ++g) {
      real *biasGrad = biases_->getWGrad()->getData() + biasOffset_ * g;
      real *outGrad = getOutputGrad()->getData() + outputOffset_[0] * g;
      hl_convolution_backward_bias(biasDesc_, biasGrad,
                                   outputDesc_[0], outGrad);
    }
  } else {
    LOG(FATAL) << "Not supported";
  }
}

void CudnnConvLayer::backward(const UpdateCallback &callback) {
  backwardActivation();

  if (biases_ && biases_->getWGrad()) {
    REGISTER_TIMER_INFO("CudnnConvBpBiasTimer", getName().c_str());
    bpropBiases();
    biases_->getParameterPtr()->incUpdate(callback);
  }

  for (size_t i = 0; i != inputLayers_.size(); ++i) {
    REGISTER_TIMER_INFO("CudnnConvBpTimer", getName().c_str());
    for (int g = 0; g < groups_[i]; ++g) {
      real *outGrad = getOutputGrad()->getData() + outputOffset_[i] * g;
      if (weights_[i]->getWGrad()) {
        real *inputData = getInputValue(i)->getData() + inputOffset_[i] * g;
        real *weightGrad =
            weights_[i]->getWGrad()->getData() + weightOffset_[i] * g;
        hl_convolution_backward_filter(
            inputDesc_[i], inputData, outputDesc_[i], outGrad, filterDesc_[i],
            weightGrad, convDesc_[i], workSpace_[g], bwdFilterLimitBytes_[i],
            bwdFilterAlgo_[i]);
      }

      MatrixPtr preGrad = getInputGrad(i);
      if (NULL != preGrad) {
        real *inputGrad = preGrad->getData() + inputOffset_[i] * g;
        real *wgtData = weights_[i]->getW()->getData() + weightOffset_[i] * g;
        hl_convolution_backward_data(
            inputDesc_[i], inputGrad, outputDesc_[i], outGrad, filterDesc_[i],
            wgtData, convDesc_[i], workSpace_[g], bwdDataLimitBytes_[i],
            bwdDataAlgo_[i]);
      }
    }
    weights_[i]->getParameterPtr()->incUpdate(callback);
  }
}

CudnnConvLayer::~CudnnConvLayer() {
  if (biasDesc_) {
    hl_destroy_tensor_descriptor(biasDesc_);
  }

  for (size_t i = 0; i < inputDesc_.size(); i++) {
    hl_destroy_tensor_descriptor(inputDesc_[i]);
    hl_destroy_tensor_descriptor(outputDesc_[i]);
    hl_destroy_filter_descriptor(filterDesc_[i]);
    hl_destroy_convolution_descriptor(convDesc_[i]);
  }
  if (workSpaceInBytes_ != 0) {
    hl_free_mem_device(workSpaceData_);
    workSpaceInBytes_ = 0;
  }
}

}  // namespace paddle