deformable_conv_op_xpu.cc 12.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Copyright (c) 2020 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 <algorithm>
#include <vector>
18

19
#include "paddle/fluid/framework/op_registry.h"
20
#include "paddle/fluid/platform/device/xpu/xpu_header.h"
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 47

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

template <typename DeviceContext, typename T>
class DeformableConvXPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* input = ctx.Input<Tensor>("Input");
    auto* offset = ctx.Input<Tensor>("Offset");
    auto* mask = ctx.Input<Tensor>("Mask");
    Tensor filter = *ctx.Input<Tensor>("Filter");
    Tensor* output = ctx.Output<Tensor>("Output");
    output->mutable_data<T>(ctx.GetPlace());

    auto& dev_ctx = ctx.template device_context<DeviceContext>();

    const int groups = ctx.Attr<int>("groups");
    const int deformable_groups = ctx.Attr<int>("deformable_groups");
    const int im2col_step = ctx.Attr<int>("im2col_step");
    const std::vector<int> strides = ctx.Attr<std::vector<int>>("strides");
    const std::vector<int> paddings = ctx.Attr<std::vector<int>>("paddings");
    const std::vector<int> dilations = ctx.Attr<std::vector<int>>("dilations");

    PADDLE_ENFORCE_EQ(
48 49
        deformable_groups == 1,
        true,
50 51 52
        platform::errors::InvalidArgument((
            "XPU only support deformable_groups == 1 in deformable_conv op.")));
    PADDLE_ENFORCE_EQ(
53 54
        groups == 1,
        true,
55 56
        platform::errors::InvalidArgument(
            ("XPU only support groups == 1 in deformable_conv op.")));
57 58
    PADDLE_ENFORCE_EQ(filter.dims()[2] <= 8 && filter.dims()[3] <= 8,
                      true,
59 60 61 62 63
                      platform::errors::InvalidArgument(
                          "Filter high and weight should less than 8 on xpu "
                          "in deformable_conv op."));

    const int batch_size = static_cast<int>(input->dims()[0]);
64
    std::vector<int64_t> output_shape_vec(phi::vectorize(output->dims()));
65 66 67 68 69 70 71 72 73

    const T* input_ptr = input->data<T>();
    const T* filter_ptr = filter.data<T>();
    const float* offset_ptr = offset->data<T>();
    const float* mask_ptr = mask->data<T>();
    T* output_prt = output->data<T>();

    // set zeros for d_table_data
    const int zero = 0;
74 75 76 77
    int r = xpu::constant<T>(
        dev_ctx.x_context(), output_prt, output->numel(), zero);
    PADDLE_ENFORCE_EQ(r == xpu::Error_t::SUCCESS,
                      true,
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
                      platform::errors::External(
                          "XPU API return wrong value[%d], please check where "
                          "Baidu Kunlun Card is properly installed.",
                          r));
    int input_dim = input->numel() / input->dims()[0];
    int input_offset_dim = offset->numel() / offset->dims()[0];
    int input_mask_dim = mask->numel() / mask->dims()[0];
    int output_dim =
        output_shape_vec[1] * output_shape_vec[2] * output_shape_vec[3];
    std::vector<int> ksize{static_cast<int>(filter.dims()[2]),
                           static_cast<int>(filter.dims()[3])};
    int n = im2col_step;
    int c = input->dims()[1];
    int h = input->dims()[2];
    int w = input->dims()[3];
    int f = filter.dims()[0];

    for (int i = 0; i < batch_size / im2col_step; ++i) {
      int r = xpu::deformable_conv<float, float, float, int>(
97 98 99 100
          dev_ctx.x_context(),
          input_ptr + i * im2col_step * input_dim,
          filter_ptr,
          offset_ptr + i * im2col_step * input_offset_dim,
101
          mask_ptr + i * im2col_step * input_mask_dim,
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
          output_prt + i * im2col_step * output_dim,
          n,
          c,
          h,
          w,
          f,
          ksize,
          strides,
          paddings,
          dilations,
          groups,
          deformable_groups,
          nullptr,
          nullptr,
          nullptr,
          true);
118
      PADDLE_ENFORCE_EQ(
119 120
          r,
          XPU_SUCCESS,
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
          platform::errors::External(
              "XPU deformable_conv kernel return wrong value[%d].", r));
    }
  }
};

