GemmConvOp.cpp 13.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 PaddlePaddle Authors. 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. */

15 16
#include "GemmConvOp.h"
#include "GemmFunctor.h"
17 18 19 20 21 22 23 24 25 26
#include "paddle/math/MemoryHandle.h"

namespace paddle {

/*
 * imData = [input_channels, input_height, input_width]
 * colData = [input_channels, filter_height, filter_width,
 *            output_height, output_width]
 */
template <class T>
27
class Im2ColFunctor<DEVICE_TYPE_CPU, T> {
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
public:
  void operator()(const T* imData,
                  int inputChannels,
                  int inputHeight,
                  int inputWidth,
                  int filterHeight,
                  int filterWidth,
                  int strideHeight,
                  int strideWidth,
                  int paddingHeight,
                  int paddingWidth,
                  int outputHeight,
                  int outputWidth,
                  T* colData) {
    int channelsCol = inputChannels * filterHeight * filterWidth;

    for (int c = 0; c < channelsCol; ++c) {
      int wOffset = c % filterWidth;
      int hOffset = (c / filterWidth) % filterHeight;
47
      int c_im = c / filterWidth / filterHeight;
48 49
      for (int h = 0; h < outputHeight; ++h) {
        for (int w = 0; w < outputWidth; ++w) {
50 51 52 53 54 55
          int imRowIdx = h * strideHeight + hOffset;
          int imColIdx = w * strideWidth + wOffset;
          if ((imRowIdx - paddingHeight) < 0 ||
              (imRowIdx - paddingHeight) >= inputHeight ||
              (imColIdx - paddingWidth) < 0 ||
              (imColIdx - paddingWidth) >= inputWidth) {
56 57
            colData[(c * outputHeight + h) * outputWidth + w] = T(0);
          } else {
58 59
            imRowIdx += c_im * inputHeight - paddingHeight;
            imColIdx -= paddingWidth;
60
            colData[(c * outputHeight + h) * outputWidth + w] =
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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
                imData[imRowIdx * inputWidth + imColIdx];
          }
        }
      }
    }
  }
};

template <class T>
class Col2ImFunctor<DEVICE_TYPE_CPU, T> {
public:
  void operator()(const T* colData,
                  int inputChannels,
                  int inputHeight,
                  int inputWidth,
                  int filterHeight,
                  int filterWidth,
                  int strideHeight,
                  int strideWidth,
                  int paddingHeight,
                  int paddingWidth,
                  int outputHeight,
                  int outputWidth,
                  T* imData) {
    int channelsCol = inputChannels * filterHeight * filterWidth;

    for (int c = 0; c < channelsCol; ++c) {
      int wOffset = c % filterWidth;
      int hOffset = (c / filterWidth) % filterHeight;
      int c_im = c / filterWidth / filterHeight;
      for (int h = 0; h < outputHeight; ++h) {
        for (int w = 0; w < outputWidth; ++w) {
          int imRowIdx = h * strideHeight + hOffset;
          int imColIdx = w * strideWidth + wOffset;
          if ((imRowIdx - paddingHeight) >= 0 &&
              (imRowIdx - paddingHeight) < inputHeight &&
              (imColIdx - paddingWidth) >= 0 &&
              (imColIdx - paddingWidth) < inputWidth) {
            imRowIdx += c_im * inputHeight - paddingHeight;
            imColIdx -= paddingWidth;
            imData[imRowIdx * inputWidth + imColIdx] +=
                colData[(c * outputHeight + h) * outputWidth + w];
103 104 105 106 107 108 109 110
          }
        }
      }
    }
  }
};

/*
111
 * \brief Forward calculation of convolution.
112 113 114 115 116 117 118 119
 */
template <DeviceType Device>
class GemmConvFunction : public ConvFunctionBase {
public:
  void init(const FuncConfig& config) override {
    ConvFunctionBase::init(config);
  }

L
liaogang 已提交
120
  void check(const BufferArgs& inputs, const BufferArgs& outputs) override {
H
hedaoyuan 已提交
121 122 123 124 125 126
    const TensorShape& input = inputs[0].shape();
    const TensorShape& filter = inputs[1].shape();
    const TensorShape& output = outputs[0].shape();
    checkShape(input, filter, output);
  }

127
  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
128 129
    CHECK_EQ(numInputs_, inputs.size());
    CHECK_EQ(numOutputs_, outputs.size());
H
hedaoyuan 已提交
130
    check(inputs, outputs);
131 132 133 134 135 136 137 138 139 140 141 142
    // TODO(hedaoyuan): Need to define some index macros,
    // to avoid useing 0 and 1.
    const TensorShape& input = inputs[0].shape();
    const TensorShape& filter = inputs[1].shape();
    const TensorShape& output = outputs[0].shape();

