ROIPoolLayer.cpp 8.4 KB
Newer Older
G
guosheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* 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. */

#include "ROIPoolLayer.h"
D
dangqingqing 已提交
16
#include <cfloat>
G
guosheng 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

namespace paddle {

REGISTER_LAYER(roi_pool, ROIPoolLayer);

bool ROIPoolLayer::init(const LayerMap& layerMap,
                        const ParameterMap& parameterMap) {
  Layer::init(layerMap, parameterMap);

  const ROIPoolConfig& layerConf = config_.inputs(0).roi_pool_conf();
  pooledWidth_ = layerConf.pooled_width();
  pooledHeight_ = layerConf.pooled_height();
  spatialScale_ = layerConf.spatial_scale();

  return true;
}

void ROIPoolLayer::forward(PassType passType) {
  Layer::forward(passType);

  const ROIPoolConfig& layerConf = config_.inputs(0).roi_pool_conf();
  height_ = getInput(0).getFrameHeight();
  if (!height_) height_ = layerConf.height();
  width_ = getInput(0).getFrameWidth();
  if (!width_) width_ = layerConf.width();
  channels_ = getInputValue(0)->getWidth() / width_ / height_;

  size_t batchSize = getInput(0).getBatchSize();
  size_t numROIs = getInput(1).getBatchSize();

G
guosheng 已提交
47 48 49 50 51
  MatrixPtr dataValue = getInputValue(0);
  MatrixPtr roiValue = getInputValue(1);
  resetOutput(numROIs, channels_ * pooledHeight_ * pooledWidth_);
  MatrixPtr outputValue = getOutputValue();

G
guosheng 已提交
52
  if (useGpu_) {  // TODO(guosheng): implement on GPU later
G
guosheng 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    MatrixPtr dataCpuBuffer;
    Matrix::resizeOrCreate(dataCpuBuffer,
                           dataValue->getHeight(),
                           dataValue->getWidth(),
                           false,
                           false);
    MatrixPtr roiCpuBuffer;
    Matrix::resizeOrCreate(roiCpuBuffer,
                           roiValue->getHeight(),
                           roiValue->getWidth(),
                           false,
                           false);
    dataCpuBuffer->copyFrom(*dataValue);
    roiCpuBuffer->copyFrom(*roiValue);
    dataValue = dataCpuBuffer;
    roiValue = roiCpuBuffer;
    MatrixPtr outputCpuBuffer;
    Matrix::resizeOrCreate(outputCpuBuffer,
                           outputValue->getHeight(),
                           outputValue->getWidth(),
                           false,
                           false);
    outputCpuBuffer->copyFrom(*outputValue);
    outputValue = outputCpuBuffer;
  }

  real* bottomData = dataValue->getData();
  size_t batchOffset = dataValue->getWidth();
G
guosheng 已提交
81
  size_t channelOffset = height_ * width_;
G
guosheng 已提交
82 83
  real* bottomROIs = roiValue->getData();
  size_t roiOffset = roiValue->getWidth();
G
guosheng 已提交
84 85
  size_t poolChannelOffset = pooledHeight_ * pooledWidth_;

G
guosheng 已提交
86
  real* outputData = outputValue->getData();
87 88 89 90 91 92 93 94 95
  real* argmaxData = nullptr;
  if (passType != PASS_TEST) {
    Matrix::resizeOrCreate(maxIdxs_,
                           numROIs,
                           channels_ * pooledHeight_ * pooledWidth_,
                           false,
                           false);
    argmaxData = maxIdxs_->getData();
  }
G
guosheng 已提交
96 97

  for (size_t n = 0; n < numROIs; ++n) {
98 99
    // the first five elememts of each RoI should be:
    // batch_idx, roi_x_start, roi_y_start, roi_x_end, roi_y_end
G
guosheng 已提交
100
    size_t roiBatchIdx = bottomROIs[0];
G
guosheng 已提交
101 102 103 104
    size_t roiStartW = round(bottomROIs[1] * spatialScale_);
    size_t roiStartH = round(bottomROIs[2] * spatialScale_);
    size_t roiEndW = round(bottomROIs[3] * spatialScale_);
    size_t roiEndH = round(bottomROIs[4] * spatialScale_);
105
    CHECK_GE(roiBatchIdx, 0UL);
G
guosheng 已提交
106
    CHECK_LT(roiBatchIdx, batchSize);
107 108 109
    size_t roiHeight =
        std::max(roiEndH - roiStartH + 1, static_cast<size_t>(1));
    size_t roiWidth = std::max(roiEndW - roiStartW + 1, static_cast<size_t>(1));
G
guosheng 已提交
110 111 112 113 114 115 116 117 118 119 120 121
    real binSizeH =
        static_cast<real>(roiHeight) / static_cast<real>(pooledHeight_);
    real binSizeW =
        static_cast<real>(roiWidth) / static_cast<real>(pooledWidth_);
    real* batchData = bottomData + batchOffset * roiBatchIdx;
    for (size_t c = 0; c < channels_; ++c) {
      for (size_t ph = 0; ph < pooledHeight_; ++ph) {
        for (size_t pw = 0; pw < pooledWidth_; ++pw) {
          size_t hstart = static_cast<size_t>(std::floor(ph * binSizeH));
          size_t wstart = static_cast<size_t>(std::floor(pw * binSizeW));
          size_t hend = static_cast<size_t>(std::ceil((ph + 1) * binSizeH));
          size_t wend = static_cast<size_t>(std::ceil((pw + 1) * binSizeW));
122 123 124 125 126 127 128 129
          hstart = std::min(
              std::max(hstart + roiStartH, static_cast<size_t>(0)), height_);
          wstart = std::min(
              std::max(wstart + roiStartW, static_cast<size_t>(0)), width_);
          hend = std::min(std::max(hend + roiStartH, static_cast<size_t>(0)),
                          height_);
          wend = std::min(std::max(wend + roiStartW, static_cast<size_t>(0)),
                          width_);
G
guosheng 已提交
130 131 132

          bool isEmpty = (hend <= hstart) || (wend <= wstart);
          size_t poolIndex = ph * pooledWidth_ + pw;
D
dangqingqing 已提交
133
          outputData[poolIndex] = isEmpty ? 0 : -FLT_MAX;
134 135 136
          if (argmaxData) {
            argmaxData[poolIndex] = -1;
          }
G
guosheng 已提交
137 138 139 140 141 142

          for (size_t h = hstart; h < hend; ++h) {
            for (size_t w = wstart; w < wend; ++w) {
              size_t index = h * width_ + w;
              if (batchData[index] > outputData[poolIndex]) {
                outputData[poolIndex] = batchData[index];
143 144 145
                if (argmaxData) {
                  argmaxData[poolIndex] = index;
                }
G
guosheng 已提交
146 147 148 149 150 151 152
              }
            }
          }
        }
      }
      batchData += channelOffset;
      outputData += poolChannelOffset;
153 154 155
      if (argmaxData) {
        argmaxData += poolChannelOffset;
      }
G
guosheng 已提交
156 157 158
    }
    bottomROIs += roiOffset;
  }
G
guosheng 已提交
159 160 161
  if (useGpu_) {
    getOutputValue()->copyFrom(*outputValue);
  }
G
guosheng 已提交
162 163 164
}

void ROIPoolLayer::backward(const UpdateCallback& callback) {
G
guosheng 已提交
165 166 167 168 169 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
  MatrixPtr inGradValue = getInputGrad(0);
  MatrixPtr outGradValue = getOutputGrad();
  MatrixPtr roiValue = getInputValue(1);

  if (useGpu_) {
    MatrixPtr inGradCpuBuffer;
    Matrix::resizeOrCreate(inGradCpuBuffer,
                           inGradValue->getHeight(),
                           inGradValue->getWidth(),
                           false,
                           false);
    MatrixPtr outGradCpuBuffer;
    Matrix::resizeOrCreate(outGradCpuBuffer,
                           outGradValue->getHeight(),
                           outGradValue->getWidth(),
                           false,
                           false);
    MatrixPtr roiCpuBuffer;
    Matrix::resizeOrCreate(roiCpuBuffer,
                           roiValue->getHeight(),
                           roiValue->getWidth(),
                           false,
                           false);
    inGradCpuBuffer->copyFrom(*inGradValue);
    outGradCpuBuffer->copyFrom(*outGradValue);
    roiCpuBuffer->copyFrom(*roiValue);
    inGradValue = inGradCpuBuffer;
    outGradValue = outGradCpuBuffer;
    roiValue = roiCpuBuffer;
  }

  real* bottomROIs = roiValue->getData();
G
guosheng 已提交
197 198 199
  size_t numROIs = getInput(1).getBatchSize();
  size_t roiOffset = getInputValue(1)->getWidth();

G
guosheng 已提交
200
  real* inDiffData = inGradValue->getData();
G
guosheng 已提交
201 202 203
  size_t batchOffset = getInputValue(0)->getWidth();
  size_t channelOffset = height_ * width_;

G
guosheng 已提交
204
  real* outDiffData = outGradValue->getData();
G
guosheng 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
  size_t poolChannelOffset = pooledHeight_ * pooledWidth_;
  real* argmaxData = maxIdxs_->getData();

  for (size_t n = 0; n < numROIs; ++n) {
    size_t roiBatchIdx = bottomROIs[0];
    real* batchDiffData = inDiffData + batchOffset * roiBatchIdx;
    for (size_t c = 0; c < channels_; ++c) {
      for (size_t ph = 0; ph < pooledHeight_; ++ph) {
        for (size_t pw = 0; pw < pooledWidth_; ++pw) {
          size_t poolIndex = ph * pooledWidth_ + pw;
          if (argmaxData[poolIndex] > 0) {
            size_t index = static_cast<size_t>(argmaxData[poolIndex]);
            batchDiffData[index] += outDiffData[poolIndex];
          }
        }
      }
      batchDiffData += channelOffset;
      outDiffData += poolChannelOffset;
      argmaxData += poolChannelOffset;
    }
    bottomROIs += roiOffset;
  }
G
guosheng 已提交
227 228 229 230

  if (useGpu_) {
    getInputGrad(0)->copyFrom(*inGradValue);
  }
G
guosheng 已提交
231 232 233
}

}  // namespace paddle