ExpandConvLayer.cpp 8.7 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

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. */

Y
Yu Yang 已提交
15
#include "ExpandConvLayer.h"
Z
zhangjinchao01 已提交
16 17 18
#include "paddle/utils/Logging.h"
#include "paddle/utils/Stat.h"

19 20 21 22
DEFINE_bool(use_nnpack,
            false,
            "Whether to use nnpack for convolution calculation.");

Z
zhangjinchao01 已提交
23 24
namespace paddle {

25 26 27 28
/*
 * The calculation of the exconvt(convolution transpose (deconv) operation)
 * is a swap of forward and backward of the calculation of exconv.
 * */
Z
zhangjinchao01 已提交
29
REGISTER_LAYER(exconv, ExpandConvLayer);
30
REGISTER_LAYER(exconvt, ExpandConvLayer);
Z
zhangjinchao01 已提交
31

32 33 34 35
inline bool isDepthwiseConv(int channels, int groups) {
  return channels == groups;
}

Z
zhangjinchao01 已提交
36 37 38
bool ExpandConvLayer::init(const LayerMap &layerMap,
                           const ParameterMap &parameterMap) {
  /* Initialize the basic convolutional parent class */
H
hedaoyuan 已提交
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
  ConvBaseLayer::init(layerMap, parameterMap);

  int index = 0;
  for (auto &inputConfig : config_.inputs()) {
    const ConvConfig &conf = inputConfig.conv_conf();
    /* Consistent caffe mode for multiple input */
    caffeMode_ = conf.caffe_mode();

    // create a new weight
    size_t height, width;
    height = filterPixels_[index] * filterChannels_[index];
    width = (!isDeconv_) ? numFilters_ : channels_[index];
    CHECK_EQ(parameters_[index]->getSize(), width * height);
    Weight *w = new Weight(height, width, parameters_[index]);
    weights_.emplace_back(w);
    index++;
  }
  if (biasParameter_.get()) {
    if (sharedBiases_) {
      CHECK_EQ((size_t)numFilters_, biasParameter_->getSize());
      biases_ =
          std::unique_ptr<Weight>(new Weight(numFilters_, 1, biasParameter_));
    } else {
      biases_ =
          std::unique_ptr<Weight>(new Weight(getSize(), 1, biasParameter_));
    }
  }

  getOutputSize();
68 69 70 71 72

  size_t numInputs = config_.inputs_size();
  inputShape_.resize(numInputs);
  filterShape_.resize(numInputs);
  outputShape_.resize(numInputs);
X
xzl 已提交
73

74 75 76
  std::string convType;
  std::string convGradInputType;
  std::string convGradFilterType;
X
xzl 已提交
77

78 79 80 81
  for (int i = 0; i < config_.inputs_size(); i++) {
    std::vector<size_t> paddings = {(size_t)paddingY_[i], (size_t)padding_[i]};
    std::vector<size_t> strides = {(size_t)strideY_[i], (size_t)stride_[i]};

82 83 84 85 86 87 88
    // Convolution Layer uses the GemmConv function by default.
    convType = "GemmConv";
    convGradInputType = "GemmConvGradInput";
    convGradFilterType = "GemmConvGradFilter";

    // If depth wise convolution and useGpu == true
    if (useGpu_ && isDepthwiseConv(channels_[i], groups_[i]) && !isDeconv_) {
89 90 91
      convType = "DepthwiseConv";
      convGradInputType = "DepthwiseConvGradInput";
      convGradFilterType = "DepthwiseConvGradFilter";
92 93 94 95 96
    }

    // If depth wise convolution and useGpu == false and ARM-NEON
    if (!useGpu_ && isDepthwiseConv(channels_[i], groups_[i]) && !isDeconv_) {
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
H
hedaoyuan 已提交
97 98 99 100 101
      if ((filterSize_[i] == filterSizeY_[i]) &&
          (filterSize_[i] == 3 || filterSize_[i] == 4) &&
          (stride_[i] == strideY_[i]) && (stride_[i] == 1 || stride_[i] == 2)) {
        convType = "NeonDepthwiseConv";
      }
102
#endif
X
xzl 已提交
103 104
    }

105
    if (FLAGS_use_nnpack && !isDeconv_) {
106 107 108 109 110 111
      createFunction(forward_,
                     "NNPACKConv",
                     FuncConfig()
                         .set("paddings", paddings)
                         .set("strides", strides)
                         .set("groups", (size_t)groups_[i])
H
hedaoyuan 已提交
112
                         .set("algo", std::string("auto")));
113 114
    } else {
      createFunction(forward_,
X
xzl 已提交
115
                     !isDeconv_ ? convType : convGradInputType,
116 117 118 119 120 121
                     FuncConfig()
                         .set("paddings", paddings)
                         .set("strides", strides)
                         .set("groups", (size_t)groups_[i]));

      createFunction(backward_,
X
xzl 已提交
122
                     !isDeconv_ ? convGradInputType : convType,
123 124 125 126
                     FuncConfig()
                         .set("paddings", paddings)
                         .set("strides", strides)
                         .set("groups", (size_t)groups_[i]));
127

128
      createFunction(backward_,
X
xzl 已提交
129
                     convGradFilterType,
130 131 132 133 134
                     FuncConfig()
                         .set("paddings", paddings)
                         .set("strides", strides)
                         .set("groups", (size_t)groups_[i]));
    }
135
  }
Z
zhangjinchao01 已提交
136 137 138
  return true;
}

H
hedaoyuan 已提交
139 140 141 142 143 144
size_t ExpandConvLayer::getOutputSize() {
  CHECK_NE(inputLayers_.size(), 0UL);
  size_t layerSize = ConvBaseLayer::calOutputSize();
  return layerSize;
}

145 146 147 148 149 150
// i is the index of input layers
#define BACKWARD_INPUT(i, inputs, outputs) \
  backward_[2 * i]->calc(inputs, outputs)
#define BACKWARD_FILTER(i, inputs, outputs) \
  backward_[2 * i + 1]->calc(inputs, outputs)

Z
zhangjinchao01 已提交
151 152 153
void ExpandConvLayer::forward(PassType passType) {
  Layer::forward(passType);

154
  size_t batchSize = inputLayers_[0]->getOutputValue()->getHeight();
155
  resetOutput(batchSize, getOutputSize());
Z
zhangjinchao01 已提交
156

157
  // Calculate the shape of the input, output, and filter.
158
  for (size_t i = 0; i < inputLayers_.size(); ++i) {
159 160 161 162 163
    inputShape_[i] = TensorShape({(size_t)batchSize,
                                  (size_t)channels_[i],
                                  (size_t)imgSizeH_[i],
                                  (size_t)imgSizeW_[i]});
    filterShape_[i] =
H
hedaoyuan 已提交
164 165 166 167 168
        TensorShape({(size_t)groups_[i],
                     !isDeconv_ ? (size_t)numFilters_ / groups_[i]
                                : (size_t)channels_[i] / groups_[i],
                     !isDeconv_ ? (size_t)channels_[i] / groups_[i]
                                : (size_t)numFilters_ / groups_[i],
169 170 171 172 173 174
                     (size_t)filterSizeY_[i],
                     (size_t)filterSize_[i]});
    outputShape_[i] = TensorShape({(size_t)batchSize,
                                   (size_t)numFilters_,
                                   (size_t)outputH_[i],
                                   (size_t)outputW_[i]});
Z
zhangjinchao01 已提交
175
  }
176 177 178 179 180 181 182

  // Calculate the output value.
  for (size_t i = 0; i < inputLayers_.size(); ++i) {
    BufferArgs inputs;
    BufferArgs outputs;
    inputs.addArg(*getInputValue(i), inputShape_[i]);
    inputs.addArg(*weights_[i]->getW(), filterShape_[i]);
H
hedaoyuan 已提交
183 184 185
    outputs.addArg(*getOutputValue(),
                   outputShape_[i],
                   !isDeconv_ && i == 0 ? ASSIGN_TO : ADD_TO);
186 187 188 189

    forward_[i]->calc(inputs, outputs);
  }

Z
zhangjinchao01 已提交
190
  /* add the bias-vector */
191
  if (biases_.get()) {
H
hedaoyuan 已提交
192 193 194 195 196 197
    MatrixPtr bias = Matrix::create(biases_->getW()->getData(),
                                    1,
                                    biases_->getW()->getElementCnt(),
                                    false,
                                    useGpu_);
    output_.value->addBias(*bias, 1.0, sharedBiases_);
Z
zhangjinchao01 已提交
198 199 200 201 202 203 204 205 206 207 208
  }

  /* activation */
  forwardActivation();
}

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

