interpolate_v2_op_xpu.cc 11.7 KB
Newer Older
T
TTerror 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2018 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 <memory>
#include <string>
#include <vector>

#include "paddle/fluid/framework/op_registry.h"
17
#include "paddle/phi/kernels/funcs/interpolate_function.h"
T
TTerror 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#ifdef PADDLE_WITH_XPU

namespace paddle {
namespace operators {

using framework::Tensor;
using DataLayout = framework::DataLayout;

inline std::vector<int> get_new_shape_xpu(
    const std::vector<const Tensor*>& list_new_shape_tensor) {
  // get tensor from
  std::vector<int> vec_new_shape;
  for (size_t i = 0; i < list_new_shape_tensor.size(); ++i) {
    auto tensor = list_new_shape_tensor[i];
    PADDLE_ENFORCE_EQ(
33 34
        tensor->dims(),
        phi::make_ddim({1}),
T
TTerror 已提交
35 36
        platform::errors::InvalidArgument("shape of dim tensor should be [1]"));
    framework::Tensor temp;
37
    paddle::framework::TensorCopySync(*tensor, platform::CPUPlace(), &temp);
T
TTerror 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    vec_new_shape.push_back(static_cast<int32_t>(*temp.data<int32_t>()));
  }

  return vec_new_shape;
}

template <typename T>
class InterpolateV2XPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* input = ctx.Input<Tensor>("X");
    auto* output = ctx.Output<Tensor>("Out");

    auto input_dims = input->dims();
    PADDLE_ENFORCE_EQ(
53 54
        input_dims.size(),
        4,
T
TTerror 已提交
55 56 57 58 59 60
        platform::errors::External("XPU Interpolate kernel only support 2d"));

    const std::string data_layout_str = ctx.Attr<std::string>("data_layout");
    const DataLayout data_layout =
        framework::StringToDataLayout(data_layout_str);
    int n, c, in_d, in_h, in_w;
61 62
    phi::funcs::ExtractNCDWH(
        input_dims, data_layout, &n, &c, &in_d, &in_h, &in_w);
T
TTerror 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

    auto interp_method = ctx.Attr<std::string>("interp_method");
    bool align_corners = ctx.Attr<bool>("align_corners");
    int align_mode = ctx.Attr<int>("align_mode");

    int out_h = ctx.Attr<int>("out_h");
    int out_w = ctx.Attr<int>("out_w");
    float scale_h = -1;
    float scale_w = -1;

    auto list_new_size_tensor = ctx.MultiInput<framework::Tensor>("SizeTensor");
    if (list_new_size_tensor.size() > 0) {
      // have size tensor
      auto new_size = get_new_shape_xpu(list_new_size_tensor);
      out_h = new_size[0];
      out_w = new_size[1];
    } else {
      auto scale_tensor = ctx.Input<Tensor>("Scale");
      auto scale = ctx.Attr<std::vector<float>>("scale");
      if (scale_tensor != nullptr) {
83 84
        auto scale_data =
            phi::funcs::get_new_data_from_tensor<float>(scale_tensor);
T
TTerror 已提交
85 86 87 88 89 90 91 92
        if (scale_data.size() > 1) {
          scale_h = scale_data[0];
          scale_w = scale_data[1];
        } else {
          scale_h = scale_data[0];
          scale_w = scale_data[0];
        }
        PADDLE_ENFORCE_EQ(
93 94
            scale_w > 0 && scale_h > 0,
            true,
T
TTerror 已提交
95 96 97 98 99 100 101 102
            platform::errors::InvalidArgument("scale  of Op(interpolate) "
                                              "should be greater than 0."));
      } else {
        if (scale.size() > 1) {
          scale_h = scale[0];
          scale_w = scale[1];

          PADDLE_ENFORCE_EQ(
103 104
              scale_w > 0 && scale_h > 0,
              true,
T
TTerror 已提交
105 106 107 108 109 110 111 112 113 114
              platform::errors::InvalidArgument("scale  of Op(interpolate) "
                                                "should be greater than 0."));
        }
      }
      if (scale_h > 0. && scale_w > 0.) {
        out_h = static_cast<int>(in_h * scale_h);
        out_w = static_cast<int>(in_w * scale_w);
      }
      auto out_size = ctx.Input<Tensor>("OutSize");
      if (out_size != nullptr) {
115 116
        auto out_size_data =
            phi::funcs::get_new_data_from_tensor<int>(out_size);
T
TTerror 已提交
117 118 119 120
        out_h = out_size_data[0];
        out_w = out_size_data[1];
      }
    }
121
    PADDLE_ENFORCE_GT(
122 123
        out_h,
        0,
124 125 126 127
        platform::errors::InvalidArgument("out_h in Attr(out_shape) of "
                                          "Op(interpolate) "
                                          "should be greater than 0."));
    PADDLE_ENFORCE_GT(
128 129
        out_w,
        0,
130 131 132
        platform::errors::InvalidArgument("out_w in Attr(out_shape) of "
                                          "Op(interpolate) "
                                          "should be greater than 0."));
T
TTerror 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    framework::DDim dim_out;
    if (data_layout == DataLayout::kNCHW) {
      dim_out = {n, c, out_h, out_w};
    } else {
      dim_out = {n, out_h, out_w, c};
    }
    output->mutable_data<T>(dim_out, ctx.GetPlace());

