conv_op_npu.cc 26.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2021 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.

#include "paddle/fluid/operators/conv_op.h"
16
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
17 18 19 20 21

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
22
using NPUDeviceContext = platform::NPUDeviceContext;
23
static void CastToFP16(const framework::ExecutionContext& ctx,
24 25
                       const aclrtStream& stream,
                       const Tensor& in,
26 27 28 29 30 31 32 33 34 35 36
                       Tensor* out) {
  out->mutable_data<paddle::platform::float16>(ctx.GetPlace());
  NpuOpRunner runner;
  runner.SetType("Cast")
      .AddInput(in)
      .AddOutput(*out)
      .AddAttr("dst_type", ACL_FLOAT16)
      .Run(stream);
}

static void CastToFP32(const framework::ExecutionContext& ctx,
37 38
                       const aclrtStream& stream,
                       const Tensor& in,
39 40 41 42 43 44 45 46 47
                       Tensor* out) {
  out->mutable_data<float>(ctx.GetPlace());
  NpuOpRunner runner;
  runner.SetType("Cast")
      .AddInput(in)
      .AddOutput(*out)
      .AddAttr("dst_type", ACL_FLOAT)
      .Run(stream);
}
48

49
template <typename T>
50 51
class DepthwiseConvNPUKernel : public framework::OpKernel<T> {
 public:
52 53 54 55 56
  void Compute(const framework::ExecutionContext& ctx) const override {
    const Tensor* input = ctx.Input<Tensor>("Input");
    const Tensor* filter = ctx.Input<Tensor>("Filter");
    Tensor* output = ctx.Output<Tensor>("Output");
    output->mutable_data<T>(ctx.GetPlace());
57

58 59 60 61 62 63
    const std::vector<int> stride = ctx.Attr<std::vector<int>>("strides");
    std::vector<int> padding = ctx.Attr<std::vector<int>>("paddings");
    std::vector<int> dilation = ctx.Attr<std::vector<int>>("dilations");
    const std::string data_format = ctx.Attr<std::string>("data_format");
    const std::string padding_algorithm =
        ctx.Attr<std::string>("padding_algorithm");
64 65 66 67 68 69 70 71 72 73 74 75 76 77

    const bool channel_last = data_format == "NHWC";
    if (channel_last) {
      PADDLE_ENFORCE_EQ(
          output->dims()[output->dims().size() - 1],
          input->dims()[input->dims().size() - 1],
          platform::errors::InvalidArgument(
              "ShapeError: The output channels must be equal to the "
              "input channels. But receivced output channel number is %d "
              "and input channel number is %d",
              output->dims()[output->dims().size() - 1],
              input->dims()[input->dims().size() - 1]));
    } else {
      PADDLE_ENFORCE_EQ(
78 79
          output->dims()[1],
          input->dims()[1],
80 81 82 83
          platform::errors::InvalidArgument(
              "ShapeError: The output channels must be equal to the "
              "input channels. But receivced output channel number is %d "
              "and input channel number is %d",
84 85
              output->dims()[1],
              input->dims()[1]));
86 87 88 89 90 91 92 93
    }

    auto in_dims = input->dims();
    auto filter_dims = filter->dims();
    framework::DDim in_data_dims;
    framework::DDim filter_data_dims;

    if (channel_last) {
94
      in_data_dims = phi::slice_ddim(in_dims, 1, in_dims.size() - 1);
95
    } else {
96
      in_data_dims = phi::slice_ddim(in_dims, 2, in_dims.size());
97
    }
98
    filter_data_dims = phi::slice_ddim(filter_dims, 2, in_dims.size());
99

100
    std::vector<int> ksize = phi::vectorize<int>(filter_data_dims);
101 102
    UpdatePaddingAndDilation(
        &padding, &dilation, padding_algorithm, in_data_dims, stride, ksize);
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

    std::vector<int> strides(4, 1);
    std::vector<int> dilations(4, 1);

    Tensor input_tensor, output_tensor;
    input_tensor.ShareDataWith(*input);
    output_tensor.ShareDataWith(*output);

    if (channel_last) {
      input_tensor.set_layout(DataLayout::kNHWC);
      output_tensor.set_layout(DataLayout::kNHWC);
      strides[1] = stride[0];
      strides[2] = stride[1];
      dilations[1] = dilation[0];
      dilations[2] = dilation[1];
    } else {
      strides[2] = stride[0];
      strides[3] = stride[1];
      dilations[2] = dilation[0];
      dilations[3] = dilation[1];
    }

125 126 127 128
    auto stream = ctx.template device_context<NPUDeviceContext>().stream();

    // Transform filter (n, 1, h, w) --> (1, n, h, w)
    Tensor transformed_filter(filter->type());
129 130 131 132
    transformed_filter.mutable_data<T>({filter->dims()[1],
                                        filter->dims()[0],
                                        filter->dims()[2],
                                        filter->dims()[3]},
133 134 135 136 137 138
                                       ctx.device_context().GetPlace());
    std::vector<int> perm = {1, 0, 2, 3};
    const auto& runner_trans = NpuOpRunner(
        "TransposeD", {*filter}, {transformed_filter}, {{"perm", perm}});
    runner_trans.Run(stream);

139 140 141 142 143 144 145
    const auto& runner = NpuOpRunner("DepthwiseConv2D",
                                     {input_tensor, transformed_filter},
                                     {output_tensor},
                                     {{"strides", strides},
                                      {"dilations", dilations},
                                      {"pads", padding},
                                      {"data_format", data_format}});
146 147 148 149
    runner.Run(stream);
  }
};

