ExpandConvBaseLayer.cpp 10.2 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

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 "ExpandConvBaseLayer.h"

17 18 19
#include "paddle/utils/Logging.h"
namespace paddle {

20
bool ExpandConvBaseLayer::init(const LayerMap &layerMap,
21
                               const ParameterMap &parameterMap) {
22 23 24
  /* Initialize the basic convolutional parent class */
  ConvBaseLayer::init(layerMap, parameterMap);

25 26 27 28 29 30 31
  /* The class fields channels_ and numFilters_ are the same as in the config
   * i.e., channels_ is the for the input and numFilters_ is for the output
   *
   * But in order for the variables in convTrans having the same semantic
   * meaning as in conv, we need to swap channels_ and numFilters here for
   * convTrans, and in other functions too.
   * */
L
Luo Tao 已提交
32

33 34 35
  /* Initialize the projection */
  for (auto &inputConfig : config_.inputs()) {
    const ConvConfig &conf = inputConfig.conv_conf();
L
Luo Tao 已提交
36
    int numFilters = isDeconv_ ? conf.channels() : numFilters_;
37
    subM_.push_back(numFilters / conf.groups());
L
Luo Tao 已提交
38 39 40 41 42 43 44
    subN_.push_back(conf.output_x() *
                    (conf.has_output_y() ? conf.output_y() : conf.output_x()));
    int channel = isDeconv_ ? numFilters_ : conf.channels();
    subK_.push_back(
        channel * conf.filter_size() *
        (conf.has_filter_size_y() ? conf.filter_size_y() : conf.filter_size()) /
        conf.groups());
45 46 47 48
    /* Consistent caffe mode for multiple input */
    caffeMode_ = conf.caffe_mode();
  }

49 50
  getOutputSize();

51 52 53
  return true;
}

54 55 56 57 58 59 60 61 62 63
size_t ExpandConvBaseLayer::getOutputSize() {
  CHECK_NE(inputLayers_.size(), 0UL);
  size_t layerSize = ConvBaseLayer::calOutputSize();
  subN_.clear();
  for (size_t i = 0; i < inputLayers_.size(); i++) {
    subN_.push_back(outputH_[i] * outputW_[i]);
  }
  return layerSize;
}

64
void ExpandConvBaseLayer::resetExpandInput(size_t height, size_t width) {
65 66 67
  Matrix::resizeOrCreate(expandInput_, height, width, false, useGpu_);
}

68
void ExpandConvBaseLayer::addSharedBias() {
69
  size_t mapW = getOutputSize() / numFilters_;
70 71 72 73 74 75 76 77 78 79
  size_t mapH = getOutputValue()->getElementCnt() / mapW;
  MatrixPtr out =
      Matrix::create(getOutputValue()->getData(), mapH, mapW, false, useGpu_);

  Matrix::resizeOrCreate(transOutValue_, mapW, mapH, false, useGpu_);

  out->transpose(transOutValue_, false);  // false means no memory allocation
  transOutValue_->reshape(transOutValue_->getElementCnt() / numFilters_,
                          numFilters_);

80 81 82 83 84
  MatrixPtr bias = Matrix::create(biases_->getW()->getData(),
                                  1,
                                  biases_->getW()->getElementCnt(),
                                  false,
                                  useGpu_);
85 86 87 88 89 90 91 92 93
  transOutValue_->addBias(*bias, 1.0f);

  transOutValue_->reshape(mapW, mapH);
  transOutValue_->transpose(out, false);  // false means no memory allocation

  out->clear();
  bias->clear();
}

94
void ExpandConvBaseLayer::addUnsharedBias() {
95
  MatrixPtr outValue = getOutputValue();
96 97 98 99 100
  MatrixPtr bias = Matrix::create(biases_->getW()->getData(),
                                  1,
                                  biases_->getW()->getElementCnt(),
                                  false,
                                  useGpu_);
101 102 103
  outValue->addBias(*bias, 1.0f);
}

104 105 106
void ExpandConvBaseLayer::expandOneFrame(MatrixPtr image,
                                         size_t startIdx,
                                         int inIdx) {
107
  int channel = isDeconv_ ? numFilters_ : channels_[inIdx];
108 109

  resetExpandInput(subK_[inIdx] * groups_[inIdx], subN_[inIdx]);
110 111 112 113

  CHECK_EQ(image->getWidth(),
           static_cast<size_t>(imgSizeH_[inIdx] * imgSizeW_[inIdx] * channel));

114
  real *imgData = image->getData() + startIdx * image->getWidth();
115 116 117 118 119 120 121 122 123 124
  MatrixPtr imageTmp =
      Matrix::create(imgData,
                     1,
                     imgSizeH_[inIdx] * imgSizeW_[inIdx] * channel,
                     false,
                     useGpu_);
  expandInput_->convExpand(*imageTmp,
                           imgSizeH_[inIdx],
                           imgSizeW_[inIdx],
                           channel,
L
Luo Tao 已提交
125
                           filterSizeY_[inIdx],
126
                           filterSize_[inIdx],
L
Luo Tao 已提交
127
                           strideY_[inIdx],
128
                           stride_[inIdx],
L
Luo Tao 已提交
129
                           paddingY_[inIdx],
130 131 132
                           padding_[inIdx],
                           outputH_[inIdx],
                           outputW_[inIdx]);
133 134 135
  imageTmp->clear();
}

136 137 138 139
void ExpandConvBaseLayer::expandFwdOnce(MatrixPtr image,
                                        MatrixPtr out,
                                        int inIdx,
                                        int startIdx) {
140 141 142 143 144 145
  int subM = subM_[inIdx];
  int subN = subN_[inIdx];
  int subK = subK_[inIdx];

  expandOneFrame(image, startIdx, inIdx);

146
  int numFilters = isDeconv_ ? channels_[inIdx] : numFilters_;
147

148
  real *outData = out->getData() + startIdx * subN * numFilters;
149 150 151 152 153

  real *wgtData = weights_[inIdx]->getW()->getData();
  real *expInData = expandInput_->getData();
  for (int g = 0; g < groups_[inIdx]; ++g) {
    MatrixPtr A =
154
        Matrix::create(wgtData, subM, subK, false, useGpu_);  // mark transpose
155 156
    MatrixPtr B = Matrix::create(expInData, subK, subN, false, useGpu_);
    MatrixPtr C = Matrix::create(outData, subM, subN, false, useGpu_);
157
    C->mul(*A, *B, 1, 1);
158 159 160 161 162 163 164 165 166 167

    A->clear();
    B->clear();
    C->clear();
    wgtData += subK * subM;
    expInData += subK * subN;
    outData += subM * subN;
  }
}

168 169
void ExpandConvBaseLayer::bpropActs(MatrixPtr out,
                                    MatrixPtr image,
170
                                    int inpIdx) {
171
  int channel = isDeconv_ ? numFilters_ : channels_[inpIdx];
172 173 174 175 176 177 178 179 180

  int subM = subM_[inpIdx];
  int subN = subN_[inpIdx];
  int subK = subK_[inpIdx];
  size_t batchSize = image->getHeight();

  /* reset the expand-grad memory */
  resetExpandInput(subK * groups_[inpIdx], subN);

181 182
  real *localGradData = out->getData();
  real *tgtGradData = image->getData();
183 184 185 186 187 188 189 190
  for (size_t n = 0; n < batchSize; n++) {
    real *wgtData = weights_[inpIdx]->getW()->getData();
    real *expandInData = expandInput_->getData();

    for (int g = 0; g < groups_[inpIdx]; g++) {
      // create temporary matrix
      MatrixPtr C = Matrix::create(expandInData, subK, subN, false, useGpu_);
      MatrixPtr B = Matrix::create(localGradData, subM, subN, false, useGpu_);
191
      MatrixPtr A = Matrix::create(wgtData, subM, subK, true, useGpu_);
192
      C->mul(*A, *B);  // mul
193 194 195 196 197 198 199 200 201 202 203 204 205 206

      // clear the temporary matrix
      A->clear();
      B->clear();
      C->clear();

      expandInData += subK * subN;
      localGradData += subM * subN;
      wgtData += subK * subM;
    }

    // shrink one frame outGrad
    MatrixPtr oneGradTmp = Matrix::create(
        expandInput_->getData(), subK * groups_[inpIdx], subN, false, useGpu_);
207 208 209 210 211 212 213 214 215 216
    MatrixPtr vTmp =
        Matrix::create(tgtGradData,
                       1,
                       imgSizeH_[inpIdx] * imgSizeW_[inpIdx] * channel,
                       false,
                       useGpu_);
    vTmp->convShrink(*oneGradTmp,
                     imgSizeH_[inpIdx],
                     imgSizeW_[inpIdx],
                     channel,
L
Luo Tao 已提交
217
                     filterSizeY_[inpIdx],
218
                     filterSize_[inpIdx],
L
Luo Tao 已提交
219
                     strideY_[inpIdx],
220
                     stride_[inpIdx],
L
Luo Tao 已提交
221
                     paddingY_[inpIdx],
222 223 224 225 226
                     padding_[inpIdx],
                     outputH_[inpIdx],
                     outputW_[inpIdx],
                     1.0f,
                     1.0f);
227 228 229 230 231 232 233 234
    vTmp->clear();
    oneGradTmp->clear();

    // move the data-pointer
    tgtGradData += imgSizeH_[inpIdx] * imgSizeW_[inpIdx] * channel;
  }
}

235 236 237
void ExpandConvBaseLayer::bpropWeights(MatrixPtr image,
                                       MatrixPtr out,
                                       int inpIdx) {
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  MatrixPtr weightGrad = weights_[inpIdx]->getWGrad();

  int subM = subM_[inpIdx];
  int subN = subN_[inpIdx];
  int subK = subK_[inpIdx];
  size_t batchSize = image->getHeight();
  resetExpandInput(subK * groups_[inpIdx], subN);

  real *gradData = out->getData();

  for (size_t n = 0; n < batchSize; n++) {  // frame by frame
    // expand
    expandOneFrame(image, n, inpIdx);
    real *wGradData = weightGrad->getData();
    real *expandInData = expandInput_->getData();

    // expand-mul one-group by one
    for (int g = 0; g < groups_[inpIdx]; g++) {
256 257 258
      MatrixPtr A = Matrix::create(expandInData, subK, subN, true, useGpu_);
      MatrixPtr B = Matrix::create(gradData, subM, subN, false, useGpu_);
      MatrixPtr C = Matrix::create(wGradData, subM, subK, false, useGpu_);
259
      C->mul(*B, *A, 1, 1);
260 261 262 263 264 265 266 267 268 269 270

      A->clear();
      B->clear();
      C->clear();
      gradData += subM * subN;
      wGradData += subK * subM;
      expandInData += subK * subN;
    }
  }
}

271
void ExpandConvBaseLayer::bpropSharedBias(MatrixPtr biases, MatrixPtr v) {
272
  size_t mapW = getOutputSize() / numFilters_;
273 274 275 276 277 278 279 280 281 282 283
  size_t mapH = v->getElementCnt() / mapW;
  MatrixPtr vTmp = Matrix::create(v->getData(), mapH, mapW, false, useGpu_);

  Matrix::resizeOrCreate(transOutValue_, mapW, mapH, false, useGpu_);

  vTmp->transpose(transOutValue_, false);  // false means no memory allocation
  transOutValue_->reshape(transOutValue_->getElementCnt() / numFilters_,
                          numFilters_);
  biases->collectBias(*transOutValue_, 1.0f);
}

284
void ExpandConvBaseLayer::bpropBiases(MatrixPtr v) {
285 286 287 288 289
  MatrixPtr biases = Matrix::create(biases_->getWGrad()->getData(),
                                    1,
                                    biases_->getWGrad()->getElementCnt(),
                                    false,
                                    useGpu_);
290 291 292 293 294 295 296 297 298
  if (sharedBiases_) {
    bpropSharedBias(biases, v);
  } else {
    biases->collectBias(*v, 1.0f);
  }
  biases->clear();
}

}  // namespace paddle