template <typename DeviceContext, typename T>
class DeformableConvGradXPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    const Tensor* output_grad =
        ctx.Input<Tensor>(framework::GradVarName("Output"));
    Tensor* input_grad = ctx.Output<Tensor>(framework::GradVarName("Input"));
    Tensor* filter_grad = ctx.Output<Tensor>(framework::GradVarName("Filter"));
    Tensor* offset_grad = ctx.Output<Tensor>(framework::GradVarName("Offset"));
    Tensor* mask_grad = ctx.Output<Tensor>(framework::GradVarName("Mask"));
    T* dx_data = nullptr;
    T* dw_data = nullptr;
    T* dmask_data = nullptr;
    T* doffset_data = nullptr;

    if (input_grad != nullptr) {
      input_grad->mutable_data<T>(ctx.GetPlace());
      dx_data = input_grad->data<T>();
    }
    if (filter_grad != nullptr) {
      filter_grad->mutable_data<T>(ctx.GetPlace());
      dw_data = filter_grad->data<T>();
    }
    if (offset_grad != nullptr) {
      offset_grad->mutable_data<T>(ctx.GetPlace());
      doffset_data = offset_grad->data<T>();
    }
    if (mask_grad != nullptr) {
      mask_grad->mutable_data<T>(ctx.GetPlace());
      dmask_data = mask_grad->data<T>();
    }

    const Tensor* input = ctx.Input<Tensor>("Input");
    Tensor offset = *ctx.Input<Tensor>("Offset");
    Tensor mask = *ctx.Input<Tensor>("Mask");
    Tensor filter = *ctx.Input<Tensor>("Filter");

    int groups = ctx.Attr<int>("groups");
    int deformable_groups = ctx.Attr<int>("deformable_groups");
    int im2col_step = ctx.Attr<int>("im2col_step");
    std::vector<int> strides = ctx.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = ctx.Attr<std::vector<int>>("paddings");
    std::vector<int> dilations = ctx.Attr<std::vector<int>>("dilations");

    PADDLE_ENFORCE_EQ(
172 173
        deformable_groups == 1,
        true,
174 175 176
        platform::errors::InvalidArgument((
            "XPU only support deformable_groups == 1 in deformable_conv op.")));
    PADDLE_ENFORCE_EQ(
177 178
        groups == 1,
        true,
179 180
        platform::errors::InvalidArgument(
            ("XPU only support groups == 1 in deformable_conv op.")));
181 182
    PADDLE_ENFORCE_EQ(filter.dims()[2] <= 8 && filter.dims()[3] <= 8,
                      true,
183 184 185 186 187 188
                      platform::errors::InvalidArgument(
                          "Filter high and weight should less than 8 on xpu "
                          "in deformable_conv op."));

    auto& dev_ctx = ctx.template device_context<DeviceContext>();
    const int batch_size = static_cast<int>(input->dims()[0]);
189
    std::vector<int64_t> output_shape_vec(phi::vectorize(output_grad->dims()));
190 191 192 193 194 195
    const T* output_grad_ptr = output_grad->data<T>();
    const T* input_ptr = input->data<T>();
    const T* filter_ptr = filter.data<T>();
    const float* offset_ptr = offset.data<float>();
    const float* mask_ptr = mask.data<float>();
    if (dx_data == nullptr) {
196 197 198 199 200
      PADDLE_ENFORCE_EQ(
          xpu_malloc(reinterpret_cast<void**>(&dx_data),
                     input->numel() * sizeof(T)),
          XPU_SUCCESS,
          platform::errors::ResourceExhausted("XPU has no enough memory"));
201 202
    }
    if (dw_data == nullptr) {
203 204 205 206 207
      PADDLE_ENFORCE_EQ(
          xpu_malloc(reinterpret_cast<void**>(&dw_data),
                     filter.numel() * sizeof(T)),
          XPU_SUCCESS,
          platform::errors::ResourceExhausted("XPU has no enough memory"));
208 209
    }
    if (doffset_data == nullptr) {
210 211 212 213 214
      PADDLE_ENFORCE_EQ(
          xpu_malloc(reinterpret_cast<void**>(&doffset_data),
                     offset.numel() * sizeof(T)),
          XPU_SUCCESS,
          platform::errors::ResourceExhausted("XPU has no enough memory"));
215 216
    }
    if (dmask_data == nullptr) {
217 218 219 220 221
      PADDLE_ENFORCE_EQ(
          xpu_malloc(reinterpret_cast<void**>(&dmask_data),
                     mask.numel() * sizeof(T)),
          XPU_SUCCESS,
          platform::errors::ResourceExhausted("XPU has no enough memory"));
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    }

    int input_dim = input->numel() / input->dims()[0];
    int input_offset_dim = offset.numel() / offset.dims()[0];
    int input_mask_dim = mask.numel() / mask.dims()[0];
    int output_dim =
        output_shape_vec[1] * output_shape_vec[2] * output_shape_vec[3];
    std::vector<int> ksize{static_cast<int>(filter.dims()[2]),
                           static_cast<int>(filter.dims()[3])};
    int n = im2col_step;
    int c = input->dims()[1];
    int h = input->dims()[2];
    int w = input->dims()[3];
    int f = filter.dims()[0];

    T* filter_grad_tmp = nullptr;