  MatrixPtr outGrad = getOutputGrad();
  if (biases_ && biases_->getWGrad()) {
H
hedaoyuan 已提交
209 210 211 212 213 214 215
    // bpropBiases(outGrad);
    MatrixPtr bias = Matrix::create(biases_->getWGrad()->getData(),
                                    1,
                                    biases_->getWGrad()->getElementCnt(),
                                    false,
                                    useGpu_);
    bias->collectBias(*getOutputGrad(), 1, sharedBiases_);
Z
zhangjinchao01 已提交
216 217 218 219
    /* Increasing the number of gradient */
    biases_->getParameterPtr()->incUpdate(callback);
  }

220
  // Calculate the input grad and filter grad.
221
  for (size_t i = 0; i < inputLayers_.size(); ++i) {
222 223 224 225 226 227 228
    if (getInputGrad(i)) {
      BufferArgs inputs;
      BufferArgs outputs;
      inputs.addArg(*getOutputGrad(), outputShape_[i]);
      inputs.addArg(*weights_[i]->getW(), filterShape_[i]);
      outputs.addArg(*getInputGrad(i), inputShape_[i], ADD_TO);
      BACKWARD_INPUT(i, inputs, outputs);
229
    }
230

Z
zhangjinchao01 已提交
231
    if (weights_[i]->getWGrad()) {
232 233 234 235 236 237 238 239 240 241 242 243
      BufferArgs inputs;
      BufferArgs outputs;
      if (!isDeconv_) {
        inputs.addArg(*getOutputGrad(), outputShape_[i]);
        inputs.addArg(*getInputValue(i), inputShape_[i]);
      } else {
        inputs.addArg(*getInputValue(i), inputShape_[i]);
        inputs.addArg(*getOutputGrad(), outputShape_[i]);
      }
      outputs.addArg(*weights_[i]->getWGrad(), filterShape_[i], ADD_TO);
      BACKWARD_FILTER(i, inputs, outputs);

Z
zhangjinchao01 已提交
244 245 246 247 248 249 250
      /* Increasing the number of gradient */
      weights_[i]->getParameterPtr()->incUpdate(callback);
    }
  }
}

}  // namespace paddle