150 151 152
template <typename T>
class DepthwiseConvGradNPUKernel : public framework::OpKernel<T> {
 public:
153 154 155 156 157 158
  void Compute(const framework::ExecutionContext& ctx) const override {
    const Tensor* input = ctx.Input<Tensor>("Input");
    const Tensor* filter = ctx.Input<Tensor>("Filter");
    auto output_grad = ctx.Input<Tensor>(framework::GradVarName("Output"));
    auto input_grad = ctx.Output<Tensor>(framework::GradVarName("Input"));
    auto filter_grad = ctx.Output<Tensor>(framework::GradVarName("Filter"));
159

160 161 162 163 164 165
    const std::vector<int> stride = ctx.Attr<std::vector<int>>("strides");
    std::vector<int> padding = ctx.Attr<std::vector<int>>("paddings");
    std::vector<int> dilation = ctx.Attr<std::vector<int>>("dilations");
    const std::string data_format = ctx.Attr<std::string>("data_format");
    const std::string padding_algorithm =
        ctx.Attr<std::string>("padding_algorithm");
166 167 168 169 170 171 172 173 174 175

    const bool channel_last = data_format == "NHWC";

    // update padding and dilation
    auto in_dims = input->dims();
    auto filter_dims = filter->dims();
    framework::DDim in_data_dims;
    framework::DDim filter_data_dims;

    if (channel_last) {
176
      in_data_dims = phi::slice_ddim(in_dims, 1, in_dims.size() - 1);
177
    } else {
178
      in_data_dims = phi::slice_ddim(in_dims, 2, in_dims.size());
179
    }
180
    filter_data_dims = phi::slice_ddim(filter_dims, 2, in_dims.size());
181

182
    std::vector<int> ksize = phi::vectorize<int>(filter_data_dims);
183 184
    UpdatePaddingAndDilation(
        &padding, &dilation, padding_algorithm, in_data_dims, stride, ksize);
185

186 187
    auto stream = ctx.template device_context<NPUDeviceContext>().stream();

188 189
    // Transform filter (n, 1, h, w) --> (1, n, h, w)
    Tensor transformed_filter(filter->type());
190 191 192 193
    transformed_filter.mutable_data<T>({filter->dims()[1],
                                        filter->dims()[0],
                                        filter->dims()[2],
                                        filter->dims()[3]},
194
                                       ctx.device_context().GetPlace());
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    std::vector<int> perm = {1, 0, 2, 3};
    const auto& runner_trans = NpuOpRunner(
        "TransposeD", {*filter}, {transformed_filter}, {{"perm", perm}});
    runner_trans.Run(stream);

    // construct NPU attr
    std::vector<int> strides(4, 1);
    std::vector<int> dilations(4, 1);

    Tensor input_tensor, output_grad_tensor;
    input_tensor.ShareDataWith(*input);
    output_grad_tensor.ShareDataWith(*output_grad);
    if (channel_last) {
      input_tensor.set_layout(DataLayout::kNHWC);
      output_grad_tensor.set_layout(DataLayout::kNHWC);
      strides[1] = stride[0];
      strides[2] = stride[1];
      dilations[1] = dilation[0];
      dilations[2] = dilation[1];
    } else {
      strides[2] = stride[0];
      strides[3] = stride[1];
      dilations[2] = dilation[0];
      dilations[3] = dilation[1];
    }

    if (filter_grad) {
222
      filter_grad->mutable_data<T>(ctx.GetPlace());
223

224
      PADDLE_ENFORCE_EQ(
225 226
          (dilations[2] == 1 && dilations[3] == 1),
          true,
227 228 229
          platform::errors::InvalidArgument(
              "dilation_h and dilation_w in DepthwiseConv2DBackpropFilterD "
              "must be equal to 1, but got dilation_h %d, dilation_w %d",
230 231
              dilation[2],
              dilation[3]));
232 233 234 235 236 237

      NpuOpRunner runner;
      runner.SetType("DepthwiseConv2DBackpropFilterD")
          .AddInput(input_tensor)
          .AddInput(output_grad_tensor)
          .AddOutput(*filter_grad)
238
          .AddAttr("filter_size", phi::vectorize(transformed_filter.dims()))
239 240 241 242 243
          .AddAttr("strides", strides)
          .AddAttr("dilations", dilations)
          .AddAttr("pads", padding)
          .AddAttr("data_format", data_format)
          .Run(stream);
244 245
    }
    if (input_grad) {
246
      input_grad->mutable_data<T>(ctx.GetPlace());
247 248 249 250 251
      Tensor input_grad_tensor;
      input_grad_tensor.ShareDataWith(*input_grad);
      if (channel_last) {
        input_grad_tensor.set_layout(DataLayout::kNHWC);
      }
252 253 254 255 256
      NpuOpRunner runner;
      runner.SetType("DepthwiseConv2DBackpropInputD")
          .AddInput(transformed_filter)
          .AddInput(output_grad_tensor)
          .AddOutput(input_grad_tensor)
257
          .AddAttr("input_size", phi::vectorize(input->dims()))
258 259 260 261 262
          .AddAttr("strides", strides)
          .AddAttr("dilations", dilations)
          .AddAttr("pads", padding)
          .AddAttr("data_format", data_format)
          .Run(stream);
263 264 265 266
    }
  }
};

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
template <typename T>
class NPUConvOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    const Tensor* input = ctx.Input<Tensor>("Input");
    auto* filter = ctx.Input<Tensor>("Filter");
    auto* output = ctx.Output<Tensor>("Output");
    output->mutable_data<T>(ctx.GetPlace());
    const 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");
    int groups = ctx.Attr<int>("groups");
    const std::string padding_algorithm =
        ctx.Attr<std::string>("padding_algorithm");
    const std::string data_format = ctx.Attr<std::string>("data_format");

    const bool channel_last = data_format == "NHWC";

    // update padding and dilation
    auto in_dims = input->dims();
    auto filter_dims = filter->dims();
    framework::DDim in_data_dims;
    framework::DDim filter_data_dims;

    if (channel_last) {
292
      in_data_dims = phi::slice_ddim(in_dims, 1, in_dims.size() - 1);
293
    } else {
294
      in_data_dims = phi::slice_ddim(in_dims, 2, in_dims.size());
295
    }
