roi_align_op_xpu.cc 9.8 KB
Newer Older
D
Double_V 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

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

#ifdef PADDLE_WITH_XPU
#include <memory>
#include <string>
18

19
#include "paddle/fluid/framework/op_registry.h"
D
Double_V 已提交
20 21 22 23

namespace paddle {
namespace operators {

24 25 26
using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;

D
Double_V 已提交
27 28 29 30
template <typename DeviceContext, typename T>
class XPUROIAlignOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
31 32 33 34
    auto* in = ctx.Input<Tensor>("X");
    auto* rois = ctx.Input<LoDTensor>("ROIs");
    auto* out = ctx.Output<Tensor>("Out");

D
Double_V 已提交
35 36 37 38
    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 sampling_ratio = ctx.Attr<int>("sampling_ratio");
39
    auto aligned = ctx.Attr<bool>("aligned");
40

41
    const auto& in_dims = in->dims();
D
Double_V 已提交
42 43 44 45
    int batch_size = in_dims[0];
    int channels = in_dims[1];
    int height = in_dims[2];
    int width = in_dims[3];
46

D
Double_V 已提交
47
    int rois_num = rois->dims()[0];
48

49 50 51 52 53 54 55
    if (rois_num == 0) return;

    Tensor roi_batch_id_list;
    roi_batch_id_list.Resize({rois_num});
    auto cplace = platform::CPUPlace();
    int* roi_batch_id_data = roi_batch_id_list.mutable_data<int>(cplace);
    auto& dev_ctx = ctx.template device_context<DeviceContext>();
56
    auto xplace = ctx.GetPlace();
57 58
    int rois_batch_size = 0;
    int* cpu_lod = nullptr;
59
    if (ctx.HasInput("RoisNum")) {
60
      auto* rois_num_t = ctx.Input<Tensor>("RoisNum");
61 62
      rois_batch_size = rois_num_t->numel();
      PADDLE_ENFORCE_EQ(
63 64
          rois_batch_size,
          batch_size,
65
          platform::errors::InvalidArgument(
66 67 68
              "The rois_batch_size and imgs "
              "batch_size must be the same. But received rois_batch_size = %d, "
              "batch_size = %d",
69 70
              rois_batch_size,
              batch_size));
71 72

      std::vector<int> rois_num_list(rois_batch_size);
73 74 75 76 77
      memory::Copy(cplace,
                   rois_num_list.data(),
                   xplace,
                   rois_num_t->data<int>(),
                   sizeof(int) * rois_batch_size);
78 79 80 81
      cpu_lod = new int[rois_batch_size + 1];
      cpu_lod[0] = 0;
      for (int i = 0; i < rois_batch_size; i++) {
        cpu_lod[i + 1] = cpu_lod[i] + rois_num_list[i];
82 83
      }
    } else {
84 85
      auto lod = rois->lod();
      PADDLE_ENFORCE_EQ(
86 87
          lod.empty(),
          false,
88 89 90 91
          platform::errors::InvalidArgument("Input(ROIs) in ROIAlignOp does "
                                            "not contain LoD information."));
      auto rois_lod = lod.back();
      rois_batch_size = rois_lod.size() - 1;
92
      PADDLE_ENFORCE_EQ(
93 94
          rois_batch_size,
          batch_size,
95
          platform::errors::InvalidArgument(
96 97 98
              "The batch size of rois and batch size "
              "of images must be the same. But received rois batch size = %d, "
              "and images batch size = %d",
99 100
              rois_batch_size,
              batch_size));
101 102
      int rois_num_with_lod = rois_lod[rois_batch_size];
      PADDLE_ENFORCE_EQ(
103 104
          rois_num,
          rois_num_with_lod,
105 106 107 108 109
          platform::errors::InvalidArgument(
              "The actual number of rois and the number of rois "
              "provided from Input(RoIsLoD) in RoIAlign must be the same."
              " But received actual number of rois is %d, and the number "
              "of rois from RoIsLoD is %d",
110 111
              rois_num,
              rois_num_with_lod));
112 113 114 115 116 117 118 119 120
      for (int n = 0; n < rois_batch_size; ++n) {
        for (size_t i = rois_lod[n]; i < rois_lod[n + 1]; ++i) {
          roi_batch_id_data[i] = n;
        }
      }
      cpu_lod = new int[rois_batch_size + 1];
      for (int i = 0; i < rois_batch_size + 1; i++) {
        cpu_lod[i] = rois_lod[i];
      }
121
    }
122 123 124 125

