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

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 已提交
46 47 48 49 50
  MatrixPtr dataValue = getInputValue(0);
  MatrixPtr roiValue = getInputValue(1);
  resetOutput(numROIs, channels_ * pooledHeight_ * pooledWidth_);
  MatrixPtr outputValue = getOutputValue();

G
guosheng 已提交
51
  if (useGpu_) {  // TODO(guosheng): implement on GPU later
G
guosheng 已提交
52 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
    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 已提交
80
  size_t channelOffset = height_ * width_;
G
guosheng 已提交
81 82
  real* bottomROIs = roiValue->getData();
  size_t roiOffset = roiValue->getWidth();
G
guosheng 已提交
83 84
  size_t poolChannelOffset = pooledHeight_ * pooledWidth_;

G
guosheng 已提交
85
  real* outputData = outputValue->getData();
G
guosheng 已提交
86 87 88 89 90 91 92 93
  Matrix::resizeOrCreate(maxIdxs_,
                         numROIs,
                         channels_ * pooledHeight_ * pooledWidth_,
                         false,
                         false);
  real* argmaxData = maxIdxs_->getData();

  for (size_t n = 0; n < numROIs; ++n) {
94 95
    // 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 已提交
96
    size_t roiBatchIdx = bottomROIs[0];
G
guosheng 已提交
97 98 99 100
    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_);
101
    CHECK_GE(roiBatchIdx, 0UL);
G
guosheng 已提交
102
    CHECK_LT(roiBatchIdx, batchSize);
103 104 105
    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 已提交
106 107 108 109 110 111 112 113 114 115 116 117
    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));
118 119 120 121 122 123 124 125
          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 已提交
126 127 128

          bool isEmpty = (hend <= hstart) || (wend <= wstart);
          size_t poolIndex = ph * pooledWidth_ + pw;
D
dangqingqing 已提交
129 130
          outputData[poolIndex] = isEmpty ? 0 : -FLT_MAX;
          argmaxData[poolIndex] = -1;
G
guosheng 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

          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];
                argmaxData[poolIndex] = index;
              }
            }
          }
        }
      }
      batchData += channelOffset;
      outputData += poolChannelOffset;
      argmaxData += poolChannelOffset;
    }
    bottomROIs += roiOffset;
  }
G
guosheng 已提交
149 150 151
  if (useGpu_) {
    getOutputValue()->copyFrom(*outputValue);
  }
G
guosheng 已提交
152 153 154
}

void ROIPoolLayer::backward(const UpdateCallback& callback) {
G
guosheng 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
  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 已提交
187 188 189
  size_t numROIs = getInput(1).getBatchSize();
  size_t roiOffset = getInputValue(1)->getWidth();

G
guosheng 已提交
190
  real* inDiffData = inGradValue->getData();
G
guosheng 已提交
191 192 193
  size_t batchOffset = getInputValue(0)->getWidth();
  size_t channelOffset = height_ * width_;

G
guosheng 已提交
194
  real* outDiffData = outGradValue->getData();
G
guosheng 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
  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 已提交
217 218 219 220

  if (useGpu_) {
    getInputGrad(0)->copyFrom(*inGradValue);
  }
G
guosheng 已提交
221 222 223
}

}  // namespace paddle