296
    filter_data_dims = phi::slice_ddim(filter_dims, 2, in_dims.size());
297

298
    std::vector<int> ksize = phi::vectorize<int>(filter_data_dims);
299 300
    UpdatePaddingAndDilation(
        &paddings, &dilations, padding_algorithm, in_data_dims, strides, ksize);
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321

    std::vector<int> strides_vec(4, 1);
    std::vector<int> dilations_vec(4, 1);

    Tensor input_tensor, output_tensor;
    input_tensor.ShareDataWith(*input);
    output_tensor.ShareDataWith(*output);
    if (channel_last) {
      input_tensor.set_layout(DataLayout::kNHWC);
      output_tensor.set_layout(DataLayout::kNHWC);
      strides_vec[1] = strides[0];
      strides_vec[2] = strides[1];
      dilations_vec[1] = dilations[0];
      dilations_vec[2] = dilations[1];
    } else {
      strides_vec[2] = strides[0];
      strides_vec[3] = strides[1];
      dilations_vec[2] = dilations[0];
      dilations_vec[3] = dilations[1];
    }

322
    auto stream = ctx.template device_context<NPUDeviceContext>().stream();
323 324 325 326 327 328 329 330
    const auto& runner = NpuOpRunner("Conv2D",
                                     {input_tensor, *filter},
                                     {output_tensor},
                                     {{"strides", strides_vec},
                                      {"pads", paddings},
                                      {"dilations", dilations_vec},
                                      {"groups", groups},
                                      {"data_format", data_format}});
