conv_cudnn_op.cu 59.8 KB
Newer Older
L
liym27 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the spopecific language governing permissions and
limitations under the License. */

#include <utility>
#include <vector>
17

L
liym27 已提交
18 19 20 21
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/memory/memory.h"
22 23 24
#ifdef PADDLE_WITH_HIP
#include "paddle/fluid/operators/conv_miopen_helper.h"
#else
L
liym27 已提交
25
#include "paddle/fluid/operators/conv_cudnn_helper.h"
26
#endif
L
liym27 已提交
27
#include "paddle/fluid/operators/conv_op.h"
28
#include "paddle/fluid/operators/math/padding.h"
L
liym27 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#include "paddle/fluid/platform/cudnn_workspace_helper.h"
#include "paddle/fluid/platform/float16.h"
#include "paddle/fluid/platform/profiler.h"

DECLARE_bool(cudnn_deterministic);
DECLARE_uint64(conv_workspace_size_limit);
DECLARE_bool(cudnn_exhaustive_search);

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using ScopedTensorDescriptor = platform::ScopedTensorDescriptor;
using ScopedFilterDescriptor = platform::ScopedFilterDescriptor;
using ScopedConvolutionDescriptor = platform::ScopedConvolutionDescriptor;
using DataLayout = platform::DataLayout;

46 47 48 49
static inline bool IsVoltaOrLater(const platform::CUDADeviceContext& dev_ctx) {
  return dev_ctx.GetComputeCapability() >= 70;
}

L
liym27 已提交
50 51 52 53 54
template <typename T>
class CUDNNConvOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& dev_ctx = ctx.template device_context<platform::CUDADeviceContext>();
55 56 57
    PADDLE_ENFORCE_EQ(
        platform::is_gpu_place(ctx.GetPlace()), true,
        paddle::platform::errors::PreconditionNotMet("It must use CUDAPlace."));
L
liym27 已提交
58 59 60 61 62 63 64 65
    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");
66

L
liym27 已提交
67
    bool exhaustive_search =
68 69
        FLAGS_cudnn_exhaustive_search || (ctx.HasAttr("exhaustive_search") &&
                                          ctx.Attr<bool>("exhaustive_search"));
70 71 72 73 74 75
    bool deterministic = FLAGS_cudnn_deterministic;
    auto exhaustive_deterministic = exhaustive_search && deterministic;
    PADDLE_ENFORCE_EQ(exhaustive_deterministic, false,
                      platform::errors::InvalidArgument(
                          "Cann't set exhaustive_search True and "
                          "FLAGS_cudnn_deterministic True at same time."));
L
liym27 已提交
76 77 78 79 80 81

    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" || data_format == "NDHWC");

82 83
    auto dtype = platform::CudnnDataType<T>::type;

84 85 86 87
#ifdef PADDLE_WITH_HIP
    // HIP MIOPEN ONLY SUPPORT NCHW format
    auto compute_format = DataLayout::kNCHW;
#else
88 89 90 91 92 93 94 95
    // Tensor Core introduced from Volta GPUs supports more faster conv op
    // with FP16 in NHWC data format.
    const bool compute_in_nhwc =
        dtype == CUDNN_DATA_HALF && IsVoltaOrLater(dev_ctx);
    // We will only do data format conversion from NHWC to NCHW.
    // cudnn will convert NCHW to NHWC automatically on Tensor Core.
    auto compute_format =
        compute_in_nhwc && channel_last ? DataLayout::kNHWC : DataLayout::kNCHW;
96
#endif
97 98 99 100
    VLOG(3) << "Compute ConvOp with cuDNN:"
            << " data_format=" << data_format << " compute_format="
            << (compute_format == DataLayout::kNHWC ? "NHWC" : "NCHW");

L
liym27 已提交
101 102 103
    // ------------ transformed tensor -----------
    Tensor transformed_input_channel(input->type());
    Tensor transformed_output(output->type());
104
    Tensor transformed_filter_channel(filter->type());
L
liym27 已提交
105
    T* output_data = nullptr;
106 107
    if (channel_last && compute_format == DataLayout::kNCHW) {
      VLOG(3) << "Transform input tensor from NHWC to NCHW.";
L
liym27 已提交
108 109 110 111 112 113 114 115 116
      ResizeToChannelFirst<platform::CUDADeviceContext, T>(
          ctx, input, &transformed_input_channel);
      TransToChannelFirst<platform::CUDADeviceContext, T>(
          ctx, input, &transformed_input_channel);

      ResizeToChannelFirst<platform::CUDADeviceContext, T>(ctx, output,
                                                           &transformed_output);

    } else {
117 118 119 120 121 122 123 124 125 126 127
      transformed_input_channel.ShareDataWith(*input);
      transformed_output.ShareDataWith(*output);
    }
    if (compute_format == DataLayout::kNHWC) {
      VLOG(3) << "Transform filter tensor from NCHW to NHWC.";
      ResizeToChannelLast<platform::CUDADeviceContext, T>(
          ctx, filter, &transformed_filter_channel);
      TransToChannelLast<platform::CUDADeviceContext, T>(
          ctx, filter, &transformed_filter_channel);
    } else {
      transformed_filter_channel.ShareDataWith(*filter);
L
liym27 已提交
128 129 130 131 132
    }
    output_data = transformed_output.data<T>();

    // update padding and dilation
    auto in_dims = transformed_input_channel.dims();
133
    auto filter_dims = transformed_filter_channel.dims();
L
liym27 已提交
134
    framework::DDim in_data_dims;
135 136 137
    framework::DDim filter_data_dims;

    if (compute_format == DataLayout::kNCHW) {
138 139
      in_data_dims = pten::slice_ddim(in_dims, 2, in_dims.size());
      filter_data_dims = pten::slice_ddim(filter_dims, 2, filter_dims.size());
140
    } else {
141
      in_data_dims = pten::slice_ddim(in_dims, 1, in_dims.size() - 1);
142
      filter_data_dims =
143
          pten::slice_ddim(filter_dims, 1, filter_dims.size() - 1);
144
    }
L
liym27 已提交
145

146
    std::vector<int> ksize = pten::vectorize<int>(filter_data_dims);
L
liym27 已提交
147 148 149 150
    UpdatePaddingAndDilation(&paddings, &dilations, padding_algorithm,
                             in_data_dims, strides, ksize);

    int data_dim = strides.size();  // 2d or 3d
151
    bool is_sys_pad = math::IsSymmetricPadding(paddings, data_dim);
L
liym27 已提交
152 153 154 155 156 157 158

    Tensor transformed_input;
    std::vector<int> padding_common(data_dim, 0);
    if (!is_sys_pad) {
      std::vector<int> padding_diff(data_dim);
      std::vector<int> new_input_shape_vec(data_dim + 2);
      new_input_shape_vec[0] = transformed_input_channel.dims()[0];
159 160 161 162 163 164 165

      if (compute_format == DataLayout::kNCHW) {
        new_input_shape_vec[1] = transformed_input_channel.dims()[1];
      } else {
        new_input_shape_vec[data_dim + 1] =
            transformed_input_channel.dims()[data_dim + 1];
      }
L
liym27 已提交
166 167 168 169 170 171

      std::vector<int> input_pad(transformed_input_channel.dims().size() * 2,
                                 0);
      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]);
172 173 174 175 176 177 178 179 180 181 182 183 184 185
        if (compute_format == DataLayout::kNCHW) {
          new_input_shape_vec[i + 2] =
              transformed_input_channel.dims()[i + 2] + padding_diff[i];
        } else {
          new_input_shape_vec[i + 1] =
              transformed_input_channel.dims()[i + 1] + padding_diff[i];
        }
        if (compute_format == DataLayout::kNCHW) {
          input_pad[2 * i + 4] = paddings[2 * i] - padding_common[i];
          input_pad[2 * i + 4 + 1] = paddings[2 * i + 1] - padding_common[i];
        } else {
          input_pad[2 * i + 2] = paddings[2 * i] - padding_common[i];
          input_pad[2 * i + 2 + 1] = paddings[2 * i + 1] - padding_common[i];
        }
L
liym27 已提交
186
      }
187
      framework::DDim new_input_shape(pten::make_ddim(new_input_shape_vec));