238 239 240 241 242
    PADDLE_ENFORCE_EQ(
        xpu_malloc(reinterpret_cast<void**>(&filter_grad_tmp),
                   filter_grad->numel() * sizeof(T)),
        XPU_SUCCESS,
        platform::errors::ResourceExhausted("XPU has no enough memory"));
243 244 245 246 247 248 249

    // set zeros for d_table_data
    const int zero = 0;
    int r_dx =
        xpu::constant<T>(dev_ctx.x_context(), dx_data, input->numel(), zero);
    int r_dw =
        xpu::constant<T>(dev_ctx.x_context(), dw_data, filter.numel(), zero);
250 251
    int r_doffset = xpu::constant<T>(
        dev_ctx.x_context(), doffset_data, offset.numel(), zero);
252 253
    int r_dmask =
        xpu::constant<T>(dev_ctx.x_context(), dmask_data, mask.numel(), zero);
254 255
    int r_filter = xpu::constant<T>(
        dev_ctx.x_context(), filter_grad_tmp, filter.numel(), zero);
256 257
    auto ret = (r_dx == xpu::Error_t::SUCCESS) && (r_dx == r_dw) &&
               (r_dx == r_doffset) && (r_dx == r_dmask) && (r_dx == r_filter);
258 259
    PADDLE_ENFORCE_EQ(ret,
                      true,
260 261 262 263 264 265
                      platform::errors::External(
                          "XPU API return wrong value, please check where "
                          "Baidu Kunlun Card is properly installed."));

    for (int i = 0; i < batch_size / im2col_step; ++i) {
      int r = xpu::deformable_conv_grad<float, float, float, int>(
266 267 268 269
          dev_ctx.x_context(),
          input_ptr + i * im2col_step * input_dim,
          filter_ptr,
          offset_ptr + i * im2col_step * input_offset_dim,
270 271
          mask_ptr + i * im2col_step * input_mask_dim,
          output_grad_ptr + i * im2col_step * output_dim,
272 273
          dx_data + i * im2col_step * input_dim,
          filter_grad_tmp,
274
          doffset_data + i * im2col_step * input_offset_dim,
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
          dmask_data + i * im2col_step * input_mask_dim,
          n,
          c,
          h,
          w,
          f,
          ksize,
          strides,
          paddings,
          dilations,
          groups,
          deformable_groups,
          nullptr,
          nullptr,
          nullptr,
          nullptr,
          nullptr,
          true);
293
      PADDLE_ENFORCE_EQ(
294 295
          r,
          XPU_SUCCESS,
296 297
          platform::errors::External(
              "XPU deformable_conv_grad kernel return wrong value[%d].", r));
298 299 300 301 302 303 304
      r = baidu::xpu::api::add<T>(dev_ctx.x_context(),
                                  filter_grad_tmp,
                                  dw_data,
                                  dw_data,
                                  filter.numel());
      PADDLE_ENFORCE_EQ(r,
                        XPU_SUCCESS,
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
                        platform::errors::External(
                            "XPU add kernel return wrong value[%d].", r));
    }

    dev_ctx.Wait();
    xpu_free(filter_grad_tmp);
    if (input_grad == nullptr) {
      xpu_free(dx_data);
    }
    if (filter_grad == nullptr) {
      xpu_free(dw_data);
    }
    if (offset_grad == nullptr) {
      xpu_free(doffset_data);
    }
    if (mask_grad == nullptr) {
      xpu_free(dmask_data);
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
using XPUDeviceContext = paddle::platform::XPUDeviceContext;

REGISTER_OP_XPU_KERNEL(deformable_conv,
                       ops::DeformableConvXPUKernel<XPUDeviceContext, float>);
REGISTER_OP_XPU_KERNEL(
    deformable_conv_grad,
    ops::DeformableConvGradXPUKernel<XPUDeviceContext, float>);

#endif