331
    runner.Run(stream);
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
  }
};

template <typename T>
class NPUConvGradOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto input = ctx.Input<Tensor>("Input");
    auto filter = ctx.Input<Tensor>("Filter");
    auto output_grad = ctx.Input<Tensor>(framework::GradVarName("Output"));
    auto input_grad = ctx.Output<Tensor>(framework::GradVarName("Input"));
    auto filter_grad = ctx.Output<Tensor>(framework::GradVarName("Filter"));

    const 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");
    int groups = ctx.Attr<int>("groups");
    const std::string padding_algorithm =
        ctx.Attr<std::string>("padding_algorithm");
    const std::string data_format = ctx.Attr<std::string>("data_format");

    const bool channel_last = data_format == "NHWC";

    // update padding and dilation
    auto in_dims = input->dims();
    auto filter_dims = filter->dims();
    framework::DDim in_data_dims;
    framework::DDim filter_data_dims;

    if (channel_last) {
362
      in_data_dims = phi::slice_ddim(in_dims, 1, in_dims.size() - 1);
363
    } else {
364
      in_data_dims = phi::slice_ddim(in_dims, 2, in_dims.size());
365
    }
366
    filter_data_dims = phi::slice_ddim(filter_dims, 2, in_dims.size());
367

368
    std::vector<int> ksize = phi::vectorize<int>(filter_data_dims);
369 370
    UpdatePaddingAndDilation(
        &paddings, &dilations, padding_algorithm, in_data_dims, strides, ksize);
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391

    std::vector<int> strides_vec(4, 1);
    std::vector<int> dilations_vec(4, 1);

    Tensor input_tensor, output_grad_tensor;
    input_tensor.ShareDataWith(*input);
    output_grad_tensor.ShareDataWith(*output_grad);
    if (channel_last) {
      input_tensor.set_layout(DataLayout::kNHWC);
      output_grad_tensor.set_layout(DataLayout::kNHWC);
      strides_vec[1] = strides[0];
      strides_vec[2] = strides[1];
      dilations_vec[1] = dilations[0];
      dilations_vec[2] = dilations[1];
    } else {
      strides_vec[2] = strides[0];
      strides_vec[3] = strides[1];
      dilations_vec[2] = dilations[0];
      dilations_vec[3] = dilations[1];
    }