L
liym27 已提交
188 189 190 191 192 193 194 195 196 197 198
      transformed_input.Resize(new_input_shape);
      auto& dev_ctx =
          ctx.template device_context<paddle::platform::CUDADeviceContext>();

      transformed_input =
          ctx.AllocateTmpTensor<T, paddle::platform::CUDADeviceContext>(
              new_input_shape, dev_ctx);
      const int rank = transformed_input_channel.dims().size();
      T pad_value(0.0);
      switch (rank) {
        case 4: {
199
          math::PadFunction<paddle::platform::CUDADeviceContext, T, 4>(
L
liym27 已提交
200 201 202 203
              ctx, input_pad, transformed_input_channel, pad_value,
              &transformed_input);
        } break;
        case 5: {
204
          math::PadFunction<paddle::platform::CUDADeviceContext, T, 5>(
L
liym27 已提交
205 206 207 208
              ctx, input_pad, transformed_input_channel, pad_value,
              &transformed_input);
        } break;
        default:
209 210
          PADDLE_THROW(platform::errors::InvalidArgument(
              "ConvOp only support tensors with 4 or 5 dimensions."));
L
liym27 已提交
211 212 213
      }

    } else {
214
      transformed_input.ShareDataWith(transformed_input_channel);
L
liym27 已提交
215 216 217 218 219 220 221 222 223 224 225 226
      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* input_data = transformed_input.data<T>();
227
    const T* filter_data = transformed_filter_channel.data<T>();
L
liym27 已提交
228 229

    // ------------------- cudnn descriptors ---------------------
230 231 232 233 234 235 236
    ConvArgs args{&transformed_input,
                  &transformed_filter_channel,
                  &transformed_output,
                  strides,
                  padding_common,
                  dilations,
                  dtype};
L
liym27 已提交
237 238 239

    auto handle = dev_ctx.cudnn_handle();
    auto workspace_handle = dev_ctx.cudnn_workspace_handle();
240 241 242 243 244
    DataLayout layout = compute_format == DataLayout::kNHWC ? DataLayout::kNHWC
                                                            : DataLayout::kNCHW;
    if (transformed_input.dims().size() == 5) {
      layout = compute_format == DataLayout::kNHWC ? DataLayout::kNDHWC
                                                   : DataLayout::kNCDHW;
L
liym27 已提交
245 246 247 248
    }
    auto layout_format = GetCudnnTensorFormat(layout);

    args.handle = handle;
249 250

#ifdef PADDLE_WITH_HIP
251
    // MIOPEN need to set groups in cdesc in miopen_desc.h
252 253 254
    args.cdesc.set(dtype, padding_common, strides, dilations,
                   platform::AllowTF32Cudnn(), groups);
#else
A
AshburnLee 已提交
255 256
    args.cdesc.set(dtype, padding_common, strides, dilations,
                   platform::AllowTF32Cudnn());
257
#endif
L
liym27 已提交
258

259
#if defined(PADDLE_WITH_CUDA) && CUDNN_VERSION_MIN(7, 0, 1)
L
liym27 已提交
260 261 262
    // cudnn 7 can support groups, no need to do it manually
    // FIXME(typhoonzero): find a better way to disable groups
    // rather than setting it to 1.
263 264
    PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::cudnnSetConvolutionGroupCount(
        args.cdesc.desc(), groups));
L
liym27 已提交
265
    groups = 1;
266 267 268 269
#endif
#ifdef PADDLE_WITH_HIP
    // MIOPEN do not set groups in wdesc after set groups in cdesc
    groups = 1;
L
liym27 已提交
270
#endif
271 272 273
    args.idesc.set(transformed_input, layout_format);
    args.wdesc.set(transformed_filter_channel, layout_format, groups);
    args.odesc.set(transformed_output, layout_format);
L
liym27 已提交
274 275
    int i_n, i_c, i_d, i_h, i_w;
    int o_n, o_c, o_d, o_h, o_w;
276 277 278 279 280 281 282 283 284 285 286 287

    if (compute_format == DataLayout::kNHWC) {
      GetNCDHW(transformed_input.dims(), DataLayout::kNHWC, &i_n, &i_c, &i_d,
               &i_h, &i_w);
      GetNCDHW(transformed_output.dims(), DataLayout::kNHWC, &o_n, &o_c, &o_d,
               &o_h, &o_w);
    } else {
      GetNCDHW(transformed_input.dims(), DataLayout::kNCHW, &i_n, &i_c, &i_d,
               &i_h, &i_w);
      GetNCDHW(transformed_output.dims(), DataLayout::kNCHW, &o_n, &o_c, &o_d,
               &o_h, &o_w);
    }
L
liym27 已提交
288 289 290

    int group_offset_in = i_c / groups * i_h * i_w * i_d;
    int group_offset_out = o_c / groups * o_h * o_w * o_d;
291
    int group_offset_filter = transformed_filter_channel.numel() / groups;
L
liym27 已提交
292 293
    // ------------------- cudnn conv workspace ---------------------
    size_t workspace_size = 0;  // final workspace to allocate.
294 295 296 297
// ------------------- cudnn conv algorithm ---------------------
#ifdef PADDLE_WITH_HIP
    miopenConvFwdAlgorithm_t algo{};
    using search = SearchAlgorithm<miopenConvFwdAlgorithm_t>;
298
    workspace_size = search::GetWorkspaceSize(args);
299 300
    algo = search::Find<T>(args, exhaustive_search, deterministic,
                           workspace_size, ctx);
301
#else
L
liym27 已提交
302 303
    cudnnConvolutionFwdAlgo_t algo{};
    using search = SearchAlgorithm<cudnnConvolutionFwdAlgoPerf_t>;
304
    algo = search::Find<T>(args, exhaustive_search, deterministic, ctx);
L
liym27 已提交
305
    workspace_size = search::GetWorkspaceSize(args, algo);
306
#endif
L
liym27 已提交
307

308
#if defined(PADDLE_WITH_CUDA) && CUDNN_VERSION_MIN(7, 0, 1)
309 310 311 312 313 314 315 316 317
    // when groups > 1, SearchAlgorithm find algo is CUDNN_CONVOLUTION_\
    // FWD_ALGO_WINOGRAD_NONFUSED, but this kind of algorithm is unstable
    // in forward computation, so change the algorithm to CUDNN_CONVOLUTION_\
    // FWD_ALGO_IMPLICIT_GEMM manually.
    if (ctx.Attr<int>("groups") > 1) {
      algo = static_cast<cudnnConvolutionFwdAlgo_t>(0);
    }
#endif

L
liym27 已提交
318
    // ------------------- cudnn conv forward ---------------------
319
    ScalingParamType<T> alpha = 1.0f;
320 321
    ScalingParamType<T> beta = 0.0f;

322 323 324 325 326 327 328
// NOTE(zhiqiu): inplace addto is not supportted in double grad yet.
// ScalingParamType<T> beta = ctx.Attr<bool>("use_addto") ? 1.0f : 0.0f;
// VLOG(4) << "Conv: use_addto = " << ctx.Attr<bool>("use_addto");

#ifdef PADDLE_WITH_HIP
    workspace_handle.RunFunc(
        [&](void* workspace_ptr) {
329
          PADDLE_ENFORCE_GPU_SUCCESS(
330 331 332 333 334 335 336 337
              platform::dynload::miopenConvolutionForward(
                  handle, &alpha, args.idesc.desc(), input_data,
                  args.wdesc.desc(), filter_data, args.cdesc.desc(), algo,
                  &beta, args.odesc.desc(), output_data, workspace_ptr,
                  workspace_size));
        },
        workspace_size);
#else
L
liym27 已提交
338 339 340
    for (int i = 0; i < groups; i++) {
      workspace_handle.RunFunc(
          [&](void* workspace_ptr) {
341
            PADDLE_ENFORCE_GPU_SUCCESS(
342 343 344 345 346 347
                platform::dynload::cudnnConvolutionForward(
                    handle, &alpha, args.idesc.desc(),
                    input_data + i * group_offset_in, args.wdesc.desc(),
                    filter_data + i * group_offset_filter, args.cdesc.desc(),
                    algo, workspace_ptr, workspace_size, &beta,
                    args.odesc.desc(), output_data + i * group_offset_out));
L
liym27 已提交
348 349 350
          },
          workspace_size);
    }
351
#endif
L
liym27 已提交
352

353
    if (channel_last && compute_format == DataLayout::kNCHW) {
L
liym27 已提交
354 355 356 357 358 359 360 361 362 363 364
      TransToChannelLast<paddle::platform::CUDADeviceContext, T>(
          ctx, &transformed_output, output);
    }
  }
};

template <typename T>
class CUDNNConvGradOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& dev_ctx = ctx.template device_context<platform::CUDADeviceContext>();
365 366 367
    PADDLE_ENFORCE_EQ(
        platform::is_gpu_place(ctx.GetPlace()), true,
        paddle::platform::errors::PreconditionNotMet("It must use CUDAPlace."));
L
liym27 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
    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"));

    if (input_grad) {
      input_grad->mutable_data<T>(ctx.GetPlace());
    }
    if (filter_grad) {
      filter_grad->mutable_data<T>(ctx.GetPlace());
    }

    std::vector<int> dilations = ctx.Attr<std::vector<int>>("dilations");
    std::vector<int> strides = ctx.Attr<std::vector<int>>("strides");
    std::vector<int> paddings = ctx.Attr<std::vector<int>>("paddings");
    std::string padding_algorithm = ctx.Attr<std::string>("padding_algorithm");
    int groups = ctx.Attr<int>("groups");
386

L
liym27 已提交
387
    bool exhaustive_search =
388 389
        FLAGS_cudnn_exhaustive_search || (ctx.HasAttr("exhaustive_search") &&
                                          ctx.Attr<bool>("exhaustive_search"));
L
liym27 已提交
390
    bool deterministic = FLAGS_cudnn_deterministic;
