roi_pool_op.cu 8.3 KB
Newer Older
W
wanghaox 已提交
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 "paddle/operators/roi_pool_op.h"
W
wanghaox 已提交
16
#include "paddle/platform/cuda_helper.h"
W
wanghaox 已提交
17 18 19 20

namespace paddle {
namespace operators {

W
wanghaox 已提交
21 22 23
static constexpr int kNumCUDAThreads = 512;
static constexpr int kNumMaxinumNumBlocks = 4096;
static constexpr int kROISize = 5;
W
wanghaox 已提交
24

W
wanghaox 已提交
25 26 27 28
static inline int NumBlocks(const int N) {
  return std::min((N + kNumCUDAThreads - 1) / kNumCUDAThreads,
                  kNumMaxinumNumBlocks);
  }
W
wanghaox 已提交
29

W
wanghaox 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42
  template <typename T>
  __global__ void GPUROIPoolForward(
      const int nthreads, const T* input_data, const int64_t* input_rois,
      const float spatial_scale, const int channels, const int height,
      const int width, const int pooled_height, const int pooled_width,
      T* output_data, int64_t* argmax_data) {
    int index = blockIdx.x * blockDim.x + threadIdx.x;
    int offset = blockDim.x * gridDim.x;
    for (size_t i = index; i < nthreads; i += offset) {
      int pw = index % pooled_width;
      int ph = (index / pooled_width) % pooled_height;
      int c = (index / pooled_width / pooled_height) % channels;
      int n = index / pooled_width / pooled_height / channels;
W
wanghaox 已提交
43

W
wanghaox 已提交
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 71 72 73 74 75 76
      const int64_t* offset_input_rois = input_rois + n * kROISize;
      int roi_batch_ind = offset_input_rois[0];
      int roi_start_w = round(offset_input_rois[1] * spatial_scale);
      int roi_start_h = round(offset_input_rois[2] * spatial_scale);
      int roi_end_w = round(offset_input_rois[3] * spatial_scale);
      int roi_end_h = round(offset_input_rois[4] * spatial_scale);

      int roi_width = max(roi_end_w - roi_start_w + 1, 1);
      int roi_height = max(roi_end_h - roi_start_h + 1, 1);
      T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pooled_height);
      T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pooled_width);

      int hstart = static_cast<int>(floor(static_cast<T>(ph) * bin_size_h));
      int wstart = static_cast<int>(floor(static_cast<T>(pw) * bin_size_w));
      int hend = static_cast<int>(ceil(static_cast<T>(ph + 1) * bin_size_h));
      int wend = static_cast<int>(ceil(static_cast<T>(pw + 1) * bin_size_w));

      hstart = min(max(hstart + roi_start_h, 0), height);
      hend = min(max(hend + roi_start_h, 0), height);
      wstart = min(max(wstart + roi_start_w, 0), width);
      wend = min(max(wend + roi_start_w, 0), width);
      bool is_empty = (hend <= hstart) || (wend <= wstart);

      T maxval = is_empty ? 0 : -std::numeric_limits<float>::max();
      int maxidx = -1;
      const T* offset_input_data =
          input_data + (roi_batch_ind * channels + c) * height * width;
      for (int h = hstart; h < hend; ++h) {
        for (int w = wstart; w < wend; ++w) {
          int input_data_index = h * width + w;
          if (offset_input_data[input_data_index] > maxval) {
            maxval = offset_input_data[input_data_index];
            maxidx = input_data_index;
W
wanghaox 已提交
77 78
          }
        }
W
wanghaox 已提交
79 80 81 82 83
      }
      output_data[index] = maxval;
      if (argmax_data) {
        argmax_data[index] = maxidx;
      }
W
wanghaox 已提交
84 85 86 87
    }
  }

template <typename T>
W
wanghaox 已提交
88
__global__ void GPUROIPoolBackward(
W
wanghaox 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    const int nthreads,
    const int64_t* input_rois,
    const T* output_grad,
    const int64_t* argmax_data,
    const int num_rois,
    const float spatial_scale,
    const int channels,
    const int height,
    const int width,
    const int pooled_height,
    const int pooled_width,
    T* input_grad) {
    int index = blockIdx.x * blockDim.x + threadIdx.x;
    int offset = blockDim.x * gridDim.x;
    for (int i = index; i < nthreads; i += offset) {
      int pw = index % pooled_width;
      int ph = (index / pooled_width) % pooled_height;
      int c = (index / pooled_width / pooled_height) % channels;
      int n = index / pooled_width / pooled_height / channels;

W
wanghaox 已提交
109
      const int64_t* offset_input_rois = input_rois + n * kROISize;
W
wanghaox 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
      int roi_batch_ind = offset_input_rois[0];
      int input_offset = (roi_batch_ind * channels + c) * height * width;
      int output_offset = (n * channels + c) * pooled_height * pooled_width;
      const T* offset_output_grad = output_grad + output_offset;
      T* offset_input_grad = input_grad + input_offset;
      const int64_t* offset_argmax_data = argmax_data + output_offset;

      int argmax = offset_argmax_data[ph * pooled_width + pw];
      if (argmax != -1) {
        platform::CudaAtomicAdd(offset_input_grad + argmax,
          static_cast<T>(offset_output_grad[ph * pooled_width + pw]));
      }
    }
  }