    if (in_h == out_h && in_w == out_w) {
      framework::TensorCopy(*input, ctx.GetPlace(), output);
      return;
    }
    bool nearest = "nearest" == interp_method;
    int trans_mode = (align_corners) ? (0) : ((align_mode == 0) ? (1) : (2));
    auto& dev_ctx = ctx.template device_context<platform::XPUDeviceContext>();
    if (nearest) {
149 150
      PADDLE_ENFORCE_EQ((data_layout == DataLayout::kNCHW),
                        true,
T
TTerror 已提交
151 152 153
                        platform::errors::InvalidArgument(
                            "XPU nearest is only support NCHW"));
    }
154 155 156 157 158 159 160 161 162 163 164
    int r = xpu::interpolate2d<T>(dev_ctx.x_context(),
                                  input->data<T>(),
                                  output->data<T>(),
                                  n,
                                  c,
                                  in_h,
                                  in_w,
                                  out_h,
                                  out_w,
                                  nearest,
                                  trans_mode,
T
TTerror 已提交
165
                                  (data_layout == DataLayout::kNCHW));
166 167
    PADDLE_ENFORCE_EQ(r,
                      XPU_SUCCESS,
T
TTerror 已提交
168 169
                      platform::errors::External("XPU interpolate2d kernel "
                                                 "return wrong value[%d %s]",
170 171
                                                 r,
                                                 XPUAPIErrorMsg[r]));
T
TTerror 已提交
172 173 174 175 176 177 178 179 180 181 182 183
  }
};

template <typename T>
class InterpolateV2GradXPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* input_grad = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto* output_grad = ctx.Input<Tensor>(framework::GradVarName("Out"));

    auto output_grad_dims = output_grad->dims();

184 185
    PADDLE_ENFORCE_EQ(output_grad_dims.size(),
                      4,
T
TTerror 已提交
186 187 188 189 190 191 192 193
                      platform::errors::External(
                          "XPU Interpolategrad kernel only support 2d"));

    auto* input = ctx.Input<Tensor>("X");
    const std::string data_layout_str = ctx.Attr<std::string>("data_layout");
    const DataLayout data_layout =
        framework::StringToDataLayout(data_layout_str);
    int n, c, in_d, in_h, in_w;
194 195
    phi::funcs::ExtractNCDWH(
        input->dims(), data_layout, &n, &c, &in_d, &in_h, &in_w);