391 392 393 394 395 396
    auto exhaustive_deterministic = exhaustive_search && deterministic;
    PADDLE_ENFORCE_EQ(exhaustive_deterministic, false,
                      platform::errors::InvalidArgument(
                          "Cann't set exhaustive_search True and "
                          "FLAGS_cudnn_deterministic True at same time."));

L
liym27 已提交
397 398 399
    const std::string data_format = ctx.Attr<std::string>("data_format");
    const bool channel_last = (data_format == "NHWC" || data_format == "NDHWC");

400
    auto dtype = platform::CudnnDataType<T>::type;
401 402 403 404 405

#ifdef PADDLE_WITH_HIP
    // HIP MIOPEN ONLY SUPPORT NCHW format
    auto compute_format = DataLayout::kNCHW;
#else
406 407 408 409
    const bool compute_in_nhwc =
        dtype == CUDNN_DATA_HALF && IsVoltaOrLater(dev_ctx);
    auto compute_format =
        compute_in_nhwc && channel_last ? DataLayout::kNHWC : DataLayout::kNCHW;
410
#endif
411 412 413 414
    VLOG(3) << "Compute ConvGradOp with cuDNN:"
            << " data_format=" << data_format << " compute_format="
            << (compute_format == DataLayout::kNHWC ? "NHWC" : "NCHW");

L
liym27 已提交
415 416 417 418
    // transform Tensor
    Tensor transformed_input_channel(input->type());
    Tensor transformed_output_grad_channel(output_grad->type());
    Tensor transformed_input_grad_channel(input->type());
419 420
    Tensor transformed_filter_channel(filter->type());
    Tensor transformed_filter_grad_channel(filter->type());
L
liym27 已提交
421

422 423 424
    if (channel_last && compute_format == DataLayout::kNCHW) {
      VLOG(3) << "Transform input, output_grad, input_grad and tensor from "
                 "NHWC to NCHW.";
L
liym27 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437
      ResizeToChannelFirst<platform::CUDADeviceContext, T>(
          ctx, input, &transformed_input_channel);
      TransToChannelFirst<platform::CUDADeviceContext, T>(
          ctx, input, &transformed_input_channel);

      ResizeToChannelFirst<platform::CUDADeviceContext, T>(
          ctx, output_grad, &transformed_output_grad_channel);
      TransToChannelFirst<platform::CUDADeviceContext, T>(
          ctx, output_grad, &transformed_output_grad_channel);

      if (input_grad) {
        ResizeToChannelFirst<platform::CUDADeviceContext, T>(
            ctx, input_grad, &transformed_input_grad_channel);
438 439
        // NOTE(zhiqiu): If inplace_addto strategy is enabled, we need to copy
        // the data of input_grad to transformed_input_grad_channel.
440
        if (ctx.HasAttr("use_addto") && ctx.Attr<bool>("use_addto")) {
441 442 443
          TransToChannelFirst<platform::CUDADeviceContext, T>(
              ctx, input_grad, &transformed_input_grad_channel);
        }
L
liym27 已提交
444 445
      }
    } else {
446 447
      transformed_input_channel.ShareDataWith(*input);
      transformed_output_grad_channel.ShareDataWith(*output_grad);
L
liym27 已提交
448 449 450 451 452
      if (input_grad) {
        transformed_input_grad_channel.ShareDataWith(*input_grad);
      }
    }

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    if (compute_format == DataLayout::kNHWC) {
      VLOG(3) << "Transform filter and filter_grad tensor from NCHW to NHWC.";
      ResizeToChannelLast<platform::CUDADeviceContext, T>(
          ctx, filter, &transformed_filter_channel);
      TransToChannelLast<platform::CUDADeviceContext, T>(
          ctx, filter, &transformed_filter_channel);

      if (filter_grad) {
        ResizeToChannelLast<platform::CUDADeviceContext, T>(
            ctx, filter_grad, &transformed_filter_grad_channel);
      }
    } else {
      transformed_filter_channel.ShareDataWith(*filter);
      if (filter_grad) {
        transformed_filter_grad_channel.ShareDataWith(*filter_grad);
      }
    }

L
liym27 已提交
471 472
    //  update paddings
    auto in_dims = transformed_input_channel.dims();
473
    auto filter_dims = transformed_filter_channel.dims();
L
liym27 已提交
474
    framework::DDim in_data_dims;
475 476
    framework::DDim filter_data_dims;
    if (compute_format == DataLayout::kNCHW) {
477 478
      in_data_dims = pten::slice_ddim(in_dims, 2, in_dims.size());
      filter_data_dims = pten::slice_ddim(filter_dims, 2, filter_dims.size());
479
    } else {
480
      in_data_dims = pten::slice_ddim(in_dims, 1, in_dims.size() - 1);
481
      filter_data_dims =
482
          pten::slice_ddim(filter_dims, 1, filter_dims.size() - 1);
483
    }
484
    std::vector<int> ksize = pten::vectorize<int>(filter_data_dims);
L
liym27 已提交
485 486 487 488 489 490
    UpdatePaddingAndDilation(&paddings, &dilations, padding_algorithm,
                             in_data_dims, strides, ksize);

    // cuDNN only supports padding the same amount on every dimension.
    // So we create a new padded input tensor.
    int data_dim = strides.size();  // 2d or 3d
491
    bool is_sys_pad = math::IsSymmetricPadding(paddings, data_dim);
L
liym27 已提交
492 493 494 495 496 497 498 499 500 501
    Tensor transformed_input(input->type());
    Tensor transformed_input_grad(input->type());
    std::vector<int> padding_common(data_dim, 0);
    std::vector<int> input_pad(transformed_input_channel.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);
      new_input_shape_vec[0] = transformed_input_channel.dims()[0];
502 503 504 505 506 507
      if (compute_format == DataLayout::kNCHW) {
        new_input_shape_vec[1] = transformed_input_channel.dims()[1];
      } else {
        new_input_shape_vec[data_dim + 1] =
            transformed_input_channel.dims()[data_dim + 1];
      }
L
liym27 已提交
508 509 510 511

      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]);
512 513 514 515 516 517 518 519 520 521 522 523 524 525
        if (compute_format == DataLayout::kNCHW) {
          new_input_shape_vec[i + 2] =
              transformed_input_channel.dims()[i + 2] + padding_diff[i];
        } else {
          new_input_shape_vec[i + 1] =
              transformed_input_channel.dims()[i + 1] + padding_diff[i];
        }
        if (compute_format == DataLayout::kNCHW) {
          input_pad[2 * i + 4] = paddings[2 * i] - padding_common[i];
          input_pad[2 * i + 4 + 1] = paddings[2 * i + 1] - padding_common[i];
        } else {
          input_pad[2 * i + 2] = paddings[2 * i] - padding_common[i];
          input_pad[2 * i + 2 + 1] = paddings[2 * i + 1] - padding_common[i];
        }
L
liym27 已提交
526
      }
527
      framework::DDim new_input_shape(pten::make_ddim(new_input_shape_vec));
L
liym27 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
      transformed_input.Resize(new_input_shape);

      transformed_input_grad.Resize(new_input_shape);
      auto& dev_ctx =
          ctx.template device_context<paddle::platform::CUDADeviceContext>();

      transformed_input =
          ctx.AllocateTmpTensor<T, paddle::platform::CUDADeviceContext>(
              new_input_shape, dev_ctx);
      if (input_grad) {
        transformed_input_grad =
            ctx.AllocateTmpTensor<T, paddle::platform::CUDADeviceContext>(
                new_input_shape, dev_ctx);
      }
      // pad for input
      const int rank = transformed_input_channel.dims().size();
      T pad_value(0.0);
      switch (rank) {
        case 4: {
547
          math::PadFunction<paddle::platform::CUDADeviceContext, T, 4>(
L
liym27 已提交
548 549 550 551
              ctx, input_pad, transformed_input_channel, pad_value,
              &transformed_input);
        } break;
        case 5: {
552
          math::PadFunction<paddle::platform::CUDADeviceContext, T, 5>(
L
liym27 已提交
553 554 555 556
              ctx, input_pad, transformed_input_channel, pad_value,
              &transformed_input);
        } break;
        default:
557 558
          PADDLE_THROW(platform::errors::InvalidArgument(
              "ConvOp only support tensors with 4 or 5 dimensions."));
L
liym27 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
      }
    } else {
      transformed_input.ShareDataWith(transformed_input_channel);
      if (input_grad) {
        transformed_input_grad.ShareDataWith(transformed_input_grad_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];
        }
      }
    }

    const T* input_data = transformed_input.data<T>();
    const T* output_grad_data = transformed_output_grad_channel.data<T>();
578
    const T* filter_data = transformed_filter_channel.data<T>();
L
liym27 已提交
579 580 581 582 583
    T* filter_grad_data = nullptr;
    T* input_grad_data = nullptr;
    T* transformed_input_grad_data = nullptr;

    ConvArgs args1{&transformed_input_grad,
584
                   &transformed_filter_channel,
L
liym27 已提交
585 586 587
                   &transformed_output_grad_channel,
                   strides,
                   padding_common,
588 589
                   dilations,
                   dtype};
