conv_transpose_grad_kernel.cu 41.7 KB
Newer Older
F
From00 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2022 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 <algorithm>
16

F
From00 已提交
17 18 19 20
#include "paddle/phi/backends/dynload/cudnn.h"
#include "paddle/phi/common/float16.h"
#include "paddle/phi/core/ddim.h"
#include "paddle/phi/core/kernel_registry.h"
21
#include "paddle/phi/kernels/conv_transpose_grad_kernel.h"
F
From00 已提交
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 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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
#include "paddle/phi/kernels/cpu/conv_util.h"
#include "paddle/phi/kernels/funcs/batch_norm_utils.h"
#include "paddle/phi/kernels/funcs/math_function.h"
#include "paddle/phi/kernels/funcs/padding.h"
#include "paddle/phi/kernels/funcs/slice.h"
#include "paddle/phi/kernels/transpose_kernel.h"

#ifdef PADDLE_WITH_HIP
#include "paddle/fluid/operators/conv_miopen_helper.h"
#include "paddle/fluid/platform/device/gpu/rocm/miopen_helper.h"
#else
#include "paddle/fluid/operators/conv_cudnn_helper.h"
#include "paddle/fluid/platform/device/gpu/cuda/cudnn_helper.h"
#endif

namespace phi {

using GPUDNNDataLayout = paddle::platform::DataLayout;

template <typename T, typename Context>
void ConvTransposeGradRawGPUDNNKernel(const Context& ctx,
                                      const DenseTensor& x,
                                      const DenseTensor& filter,
                                      const DenseTensor& dout,
                                      const std::vector<int>& strides,
                                      const std::vector<int>& paddings,
                                      const std::string& padding_algorithm,
                                      int groups,
                                      const std::vector<int>& dilations,
                                      const std::string& data_format,
                                      DenseTensor* dx,
                                      DenseTensor* dfilter) {
  const T* filter_data = filter.data<T>();
  std::vector<int> paddings_ = paddings;
  std::vector<int> dilations_ =
      dilations;  // cudnn v5 does not support dilations
  const GPUDNNDataLayout data_layout =
      (data_format != "NHWC" ? GPUDNNDataLayout::kNCHW
                             : GPUDNNDataLayout::kNHWC);

  // if channel_last, transpose to channel_first
  DenseTensor x_transpose;
  DenseTensor dout_transpose;
  std::vector<int> x_vec = vectorize<int>(x.dims());
  std::vector<int> out_vec = vectorize<int>(dout.dims());
  if (data_layout == GPUDNNDataLayout::kNHWC) {
    if (strides.size() == 2U) {
      std::vector<int> axis = {0, 3, 1, 2};
      for (size_t i = 0; i < axis.size(); ++i) {
        x_vec[i] = x.dims()[axis[i]];
        out_vec[i] = dout.dims()[axis[i]];
      }
      x_transpose = Transpose<T, Context>(ctx, x, axis);
      dout_transpose = Transpose<T, Context>(ctx, dout, axis);
    } else if (strides.size() == 3U) {
      std::vector<int> axis = {0, 4, 1, 2, 3};
      for (size_t i = 0; i < axis.size(); ++i) {
        x_vec[i] = x.dims()[axis[i]];
        out_vec[i] = dout.dims()[axis[i]];
      }
      x_transpose = Transpose<T, Context>(ctx, x, axis);
      dout_transpose = Transpose<T, Context>(ctx, dout, axis);
    }
  } else {
    x_transpose = x;
    dout_transpose = dout;
  }

  // update padding and dilation
  auto x_dims = x_transpose.dims();
  auto filter_dims = filter.dims();
  DDim x_data_dims;
  x_data_dims = slice_ddim(x_dims, 2, x_dims.size());
  DDim filter_data_dims = slice_ddim(filter_dims, 2, filter_dims.size());
  std::vector<int> ksize = vectorize<int>(filter_data_dims);
  UpdatePaddingAndDilation(
      &paddings_, &dilations_, padding_algorithm, x_data_dims, strides, ksize);

  int data_dim = strides.size();  // 2d or 3d
  bool is_sys_pad = funcs::IsSymmetricPadding(paddings_, data_dim);

  std::vector<int> x_pad(x_dims.size() * 2, 0);
  DenseTensor transformed_dout;
  std::vector<int> padding_common(data_dim, 0);
  if (!is_sys_pad) {
    std::vector<int> padding_diff(data_dim);
    std::vector<int> new_dout_shape_vec(data_dim + 2);
    new_dout_shape_vec[0] = dout_transpose.dims()[0];
    new_dout_shape_vec[1] = dout_transpose.dims()[1];

    for (size_t i = 0; i < data_dim; ++i) {
      padding_diff[i] = std::abs(paddings_[2 * i] - paddings_[2 * i + 1]);
      padding_common[i] = std::min(paddings_[2 * i], paddings_[2 * i + 1]);
      new_dout_shape_vec[i + 2] =
          dout_transpose.dims()[i + 2] + padding_diff[i];
      x_pad[2 * i + 4] = paddings_[2 * i] - padding_common[i];
      x_pad[2 * i + 4 + 1] = paddings_[2 * i + 1] - padding_common[i];
    }

    transformed_dout.Resize(make_ddim(new_dout_shape_vec));
    ctx.template Alloc<T>(&transformed_dout);

    const int rank = x_transpose.dims().size();
    T pad_value(0.0);
    switch (rank) {
      case 4: {
        funcs::PadFunction<Context, T, 4>(
            ctx, x_pad, dout_transpose, pad_value, &transformed_dout);
      } break;
      case 5: {
        funcs::PadFunction<Context, T, 5>(
            ctx, x_pad, dout_transpose, pad_value, &transformed_dout);
      } break;
      default:
        PADDLE_THROW(errors::InvalidArgument(
            "Op(ConvTranspose) only supports 4-D or 5-D x DenseTensor."));
    }
  } else {
    transformed_dout = dout_transpose;
    if (paddings_.size() == data_dim) {
      for (size_t i = 0; i < data_dim; ++i) {
        padding_common[i] = paddings_[i];
      }
    } else {
      for (size_t i = 0; i < data_dim; ++i) {
        padding_common[i] = paddings_[2 * i];
      }
    }
  }

  const T* x_data = x_transpose.data<T>();
  const T* dout_data = transformed_dout.data<T>();
  out_vec = vectorize<int>(transformed_dout.dims());

  // ------------------- cudnn descriptors ---------------------
  GPUDNNDataLayout layout;

  if (strides.size() == 2U) {
    layout = GPUDNNDataLayout::kNCHW;
  } else {
    layout = GPUDNNDataLayout::kNCDHW;
  }

  int iwo_groups = groups;
  int c_groups = 1;
#if defined(PADDLE_WITH_HIP) || CUDNN_VERSION_MIN(7, 0, 1)
  iwo_groups = 1;
  c_groups = groups;
  groups = 1;
#endif

  auto dtype = paddle::platform::CudnnDataType<T>::type;

  paddle::operators::ConvArgs args1{&transformed_dout,
                                    &filter,
                                    &x_transpose,
                                    strides,
                                    padding_common,
                                    dilations_,
                                    dtype};
  paddle::operators::ConvArgs args2{&transformed_dout,
                                    &filter,
                                    &x_transpose,
                                    strides,
                                    padding_common,
                                    dilations_,
                                    dtype};

#ifdef PADDLE_WITH_HIP
191 192 193
  paddle::operators::SearchResult<miopenConvFwdAlgorithm_t> fwd_result;
  paddle::operators::SearchResult<miopenConvBwdWeightsAlgorithm_t>
      filter_result;
F
From00 已提交
194
#else
195 196 197
  paddle::operators::SearchResult<cudnnConvolutionFwdAlgo_t> fwd_result;
  paddle::operators::SearchResult<cudnnConvolutionBwdFilterAlgo_t>
      filter_result;
F
From00 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
#endif

  auto layout_tensor = paddle::platform::GetCudnnTensorFormat(layout);
  size_t workspace_size = 0;
  auto handle = ctx.cudnn_handle();
  bool deterministic = FLAGS_cudnn_deterministic;
  T* dx_data = nullptr;
  T* dfilter_data = nullptr;

  if (dx) {
    dx_data = ctx.template Alloc<T>(dx);
    args1.handle = handle;
    args1.idesc.set(transformed_dout, iwo_groups);
    args1.wdesc.set(filter, layout_tensor, iwo_groups);
    args1.odesc.set(x_transpose, iwo_groups);
    args1.cdesc.set(dtype,
                    padding_common,
                    strides,
                    dilations_,
                    paddle::platform::AllowTF32Cudnn(),
                    c_groups);
#ifdef PADDLE_WITH_HIP
    using search1 =
        paddle::operators::SearchAlgorithm<miopenConvFwdAlgorithm_t>;
    workspace_size = std::max(workspace_size, search1::GetWorkspaceSize(args1));
223
    fwd_result.algo =
F
From00 已提交
224 225 226 227
        search1::Find<T>(args1, false, deterministic, workspace_size, ctx);
#else
    using search1 =
        paddle::operators::SearchAlgorithm<cudnnConvolutionFwdAlgoPerf_t>;
228 229 230
    fwd_result = search1::Find<T>(args1, false, deterministic, ctx);
    workspace_size = std::max(
        workspace_size, search1::GetWorkspaceSize(args1, fwd_result.algo));
F
From00 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
#endif
  }

  if (dfilter) {
    dfilter_data = ctx.template Alloc<T>(dfilter);
    args2.handle = handle;
    args2.idesc.set(transformed_dout, iwo_groups);
    args2.wdesc.set(*dfilter, layout_tensor, iwo_groups);
    args2.odesc.set(x_transpose, iwo_groups);
    args2.cdesc.set(dtype,
                    padding_common,
                    strides,
                    dilations_,
                    paddle::platform::AllowTF32Cudnn(),
                    c_groups);
#ifdef PADDLE_WITH_HIP
    using search2 =
        paddle::operators::SearchAlgorithm<miopenConvBwdWeightsAlgorithm_t>;
    workspace_size = std::max(workspace_size, search2::GetWorkspaceSize(args2));
250
    filter_result.algo =
F
From00 已提交
251 252 253 254
        search2::Find<T>(args2, false, deterministic, workspace_size, ctx);
#else
    using search2 =
        paddle::operators::SearchAlgorithm<cudnnConvolutionBwdFilterAlgoPerf_t>;
255 256 257
    filter_result = search2::Find<T>(args2, false, deterministic, ctx);
    workspace_size = std::max(
        workspace_size, search2::GetWorkspaceSize(args2, filter_result.algo));
F
From00 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
#endif
  }

  // ------------------- cudnn conv backward data ---------------------
  // FIxME(typhoonzero): template type T may not be the same as cudnn call.
  int x_offset = x.numel() / x.dims()[0] / groups;
  int dout_offset =
      transformed_dout.numel() / transformed_dout.dims()[0] / groups;
  int filter_offset = filter.numel() / groups;
  paddle::operators::ScalingParamType<T> alpha = 1.0f;
  paddle::operators::ScalingParamType<T> beta = 0.0f;
  auto workspace_handle = ctx.cudnn_workspace_handle();
  if (dx) {
    // Because beta is zero, it is unnecessary to reset dx.
    for (int g = 0; g < groups; g++) {
#ifdef PADDLE_WITH_HIP
      auto cudnn_func = [&](void* cudnn_workspace) {
        PADDLE_ENFORCE_GPU_SUCCESS(
            dynload::miopenConvolutionForward(handle,
                                              &alpha,
                                              args1.idesc.desc(),
                                              dout_data + dout_offset * g,
                                              args1.wdesc.desc(),
                                              filter_data + filter_offset * g,
                                              args1.cdesc.desc(),
283
                                              fwd_result.algo,
F
From00 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
                                              &beta,
                                              args1.odesc.desc(),
                                              dx_data + x_offset * g,
                                              cudnn_workspace,
                                              workspace_size));
      };
#else   // PADDLE_WITH_HIP
      auto cudnn_func = [&](void* cudnn_workspace) {
        PADDLE_ENFORCE_GPU_SUCCESS(
            dynload::cudnnConvolutionForward(handle,
                                             &alpha,
                                             args1.idesc.desc(),
                                             dout_data + dout_offset * g,
                                             args1.wdesc.desc(),
                                             filter_data + filter_offset * g,
                                             args1.cdesc.desc(),
300
                                             fwd_result.algo,
F
From00 已提交
301 302 303 304 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 339 340 341 342
                                             cudnn_workspace,
                                             workspace_size,
                                             &beta,
                                             args1.odesc.desc(),
                                             dx_data + x_offset * g));
      };
#endif  // PADDLE_WITH_HIP
      workspace_handle.RunFunc(cudnn_func, workspace_size);
    }

    if (data_layout == GPUDNNDataLayout::kNHWC) {
      DenseTensor dx_transpose;
      DenseTensor dx_nchw;
      dx_nchw.ShareDataWith(*dx);
      dx_nchw.Resize(make_ddim(x_vec));
      if (strides.size() == 2U) {
        std::vector<int> axis = {0, 2, 3, 1};
        dx_transpose = Transpose<T, Context>(ctx, dx_nchw, axis);
        *dx = dx_transpose;
      } else if (strides.size() == 3U) {
        std::vector<int> axis = {0, 2, 3, 4, 1};
        dx_transpose = Transpose<T, Context>(ctx, dx_nchw, axis);
        *dx = dx_transpose;
      }
    }
  }

  // ------------------- cudnn conv backward filter ---------------------
  if (dfilter) {
    // Because beta is zero, it is unnecessary to reset dfilter.
    // Gradient with respect to the filter
    for (int g = 0; g < groups; g++) {
#ifdef PADDLE_WITH_HIP
      auto cudnn_func = [&](void* cudnn_workspace) {
        PADDLE_ENFORCE_GPU_SUCCESS(dynload::miopenConvolutionBackwardWeights(
            handle,
            &alpha,
            args2.odesc.desc(),
            x_data + x_offset * g,
            args2.idesc.desc(),
            dout_data + dout_offset * g,
            args2.cdesc.desc(),
343
            filter_result.algo,
F
From00 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
            &beta,
            args2.wdesc.desc(),
            dfilter_data + filter_offset * g,
            cudnn_workspace,
            workspace_size));
      };
#else   // PADDLE_WITH_HIP
      auto cudnn_func = [&](void* cudnn_workspace) {
        PADDLE_ENFORCE_GPU_SUCCESS(dynload::cudnnConvolutionBackwardFilter(
            handle,
            &alpha,
            args2.idesc.desc(),
            dout_data + dout_offset * g,
            args2.odesc.desc(),
            x_data + x_offset * g,
            args2.cdesc.desc(),
360
            filter_result.algo,
F
From00 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 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 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 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 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
            cudnn_workspace,
            workspace_size,
            &beta,
            args2.wdesc.desc(),
            dfilter_data + filter_offset * g));
      };
#endif  // PADDLE_WITH_HIP
      workspace_handle.RunFunc(cudnn_func, workspace_size);
    }
  }
}

template <typename T, typename Context>
void Conv2dTransposeGradGPUDNNKernel(const Context& ctx,
                                     const DenseTensor& x,
                                     const DenseTensor& filter,
                                     const DenseTensor& dout,
                                     const std::vector<int>& strides,
                                     const std::vector<int>& paddings_,
                                     const std::vector<int>& output_padding,
                                     const std::vector<int>& output_size,
                                     const std::string& padding_algorithm,
                                     int groups,
                                     const std::vector<int>& dilations_,
                                     const std::string& data_format,
                                     DenseTensor* dx,
                                     DenseTensor* dfilter) {
  ConvTransposeGradRawGPUDNNKernel<T, Context>(ctx,
                                               x,
                                               filter,
                                               dout,
                                               strides,
                                               paddings_,
                                               padding_algorithm,
                                               groups,
                                               dilations_,
                                               data_format,
                                               dx,
                                               dfilter);
}

/*
 * Inputs:  I, filter, dout, ddI, ddfilter
 * Outputs: ddout, dfilter, dI
 * ddo = conv_bp_data(filter, ddI) + conv_bp_data(ddfilter, I)
 * dfilter = conv_bp_filter(dout, ddI)
 * dI = conv(dout, ddfilter)
 */
template <typename T, typename Context>
void Conv2dTransposeDoubleGradGPUDNNKernel(
    const Context& ctx,
    const DenseTensor& x,
    const DenseTensor& filter,
    const DenseTensor& dout,
    const DenseTensor& ddx,
    const DenseTensor& ddfilter,
    const std::vector<int>& strides,
    const std::vector<int>& paddings,
    const std::vector<int>& output_padding,
    const std::vector<int>& output_size,
    const std::string& padding_algorithm,
    int groups,
    const std::vector<int>& dilations,
    const std::string& data_format,
    DenseTensor* dx,
    DenseTensor* dfilter,
    DenseTensor* ddout) {
  if (dx) {
    ctx.template Alloc<T>(dx);
  }
  if (dfilter) {
    ctx.template Alloc<T>(dfilter);
  }
  if (ddout) {
    ctx.template Alloc<T>(ddout);
    funcs::SetConstant<Context, T> set_zero;
    set_zero(ctx, ddout, static_cast<T>(0));
  }

  const T* filter_ = filter.data<T>();
  const T* dout_ = dout.data<T>();
  const T* ddx_ = nullptr;
  const T* ddfilter_ = nullptr;
  T* dx_ = nullptr;
  T* dfilter_ = nullptr;
  T* ddout_ = nullptr;
  T* transformed_dx_ = nullptr;

  std::vector<int> paddings_ = paddings;
  std::vector<int> dilations_ = dilations;

  bool deterministic = FLAGS_cudnn_deterministic;
  const bool channel_last = (data_format == "NHWC" || data_format == "NDHWC");

  // transform DenseTensors to channel first-----------
  DenseTensor transformed_x_channel(x.type());
  DenseTensor transformed_dout_channel(dout.type());
  DenseTensor transformed_ddx_channel(x.type());

  DenseTensor transformed_dx_channel(x.type());
  DenseTensor transformed_ddout_channel(dout.type());

  if (channel_last) {
    ResizeToChannelFirst<Context, T>(ctx, &x, &transformed_x_channel);
    TransToChannelFirst<Context, T>(ctx, &x, &transformed_x_channel);

    ResizeToChannelFirst<Context, T>(ctx, &dout, &transformed_dout_channel);
    TransToChannelFirst<Context, T>(ctx, &dout, &transformed_dout_channel);

    ResizeToChannelFirst<Context, T>(ctx, &ddx, &transformed_ddx_channel);
    TransToChannelFirst<Context, T>(ctx, &ddx, &transformed_ddx_channel);

    if (dx) {
      ResizeToChannelFirst<Context, T>(ctx, dx, &transformed_dx_channel);
      ctx.template Alloc<T>(&transformed_dx_channel);
    }
    if (ddout) {
      ResizeToChannelFirst<Context, T>(ctx, ddout, &transformed_ddout_channel);
    }
  } else {
    transformed_x_channel = x;
    transformed_dout_channel = dout;
    transformed_ddx_channel = ddx;

    if (dx) {
      transformed_dx_channel = *dx;
    }
  }
  std::vector<int> out_vec = vectorize<int>(transformed_dout_channel.dims());

  auto x_dims = transformed_x_channel.dims();
  auto filter_dims = filter.dims();
  DDim x_data_dims = slice_ddim(x_dims, 2, x_dims.size());
  DDim filter_data_dims = slice_ddim(filter_dims, 2, filter_dims.size());
  std::vector<int> ksize = vectorize<int>(filter_data_dims);
  UpdatePaddingAndDilation(
      &paddings_, &dilations_, padding_algorithm, x_data_dims, strides, ksize);

  int data_dim = strides.size();  // 2d or 3d
  bool is_sys_pad = funcs::IsSymmetricPadding(paddings_, data_dim);
  DenseTensor transformed_x(x.type());
  DenseTensor transformed_ddx(x.type());

  DenseTensor transformed_dout(dout.type());

  std::vector<int> padding_common(data_dim, 0);
  std::vector<int> input_pad(x.dims().size() * 2, 0);

  if (!is_sys_pad) {
    // get pad
    std::vector<int> padding_diff(data_dim);
    std::vector<int> new_input_shape_vec(data_dim + 2);
    std::vector<int> new_output_grad_shape_vec(data_dim + 2);

    new_input_shape_vec[0] = transformed_x_channel.dims()[0];
    new_input_shape_vec[1] = transformed_x_channel.dims()[1];

    new_output_grad_shape_vec[0] = transformed_dout_channel.dims()[0];
    new_output_grad_shape_vec[1] = transformed_dout_channel.dims()[1];

    for (size_t i = 0; i < data_dim; ++i) {
      padding_diff[i] = std::abs(paddings_[2 * i] - paddings_[2 * i + 1]);
      padding_common[i] = std::min(paddings_[2 * i], paddings_[2 * i + 1]);
      new_input_shape_vec[i + 2] =
          transformed_x_channel.dims()[i + 2] + padding_diff[i];

      new_output_grad_shape_vec[i + 2] =
          transformed_dout_channel.dims()[i + 2] + padding_diff[i];

      input_pad[2 * i + 4] = paddings_[2 * i] - padding_common[i];
      input_pad[2 * i + 4 + 1] = paddings_[2 * i + 1] - padding_common[i];
    }
    DDim new_input_shape(make_ddim(new_input_shape_vec));
    transformed_x.Resize(new_input_shape);
    transformed_ddx.Resize(new_input_shape);
    transformed_dout.Resize(make_ddim(new_output_grad_shape_vec));

    ctx.template Alloc<T>(&transformed_x);
    ctx.template Alloc<T>(&transformed_ddx);
    ctx.template Alloc<T>(&transformed_dout);

    // pad for input
    const int rank = x.dims().size();
    T pad_value(0.0);
    switch (rank) {
      case 4: {
        funcs::PadFunction<Context, T, 4>(
            ctx, input_pad, transformed_x_channel, pad_value, &transformed_x);
        funcs::PadFunction<Context, T, 4>(ctx,
                                          input_pad,
                                          transformed_dout_channel,
                                          pad_value,
                                          &transformed_dout);
        funcs::PadFunction<Context, T, 4>(ctx,
                                          input_pad,
                                          transformed_ddx_channel,
                                          pad_value,
                                          &transformed_ddx);
      } break;
      case 5: {
        funcs::PadFunction<Context, T, 5>(
            ctx, input_pad, transformed_x_channel, pad_value, &transformed_x);
        funcs::PadFunction<Context, T, 5>(ctx,
                                          input_pad,
                                          transformed_ddx_channel,
                                          pad_value,
                                          &transformed_ddx);
      } break;
      default:
        PADDLE_THROW(errors::InvalidArgument(
            "ConvOp only support tensors with 4 or 5 dimensions."));
    }
  } else {
    transformed_x = transformed_x_channel;
    transformed_dout = transformed_dout_channel;
    transformed_ddx = transformed_ddx_channel;

    if (paddings_.size() == data_dim) {
      for (size_t i = 0; i < data_dim; ++i) {
        padding_common[i] = paddings_[i];
      }
    } else {
      for (size_t i = 0; i < data_dim; ++i) {
        padding_common[i] = paddings_[2 * i];
      }
    }
  }

  std::vector<int64_t> starts(data_dim, 0);
  std::vector<int64_t> ends(data_dim, 0);
  std::vector<int64_t> axes(data_dim, 0);
  for (size_t i = 0; i < data_dim; ++i) {
    starts[i] = input_pad[2 * i + 4] * (strides[i] + 1);
    ends[i] = starts[i] + out_vec[i + 2];
    axes[i] = i + 2;
  }

  std::vector<int> transformed_out_vec = out_vec;
  for (size_t i = 0; i < data_dim; ++i) {
    transformed_out_vec[i + 2] =
        out_vec[i + 2] +
        (input_pad[2 * i + 4] + input_pad[2 * i + 5]) * strides[i] -
        2 * padding_common[i] + paddings_[2 * i] + paddings_[2 * i + 1];
  }

  if (!is_sys_pad) {
    transformed_ddout_channel.Resize(make_ddim(transformed_out_vec));
    ctx.template Alloc<T>(&transformed_ddout_channel);
  } else {
    ctx.template Alloc<T>(ddout);
    transformed_ddout_channel = *ddout;
    transformed_ddout_channel.Resize(make_ddim(transformed_out_vec));
  }

  const T* x_ = transformed_x.data<T>();

  int iwo_group = groups;
  int c_group = 1;
#if defined(PADDLE_WITH_HIP) || CUDNN_VERSION_MIN(7, 0, 1)
  iwo_group = 1;
  c_group = groups;
  groups = 1;
#endif
  auto dtype = paddle::platform::CudnnDataType<T>::type;

  auto handle = ctx.cudnn_handle();

  paddle::operators::ConvArgs args1{&transformed_ddout_channel,
                                    &filter,
                                    &transformed_ddx,
                                    strides,
                                    padding_common,
                                    dilations_,
                                    dtype};
  paddle::operators::ConvArgs args2{&transformed_ddout_channel,
                                    &ddfilter,
                                    &transformed_x,
                                    strides,
                                    padding_common,
                                    dilations_,
                                    dtype};

  paddle::operators::ConvArgs args3{&transformed_dout,
                                    dfilter,
                                    &transformed_ddx_channel,
                                    strides,
                                    padding_common,
                                    dilations_,
                                    dtype};
  paddle::operators::ConvArgs args4{&transformed_dout,
                                    &ddfilter,
                                    &transformed_dx_channel,
                                    strides,
                                    padding_common,
                                    dilations_,
                                    dtype};
#ifdef PADDLE_WITH_HIP
658 659 660 661 662
  paddle::operators::SearchResult<miopenConvBwdDataAlgorithm_t> bwd_result1;
  paddle::operators::SearchResult<miopenConvBwdDataAlgorithm_t> bwd_result2;
  paddle::operators::SearchResult<miopenConvBwdWeightsAlgorithm_t>
      filter_result;
  paddle::operators::SearchResult<miopenConvFwdAlgorithm_t> fwd_result;
F
From00 已提交
663
#else
664 665 666 667 668
  paddle::operators::SearchResult<cudnnConvolutionBwdDataAlgo_t> bwd_result1;
  paddle::operators::SearchResult<cudnnConvolutionBwdDataAlgo_t> bwd_result2;
  paddle::operators::SearchResult<cudnnConvolutionBwdFilterAlgo_t>
      filter_result;
  paddle::operators::SearchResult<cudnnConvolutionFwdAlgo_t> fwd_result;
F
From00 已提交
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
#endif

  auto layout = paddle::platform::GetCudnnTensorFormat(GPUDNNDataLayout::kNCHW);

  // ddo = conv(ddI, filter) + conv(I, ddfilter)
  size_t workspace_size = 0;

  T* transformed_ddout_channel_ = nullptr;

  if (ddout) {
    ddout_ = ddout->data<T>();
    transformed_ddout_channel_ = transformed_ddout_channel.data<T>();

    args1.handle = handle;
    args1.idesc.set(transformed_ddout_channel, iwo_group);
    args1.wdesc.set(filter, layout, iwo_group);
    args1.odesc.set(transformed_ddx, iwo_group);
    args1.cdesc.set(dtype,
                    padding_common,
                    strides,
                    dilations_,
                    paddle::platform::AllowTF32Cudnn(),
                    c_group);
#ifdef PADDLE_WITH_HIP
    using search1 =
        paddle::operators::SearchAlgorithm<miopenConvBwdDataAlgorithm_t>;
    workspace_size = search1::GetWorkspaceSize(args1);
696
    bwd_result1.algo =
F
From00 已提交
697 698 699 700
        search1::Find<T>(args1, false, deterministic, workspace_size, ctx);
#else
    using search1 =
        paddle::operators::SearchAlgorithm<cudnnConvolutionBwdDataAlgoPerf_t>;
701 702
    bwd_result1 = search1::Find<T>(args1, false, deterministic, ctx);
    workspace_size = search1::GetWorkspaceSize(args1, bwd_result1.algo);
F
From00 已提交
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
#endif

    ddfilter_ = ddfilter.data<T>();
    args2.handle = handle;
    args2.idesc.set(transformed_ddout_channel, iwo_group);
    args2.wdesc.set(ddfilter, layout, iwo_group);
    args2.odesc.set(transformed_x, iwo_group);
    args2.cdesc.set(dtype,
                    padding_common,
                    strides,
                    dilations_,
                    paddle::platform::AllowTF32Cudnn(),
                    c_group);
#ifdef PADDLE_WITH_HIP
    using search2 =
        paddle::operators::SearchAlgorithm<miopenConvBwdDataAlgorithm_t>;
    workspace_size = std::max(workspace_size, search2::GetWorkspaceSize(args2));
720
    bwd_result2.algo =
F
From00 已提交
721 722 723 724
        search2::Find<T>(args2, false, deterministic, workspace_size, ctx);
#else
    using search2 =
        paddle::operators::SearchAlgorithm<cudnnConvolutionBwdDataAlgoPerf_t>;
725 726 727
    bwd_result2 = search2::Find<T>(args2, false, deterministic, ctx);
    workspace_size = std::max(
        workspace_size, search2::GetWorkspaceSize(args2, bwd_result2.algo));
F
From00 已提交
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
#endif
  }

  if (dfilter) {
    dfilter_ = dfilter->data<T>();
    args3.handle = handle;
    args3.idesc.set(transformed_dout, iwo_group);
    args3.wdesc.set(*dfilter, layout, iwo_group);
    args3.odesc.set(transformed_ddx_channel, iwo_group);
    args3.cdesc.set(dtype,
                    padding_common,
                    strides,
                    dilations_,
                    paddle::platform::AllowTF32Cudnn(),
                    c_group);
#ifdef PADDLE_WITH_HIP
    using search3 =
        paddle::operators::SearchAlgorithm<miopenConvBwdWeightsAlgorithm_t>;
    workspace_size = std::max(workspace_size, search3::GetWorkspaceSize(args3));
747
    filter_result.algo =
F
From00 已提交
748 749 750 751
        search3::Find<T>(args3, false, deterministic, workspace_size, ctx);
#else
    using search3 =
        paddle::operators::SearchAlgorithm<cudnnConvolutionBwdFilterAlgoPerf_t>;
752 753 754
    filter_result = search3::Find<T>(args3, false, deterministic, ctx);
    workspace_size = std::max(
        workspace_size, search3::GetWorkspaceSize(args3, filter_result.algo));
F
From00 已提交
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
#endif
  }

  if (dx) {
    transformed_dx_ = transformed_dx_channel.data<T>();

    args4.handle = handle;
    args4.idesc.set(transformed_dout, iwo_group);
    args4.wdesc.set(ddfilter, layout, iwo_group);
    args4.odesc.set(transformed_dx_channel, iwo_group);
    args4.cdesc.set(dtype,
                    padding_common,
                    strides,
                    dilations_,
                    paddle::platform::AllowTF32Cudnn(),
                    c_group);
#ifdef PADDLE_WITH_HIP
    using search4 =
        paddle::operators::SearchAlgorithm<miopenConvFwdAlgorithm_t>;
    workspace_size = std::max(workspace_size, search4::GetWorkspaceSize(args4));
775
    fwd_result.algo =
F
From00 已提交
776 777 778 779
        search4::Find<T>(args4, false, deterministic, workspace_size, ctx);
#else
    using search4 =
        paddle::operators::SearchAlgorithm<cudnnConvolutionFwdAlgoPerf_t>;
780 781 782
    fwd_result = search4::Find<T>(args4, false, deterministic, ctx);
    workspace_size = std::max(
        workspace_size, search4::GetWorkspaceSize(args4, fwd_result.algo));
F
From00 已提交
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
#endif
  }

  int i_n, i_c, i_d, i_h, i_w;
  paddle::operators::GetNCDHW(transformed_x.dims(),
                              GPUDNNDataLayout::kNCHW,
                              &i_n,
                              &i_c,
                              &i_d,
                              &i_h,
                              &i_w);

  int o_n, o_c, o_d, o_h, o_w;
  paddle::operators::GetNCDHW(transformed_dout.dims(),
                              GPUDNNDataLayout::kNCHW,
                              &o_n,
                              &o_c,
                              &o_d,
                              &o_h,
                              &o_w);

  int group_offset_in =
      transformed_x.numel() / transformed_x.dims()[0] / groups;
  int group_offset_out =
      transformed_dout.numel() / transformed_dout.dims()[0] / groups;
  int group_offset_filter = filter.numel() / groups;

  paddle::operators::ScalingParamType<T> alpha = 1.0f;
  paddle::operators::ScalingParamType<T> beta = 0.0f;

  auto wkspace_handle = ctx.cudnn_workspace_handle();

  if (ddout) {
    ddx_ = transformed_ddx.data<T>();
    for (int i = 0; i < groups; i++) {
#ifdef PADDLE_WITH_HIP
      wkspace_handle.RunFunc(
          [&](void* workspace_ptr) {
            PADDLE_ENFORCE_GPU_SUCCESS(dynload::miopenConvolutionBackwardData(
                handle,
                &alpha,
                args1.odesc.desc(),
                ddx_ + i * group_offset_in,
                args1.wdesc.desc(),
                filter_ + i * group_offset_filter,
                args1.cdesc.desc(),
829
                bwd_result1.algo,
F
From00 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
                &beta,
                args1.idesc.desc(),
                transformed_ddout_channel_ + i * group_offset_out,
                workspace_ptr,
                workspace_size));
          },
          workspace_size);
#else   // PADDLE_WITH_HIP
      wkspace_handle.RunFunc(
          [&](void* workspace_ptr) {
            PADDLE_ENFORCE_GPU_SUCCESS(dynload::cudnnConvolutionBackwardData(
                handle,
                &alpha,
                args1.wdesc.desc(),
                filter_ + i * group_offset_filter,
                args1.odesc.desc(),
                ddx_ + i * group_offset_in,
                args1.cdesc.desc(),
848
                bwd_result1.algo,
F
From00 已提交
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
                workspace_ptr,
                workspace_size,
                &beta,
                args1.idesc.desc(),
                transformed_ddout_channel_ + i * group_offset_out));
          },
          workspace_size);
#endif  // PADDLE_WITH_HIP
    }

    for (int i = 0; i < groups; i++) {
#ifdef PADDLE_WITH_HIP
      // MIOPEN ONLY support beta to be 0.0f
      DenseTensor conv_x_ddfilter(dout.type());
      conv_x_ddfilter.Resize(transformed_ddout_channel.dims());
      T* conv_x_ddfilter_data = ctx.template Alloc<T>(&conv_x_ddfilter);
      wkspace_handle.RunFunc(
          [&](void* workspace_ptr) {
            PADDLE_ENFORCE_GPU_SUCCESS(dynload::miopenConvolutionBackwardData(
                handle,
                &alpha,
                args2.odesc.desc(),
                x_ + i * group_offset_in,
                args2.wdesc.desc(),
                ddfilter_ + i * group_offset_filter,
                args2.cdesc.desc(),
875
                bwd_result2.algo,
F
From00 已提交
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
                &beta,
                args2.idesc.desc(),
                conv_x_ddfilter_data + i * group_offset_out,
                workspace_ptr,
                workspace_size));
          },
          workspace_size);
      PADDLE_ENFORCE_GPU_SUCCESS(dynload::miopenOpTensor(
          handle,
          miopenTensorOpAdd,
          &alpha,
          args2.idesc.desc(),
          transformed_ddout_channel_ + i * group_offset_out,
          &alpha,
          args2.idesc.desc(),
          conv_x_ddfilter_data + i * group_offset_out,
          &beta,
          args2.idesc.desc(),
          transformed_ddout_channel_ + i * group_offset_out));
#else   // PADDLE_WITH_HIP
      wkspace_handle.RunFunc(
          [&](void* workspace_ptr) {
            PADDLE_ENFORCE_GPU_SUCCESS(dynload::cudnnConvolutionBackwardData(
                handle,
                &alpha,
                args2.wdesc.desc(),
                ddfilter_ + i * group_offset_filter,
                args2.odesc.desc(),
                x_ + i * group_offset_in,
                args2.cdesc.desc(),
906
                bwd_result2.algo,
F
From00 已提交
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
                workspace_ptr,
                workspace_size,
                &alpha,
                args2.idesc.desc(),
                transformed_ddout_channel_ + i * group_offset_out));
          },
          workspace_size);
#endif  // PADDLE_WITH_HIP
    }

    if ((!is_sys_pad) && (!channel_last)) {
      if (strides.size() == 2U) {
        funcs::Slice<Context, T, 4>(
            ctx, &transformed_ddout_channel, ddout, starts, ends, axes);
      } else if (!is_sys_pad && strides.size() == 3U) {
        funcs::Slice<Context, T, 5>(
            ctx, &transformed_ddout_channel, ddout, starts, ends, axes);
      }
    } else if ((!is_sys_pad) && (channel_last)) {
      if (strides.size() == 2U) {
        funcs::Slice<Context, T, 4>(ctx,
                                    &transformed_ddout_channel,
                                    &transformed_ddout_channel,
                                    starts,
                                    ends,
                                    axes);
      } else if (!is_sys_pad && strides.size() == 3U) {
        funcs::Slice<Context, T, 5>(ctx,
                                    &transformed_ddout_channel,
                                    &transformed_ddout_channel,
                                    starts,
                                    ends,
                                    axes);
      }

      TransToChannelLast<Context, T>(ctx, &transformed_ddout_channel, ddout);
    }
  }

  T* transformed_dout_channel_ = transformed_dout.data<T>();
  if (dfilter) {
    ddx_ = transformed_ddx_channel.data<T>();
    for (int i = 0; i < groups; i++) {
#ifdef PADDLE_WITH_HIP
      wkspace_handle.RunFunc(
          [&](void* workspace_ptr) {
            PADDLE_ENFORCE_GPU_SUCCESS(
                dynload::miopenConvolutionBackwardWeights(
                    handle,
                    &alpha,
                    args3.odesc.desc(),
                    ddx_ + i * group_offset_in,
                    args3.idesc.desc(),
                    transformed_dout_channel_ + i * group_offset_out,
                    args3.cdesc.desc(),
962
                    filter_result.algo,
F
From00 已提交
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
                    &beta,
                    args3.wdesc.desc(),
                    dfilter_ + i * group_offset_filter,
                    workspace_ptr,
                    workspace_size));
          },
          workspace_size);
#else   // PADDLE_WITH_HIP
      wkspace_handle.RunFunc(
          [&](void* workspace_ptr) {
            PADDLE_ENFORCE_GPU_SUCCESS(dynload::cudnnConvolutionBackwardFilter(
                handle,
                &alpha,
                args3.idesc.desc(),
                transformed_dout_channel_ + i * group_offset_out,
                args3.odesc.desc(),
                ddx_ + i * group_offset_in,
                args3.cdesc.desc(),
981
                filter_result.algo,
F
From00 已提交
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
                workspace_ptr,
                workspace_size,
                &beta,
                args3.wdesc.desc(),
                dfilter_ + i * group_offset_filter));
          },
          workspace_size);
#endif  // PADDLE_WITH_HIP
    }
  }

  if (dx) {
    ddfilter_ = ddfilter.data<T>();
    for (int i = 0; i < groups; i++) {
#ifdef PADDLE_WITH_HIP
      wkspace_handle.RunFunc(
          [&](void* workspace_ptr) {
            PADDLE_ENFORCE_GPU_SUCCESS(dynload::miopenConvolutionForward(
                handle,
                &alpha,
                args4.idesc.desc(),
                transformed_dout_channel_ + i * group_offset_out,
                args4.wdesc.desc(),
                ddfilter_ + i * group_offset_filter,
                args4.cdesc.desc(),
1007
                fwd_result.algo,
F
From00 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
                &beta,
                args4.odesc.desc(),
                transformed_dx_ + i * group_offset_in,
                workspace_ptr,
                workspace_size));
          },
          workspace_size);
#else   // PADDLE_WITH_HIP
      wkspace_handle.RunFunc(
          [&](void* workspace_ptr) {
            PADDLE_ENFORCE_GPU_SUCCESS(dynload::cudnnConvolutionForward(
                handle,
                &alpha,
                args4.idesc.desc(),
                transformed_dout_channel_ + i * group_offset_out,
                args4.wdesc.desc(),
                ddfilter_ + i * group_offset_filter,
                args4.cdesc.desc(),
1026
                fwd_result.algo,
F
From00 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
                workspace_ptr,
                workspace_size,
                &beta,
                args4.odesc.desc(),
                transformed_dx_ + i * group_offset_in));
          },
          workspace_size);
#endif  // PADDLE_WITH_HIP
    }
    if (channel_last) {
      TransToChannelLast<Context, T>(ctx, &transformed_dx_channel, dx);
    }
  }
}

template <typename T, typename Context>
void Conv3dTransposeGradGPUDNNKernel(const Context& ctx,
                                     const DenseTensor& x,
                                     const DenseTensor& filter,
                                     const DenseTensor& dout,
                                     const std::vector<int>& strides,
                                     const std::vector<int>& paddings_,
                                     const std::vector<int>& output_padding,
                                     const std::vector<int>& output_size,
                                     const std::string& padding_algorithm,
                                     int groups,
                                     const std::vector<int>& dilations_,
                                     const std::string& data_format,
                                     DenseTensor* dx,
                                     DenseTensor* dfilter) {
  ConvTransposeGradRawGPUDNNKernel<T, Context>(ctx,
                                               x,
                                               filter,
                                               dout,
                                               strides,
                                               paddings_,
                                               padding_algorithm,
                                               groups,
                                               dilations_,
                                               data_format,
                                               dx,
                                               dfilter);
}

}  // namespace phi