392
    auto stream = ctx.template device_context<NPUDeviceContext>().stream();
393
    if (filter_grad) {
394
      filter_grad->mutable_data<T>(ctx.GetPlace());
395
      std::vector<int> filter_shape_vec = phi::vectorize<int>(filter->dims());
396

397 398 399 400 401 402 403 404 405 406
      Tensor filter_grad_fp32(experimental::DataType::FLOAT32);
      filter_grad_fp32.Resize(filter_grad->dims());

      if (framework::TransToProtoVarType(input->dtype()) ==
          framework::proto::VarType::FP16) {
        CastToFP32(ctx, stream, *filter_grad, &filter_grad_fp32);
      } else {
        filter_grad_fp32.ShareDataWith(*filter_grad);
      }

407 408 409 410 411 412 413 414 415
      const auto& runner = NpuOpRunner("Conv2DBackpropFilterD",
                                       {input_tensor, output_grad_tensor},
                                       {filter_grad_fp32},
                                       {{"filter_size", filter_shape_vec},
                                        {"strides", strides_vec},
                                        {"pads", paddings},
                                        {"dilations", dilations_vec},
                                        {"groups", groups},
                                        {"data_format", data_format}});
416
      runner.Run(stream);
417 418 419 420 421

      if (framework::TransToProtoVarType(input->dtype()) ==
          framework::proto::VarType::FP16) {
        CastToFP16(ctx, stream, filter_grad_fp32, filter_grad);
      }
422 423 424
    }
    if (input_grad) {
      input_grad->mutable_data<T>(ctx.GetPlace());
425
      std::vector<int> input_shape_vec = phi::vectorize<int>(input->dims());
426 427 428 429 430 431

      Tensor input_grad_tensor;
      input_grad_tensor.ShareDataWith(*input_grad);
      if (channel_last) {
        input_grad_tensor.set_layout(DataLayout::kNHWC);
      }
432 433 434 435 436 437 438 439 440
      const auto& runner = NpuOpRunner("Conv2DBackpropInputD",
                                       {*filter, output_grad_tensor},
                                       {input_grad_tensor},
                                       {{"input_size", input_shape_vec},
                                        {"strides", strides_vec},
                                        {"pads", paddings},
                                        {"dilations", dilations_vec},
                                        {"groups", groups},
                                        {"data_format", data_format}});
441
      runner.Run(stream);
442 443 444
    }
  }
};
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461

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

    const 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");
    int groups = ctx.Attr<int>("groups");
    const std::string padding_algorithm =
        ctx.Attr<std::string>("padding_algorithm");
    const std::string data_format = ctx.Attr<std::string>("data_format");

462 463
    PADDLE_ENFORCE_EQ(data_format,
                      "NCDHW",
464 465 466 467 468 469
                      platform::errors::Unimplemented(
                          "the data_format must be NCDHW in "
                          "the npu kernel of conv3d, but got data_format "
                          "= [%s]",
                          data_format));

470 471
    PADDLE_ENFORCE_EQ(groups,
                      1,
472 473 474 475 476
                      platform::errors::Unimplemented(
                          "the groups must be 1 in "
                          "the npu kernel of conv3d, but got groups "
                          "= [%d]",
                          groups));
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

    output->mutable_data<T>(ctx.GetPlace());

    auto& dev_ctx = ctx.template device_context<NPUDeviceContext>();
    auto input_tensor =
        ctx.AllocateTmpTensor<T, NPUDeviceContext>(input->dims(), dev_ctx);
    auto filter_tensor =
        ctx.AllocateTmpTensor<T, NPUDeviceContext>(filter->dims(), dev_ctx);
    auto output_tensor =
        ctx.AllocateTmpTensor<T, NPUDeviceContext>(output->dims(), dev_ctx);

    input_tensor.ShareDataWith(*input);
    filter_tensor.ShareDataWith(*filter);
    output_tensor.ShareDataWith(*output);

    input_tensor.set_layout(DataLayout::kNCDHW);
    filter_tensor.set_layout(DataLayout::kNCDHW);
    output_tensor.set_layout(DataLayout::kNCDHW);

    // update padding and dilation
    auto in_dims = input->dims();
    auto filter_dims = filter->dims();
    framework::DDim in_data_dims;
    framework::DDim filter_data_dims;

    in_data_dims = phi::slice_ddim(in_dims, 2, in_dims.size());
    filter_data_dims = phi::slice_ddim(filter_dims, 2, in_dims.size());

    std::vector<int> ksize = phi::vectorize<int>(filter_data_dims);