L
liym27 已提交
590
    ConvArgs args2{&transformed_input,
591
                   &transformed_filter_grad_channel,
L
liym27 已提交
592 593 594
                   &transformed_output_grad_channel,
                   strides,
                   padding_common,
595 596
                   dilations,
                   dtype};
L
liym27 已提交
597 598

    auto handle = dev_ctx.cudnn_handle();
599 600 601 602 603
    DataLayout layout = compute_format == DataLayout::kNHWC ? DataLayout::kNHWC
                                                            : DataLayout::kNCHW;
    if (transformed_input.dims().size() == 5) {
      layout = compute_format == DataLayout::kNHWC ? DataLayout::kNDHWC
                                                   : DataLayout::kNCDHW;
L
liym27 已提交
604 605 606 607 608 609
    }
    auto layout_tensor = GetCudnnTensorFormat(layout);
    auto workspace_handle = dev_ctx.cudnn_workspace_handle();

    int i_n, i_c, i_d, i_h, i_w;
    int o_n, o_c, o_d, o_h, o_w;
610 611 612 613 614 615 616 617 618 619 620
    if (compute_format == DataLayout::kNHWC) {
      GetNCDHW(transformed_input.dims(), DataLayout::kNHWC, &i_n, &i_c, &i_d,
               &i_h, &i_w);
      GetNCDHW(transformed_output_grad_channel.dims(), DataLayout::kNHWC, &o_n,
               &o_c, &o_d, &o_h, &o_w);
    } else {
      GetNCDHW(transformed_input.dims(), DataLayout::kNCHW, &i_n, &i_c, &i_d,
               &i_h, &i_w);
      GetNCDHW(transformed_output_grad_channel.dims(), DataLayout::kNCHW, &o_n,
               &o_c, &o_d, &o_h, &o_w);
    }
L
liym27 已提交
621 622 623

    int group_offset_in = i_c / groups * i_h * i_w * i_d;
    int group_offset_out = o_c / groups * o_h * o_w * o_d;
624
    int group_offset_filter = transformed_filter_channel.numel() / groups;
625 626 627 628 629 630 631
// ------------------- cudnn backward algorithm ---------------------
#ifdef PADDLE_WITH_HIP
    miopenConvBwdDataAlgorithm_t data_algo =
        static_cast<miopenConvBwdDataAlgorithm_t>(0);
    miopenConvBwdWeightsAlgorithm_t filter_algo =
        static_cast<miopenConvBwdWeightsAlgorithm_t>(0);
#else
L
liym27 已提交
632 633 634 635
    cudnnConvolutionBwdDataAlgo_t data_algo =
        static_cast<cudnnConvolutionBwdDataAlgo_t>(0);
    cudnnConvolutionBwdFilterAlgo_t filter_algo =
        static_cast<cudnnConvolutionBwdFilterAlgo_t>(0);
636
#endif
637 638 639 640
    // input data workspace_size
    size_t workspace_size_d = 0;
    // weight workspace_size
    size_t workspace_size_w = 0;
641 642
    int iwo_groups = groups;
    int c_groups = 1;
L
liym27 已提交
643

644
#if defined(PADDLE_WITH_HIP) || CUDNN_VERSION_MIN(7, 0, 1)
L
liym27 已提交
645 646 647 648 649 650 651 652 653 654
    iwo_groups = 1;
    c_groups = groups;
    groups = 1;
#endif

    if (input_grad) {
      // ------------------- cudnn descriptors ---------------------
      input_grad_data = input_grad->data<T>();
      transformed_input_grad_data = transformed_input_grad.data<T>();
      args1.handle = handle;
655 656 657
      args1.idesc.set(transformed_input_grad, layout_tensor);
      args1.wdesc.set(transformed_filter_channel, layout_tensor, iwo_groups);
      args1.odesc.set(transformed_output_grad_channel, layout_tensor);
A
AshburnLee 已提交
658 659
      args1.cdesc.set(dtype, padding_common, strides, dilations,
                      platform::AllowTF32Cudnn(), c_groups);
L
liym27 已提交
660

661 662
#ifdef PADDLE_WITH_HIP
      using search1 = SearchAlgorithm<miopenConvBwdDataAlgorithm_t>;
663 664
      workspace_size_d =
          std::max(workspace_size_d, search1::GetWorkspaceSize(args1));
665
      data_algo = search1::Find<T>(args1, exhaustive_search, deterministic,
666
                                   workspace_size_d, ctx);
667
#else
L
liym27 已提交
668 669
      using search1 = SearchAlgorithm<cudnnConvolutionBwdDataAlgoPerf_t>;
      data_algo =
670
          search1::Find<T>(args1, exhaustive_search, deterministic, ctx);
671 672
      workspace_size_d = std::max(workspace_size_d,
                                  search1::GetWorkspaceSize(args1, data_algo));
673
#endif
L
liym27 已提交
674 675 676 677
    }

    if (filter_grad) {
      // ------------------- cudnn descriptors ---------------------
678
      filter_grad_data = transformed_filter_grad_channel.data<T>();
L
liym27 已提交
679
      args2.handle = handle;
680 681 682 683
      args2.idesc.set(transformed_input, layout_tensor);
      args2.wdesc.set(transformed_filter_grad_channel, layout_tensor,
                      iwo_groups);
      args2.odesc.set(transformed_output_grad_channel, layout_tensor);
A
AshburnLee 已提交
684 685
      args2.cdesc.set(dtype, padding_common, strides, dilations,
                      platform::AllowTF32Cudnn(), c_groups);
686 687
#ifdef PADDLE_WITH_HIP
      using search2 = SearchAlgorithm<miopenConvBwdWeightsAlgorithm_t>;
688 689
      workspace_size_w =
          std::max(workspace_size_w, search2::GetWorkspaceSize(args2));
690
      filter_algo = search2::Find<T>(args2, exhaustive_search, deterministic,
691
                                     workspace_size_w, ctx);
692
#else
L
liym27 已提交
693 694
      using search2 = SearchAlgorithm<cudnnConvolutionBwdFilterAlgoPerf_t>;
      filter_algo =
695
          search2::Find<T>(args2, exhaustive_search, deterministic, ctx);
696 697
      workspace_size_w = std::max(
          workspace_size_w, search2::GetWorkspaceSize(args2, filter_algo));
698
#endif
L
liym27 已提交
699 700 701
    }

    // ------------------- cudnn conv backward data ---------------------
702
    ScalingParamType<T> alpha = 1.0f;
R
ronnywang 已提交
703 704 705 706
#ifdef PADDLE_WITH_HIP
    // MIOPEN ONLY support beta to be 0.0f
    ScalingParamType<T> beta = 0.0f;
#else
707 708
    ScalingParamType<T> beta =
        (ctx.HasAttr("use_addto") && ctx.Attr<bool>("use_addto")) ? 1.0f : 0.0f;
R
ronnywang 已提交
709
#endif
710 711
    VLOG(4) << "Conv_grad: use_addto = "
            << (ctx.HasAttr("use_addto") && ctx.Attr<bool>("use_addto"));
712

L
liym27 已提交
713
    if (input_grad) {
714 715
// When beta is 0, it is unnecessary to reset input_grad.
// When beta is 1, the output cannot be reset since addt strategy used.
716
#ifdef PADDLE_WITH_HIP
717
      if (ctx.HasAttr("use_addto") && ctx.Attr<bool>("use_addto")) {
R
ronnywang 已提交
718 719 720 721 722
        Tensor temp_tensor(transformed_input_grad.type());
        temp_tensor.Resize(transformed_input_grad.dims());
        T* temp_tensor_data = temp_tensor.mutable_data<T>(ctx.GetPlace());
        workspace_handle.RunFunc(
            [&](void* cudnn_workspace_ptr) {
723
              PADDLE_ENFORCE_GPU_SUCCESS(
R
ronnywang 已提交
724 725 726 727
                  platform::dynload::miopenConvolutionBackwardData(
                      handle, &alpha, args1.odesc.desc(), output_grad_data,
                      args1.wdesc.desc(), filter_data, args1.cdesc.desc(),
                      data_algo, &beta, args1.idesc.desc(), temp_tensor_data,
728
                      cudnn_workspace_ptr, workspace_size_d));
R
ronnywang 已提交
729
            },
730
            workspace_size_d);
731
        PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::miopenOpTensor(
R
ronnywang 已提交
732 733 734 735 736 737 738
            handle, miopenTensorOpAdd, &alpha, args1.idesc.desc(),
            transformed_input_grad_data, &alpha, args1.idesc.desc(),
            temp_tensor_data, &beta, args1.idesc.desc(),
            transformed_input_grad_data));
      } else {
        workspace_handle.RunFunc(
            [&](void* cudnn_workspace_ptr) {
739
              PADDLE_ENFORCE_GPU_SUCCESS(
R
ronnywang 已提交
740 741 742 743 744
                  platform::dynload::miopenConvolutionBackwardData(
                      handle, &alpha, args1.odesc.desc(), output_grad_data,
                      args1.wdesc.desc(), filter_data, args1.cdesc.desc(),
                      data_algo, &beta, args1.idesc.desc(),
                      transformed_input_grad_data, cudnn_workspace_ptr,
745
                      workspace_size_d));
R
ronnywang 已提交
746
            },
747
            workspace_size_d);
R
ronnywang 已提交
748 749
      }