    real beta;
    if (outputs[0].getArgType() == ADD_TO) {
      beta = 1.0;
    } else {
      beta = 0.0;
    }
143

H
hedaoyuan 已提交
144 145 146 147 148 149 150 151 152
    size_t batchSize = input[0];
    size_t inputChannels = input[1];
    size_t inputHeight = input[2];
    size_t inputWidth = input[3];
    size_t filterHeight = getFilterHeight(filter);
    size_t filterWidth = getFilterWidth(filter);
    size_t outputChannels = output[1];
    size_t outputHeight = output[2];
    size_t outputWidth = output[3];
153 154 155 156 157

    real* inputData = inputs[0].data<real>();
    real* filterData = inputs[1].data<real>();
    real* outputData = outputs[0].data<real>();

158 159
    size_t size = inputChannels / groups_ * filterHeight * filterWidth *
                  outputHeight * outputWidth;
160
    resizeBuffer<Device>(size);
161 162
    real* colData = reinterpret_cast<real*>(memory_->getBuf());

163 164
    Im2ColFunctor<Device, real> im2col;
    GemmFunctor<Device, real> gemm;
165 166 167
    size_t inputOffset = (inputChannels / groups_) * inputHeight * inputWidth;
    size_t outputOffset =
        (outputChannels / groups_) * outputHeight * outputWidth;
H
hedaoyuan 已提交
168 169
    size_t filterOffset = filter.getElements() / groups_;

170
    for (size_t i = 0; i < batchSize; i++) {
171
      for (size_t g = 0; g < groups_; g++) {
172 173 174 175 176 177 178 179 180 181 182 183 184 185
        im2col(inputData + g * inputOffset,
               inputChannels / groups_,
               inputHeight,
               inputWidth,
               filterHeight,
               filterWidth,
               strideH(),
               strideW(),
               paddingH(),
               paddingW(),
               outputHeight,
               outputWidth,
               colData);

H
Bug fix  
hedaoyuan 已提交
186
        int M = outputChannels / groups_;
187
        int N = outputHeight * outputWidth;
H
Bug fix  
hedaoyuan 已提交
188
        int K = inputChannels / groups_ * filterHeight * filterWidth;
189 190 191
        gemm(CblasNoTrans,
             CblasNoTrans,
             M,
192 193 194 195 196 197 198
             N,
             K,
             1.0f,
             filterData + g * filterOffset,
             K,
             colData,
             N,
199
             beta,
200 201
             outputData + g * outputOffset,
             N);
202
      }
H
hedaoyuan 已提交
203 204
      inputData += inputChannels * inputHeight * inputWidth;
      outputData += outputChannels * outputHeight * outputWidth;
205 206 207 208
    }
  }
};

209 210 211 212 213 214 215 216 217 218
/*
 * \brief Backward input calculation of convolution.
 */
template <DeviceType Device>
class GemmConvGradInputFunction : public ConvFunctionBase {
public:
  void init(const FuncConfig& config) override {
    ConvFunctionBase::init(config);
  }

L
liaogang 已提交
219
  void check(const BufferArgs& inputs, const BufferArgs& outputs) override {
H
hedaoyuan 已提交
220 221 222 223 224 225
    const TensorShape& output = inputs[0].shape();
    const TensorShape& filter = inputs[1].shape();
    const TensorShape& input = outputs[0].shape();
    checkShape(input, filter, output);
  }

226 227 228
  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_EQ(numInputs_, inputs.size());
    CHECK_EQ(numOutputs_, outputs.size());
H
hedaoyuan 已提交
229
    check(inputs, outputs);
H
hedaoyuan 已提交
230 231 232
    // Since the implementation of Col2ImFunctor is ADD_TO,
    // this function only supports ADD_TO mode.
    CHECK_EQ(outputs[0].getArgType(), ADD_TO);
233
    const TensorShape& output = inputs[0].shape();
234
    const TensorShape& filter = inputs[1].shape();
235 236 237 238 239 240
    const TensorShape& input = outputs[0].shape();

    size_t batchSize = input[0];
    size_t inputChannels = input[1];
    size_t inputHeight = input[2];
    size_t inputWidth = input[3];
H
hedaoyuan 已提交
241 242
    size_t filterHeight = getFilterHeight(filter);
    size_t filterWidth = getFilterWidth(filter);
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    size_t outputChannels = output[1];
    size_t outputHeight = output[2];
    size_t outputWidth = output[3];

    real* outputGrad = inputs[0].data<real>();
    real* filterData = inputs[1].data<real>();
    real* inputGrad = outputs[0].data<real>();

    size_t size = inputChannels / groups_ * filterHeight * filterWidth *
                  outputHeight * outputWidth;
    resizeBuffer<Device>(size);
    real* colData = reinterpret_cast<real*>(memory_->getBuf());

    Col2ImFunctor<Device, real> col2im;
    GemmFunctor<Device, real> gemm;
    size_t inputOffset = (inputChannels / groups_) * inputHeight * inputWidth;
H
format  
hedaoyuan 已提交
259
    size_t outputOffset =
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 291 292 293 294 295 296 297 298
        (outputChannels / groups_) * outputHeight * outputWidth;
    size_t filterOffset = filter.getElements() / groups_;