template <typename Place, typename T>
W
wanghaox 已提交
127
class GPUROIPoolOpKernel : public framework::OpKernel<T> {
W
wanghaox 已提交
128 129 130
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* in = ctx.Input<Tensor>("X");
W
wanghaox 已提交
131
    auto* rois = ctx.Input<Tensor>("ROIs");
W
wanghaox 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144
    auto* out = ctx.Output<Tensor>("Out");
    auto* argmax = ctx.Output<Tensor>("Argmax");

    auto pooled_height = ctx.Attr<int>("pooled_height");
    auto pooled_width = ctx.Attr<int>("pooled_width");
    auto spatial_scale = ctx.Attr<float>("spatial_scale");

    auto in_dims = in->dims();
    auto in_stride = framework::stride(in_dims);
    int channels = in_dims[1];
    int height = in_dims[2];
    int width = in_dims[3];

W
wanghaox 已提交
145
    size_t rois_num = rois->dims()[0];
W
wanghaox 已提交
146 147 148 149 150 151 152 153 154 155 156

    out->mutable_data<T>(ctx.GetPlace());
    math::SetConstant<Place, T> set_zero;
    set_zero(ctx.device_context(), out, static_cast<T>(0));
    argmax->mutable_data<int64_t>(ctx.GetPlace());
    math::SetConstant<Place, int64_t> set_init;
    set_init(ctx.device_context(), argmax, static_cast<int64_t>(-1));

    if (rois_num== 0) return;

    int output_size = out->numel();
W
wanghaox 已提交
157 158
    int blocks = NumBlocks(output_size);
    int threads = kNumCUDAThreads;
W
wanghaox 已提交
159

W
wanghaox 已提交
160
    GPUROIPoolForward<T>
W
wanghaox 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
      <<<blocks, threads, 0, ctx.cuda_device_context().stream()>>>(
      output_size,
      in->data<T>(),
      rois->data<int64_t>(),
      spatial_scale,
      channels,
      height,
      width,
      pooled_height,
      pooled_width,
      out->mutable_data<T>(ctx.GetPlace()),
      argmax->mutable_data<int64_t>(ctx.GetPlace()));
  }
};

template <typename Place, typename T>
W
wanghaox 已提交
177
class GPUROIPoolGradOpKernel : public framework::OpKernel<T> {
W
wanghaox 已提交
178 179 180
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* in = ctx.Input<Tensor>("X");
W
wanghaox 已提交
181
    auto* rois = ctx.Input<Tensor>("ROIs");
W
wanghaox 已提交
182 183 184 185 186 187 188 189 190 191 192
    auto* argmax = ctx.Input<Tensor>("Argmax");

    auto* out_grad =
        ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto* x_grad =
        ctx.Output<Tensor>(framework::GradVarName("X"));

    auto pooled_height = ctx.Attr<int>("pooled_height");
    auto pooled_width = ctx.Attr<int>("pooled_width");
    auto spatial_scale = ctx.Attr<float>("spatial_scale");

W
wanghaox 已提交
193
    size_t rois_num = rois->dims()[0];
W
wanghaox 已提交
194 195 196 197 198 199 200 201 202 203
    int channels = in->dims()[1];
    int height = in->dims()[2];
    int width = in->dims()[3];

    if (x_grad) {
      x_grad->mutable_data<T>(ctx.GetPlace());
      math::SetConstant<Place, T> set_zero;
      set_zero(ctx.device_context(), x_grad, static_cast<T>(0));

      int output_grad_size = out_grad->numel();
W
wanghaox 已提交
204 205
      int blocks = NumBlocks(output_grad_size);
      int threads = kNumCUDAThreads;
W
wanghaox 已提交
206 207

      if (output_grad_size > 0) {
W
wanghaox 已提交
208
        GPUROIPoolBackward<T>
W
wanghaox 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
          <<<blocks, threads, 0, ctx.cuda_device_context().stream()>>>(
          output_grad_size,
          rois->data<int64_t>(),
          out_grad->data<T>(),
          argmax->data<int64_t>(),
          rois_num,
          spatial_scale,
          channels,
          height,
          width,
          pooled_height,
          pooled_width,
          x_grad->mutable_data<T>(ctx.GetPlace()));
        }
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP_GPU_KERNEL(
    roi_pool,
W
wanghaox 已提交
233
    ops::GPUROIPoolOpKernel<paddle::platform::GPUPlace, float>);
W
wanghaox 已提交
234 235
REGISTER_OP_GPU_KERNEL(
    roi_pool_grad,
W
wanghaox 已提交
236
    ops::GPUROIPoolGradOpKernel<paddle::platform::GPUPlace, float>);