using float16 = phi::dtype::float16;

#ifdef PADDLE_WITH_HIP
// MIOPEN do not support double
PD_REGISTER_KERNEL(conv2d_transpose_grad,
                   GPUDNN,
                   ALL_LAYOUT,
                   phi::Conv2dTransposeGradGPUDNNKernel,
                   float,
                   float16) {}
PD_REGISTER_KERNEL(conv2d_transpose_grad_grad,
                   GPUDNN,
                   ALL_LAYOUT,
                   phi::Conv2dTransposeDoubleGradGPUDNNKernel,
                   float,
                   float16) {}
PD_REGISTER_KERNEL(conv3d_transpose_grad,
                   GPUDNN,
                   ALL_LAYOUT,
                   phi::Conv3dTransposeGradGPUDNNKernel,
                   float,
                   float16) {}
#else
PD_REGISTER_KERNEL(conv2d_transpose_grad,
                   GPUDNN,
                   ALL_LAYOUT,
                   phi::Conv2dTransposeGradGPUDNNKernel,
                   float,
                   double,
                   float16) {}
PD_REGISTER_KERNEL(conv2d_transpose_grad_grad,
                   GPUDNN,
                   ALL_LAYOUT,
                   phi::Conv2dTransposeDoubleGradGPUDNNKernel,
                   float,
                   double,
                   float16) {}
PD_REGISTER_KERNEL(conv3d_transpose_grad,
                   GPUDNN,
                   ALL_LAYOUT,
                   phi::Conv3dTransposeGradGPUDNNKernel,
                   float,
                   double,
                   float16) {}
#endif