750
#else
751
      for (int i = 0; i < groups; i++) {
L
liym27 已提交
752 753
        workspace_handle.RunFunc(
            [&](void* cudnn_workspace_ptr) {
754
              PADDLE_ENFORCE_GPU_SUCCESS(
755 756 757 758 759
                  platform::dynload::cudnnConvolutionBackwardData(
                      handle, &alpha, args1.wdesc.desc(),
                      filter_data + i * group_offset_filter, args1.odesc.desc(),
                      output_grad_data + i * group_offset_out,
                      args1.cdesc.desc(), data_algo, cudnn_workspace_ptr,
760
                      workspace_size_d, &beta, args1.idesc.desc(),
761
                      transformed_input_grad_data + i * group_offset_in));
L
liym27 已提交
762
            },
763
            workspace_size_d);
L
liym27 已提交
764
      }
765
#endif
W
wangchaochaohu 已提交
766 767 768
      if (!is_sys_pad) {
        std::vector<int> starts(transformed_input_channel.dims().size(), 0);
        std::vector<int> axes(transformed_input_channel.dims().size(), 0);
L
liym27 已提交
769

W
wangchaochaohu 已提交
770 771 772 773
        for (size_t i = 0; i < transformed_input_channel.dims().size(); ++i) {
          starts[i] = input_pad[2 * i];
          axes[i] = i;
        }
L
liym27 已提交
774

W
wangchaochaohu 已提交
775 776
        transformed_input_grad_channel.mutable_data(ctx.GetPlace());
        if (transformed_input_channel.dims().size() == 4) {
777
          RemovePaddingSlice<paddle::platform::CUDADeviceContext, T, 4>(
W
wangchaochaohu 已提交
778 779 780
              ctx, &transformed_input_grad, &transformed_input_grad_channel,
              starts, axes);
        } else {
781
          RemovePaddingSlice<paddle::platform::CUDADeviceContext, T, 5>(
W
wangchaochaohu 已提交
782 783 784
              ctx, &transformed_input_grad, &transformed_input_grad_channel,
              starts, axes);
        }
L
liym27 已提交
785 786
      }

787
      if (channel_last && compute_format == DataLayout::kNCHW) {
L
liym27 已提交
788 789 790 791
        TransToChannelLast<paddle::platform::CUDADeviceContext, T>(
            ctx, &transformed_input_grad_channel, input_grad);
      }
    }
792 793 794

    // filter_grad do not use inplace addto.
    ScalingParamType<T> beta_filter = 0.0f;
L
liym27 已提交
795 796
    // ------------------- cudnn conv backward filter ---------------------
    if (filter_grad) {
797
// Because beta is zero, it is unnecessary to reset filter_grad.
798
#ifdef PADDLE_WITH_HIP
799 800
      workspace_handle.RunFunc(
          [&](void* cudnn_workspace_ptr) {
801
            PADDLE_ENFORCE_GPU_SUCCESS(
802 803 804 805
                platform::dynload::miopenConvolutionBackwardWeights(
                    handle, &alpha, args2.odesc.desc(), output_grad_data,
                    args2.idesc.desc(), input_data, args2.cdesc.desc(),
                    filter_algo, &beta, args2.wdesc.desc(), filter_grad_data,
806
                    cudnn_workspace_ptr, workspace_size_w));
807
          },
808
          workspace_size_w);
809
#else
810
      for (int i = 0; i < groups; i++) {
L
liym27 已提交
811 812
        workspace_handle.RunFunc(
            [&](void* cudnn_workspace_ptr) {
813
              PADDLE_ENFORCE_GPU_SUCCESS(
814 815 816 817 818
                  platform::dynload::cudnnConvolutionBackwardFilter(
                      handle, &alpha, args2.idesc.desc(),
                      input_data + i * group_offset_in, args2.odesc.desc(),
                      output_grad_data + i * group_offset_out,
                      args2.cdesc.desc(), filter_algo, cudnn_workspace_ptr,
819
                      workspace_size_w, &beta_filter, args2.wdesc.desc(),
820
                      filter_grad_data + i * group_offset_filter));
L
liym27 已提交
821
            },
822
            workspace_size_w);
L
liym27 已提交
823
      }
824
#endif
825 826 827 828 829

      if (compute_format == DataLayout::kNHWC) {
        TransToChannelFirst<paddle::platform::CUDADeviceContext, T>(
            ctx, &transformed_filter_grad_channel, filter_grad);
      }
L
liym27 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
    }
  }
};

/*
 * Inputs:  I, W, dO, ddI, ddW
 * Outputs: ddO, dW, dI
 * ddo = conv(ddI, W) + conv(I, ddW)
 * dW = conv_bp_filter(ddI, dO)
 * dI = conv_bp_data(ddW, dO)
 */
template <typename T>
class CUDNNConvDoubleGradOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& dev_ctx = ctx.template device_context<platform::CUDADeviceContext>();
846 847 848
    PADDLE_ENFORCE_EQ(
        platform::is_gpu_place(ctx.GetPlace()), true,
        paddle::platform::errors::PreconditionNotMet("It must use CUDAPlace."));
L
liym27 已提交
849 850 851 852 853 854 855 856 857 858 859
    auto X = ctx.Input<Tensor>("Input");
    auto W = ctx.Input<Tensor>("Filter");
    auto dO = ctx.Input<Tensor>("DOutput");
    auto ddX = ctx.Input<Tensor>("DDInput");
    auto ddW = ctx.Input<Tensor>("DDFilter");

    auto ddO = ctx.Output<Tensor>("DDOutput");
    auto dW = ctx.Output<Tensor>("DFilter");
    auto dX = ctx.Output<Tensor>("DInput");
    if (ddO) {
      ddO->mutable_data<T>(ctx.GetPlace());
860
      pten::funcs::SetConstant<platform::CUDADeviceContext, T> set_zero;
L
lvmengsi 已提交
861
      set_zero(dev_ctx, ddO, static_cast<T>(0));
L
liym27 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
    }
    if (dW) {
      dW->mutable_data<T>(ctx.GetPlace());
    }
    if (dX) {
      dX->mutable_data<T>(ctx.GetPlace());
    }

    // const T* x = X->data<T>();
    const T* dy = dO->data<T>();
    const T* w = W->data<T>();

    const T* ddx = nullptr;
    const T* ddw = nullptr;
    T *dw, *dx, *ddy;
    dw = dx = ddy = nullptr;
    T* transformed_dx = nullptr;
    const std::vector<int>& strides = ctx.Attr<std::vector<int>>("strides");
    std::vector<int> dilations = ctx.Attr<std::vector<int>>("dilations");
    int groups = ctx.Attr<int>("groups");
882

L
liym27 已提交
883
    bool exhaustive_search =
884 885
        FLAGS_cudnn_exhaustive_search || (ctx.HasAttr("exhaustive_search") &&
                                          ctx.Attr<bool>("exhaustive_search"));
L
liym27 已提交
886
    bool deterministic = FLAGS_cudnn_deterministic;
887 888 889 890 891 892
    auto exhaustive_deterministic = exhaustive_search && deterministic;
    PADDLE_ENFORCE_EQ(exhaustive_deterministic, false,
                      platform::errors::InvalidArgument(
                          "Cann't set exhaustive_search True and "
                          "FLAGS_cudnn_deterministic True at same time."));

L
liym27 已提交
893 894 895 896 897 898 899 900 901
    std::vector<int> paddings = ctx.Attr<std::vector<int>>("paddings");

    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" || data_format == "NDHWC");

    // transform Tensors to channel first-----------
    Tensor transformed_X_channel(X->type());
    Tensor transformed_dO_channel(dO->type());
L
lvmengsi 已提交
902
    Tensor transformed_ddX_channel(X->type());