    for (size_t i = 0; i < batchSize; i++) {
      for (size_t g = 0; g < groups_; g++) {
        int K = outputChannels / groups_;
        int N = outputHeight * outputWidth;
        int M = inputChannels / groups_ * filterHeight * filterWidth;
        gemm(CblasTrans,
             CblasNoTrans,
             M,
             N,
             K,
             1.0f,
             filterData + g * filterOffset,
             M,
             outputGrad + g * outputOffset,
             N,
             0.0f,
             colData,
             N);

        col2im(colData,
               inputChannels / groups_,
               inputHeight,
               inputWidth,
               filterHeight,
               filterWidth,
               strideH(),
               strideW(),
               paddingH(),
               paddingW(),
               outputHeight,
               outputWidth,
               inputGrad + g * inputOffset);
      }
      inputGrad += inputChannels * inputHeight * inputWidth;
      outputGrad += outputChannels * outputHeight * outputWidth;
    }
299 300 301 302 303 304 305 306 307 308 309 310 311
  }
};

/*
 * \brief Backward filter calculation of convolution.
 */
template <DeviceType Device>
class GemmConvGradFilterFunction : public ConvFunctionBase {
public:
  void init(const FuncConfig& config) override {
    ConvFunctionBase::init(config);
  }

L
liaogang 已提交
312
  void check(const BufferArgs& inputs, const BufferArgs& outputs) override {
H
hedaoyuan 已提交
313 314 315 316 317 318
    const TensorShape& output = inputs[0].shape();
    const TensorShape& input = inputs[1].shape();
    const TensorShape& filter = outputs[0].shape();
    checkShape(input, filter, output);
  }

319 320 321
  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_EQ(numInputs_, inputs.size());
    CHECK_EQ(numOutputs_, outputs.size());
H
hedaoyuan 已提交
322
    check(inputs, outputs);
323
    const TensorShape& output = inputs[0].shape();
324
    const TensorShape& input = inputs[1].shape();
325 326
    const TensorShape& filter = outputs[0].shape();

327 328 329 330 331 332 333
    real beta;
    if (outputs[0].getArgType() == ADD_TO) {
      beta = 1.0;
    } else {
      beta = 0.0;
    }

334 335 336 337
    size_t batchSize = input[0];
    size_t inputChannels = input[1];
    size_t inputHeight = input[2];
    size_t inputWidth = input[3];
H
hedaoyuan 已提交
338 339
    size_t filterHeight = getFilterHeight(filter);
    size_t filterWidth = getFilterWidth(filter);
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    size_t outputChannels = output[1];
    size_t outputHeight = output[2];
    size_t outputWidth = output[3];

    real* outputGrad = inputs[0].data<real>();
    real* inputData = inputs[1].data<real>();
    real* filterGrad = outputs[0].data<real>();

    size_t size = inputChannels / groups_ * filterHeight * filterWidth *
                  outputHeight * outputWidth;
    resizeBuffer<Device>(size);
    real* colData = reinterpret_cast<real*>(memory_->getBuf());

    Im2ColFunctor<Device, real> im2col;
    GemmFunctor<Device, real> gemm;
    size_t inputOffset = (inputChannels / groups_) * inputHeight * inputWidth;
    size_t outputOffset =
        (outputChannels / groups_) * outputHeight * outputWidth;
    size_t filterOffset = filter.getElements() / groups_;
    for (size_t i = 0; i < batchSize; i++) {
      for (size_t g = 0; g < groups_; g++) {
        im2col(inputData + g * inputOffset,
               inputChannels / groups_,
               inputHeight,
               inputWidth,
               filterHeight,
               filterWidth,
               strideH(),
               strideW(),
               paddingH(),
               paddingW(),
               outputHeight,
               outputWidth,
               colData);

        int M = outputChannels / groups_;
        int K = outputHeight * outputWidth;
        int N = inputChannels / groups_ * filterHeight * filterWidth;
        gemm(CblasNoTrans,
             CblasTrans,
             M,
             N,
             K,
             1.0f,
             outputGrad + g * outputOffset,
             K,
             colData,
             K,
388
             i == 0 ? beta : 1.0f,
389 390 391
             filterGrad + g * filterOffset,
             N);
      }
392 393
      inputData += inputChannels * inputHeight * inputWidth;
      outputGrad += outputChannels * outputHeight * outputWidth;
394
    }
395 396 397
  }
};

398
REGISTER_TYPED_FUNC(GemmConv, CPU, GemmConvFunction);
399 400
REGISTER_TYPED_FUNC(GemmConvGradInput, CPU, GemmConvGradInputFunction);
REGISTER_TYPED_FUNC(GemmConvGradFilter, CPU, GemmConvGradFilterFunction);
H
hedaoyuan 已提交
401
#ifndef PADDLE_ONLY_CPU
402
REGISTER_TYPED_FUNC(GemmConv, GPU, GemmConvFunction);
403 404
REGISTER_TYPED_FUNC(GemmConvGradInput, GPU, GemmConvGradInputFunction);
REGISTER_TYPED_FUNC(GemmConvGradFilter, GPU, GemmConvGradFilterFunction);
H
hedaoyuan 已提交
405
#endif
406 407

}  // namespace paddle