    int* roi_id_data = nullptr;
    int r = xpu_malloc(reinterpret_cast<void**>(&roi_id_data),
                       (rois_batch_size + 1) * sizeof(int));
126 127
    PADDLE_ENFORCE_EQ(r,
                      xpu::Error_t::SUCCESS,
128
                      platform::errors::External("no enough memory in xpu"));
129 130 131 132
    memory::Copy(xplace,
                 roi_id_data,
                 cplace,
                 cpu_lod,
133 134
                 (rois_batch_size + 1) * sizeof(int));
    delete[] cpu_lod;
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    r = xpu::roi_align<T, int>(dev_ctx.x_context(),
                               in->data<T>(),
                               out->mutable_data<T>(ctx.GetPlace()),
                               rois->data<T>(),
                               roi_id_data,
                               batch_size,
                               channels,
                               height,
                               width,
                               out->dims()[0],
                               pooled_height,
                               pooled_width,
                               spatial_scale,
                               sampling_ratio,
                               true,
                               aligned);
    PADDLE_ENFORCE_EQ(r,
                      xpu::Error_t::SUCCESS,
153
                      platform::errors::External(
154 155
                          "The roi_align XPU OP return wrong value[%d %s]",
                          r,
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
                          XPUAPIErrorMsg[r]));
    if (dev_ctx.x_context()->xpu_stream) {
      dev_ctx.Wait();
    }
    xpu_free(roi_id_data);
  }
};

template <typename DeviceContext, typename T>
class XPUROIAlignGradOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* in = ctx.Input<Tensor>("X");
    auto* rois = ctx.Input<LoDTensor>("ROIs");

    auto* out_grad = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto* in_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");
    auto sampling_ratio = ctx.Attr<int>("sampling_ratio");
178
    auto aligned = ctx.Attr<bool>("aligned");
179 180 181 182 183 184 185 186 187 188 189 190 191 192

    int rois_num = rois->dims()[0];
    int channels = in->dims()[1];
    int height = in->dims()[2];
    int width = in->dims()[3];

    if (!in_grad) {
      return;
    }
    Tensor roi_batch_id_list;
    roi_batch_id_list.Resize({rois_num});
    auto cplace = platform::CPUPlace();

    auto& dev_ctx = ctx.template device_context<DeviceContext>();
193
    auto xplace = ctx.GetPlace();
194 195 196 197 198 199 200

    int rois_batch_size = 0;
    int* cpu_lod = nullptr;
    if (ctx.HasInput("RoisNum")) {
      auto* rois_num_t = ctx.Input<Tensor>("RoisNum");
      rois_batch_size = rois_num_t->numel();
      std::vector<int> rois_num_list(rois_batch_size);
201 202 203 204 205
      memory::Copy(cplace,
                   rois_num_list.data(),
                   xplace,
                   rois_num_t->data<int>(),
                   sizeof(int) * rois_batch_size);
206 207 208 209 210 211 212 213 214 215 216
      cpu_lod = new int[rois_batch_size + 1];
      cpu_lod[0] = 0;
      for (int i = 0; i < rois_batch_size; i++) {
        cpu_lod[i + 1] = cpu_lod[i] + rois_num_list[i];
      }
    } else {
      auto rois_lod = rois->lod().back();
      rois_batch_size = rois_lod.size() - 1;
      cpu_lod = new int[rois_batch_size + 1];
      for (int i = 0; i < rois_batch_size + 1; i++) {
        cpu_lod[i] = rois_lod[i];
D
Double_V 已提交
217 218
      }
    }
219 220 221
    int* roi_id_data = nullptr;
    int r = xpu_malloc(reinterpret_cast<void**>(&roi_id_data),
                       (rois_batch_size + 1) * sizeof(int));
222 223
    PADDLE_ENFORCE_EQ(r,
                      xpu::Error_t::SUCCESS,
224
                      platform::errors::External("no enough memory in xpu"));
225 226 227 228
    memory::Copy(xplace,
                 roi_id_data,
                 cplace,
                 cpu_lod,
229 230 231 232 233 234 235
                 (rois_batch_size + 1) * sizeof(int));
    in_grad->mutable_data<T>(ctx.GetPlace());

    int output_grad_size = out_grad->numel();

    delete[] cpu_lod;
    if (output_grad_size > 0) {
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
      r = xpu::roi_align_grad<T, int>(dev_ctx.x_context(),
                                      out_grad->data<T>(),
                                      in_grad->data<T>(),
                                      rois->data<T>(),
                                      roi_id_data,
                                      in->dims()[0],
                                      channels,
                                      height,
                                      width,
                                      out_grad->dims()[0],
                                      pooled_height,
                                      pooled_width,
                                      spatial_scale,
                                      sampling_ratio,
                                      true,
                                      aligned);
252
      PADDLE_ENFORCE_EQ(
253 254
          r,
          xpu::Error_t::SUCCESS,
255
          platform::errors::External(
256 257
              "The roi_align_grad XPU OP return wrong value[%d %s]",
              r,
258 259 260 261 262 263
              XPUAPIErrorMsg[r]));
    }
    if (dev_ctx.x_context()->xpu_stream) {
      dev_ctx.Wait();
    }
    xpu_free(roi_id_data);
D
Double_V 已提交
264 265 266 267 268
  }
};

}  // namespace operators
}  // namespace paddle
269

D
Double_V 已提交
270 271 272 273
namespace ops = paddle::operators;
REGISTER_OP_XPU_KERNEL(
    roi_align,
    ops::XPUROIAlignOpKernel<paddle::platform::XPUDeviceContext, float>);
274 275 276
REGISTER_OP_XPU_KERNEL(
    roi_align_grad,
    ops::XPUROIAlignGradOpKernel<paddle::platform::XPUDeviceContext, float>);
D
Double_V 已提交
277 278

#endif