L
liym27 已提交
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917

    Tensor transformed_ddO_channel(dO->type());
    Tensor transformed_dX_channel(X->type());

    if (channel_last) {
      ResizeToChannelFirst<platform::CUDADeviceContext, T>(
          ctx, X, &transformed_X_channel);
      TransToChannelFirst<platform::CUDADeviceContext, T>(
          ctx, X, &transformed_X_channel);

      ResizeToChannelFirst<platform::CUDADeviceContext, T>(
          ctx, dO, &transformed_dO_channel);
      TransToChannelFirst<platform::CUDADeviceContext, T>(
          ctx, dO, &transformed_dO_channel);

L
lvmengsi 已提交
918 919 920 921 922 923
      if (ddX) {
        ResizeToChannelFirst<platform::CUDADeviceContext, T>(
            ctx, ddX, &transformed_ddX_channel);
        TransToChannelFirst<platform::CUDADeviceContext, T>(
            ctx, ddX, &transformed_ddX_channel);
      }
L
liym27 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937

      if (ddO) {
        ResizeToChannelFirst<platform::CUDADeviceContext, T>(
            ctx, ddO, &transformed_ddO_channel);
      }
      if (dX) {
        ResizeToChannelFirst<platform::CUDADeviceContext, T>(
            ctx, dX, &transformed_dX_channel);
        transformed_dX_channel.mutable_data<T>(ctx.GetPlace());
      }

    } else {
      transformed_X_channel = *X;
      transformed_dO_channel = *dO;
L
lvmengsi 已提交
938 939 940
      if (ddX) {
        transformed_ddX_channel = *ddX;
      }
L
liym27 已提交
941 942 943 944 945 946 947 948 949 950
      if (ddO) {
        transformed_ddO_channel.ShareDataWith(*ddO);
      }
      if (dX) {
        transformed_dX_channel.ShareDataWith(*dX);
      }
    }

    auto in_dims = transformed_X_channel.dims();
    auto filter_dims = W->dims();
951
    framework::DDim in_data_dims = pten::slice_ddim(in_dims, 2, in_dims.size());
L
liym27 已提交
952
    framework::DDim filter_data_dims =
953 954
        pten::slice_ddim(filter_dims, 2, filter_dims.size());
    std::vector<int> ksize = pten::vectorize<int>(filter_data_dims);
L
liym27 已提交
955 956 957 958
    UpdatePaddingAndDilation(&paddings, &dilations, padding_algorithm,
                             in_data_dims, strides, ksize);

    int data_dim = strides.size();  // 2d or 3d
959
    bool is_sys_pad = math::IsSymmetricPadding(paddings, data_dim);
L
liym27 已提交
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
    Tensor transformed_X(X->type());
    Tensor transformed_ddX(X->type());

    Tensor transformed_dX(X->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);
      new_input_shape_vec[0] = transformed_X_channel.dims()[0];
      new_input_shape_vec[1] = transformed_X_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];
        input_pad[2 * i + 4] = paddings[2 * i] - padding_common[i];
        input_pad[2 * i + 4 + 1] = paddings[2 * i + 1] - padding_common[i];
      }
983
      framework::DDim new_input_shape(pten::make_ddim(new_input_shape_vec));
L
liym27 已提交
984 985 986 987 988 989 990
      transformed_X.Resize(new_input_shape);
      transformed_ddX.Resize(new_input_shape);
      transformed_dX.Resize(new_input_shape);

      transformed_X =
          ctx.AllocateTmpTensor<T, paddle::platform::CUDADeviceContext>(
              new_input_shape, dev_ctx);
L
lvmengsi 已提交
991 992 993 994 995
      if (ddX) {
        transformed_ddX =
            ctx.AllocateTmpTensor<T, paddle::platform::CUDADeviceContext>(
                new_input_shape, dev_ctx);
      }
L
liym27 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005 1006
      if (dX) {
        transformed_dX =
            ctx.AllocateTmpTensor<T, paddle::platform::CUDADeviceContext>(
                new_input_shape, dev_ctx);
      }

      // pad for input
      const int rank = X->dims().size();
      T pad_value(0.0);
      switch (rank) {
        case 4: {
1007
          math::PadFunction<paddle::platform::CUDADeviceContext, T, 4>(
L
liym27 已提交
1008
              ctx, input_pad, transformed_X_channel, pad_value, &transformed_X);
L
lvmengsi 已提交
1009 1010 1011 1012 1013
          if (ddX) {
            math::PadFunction<paddle::platform::CUDADeviceContext, T, 4>(
                ctx, input_pad, transformed_ddX_channel, pad_value,
                &transformed_ddX);
          }
L
liym27 已提交
1014 1015
        } break;
        case 5: {
1016
          math::PadFunction<paddle::platform::CUDADeviceContext, T, 5>(
L
liym27 已提交
1017
              ctx, input_pad, transformed_X_channel, pad_value, &transformed_X);
L
lvmengsi 已提交
1018 1019 1020 1021 1022
          if (ddX) {
            math::PadFunction<paddle::platform::CUDADeviceContext, T, 5>(
                ctx, input_pad, transformed_ddX_channel, pad_value,
                &transformed_ddX);
          }
L
liym27 已提交
1023 1024
        } break;
        default:
1025 1026
          PADDLE_THROW(platform::errors::InvalidArgument(
              "ConvOp only support tensors with 4 or 5 dimensions."));
L
liym27 已提交
1027 1028 1029 1030
      }

    } else {
      transformed_X.ShareDataWith(transformed_X_channel);
L
lvmengsi 已提交
1031 1032 1033
      if (ddX) {
        transformed_ddX.ShareDataWith(transformed_ddX_channel);
      }
L
liym27 已提交
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
      if (dX) {
        transformed_dX.ShareDataWith(transformed_dX_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];
        }
      }
    }

    const T* x = transformed_X.data<T>();

    int iwo_group = groups;
    int c_group = 1;
1053
#if defined(PADDLE_WITH_HIP) || CUDNN_VERSION_MIN(7, 0, 1)
L
liym27 已提交
1054 1055
    iwo_group = 1;
    c_group = groups;
1056
    groups = 1;
L
liym27 已提交
1057 1058 1059 1060 1061
#endif
    auto dtype = platform::CudnnDataType<T>::type;

    auto handle = dev_ctx.cudnn_handle();

1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
    ConvArgs args1{&transformed_ddX,
                   W,
                   &transformed_ddO_channel,
                   strides,
                   padding_common,
                   dilations,
                   dtype};
    ConvArgs args2{
        &transformed_X, ddW,  &transformed_ddO_channel, strides, padding_common,
        dilations,      dtype};
    ConvArgs args3{&transformed_ddX,
                   dW,
                   &transformed_dO_channel,
                   strides,
                   padding_common,
                   dilations,
                   dtype};
    ConvArgs args4{
        &transformed_dX, ddW,  &transformed_dO_channel, strides, padding_common,
        dilations,       dtype};
L
liym27 已提交
1082

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
#ifdef PADDLE_WITH_HIP
    miopenConvFwdAlgorithm_t fwd_algo1 =
        static_cast<miopenConvFwdAlgorithm_t>(0);
    miopenConvFwdAlgorithm_t fwd_algo2 =
        static_cast<miopenConvFwdAlgorithm_t>(0);
    miopenConvBwdDataAlgorithm_t data_algo =
        static_cast<miopenConvBwdDataAlgorithm_t>(0);
    miopenConvBwdWeightsAlgorithm_t filter_algo =
        static_cast<miopenConvBwdWeightsAlgorithm_t>(0);
#else
L
liym27 已提交
1093 1094 1095 1096 1097 1098 1099 1100
    cudnnConvolutionFwdAlgo_t fwd_algo1 =
        static_cast<cudnnConvolutionFwdAlgo_t>(0);
    cudnnConvolutionFwdAlgo_t fwd_algo2 =
        static_cast<cudnnConvolutionFwdAlgo_t>(0);
    cudnnConvolutionBwdDataAlgo_t data_algo =
        static_cast<cudnnConvolutionBwdDataAlgo_t>(0);
    cudnnConvolutionBwdFilterAlgo_t filter_algo =
        static_cast<cudnnConvolutionBwdFilterAlgo_t>(0);
