ConvProjection.cpp 8.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "ConvProjection.h"
Y
Yu Yang 已提交
16
#include "paddle/utils/Stat.h"
17 18 19 20 21

namespace paddle {

REGISTER_PROJECTION(conv, ConvProjection);

22
ThreadLocalD<std::vector<MemoryHandle *>> ConvProjection::convMem_;
23

24 25 26
ConvProjection::ConvProjection(const ProjectionConfig &config,
                               ParameterPtr parameter,
                               bool useGpu)
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    : Projection(config, parameter, useGpu) {
  CHECK(useGpu);  // only support GPU
  getConvParams();
  initCudnn();

  size_t height = filterH_ * filterW_ * channels_ / groups_;
  size_t width = numFilters_;
  weight_.reset(new Weight(height, width, parameter));
  weightOffset_ = height * width / groups_;
}

void ConvProjection::getConvParams() {
  const ConvConfig &conf = config_.conv_conf();
  paddingH_ = conf.padding_y();
  paddingW_ = conf.padding();

  strideH_ = conf.stride_y();
  strideW_ = conf.stride();

  filterH_ = conf.filter_size_y();
  filterW_ = conf.filter_size();

L
Luo Tao 已提交
49
  configImgH_ = conf.has_img_size_y() ? conf.img_size_y() : conf.img_size();
50 51 52 53 54 55 56 57 58 59 60
  configImgW_ = conf.img_size();

  channels_ = conf.channels();
  numFilters_ = config_.num_filters();

  groups_ = conf.groups();
  CHECK_EQ(channels_ % groups_, 0);
  CHECK_EQ(numFilters_ % groups_, 0);
}

void ConvProjection::initCudnn() {
L
Luo Tao 已提交
61 62 63 64 65
  hl_create_filter_descriptor(&filterDesc_,
                              channels_ / groups_,
                              numFilters_ / groups_,
                              filterH_,
                              filterW_);
66 67
  hl_create_tensor_descriptor(&inputDesc_);
  hl_create_tensor_descriptor(&outputDesc_);
68 69 70 71 72 73 74
  hl_create_convolution_descriptor(&convDesc_,
                                   inputDesc_,
                                   filterDesc_,
                                   paddingH_,
                                   paddingW_,
                                   strideH_,
                                   strideW_);
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

  // initialize all to default algorithms
  fwdAlgo_ = 0;
  bwdFilterAlgo_ = 0;
  bwdDataAlgo_ = 0;
  fwdLimitBytes_ = 0;
  bwdDataLimitBytes_ = 0;
  bwdFilterLimitBytes_ = 0;
  workSpaceInBytes_ = 0;

  batchNum_ = 0;
  isSelectAlgo_ = false;
}

void ConvProjection::reshapeTensorDesc(int batchSize) {
90 91
  hl_tensor_reshape(inputDesc_,
                    batchSize,
92
                    channels_ / groups_,
93 94 95 96 97 98 99 100 101 102 103 104 105
                    imageH_,
                    imageW_,
                    channels_ * imageH_ * imageW_,
                    imageH_ * imageW_,
                    imageW_,
                    1);
  hl_reset_convolution_descriptor(convDesc_,
                                  inputDesc_,
                                  filterDesc_,
                                  paddingH_,
                                  paddingW_,
                                  strideH_,
                                  strideW_);
106 107 108 109 110 111 112 113 114 115 116 117 118

  // The stride between two consecutive images in ConvProjection may not be 1,
  // for example, in the case of layer ConcatenateLayer2 with two
  // ConvProjection, the stride is the output_size of layer ConcatenateLayer2.
  // So the calculation of nStride is different from CudnnConvLayer.
  // In fact, only "nStride = out_->value->getStride()" is ok.
  size_t nStride = numFilters_ * outputH_ * outputW_;
  if (out_->value->isContiguous()) {
    CHECK_EQ(nStride, out_->value->getWidth());
  } else {
    nStride = out_->value->getStride();
  }

119 120
  hl_tensor_reshape(outputDesc_,
                    batchSize,
121
                    numFilters_ / groups_,
122 123 124 125 126 127
                    outputH_,
                    outputW_,
                    nStride,
                    outputH_ * outputW_,
                    outputW_,
                    1);
128 129 130 131 132 133 134 135 136 137 138
}

void ConvProjection::reshape(int batchSize) {
  size_t width = calOutputSize();
  CHECK_EQ(width, out_->value->getWidth());

  isSelectAlgo_ = (batchSize == batchNum_);
  batchNum_ = batchSize;

  if (!isSelectAlgo_) {
    reshapeTensorDesc(batchSize);
139 140 141 142 143 144 145 146 147 148
    hl_conv_workspace(inputDesc_,
                      outputDesc_,
                      filterDesc_,
                      convDesc_,
                      &fwdAlgo_,
                      &fwdLimitBytes_,
                      &bwdDataAlgo_,
                      &bwdDataLimitBytes_,
                      &bwdFilterAlgo_,
                      &bwdFilterLimitBytes_);
149 150 151 152 153 154 155

    size_t maxWorkSpace = 0;
    maxWorkSpace = std::max(fwdLimitBytes_, bwdDataLimitBytes_);
    maxWorkSpace = std::max(maxWorkSpace, bwdFilterLimitBytes_);
    workSpaceInBytes_ = maxWorkSpace;

    VLOG(3) << getName() << " Fwd / BwdData / BwdFilter algo: " << fwdAlgo_
156
            << " / " << bwdDataAlgo_ << " / " << bwdFilterAlgo_;
157 158 159 160 161 162 163 164 165
  }

  isSelectAlgo_ = true;
}

void ConvProjection::forward() {
  int batchSize = in_->value->getHeight();
  reshape(batchSize);

166
  void *workSpace = NULL;
167 168 169 170 171 172 173 174 175 176
  if (workSpaceInBytes_ > 0) {
    workSpace = getSpaceBytes(workSpaceInBytes_);
  }

  for (int g = 0; g < groups_; ++g) {
    REGISTER_TIMER_INFO("CudnnConvFwTimer", getName().c_str());

    real *inputData = in_->value->getData() + g * inputOffset_;
    real *wgtData = weight_->getW()->getData() + g * weightOffset_;
    real *outData = out_->value->getData() + g * outputOffset_;
177 178 179 180 181 182 183 184 185 186
    hl_convolution_forward(inputDesc_,
                           inputData,
                           outputDesc_,
                           outData,
                           filterDesc_,
                           wgtData,
                           convDesc_,
                           workSpace,
                           fwdLimitBytes_,
                           fwdAlgo_);
187 188 189
  }
}

190
void ConvProjection::backward(const UpdateCallback &callback) {
191 192
  REGISTER_TIMER_INFO("CudnnConvBpTimer", getName().c_str());

193
  void *workSpace = NULL;
194 195 196 197 198 199 200 201 202
  if (workSpaceInBytes_ > 0) {
    workSpace = getSpaceBytes(workSpaceInBytes_);
  }

  for (int g = 0; g < groups_; ++g) {
    real *outGrad = out_->grad->getData() + g * outputOffset_;
    if (weight_->getWGrad()) {
      real *inputData = in_->value->getData() + g * inputOffset_;
      real *weightGrad = weight_->getWGrad()->getData() + g * weightOffset_;
203 204 205 206 207 208 209 210 211 212
      hl_convolution_backward_filter(inputDesc_,
                                     inputData,
                                     outputDesc_,
                                     outGrad,
                                     filterDesc_,
                                     weightGrad,
                                     convDesc_,
                                     workSpace,
                                     bwdFilterLimitBytes_,
                                     bwdFilterAlgo_);
213 214 215 216 217
    }

    MatrixPtr preGrad = in_->grad;
    if (NULL != preGrad) {
      real *inputGrad = preGrad->getData() + g * inputOffset_;
218 219 220 221 222 223 224 225 226 227 228
      real *wgtData = weight_->getW()->getData() + g * weightOffset_;
      hl_convolution_backward_data(inputDesc_,
                                   inputGrad,
                                   outputDesc_,
                                   outGrad,
                                   filterDesc_,
                                   wgtData,
                                   convDesc_,
                                   workSpace,
                                   bwdDataLimitBytes_,
                                   bwdDataAlgo_);
229 230 231 232 233 234
    }
  }

  weight_->getParameterPtr()->incUpdate(callback);
}

235 236
void *ConvProjection::getSpaceBytes(size_t size) {
  std::vector<MemoryHandle *> &convMem = *convMem_;
237 238 239 240 241 242
  if (convMem.empty()) {
    int numDevices = hl_get_device_count();
    convMem.resize(numDevices);
  }

  int devId = hl_get_device();
243
  MemoryHandle **localMem = &(convMem[devId]);
244 245 246 247 248 249 250 251 252 253 254 255 256 257
  if (NULL == *localMem || size > (*localMem)->getAllocSize()) {
    *localMem = new GpuMemoryHandle(size);
  }
  return (*localMem)->getBuf();
}

ConvProjection::~ConvProjection() {
  hl_destroy_tensor_descriptor(inputDesc_);
  hl_destroy_tensor_descriptor(outputDesc_);
  hl_destroy_filter_descriptor(filterDesc_);
  hl_destroy_convolution_descriptor(convDesc_);
}

}  // namespace paddle