506 507
    UpdatePaddingAndDilation(
        &paddings, &dilations, padding_algorithm, in_data_dims, strides, ksize);
508 509 510 511 512 513 514 515 516 517 518 519

    std::vector<int> strides_vec(5, 1);
    std::vector<int> dilations_vec(5, 1);

    strides_vec[2] = strides[0];
    strides_vec[3] = strides[1];
    strides_vec[4] = strides[2];
    dilations_vec[2] = dilations[0];
    dilations_vec[3] = dilations[1];
    dilations_vec[4] = dilations[2];

    auto stream = ctx.template device_context<NPUDeviceContext>().stream();
520 521 522 523 524 525 526 527
    const auto& runner = NpuOpRunner("Conv3D",
                                     {input_tensor, filter_tensor},
                                     {output_tensor},
                                     {{"strides", strides_vec},
                                      {"pads", paddings},
                                      {"dilations", dilations_vec},
                                      {"groups", groups},
                                      {"data_format", data_format}});
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    runner.Run(stream);
  }
};

template <typename T>
class NPUConv3dGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    const Tensor* input = ctx.Input<Tensor>("Input");
    const Tensor* filter = ctx.Input<Tensor>("Filter");
    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"));

    const 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");
    int groups = ctx.Attr<int>("groups");
    const std::string padding_algorithm =
        ctx.Attr<std::string>("padding_algorithm");
    const std::string data_format = ctx.Attr<std::string>("data_format");

551 552
    PADDLE_ENFORCE_EQ(data_format,
                      "NCDHW",
553 554 555 556 557 558
                      platform::errors::Unimplemented(
                          "the data_format must be NCDHW in "
                          "the npu kernel of conv3d, but got data_format "
                          "= [%s]",
                          data_format));

559 560
    PADDLE_ENFORCE_EQ(groups,
                      1,
561 562 563 564 565
                      platform::errors::Unimplemented(
                          "the groups must be 1 in "
                          "the npu kernel of conv3d, but got groups "
                          "= [%d]",
                          groups));
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592

    auto& dev_ctx = ctx.template device_context<NPUDeviceContext>();
    auto input_tensor =
        ctx.AllocateTmpTensor<T, NPUDeviceContext>(input->dims(), dev_ctx);
    auto filter_tensor =
        ctx.AllocateTmpTensor<T, NPUDeviceContext>(filter->dims(), dev_ctx);
    auto output_grad_tensor = ctx.AllocateTmpTensor<T, NPUDeviceContext>(
        output_grad->dims(), dev_ctx);

    input_tensor.ShareDataWith(*input);
    filter_tensor.ShareDataWith(*filter);
    output_grad_tensor.ShareDataWith(*output_grad);

    input_tensor.set_layout(DataLayout::kNCDHW);
    filter_tensor.set_layout(DataLayout::kNCDHW);
    output_grad_tensor.set_layout(DataLayout::kNCDHW);

    // update padding and dilation
    auto in_dims = input->dims();
    auto filter_dims = filter->dims();
    framework::DDim in_data_dims;
    framework::DDim filter_data_dims;

    in_data_dims = phi::slice_ddim(in_dims, 1, in_dims.size() - 1);
    filter_data_dims = phi::slice_ddim(filter_dims, 2, in_dims.size());

    std::vector<int> ksize = phi::vectorize<int>(filter_data_dims);