1101
#endif
L
liym27 已提交
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116

    auto layout = GetCudnnTensorFormat(DataLayout::kNCHW);

    // ddo = conv(ddI, W) + conv(I, ddW)
    size_t workspace_size = 0;

    T* transformed_ddy_channel = nullptr;
    if (ddO) {
      ddy = ddO->data<T>();
      transformed_ddy_channel = transformed_ddO_channel.data<T>();
      if (ddX) {
        args1.handle = handle;
        args1.idesc.set(transformed_ddX, iwo_group);
        args1.wdesc.set(*W, layout, iwo_group);
        args1.odesc.set(transformed_ddO_channel, iwo_group);
A
AshburnLee 已提交
1117 1118
        args1.cdesc.set(dtype, padding_common, strides, dilations,
                        platform::AllowTF32Cudnn(), c_group);
L
liym27 已提交
1119

1120 1121
#ifdef PADDLE_WITH_HIP
        using search1 = SearchAlgorithm<miopenConvFwdAlgorithm_t>;
1122 1123 1124
        workspace_size = search1::GetWorkspaceSize(args1);
        fwd_algo1 = search1::Find<T>(args1, exhaustive_search, false,
                                     workspace_size, ctx);
1125
#else
L
liym27 已提交
1126
        using search1 = SearchAlgorithm<cudnnConvolutionFwdAlgoPerf_t>;
1127
        fwd_algo1 = search1::Find<T>(args1, exhaustive_search, false, ctx);
L
liym27 已提交
1128
        workspace_size = search1::GetWorkspaceSize(args1, fwd_algo1);
1129
#endif
L
liym27 已提交
1130 1131 1132 1133 1134 1135 1136 1137
      }

      if (ddW) {
        ddw = ddW->data<T>();
        args2.handle = handle;
        args2.idesc.set(transformed_X, iwo_group);
        args2.wdesc.set(*ddW, layout, iwo_group);
        args2.odesc.set(transformed_ddO_channel, iwo_group);
A
AshburnLee 已提交
1138 1139
        args2.cdesc.set(dtype, padding_common, strides, dilations,
                        platform::AllowTF32Cudnn(), c_group);
L
liym27 已提交
1140

1141 1142
#ifdef PADDLE_WITH_HIP
        using search2 = SearchAlgorithm<miopenConvFwdAlgorithm_t>;
1143 1144 1145 1146
        workspace_size =
            std::max(workspace_size, search2::GetWorkspaceSize(args2));
        fwd_algo2 = search2::Find<T>(args2, exhaustive_search, false,
                                     workspace_size, ctx);
1147
#else
L
liym27 已提交
1148
        using search2 = SearchAlgorithm<cudnnConvolutionFwdAlgoPerf_t>;
1149
        fwd_algo2 = search2::Find<T>(args2, exhaustive_search, false, ctx);
L
liym27 已提交
1150 1151
        workspace_size = std::max(workspace_size,
                                  search2::GetWorkspaceSize(args2, fwd_algo2));
1152
#endif
L
liym27 已提交
1153 1154 1155 1156 1157 1158 1159 1160 1161
      }
    }

    if (dW && ddX) {
      dw = dW->data<T>();
      args3.handle = handle;
      args3.idesc.set(transformed_ddX, iwo_group);
      args3.wdesc.set(*dW, layout, iwo_group);
      args3.odesc.set(transformed_dO_channel, iwo_group);
A
AshburnLee 已提交
1162 1163
      args3.cdesc.set(dtype, padding_common, strides, dilations,
                      platform::AllowTF32Cudnn(), c_group);
L
liym27 已提交
1164

1165 1166
#ifdef PADDLE_WITH_HIP
      using search3 = SearchAlgorithm<miopenConvBwdWeightsAlgorithm_t>;
1167 1168 1169 1170
      workspace_size =
          std::max(workspace_size, search3::GetWorkspaceSize(args3));
      filter_algo = search3::Find<T>(args3, exhaustive_search, deterministic,
                                     workspace_size, ctx);
1171
#else
L
liym27 已提交
1172 1173
      using search3 = SearchAlgorithm<cudnnConvolutionBwdFilterAlgoPerf_t>;
      filter_algo =
1174
          search3::Find<T>(args3, exhaustive_search, deterministic, ctx);
L
liym27 已提交
1175 1176
      workspace_size = std::max(workspace_size,
                                search3::GetWorkspaceSize(args3, filter_algo));
1177
#endif
L
liym27 已提交
1178 1179 1180 1181 1182 1183 1184 1185 1186
    }

    if (ddW && dX) {
      transformed_dx = transformed_dX.data<T>();

      args4.handle = handle;
      args4.idesc.set(transformed_dX, iwo_group);
      args4.wdesc.set(*ddW, layout, iwo_group);
      args4.odesc.set(transformed_dO_channel, iwo_group);
A
AshburnLee 已提交
1187 1188
      args4.cdesc.set(dtype, padding_common, strides, dilations,
                      platform::AllowTF32Cudnn(), c_group);
L
liym27 已提交
1189

1190 1191
#ifdef PADDLE_WITH_HIP
      using search4 = SearchAlgorithm<miopenConvBwdDataAlgorithm_t>;
1192 1193 1194 1195
      workspace_size =
          std::max(workspace_size, search4::GetWorkspaceSize(args4));
      data_algo = search4::Find<T>(args4, exhaustive_search, deterministic,
                                   workspace_size, ctx);
1196
#else
L
liym27 已提交
1197 1198
      using search4 = SearchAlgorithm<cudnnConvolutionBwdDataAlgoPerf_t>;
      data_algo =
1199
          search4::Find<T>(args4, exhaustive_search, deterministic, ctx);
L
liym27 已提交
1200 1201
      workspace_size =
          std::max(workspace_size, search4::GetWorkspaceSize(args4, data_algo));
1202
#endif
L
liym27 已提交
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
    }

    int i_n, i_c, i_d, i_h, i_w;
    GetNCDHW(transformed_X.dims(), DataLayout::kNCHW, &i_n, &i_c, &i_d, &i_h,
             &i_w);

    int o_n, o_c, o_d, o_h, o_w;
    GetNCDHW(transformed_dO_channel.dims(), DataLayout::kNCHW, &o_n, &o_c, &o_d,
             &o_h, &o_w);

    int group_offset_in = i_c / groups * i_h * i_w * i_d;
    int group_offset_out = o_c / groups * o_h * o_w * o_d;
    int group_offset_filter = W->numel() / groups;

1217 1218 1219 1220 1221 1222 1223
    ScalingParamType<T> alpha = 1.0f;
    ScalingParamType<T> beta = 0.0f;

    // NOTE(zhiqiu): inplace addto is not supportted in double grad yet.
    // ScalingParamType<T> beta = ctx.Attr<bool>("use_addto") ? 1.0f :
    // 0.0f;
    // VLOG(4) << "Conv_grad_grad: use_addto = " << ctx.Attr<bool>("use_addto");
L
liym27 已提交
1224 1225 1226 1227 1228
    auto wkspace_handle = dev_ctx.cudnn_workspace_handle();

    if (ddO) {
      if (ddX) {
        ddx = transformed_ddX.data<T>();
1229
#ifdef PADDLE_WITH_HIP
1230 1231
        wkspace_handle.RunFunc(
            [&](void* workspace_ptr) {
1232
              PADDLE_ENFORCE_GPU_SUCCESS(
1233 1234 1235 1236 1237 1238 1239
                  platform::dynload::miopenConvolutionForward(
                      handle, &alpha, args1.idesc.desc(), ddx,
                      args1.wdesc.desc(), w, args1.cdesc.desc(), fwd_algo1,
                      &beta, args1.odesc.desc(), transformed_ddy_channel,
                      workspace_ptr, workspace_size));
            },
            workspace_size);
1240
#else
1241
        for (int i = 0; i < groups; i++) {
L
liym27 已提交
1242 1243
          wkspace_handle.RunFunc(
              [&](void* workspace_ptr) {
1244
                PADDLE_ENFORCE_GPU_SUCCESS(
1245 1246 1247 1248 1249 1250 1251
                    platform::dynload::cudnnConvolutionForward(
                        handle, &alpha, args1.idesc.desc(),
                        ddx + i * group_offset_in, args1.wdesc.desc(),
                        w + i * group_offset_filter, args1.cdesc.desc(),
                        fwd_algo1, workspace_ptr, workspace_size, &beta,
                        args1.odesc.desc(),
                        transformed_ddy_channel + i * group_offset_out));
L
liym27 已提交
1252 1253 1254
              },
              workspace_size);
        }
1255
#endif
L
liym27 已提交
1256 1257
      }
      if (ddW) {
1258
#ifdef PADDLE_WITH_HIP
1259 1260 1261
        // MIOPEN ONLY support beta to be 0.0f
        wkspace_handle.RunFunc(
            [&](void* workspace_ptr) {
1262
              PADDLE_ENFORCE_GPU_SUCCESS(
1263 1264 1265 1266 1267 1268 1269
                  platform::dynload::miopenConvolutionForward(
                      handle, &alpha, args2.idesc.desc(), x, args2.wdesc.desc(),
                      ddw, args2.cdesc.desc(), fwd_algo2, &beta,
                      args2.odesc.desc(), transformed_ddy_channel,
                      workspace_ptr, workspace_size));
            },
            workspace_size);
1270
#else
1271
        for (int i = 0; i < groups; i++) {
L
liym27 已提交
1272 1273
          wkspace_handle.RunFunc(
              [&](void* workspace_ptr) {
1274
                PADDLE_ENFORCE_GPU_SUCCESS(
1275 1276 1277 1278 1279 1280 1281
                    platform::dynload::cudnnConvolutionForward(
                        handle, &alpha, args2.idesc.desc(),
                        x + i * group_offset_in, args2.wdesc.desc(),
                        ddw + i * group_offset_filter, args2.cdesc.desc(),
                        fwd_algo2, workspace_ptr, workspace_size, &alpha,
                        args2.odesc.desc(),
                        transformed_ddy_channel + i * group_offset_out));
L
liym27 已提交
1282 1283 1284
              },
              workspace_size);
        }
1285
#endif
L
liym27 已提交
1286 1287 1288 1289 1290 1291
      }
      if (channel_last) {
        TransToChannelLast<paddle::platform::CUDADeviceContext, T>(
            ctx, &transformed_ddO_channel, ddO);
      }
    }
L
lvmengsi 已提交
1292
    T* transformed_dy_channel = transformed_dO_channel.data<T>();
