GemmConvOp.cpp 7.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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
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;
      int c_im = c / filterHeight / filterWidth;
      for (int h = 0; h < outputHeight; ++h) {
        for (int w = 0; w < outputWidth; ++w) {
          // no c_im*height to Exclude the channel number
          int imgRowIdx = h * strideHeight + hOffset;
          int imgColIdx = w * strideWidth + wOffset;
          if ((imgRowIdx - paddingHeight) < 0 ||
              (imgRowIdx - paddingHeight) >= inputHeight ||
              (imgColIdx - paddingWidth) < 0 ||
              (imgColIdx - paddingWidth) >= inputWidth) {
            colData[(c * outputHeight + h) * outputWidth + w] = T(0);
          } else {
            imgRowIdx += c_im * inputHeight - paddingHeight;
            imgColIdx -= paddingWidth;
            colData[(c * outputHeight + h) * outputWidth + w] =
                imData[imgRowIdx * inputWidth + imgColIdx];
          }
        }
      }
    }
  }
};

/*
71
 * \brief Forward calculation of convolution.
72 73 74 75 76 77 78 79 80
 */
template <DeviceType Device>
class GemmConvFunction : public ConvFunctionBase {
public:
  void init(const FuncConfig& config) override {
    ConvFunctionBase::init(config);
  }

  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    CHECK_EQ(numInputs_, inputs.size());
    CHECK_EQ(numOutputs_, outputs.size());
    // 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();
    check(input, filter, output);

    real beta;
    if (outputs[0].getArgType() == ADD_TO) {
      beta = 1.0;
    } else {
      beta = 0.0;
    }
96 97 98 99 100 101

    size_t batchSize = inputs[0].shape()[0];
    size_t inputChannels = inputs[0].shape()[1];
    size_t inputHeight = inputs[0].shape()[2];
    size_t inputWidth = inputs[0].shape()[3];
    size_t filterHeight = inputs[1].shape()[2];
H
hedaoyuan 已提交
102
    size_t filterWidth = inputs[1].shape()[3];
103 104 105 106 107 108 109 110
    size_t outputChannels = outputs[0].shape()[1];
    size_t outputHeight = outputs[0].shape()[2];
    size_t outputWidth = outputs[0].shape()[3];

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

111 112
    size_t size = inputChannels / groups_ * filterHeight * filterWidth *
                  outputHeight * outputWidth;
113 114 115
    resizeBuffer(size);
    real* colData = reinterpret_cast<real*>(memory_->getBuf());

116 117
    Im2ColFunctor<Device, real> im2col;
    GemmFunctor<Device, real> gemm;
118 119 120 121
    size_t inputOffset = (inputChannels / groups_) * inputHeight * inputWidth;
    size_t outputOffset =
        (outputChannels / groups_) * outputHeight * outputWidth;
    size_t filterOffset = inputs[1].shape().getElements() / groups_;
122
    for (size_t i = 0; i < batchSize; i++) {
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
      for (int g = 0; g < groups_; g++) {
        im2col(inputData + g * inputOffset,
               inputChannels / groups_,
               inputHeight,
               inputWidth,
               filterHeight,
               filterWidth,
               strideH(),
               strideW(),
               paddingH(),
               paddingW(),
               outputHeight,
               outputWidth,
               colData);

H
Bug fix  
hedaoyuan 已提交
138
        int M = outputChannels / groups_;
139
        int N = outputHeight * outputWidth;
H
Bug fix  
hedaoyuan 已提交
140
        int K = inputChannels / groups_ * filterHeight * filterWidth;
141 142 143 144 145 146 147 148
        gemm(M,
             N,
             K,
             1.0f,
             filterData + g * filterOffset,
             K,
             colData,
             N,
149
             beta,
150 151
             outputData + g * outputOffset,
             N);
152
      }
H
hedaoyuan 已提交
153 154
      inputData += inputChannels * inputHeight * inputWidth;
      outputData += outputChannels * outputHeight * outputWidth;
155 156 157 158 159
    }
  }

  void resizeBuffer(size_t newSize) {
    if (!memory_ || newSize * sizeof(real) > memory_->getAllocSize()) {
H
hedaoyuan 已提交
160 161 162 163 164
      if (Device == DEVICE_TYPE_CPU) {
        memory_ = std::make_shared<CpuMemoryHandle>(newSize * sizeof(real));
      } else {
        memory_ = std::make_shared<GpuMemoryHandle>(newSize * sizeof(real));
      }
165 166 167 168
    }
  }

private:
H
hedaoyuan 已提交
169
  MemoryHandlePtr memory_;
170 171
};

172 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
/*
 * \brief Backward input calculation of convolution.
 */
template <DeviceType Device>
class GemmConvGradInputFunction : public ConvFunctionBase {
public:
  void init(const FuncConfig& config) override {
    ConvFunctionBase::init(config);
  }

  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_EQ(numInputs_, inputs.size());
    CHECK_EQ(numOutputs_, outputs.size());
    const TensorShape& outputGrad = inputs[0].shape();
    const TensorShape& filter = inputs[1].shape();
    const TensorShape& inputGrad = outputs[0].shape();
    check(inputGrad, filter, outputGrad);
  }
};

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

  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_EQ(numInputs_, inputs.size());
    CHECK_EQ(numOutputs_, outputs.size());
    const TensorShape& outputGrad = inputs[0].shape();
    const TensorShape& input = inputs[1].shape();
    const TensorShape& filterGrad = outputs[0].shape();
    check(input, filterGrad, outputGrad);
  }
};

212
REGISTER_TYPED_FUNC(GemmConv, CPU, GemmConvFunction);
213 214
REGISTER_TYPED_FUNC(GemmConvGradInput, CPU, GemmConvGradInputFunction);
REGISTER_TYPED_FUNC(GemmConvGradFilter, CPU, GemmConvGradFilterFunction);
H
hedaoyuan 已提交
215
#ifndef PADDLE_ONLY_CPU
216
REGISTER_TYPED_FUNC(GemmConv, GPU, GemmConvFunction);
217 218
REGISTER_TYPED_FUNC(GemmConvGradInput, GPU, GemmConvGradInputFunction);
REGISTER_TYPED_FUNC(GemmConvGradFilter, GPU, GemmConvGradFilterFunction);
H
hedaoyuan 已提交
219
#endif
220 221

}  // namespace paddle