593 594
    UpdatePaddingAndDilation(
        &paddings, &dilations, padding_algorithm, in_data_dims, strides, ksize);
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616

    std::vector<int> strides_vec(5, 1);
    std::vector<int> dilations_vec(5, 1);

    strides_vec[2] = strides[0];
    strides_vec[3] = strides[1];
    strides_vec[4] = strides[2];
    dilations_vec[2] = dilations[0];
    dilations_vec[3] = dilations[1];
    dilations_vec[4] = dilations[2];

    auto stream = ctx.template device_context<NPUDeviceContext>().stream();

    if (filter_grad) {
      filter_grad->mutable_data<T>(ctx.GetPlace());
      std::vector<int> filter_shape_vec = phi::vectorize<int>(filter->dims());

      Tensor filter_grad_tensor = ctx.AllocateTmpTensor<T, NPUDeviceContext>(
          filter_grad->dims(), dev_ctx);
      filter_grad_tensor.ShareDataWith(*filter_grad);
      filter_grad_tensor.set_layout(DataLayout::kNCDHW);

617 618 619 620 621 622 623 624 625
      const auto& runner = NpuOpRunner("Conv3DBackpropFilterD",
                                       {input_tensor, output_grad_tensor},
                                       {filter_grad_tensor},
                                       {{"filter_size", filter_shape_vec},
                                        {"strides", strides_vec},
                                        {"pads", paddings},
                                        {"dilations", dilations_vec},
                                        {"groups", groups},
                                        {"data_format", data_format}});
626 627 628 629 630 631 632 633 634 635 636 637
      runner.Run(stream);
    }

    if (input_grad) {
      input_grad->mutable_data<T>(ctx.GetPlace());
      std::vector<int> input_shape_vec = phi::vectorize<int>(input->dims());

      Tensor input_grad_tensor = ctx.AllocateTmpTensor<T, NPUDeviceContext>(
          input_grad->dims(), dev_ctx);
      input_grad_tensor.ShareDataWith(*input_grad);
      input_grad_tensor.set_layout(DataLayout::kNCDHW);

638 639 640 641 642 643 644 645 646
      const auto& runner = NpuOpRunner("Conv3DBackpropInputD",
                                       {filter_tensor, output_grad_tensor},
                                       {input_grad_tensor},
                                       {{"input_size", input_shape_vec},
                                        {"strides", strides_vec},
                                        {"pads", paddings},
                                        {"dilations", dilations_vec},
                                        {"groups", groups},
                                        {"data_format", data_format}});
647 648 649 650 651
      runner.Run(stream);
    }
  }
};

652 653 654 655
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
656 657
namespace plat = paddle::platform;

658 659
REGISTER_OP_NPU_KERNEL(depthwise_conv2d,
                       ops::DepthwiseConvNPUKernel<float>,
660 661 662 663 664
                       ops::DepthwiseConvNPUKernel<plat::float16>);

REGISTER_OP_NPU_KERNEL(depthwise_conv2d_grad,
                       ops::DepthwiseConvGradNPUKernel<float>,
                       ops::DepthwiseConvGradNPUKernel<plat::float16>);
665

666 667
REGISTER_OP_NPU_KERNEL(conv2d,
                       ops::NPUConvOpKernel<float>,
668 669
                       ops::NPUConvOpKernel<plat::float16>);

670 671
REGISTER_OP_NPU_KERNEL(conv2d_grad,
                       ops::NPUConvGradOpKernel<float>,
672
                       ops::NPUConvGradOpKernel<plat::float16>);
673

674 675
REGISTER_OP_NPU_KERNEL(conv3d,
                       ops::NPUConv3dKernel<float>,
676 677
                       ops::NPUConv3dKernel<plat::float16>);

678 679
REGISTER_OP_NPU_KERNEL(conv3d_grad,
                       ops::NPUConv3dGradKernel<float>,
680
                       ops::NPUConv3dGradKernel<plat::float16>);