L
liym27 已提交
1293 1294
    if (dW && ddX) {
      ddx = transformed_ddX.data<T>();
1295
#ifdef PADDLE_WITH_HIP
1296 1297
      wkspace_handle.RunFunc(
          [&](void* workspace_ptr) {
1298
            PADDLE_ENFORCE_GPU_SUCCESS(
1299 1300 1301 1302 1303 1304 1305
                platform::dynload::miopenConvolutionBackwardWeights(
                    handle, &alpha, args3.odesc.desc(), transformed_dy_channel,
                    args3.idesc.desc(), ddx, args3.cdesc.desc(), filter_algo,
                    &beta, args3.wdesc.desc(), dw, workspace_ptr,
                    workspace_size));
          },
          workspace_size);
1306
#else
1307
      for (int i = 0; i < groups; i++) {
L
liym27 已提交
1308 1309
        wkspace_handle.RunFunc(
            [&](void* workspace_ptr) {
1310
              PADDLE_ENFORCE_GPU_SUCCESS(
1311 1312 1313 1314 1315 1316 1317
                  platform::dynload::cudnnConvolutionBackwardFilter(
                      handle, &alpha, args3.idesc.desc(),
                      ddx + i * group_offset_in, args3.odesc.desc(),
                      transformed_dy_channel + i * group_offset_out,
                      args3.cdesc.desc(), filter_algo, workspace_ptr,
                      workspace_size, &beta, args3.wdesc.desc(),
                      dw + i * group_offset_filter));
L
liym27 已提交
1318 1319 1320
            },
            workspace_size);
      }
1321
#endif
L
liym27 已提交
1322 1323 1324 1325
    }

    if (dX && ddW) {
      ddw = ddW->data<T>();
1326
#ifdef PADDLE_WITH_HIP
1327 1328
      wkspace_handle.RunFunc(
          [&](void* workspace_ptr) {
1329
            PADDLE_ENFORCE_GPU_SUCCESS(
1330 1331 1332 1333 1334 1335 1336
                platform::dynload::miopenConvolutionBackwardData(
                    handle, &alpha, args4.odesc.desc(), transformed_dy_channel,
                    args4.wdesc.desc(), ddw, args4.cdesc.desc(), data_algo,
                    &beta, args4.idesc.desc(), transformed_dx, workspace_ptr,
                    workspace_size));
          },
          workspace_size);
1337
#else
1338
      for (int i = 0; i < groups; i++) {
L
liym27 已提交
1339 1340
        wkspace_handle.RunFunc(
            [&](void* workspace_ptr) {
1341
              PADDLE_ENFORCE_GPU_SUCCESS(
1342 1343 1344 1345 1346 1347 1348
                  platform::dynload::cudnnConvolutionBackwardData(
                      handle, &alpha, args4.wdesc.desc(),
                      ddw + i * group_offset_filter, args4.odesc.desc(),
                      transformed_dy_channel + i * group_offset_out,
                      args4.cdesc.desc(), data_algo, workspace_ptr,
                      workspace_size, &beta, args4.idesc.desc(),
                      transformed_dx + i * group_offset_in));
L
liym27 已提交
1349 1350 1351
            },
            workspace_size);
      }
1352
#endif
L
liym27 已提交
1353

W
wangchaochaohu 已提交
1354 1355 1356 1357
      if (!is_sys_pad) {
        // reverse padded input
        std::vector<int> starts(X->dims().size(), 0);
        std::vector<int> axes(X->dims().size(), 0);
L
liym27 已提交
1358

W
wangchaochaohu 已提交
1359 1360 1361 1362 1363
        for (size_t i = 0; i < X->dims().size(); ++i) {
          starts[i] = input_pad[2 * i];
          axes[i] = i;
        }
        if (X->dims().size() == 4) {
1364
          RemovePaddingSlice<paddle::platform::CUDADeviceContext, T, 4>(
W
wangchaochaohu 已提交
1365 1366
              ctx, &transformed_dX, &transformed_dX_channel, starts, axes);
        } else {
1367
          RemovePaddingSlice<paddle::platform::CUDADeviceContext, T, 5>(
W
wangchaochaohu 已提交
1368 1369
              ctx, &transformed_dX, &transformed_dX_channel, starts, axes);
        }
L
liym27 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
      }
      if (channel_last) {
        TransToChannelLast<paddle::platform::CUDADeviceContext, T>(
            ctx, &transformed_dX_channel, dX);
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace plat = paddle::platform;
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
#ifdef PADDLE_WITH_HIP
// MIOPEN do not support double
REGISTER_OP_KERNEL(conv2d, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvOpKernel<float>,
                   paddle::operators::CUDNNConvOpKernel<plat::float16>);
REGISTER_OP_KERNEL(conv2d_grad, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvGradOpKernel<float>,
                   paddle::operators::CUDNNConvGradOpKernel<plat::float16>);
REGISTER_OP_KERNEL(
    conv2d_grad_grad, CUDNN, plat::CUDAPlace,
    paddle::operators::CUDNNConvDoubleGradOpKernel<float>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<plat::float16>);
1395 1396 1397 1398 1399 1400 1401 1402
// ROCM has limit thread in depthwise_conv.cu and willl result in accuracy issue
// Use depthwise_conv2d in MIOPEN to resolve this issue
REGISTER_OP_KERNEL(depthwise_conv2d, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvOpKernel<float>,
                   paddle::operators::CUDNNConvOpKernel<plat::float16>);
REGISTER_OP_KERNEL(depthwise_conv2d_grad, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvGradOpKernel<float>,
                   paddle::operators::CUDNNConvGradOpKernel<plat::float16>);
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
REGISTER_OP_CUDA_KERNEL(
    depthwise_conv2d_grad_grad,
    paddle::operators::CUDNNConvDoubleGradOpKernel<float>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<plat::float16>);

REGISTER_OP_KERNEL(conv3d, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvOpKernel<float>,
                   paddle::operators::CUDNNConvOpKernel<plat::float16>);
REGISTER_OP_KERNEL(conv3d_grad, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvGradOpKernel<float>);
REGISTER_OP_KERNEL(
    conv3d_grad_grad, CUDNN, plat::CUDAPlace,
    paddle::operators::CUDNNConvDoubleGradOpKernel<float>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<plat::float16>);
#else
W
wuhuanzhou 已提交
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
#if CUDNN_VERSION_MIN(8, 1, 0)
REGISTER_OP_KERNEL(conv2d, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvOpKernel<float>,
                   paddle::operators::CUDNNConvOpKernel<double>,
                   paddle::operators::CUDNNConvOpKernel<plat::float16>,
                   paddle::operators::CUDNNConvOpKernel<plat::bfloat16>);
REGISTER_OP_KERNEL(conv2d_grad, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvGradOpKernel<float>,
                   paddle::operators::CUDNNConvGradOpKernel<double>,
                   paddle::operators::CUDNNConvGradOpKernel<plat::float16>,
                   paddle::operators::CUDNNConvGradOpKernel<plat::bfloat16>);
REGISTER_OP_KERNEL(
    conv2d_grad_grad, CUDNN, plat::CUDAPlace,
    paddle::operators::CUDNNConvDoubleGradOpKernel<float>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<double>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<plat::float16>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<plat::bfloat16>);

REGISTER_OP_CUDA_KERNEL(
    depthwise_conv2d_grad_grad,
    paddle::operators::CUDNNConvDoubleGradOpKernel<float>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<double>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<plat::float16>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<plat::bfloat16>);
#else
L
liym27 已提交
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
REGISTER_OP_KERNEL(conv2d, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvOpKernel<float>,
                   paddle::operators::CUDNNConvOpKernel<double>,
                   paddle::operators::CUDNNConvOpKernel<plat::float16>);
REGISTER_OP_KERNEL(conv2d_grad, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvGradOpKernel<float>,
                   paddle::operators::CUDNNConvGradOpKernel<double>,
                   paddle::operators::CUDNNConvGradOpKernel<plat::float16>);
REGISTER_OP_KERNEL(
    conv2d_grad_grad, CUDNN, plat::CUDAPlace,
    paddle::operators::CUDNNConvDoubleGradOpKernel<float>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<double>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<plat::float16>);

1457 1458 1459 1460 1461
REGISTER_OP_CUDA_KERNEL(
    depthwise_conv2d_grad_grad,
    paddle::operators::CUDNNConvDoubleGradOpKernel<float>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<double>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<plat::float16>);
W
wuhuanzhou 已提交
1462
#endif
1463

L
liym27 已提交
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
REGISTER_OP_KERNEL(conv3d, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvOpKernel<float>,
                   paddle::operators::CUDNNConvOpKernel<double>,
                   paddle::operators::CUDNNConvOpKernel<plat::float16>);
REGISTER_OP_KERNEL(conv3d_grad, CUDNN, plat::CUDAPlace,
                   paddle::operators::CUDNNConvGradOpKernel<float>,
                   paddle::operators::CUDNNConvGradOpKernel<double>);
REGISTER_OP_KERNEL(
    conv3d_grad_grad, CUDNN, plat::CUDAPlace,
    paddle::operators::CUDNNConvDoubleGradOpKernel<float>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<double>,
    paddle::operators::CUDNNConvDoubleGradOpKernel<plat::float16>);
1476
#endif