T
TTerror 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

    auto interp_method = ctx.Attr<std::string>("interp_method");
    bool align_corners = ctx.Attr<bool>("align_corners");
    int align_mode = ctx.Attr<int>("align_mode");

    int out_h = ctx.Attr<int>("out_h");
    int out_w = ctx.Attr<int>("out_w");
    float scale_h = -1;
    float scale_w = -1;

    auto list_new_size_tensor = ctx.MultiInput<framework::Tensor>("SizeTensor");
    if (list_new_size_tensor.size() > 0) {
      // have size tensor
      auto new_size = get_new_shape_xpu(list_new_size_tensor);
      out_h = new_size[0];
      out_w = new_size[1];
    } else {
      auto scale_tensor = ctx.Input<Tensor>("Scale");
      auto scale = ctx.Attr<std::vector<float>>("scale");
      if (scale_tensor != nullptr) {
216 217
        auto scale_data =
            phi::funcs::get_new_data_from_tensor<float>(scale_tensor);
T
TTerror 已提交
218 219 220 221 222 223 224 225
        if (scale_data.size() > 1) {
          scale_h = scale_data[0];
          scale_w = scale_data[1];
        } else {
          scale_h = scale_data[0];
          scale_w = scale_data[0];
        }
        PADDLE_ENFORCE_EQ(
226 227
            scale_w > 0 && scale_h > 0,
            true,
T
TTerror 已提交
228 229 230 231 232 233 234 235
            platform::errors::InvalidArgument("scale  of Op(interpolate) "
                                              "should be greater than 0."));
      } else {
        if (scale.size() > 1) {
          scale_h = scale[0];
          scale_w = scale[1];

          PADDLE_ENFORCE_EQ(
236 237
              scale_w > 0 && scale_h > 0,
              true,
T
TTerror 已提交
238 239 240 241 242 243 244 245 246 247
              platform::errors::InvalidArgument("scale  of Op(interpolate) "
                                                "should be greater than 0."));
        }
      }
      if (scale_h > 0. && scale_w > 0.) {
        out_h = static_cast<int>(in_h * scale_h);
        out_w = static_cast<int>(in_w * scale_w);
      }
      auto out_size = ctx.Input<Tensor>("OutSize");
      if (out_size != nullptr) {
248 249
        auto out_size_data =
            phi::funcs::get_new_data_from_tensor<int>(out_size);
T
TTerror 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        out_h = out_size_data[0];
        out_w = out_size_data[1];
      }
    }

    framework::DDim dim_grad;
    if (data_layout == DataLayout::kNCHW) {
      dim_grad = {n, c, in_h, in_w};
    } else {
      dim_grad = {n, in_h, in_w, c};
    }
    input_grad->mutable_data<T>(dim_grad, ctx.GetPlace());

    auto& dev_ctx = ctx.template device_context<platform::XPUDeviceContext>();

    int r = XPU_SUCCESS;
266 267 268 269 270 271
    r = xpu::constant<T>(dev_ctx.x_context(),
                         input_grad->data<T>(),
                         input_grad->numel(),
                         static_cast<T>(0.0));
    PADDLE_ENFORCE_EQ(r,
                      XPU_SUCCESS,
T
TTerror 已提交
272 273 274
                      platform::errors::External(
                          "XPU constant in interpolate2d_grad kernel return "
                          "wrong value[%d %s]",
275 276
                          r,
                          XPUAPIErrorMsg[r]));
T
TTerror 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289

    if (in_h == out_h && in_w == out_w) {
      framework::TensorCopy(*output_grad, ctx.GetPlace(), input_grad);
      return;
    }

    bool nearest = "nearest" == interp_method;
    int trans_mode = (align_corners) ? (0) : ((align_mode == 0) ? (1) : (2));

    if (nearest) {
      trans_mode = (align_corners) ? (0) : (2);
    }

290 291 292 293 294 295 296 297 298 299 300
    r = xpu::interpolate2d_grad<T>(dev_ctx.x_context(),
                                   output_grad->data<T>(),
                                   input_grad->data<T>(),
                                   n,
                                   c,
                                   in_h,
                                   in_w,
                                   out_h,
                                   out_w,
                                   nearest,
                                   trans_mode,
T
TTerror 已提交
301 302
                                   (data_layout == DataLayout::kNCHW));
    PADDLE_ENFORCE_EQ(
303 304
        r,
        XPU_SUCCESS,
T
TTerror 已提交
305 306
        platform::errors::External("XPU interpolate2d_grad kernel return "
                                   "wrong value[%d %s]",
307 308
                                   r,
                                   XPUAPIErrorMsg[r]));
T
TTerror 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_XPU_KERNEL(bilinear_interp_v2, ops::InterpolateV2XPUKernel<float>);
REGISTER_OP_XPU_KERNEL(nearest_interp_v2, ops::InterpolateV2XPUKernel<float>);

REGISTER_OP_XPU_KERNEL(bilinear_interp_v2_grad,
                       ops::InterpolateV2GradXPUKernel<float>);
REGISTER_OP_XPU_KERNEL(nearest_interp_v2_grad,
                       ops::InterpolateV2GradXPUKernel<float>);
#endif