conv_cudnn_op.cu.cc 23.6 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
武毅 已提交
2

L
Luo Tao 已提交
3 4 5
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
武毅 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
武毅 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
武毅 已提交
14

Y
Yi Wang 已提交
15 16 17
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/memory/memory.h"
18
#include "paddle/fluid/operators/conv_cudnn_op_cache.h"
Y
Yi Wang 已提交
19 20 21
#include "paddle/fluid/operators/conv_op.h"
#include "paddle/fluid/platform/assert.h"
#include "paddle/fluid/platform/cudnn_helper.h"
22
#include "paddle/fluid/platform/cudnn_workspace_helper.h"
K
Kexin Zhao 已提交
23
#include "paddle/fluid/platform/float16.h"
24
#include "paddle/fluid/platform/profiler.h"
武毅 已提交
25

Y
Yu Yang 已提交
26
DEFINE_bool(cudnn_deterministic, false,
C
chengduoZH 已提交
27 28
            "Whether allow using an autotuning algorithm for convolution "
            "operator. The autotuning algorithm may be non-deterministic. If "
Y
Yu Yang 已提交
29
            "true, the algorithm is deterministic.");
30 31
DEFINE_uint64(conv_workspace_size_limit,
              paddle::platform::kDefaultConvWorkspaceSizeLimitMB,
32 33 34 35
              "cuDNN convolution workspace limit in MB unit.");
DEFINE_bool(cudnn_exhaustive_search, false,
            "Whether enable exhaustive search for cuDNN convolution or "
            "not, defalut is False.");
C
chengduoZH 已提交
36

武毅 已提交
37 38 39 40 41 42 43 44
namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using ScopedTensorDescriptor = platform::ScopedTensorDescriptor;
using ScopedFilterDescriptor = platform::ScopedFilterDescriptor;
using ScopedConvolutionDescriptor = platform::ScopedConvolutionDescriptor;
using DataLayout = platform::DataLayout;
K
update  
Kexin Zhao 已提交
45 46
template <typename T>
using ScalingParamType = typename platform::CudnnDataType<T>::ScalingParamType;
47
using framework::AlgorithmsCache;
武毅 已提交
48 49

template <typename T>
50
class CUDNNConvOpKernel : public framework::OpKernel<T> {
武毅 已提交
51 52
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
53
    auto& dev_ctx = ctx.template device_context<platform::CUDADeviceContext>();
武毅 已提交
54
    PADDLE_ENFORCE(platform::is_gpu_place(ctx.GetPlace()),
D
dzhwinter 已提交
55
                   "It must use CUDAPlace.");
武毅 已提交
56 57 58 59 60 61 62 63
    auto* input = ctx.Input<Tensor>("Input");
    auto* filter = ctx.Input<Tensor>("Filter");
    auto* output = ctx.Output<Tensor>("Output");

    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");
Q
qiaolongfei 已提交
64 65
    int64_t user_workspace_size =
        static_cast<size_t>(ctx.Attr<int>("workspace_size_MB"));
66 67
    bool exhaustive_search =
        FLAGS_cudnn_exhaustive_search || ctx.Attr<bool>("exhaustive_search");
武毅 已提交
68 69 70 71 72 73 74 75 76 77 78

    const T* input_data = input->data<T>();
    const T* filter_data = filter->data<T>();
    T* output_data = output->mutable_data<T>(ctx.GetPlace());

    // ------------------- cudnn descriptors ---------------------
    ScopedTensorDescriptor input_desc;
    ScopedTensorDescriptor output_desc;
    ScopedFilterDescriptor filter_desc;
    ScopedConvolutionDescriptor conv_desc;
    DataLayout layout = DataLayout::kNCHW;
武毅 已提交
79 80 81 82 83 84 85
    if (input->dims().size() == 5) {
      layout = DataLayout::kNCDHW;
    }

    cudnnConvolutionDescriptor_t cudnn_conv_desc =
        conv_desc.descriptor<T>(paddings, strides, dilations);

武毅 已提交
86
#if CUDNN_VERSION_MIN(7, 0, 1)
武毅 已提交
87 88 89
    // cudnn 7 can support groups, no need to do it mannually
    // FIXME(typhoonzero): find a better way to disable groups
    // rather than setting it to 1.
W
Wu Yi 已提交
90
    CUDNN_ENFORCE(platform::dynload::cudnnSetConvolutionGroupCount(
武毅 已提交
91 92 93
        cudnn_conv_desc, groups));
    groups = 1;
#endif
武毅 已提交
94

C
chengduoZH 已提交
95 96 97 98 99 100
    cudnnTensorDescriptor_t cudnn_input_desc = input_desc.descriptor<T>(
        layout, framework::vectorize2int(input->dims()), groups);
    cudnnTensorDescriptor_t cudnn_output_desc = output_desc.descriptor<T>(
        layout, framework::vectorize2int(output->dims()), groups);
    cudnnFilterDescriptor_t cudnn_filter_desc = filter_desc.descriptor<T>(
        layout, framework::vectorize2int(filter->dims()), groups);
武毅 已提交
101 102

    int input_channels = input->dims()[1];
武毅 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    int input_height, input_width, input_depth;
    if (input->dims().size() == 5) {
      input_depth = input->dims()[2];
      input_height = input->dims()[3];
      input_width = input->dims()[4];
    } else {  // dim size is enforced in InferShape
      input_depth = 1;
      input_height = input->dims()[2];
      input_width = input->dims()[3];
    }
    int output_channels = filter->dims()[0];
    int output_height, output_width, output_depth;
    if (output->dims().size() == 5) {
      output_depth = output->dims()[2];
      output_height = output->dims()[3];
      output_width = output->dims()[4];
    } else {
      output_depth = 1;
      output_height = output->dims()[2];
      output_width = output->dims()[3];
    }
武毅 已提交
124

武毅 已提交
125 126
    int group_offset_in =
        input_channels / groups * input_height * input_width * input_depth;
武毅 已提交
127
    int group_offset_out =
武毅 已提交
128
        output_channels / groups * output_height * output_width * output_depth;
武毅 已提交
129 130 131
    int group_offset_filter = filter->numel() / groups;
    // ------------------- cudnn conv workspace ---------------------
    size_t workspace_size_in_bytes;  // final workspace to allocate.
132
    size_t workspace_size_limit = 0;
133 134
    if (FLAGS_conv_workspace_size_limit > 0 || user_workspace_size > 0) {
      int64_t max_user_size =
135
          std::min(static_cast<int64_t>(FLAGS_conv_workspace_size_limit),
136 137
                   user_workspace_size);
      workspace_size_limit = max_user_size * 1024 * 1024;
武毅 已提交
138
    }
139

武毅 已提交
140 141
    // ------------------- cudnn conv algorithm ---------------------
    cudnnConvolutionFwdAlgo_t algo;
142
    bool half_float = false;
143

144 145 146 147 148 149 150 151 152
#if CUDA_VERSION >= 9000 && CUDNN_VERSION_MIN(7, 0, 1)
    // Tensor core is supported since the volta GPU and
    // is only enabled when input and filter data are float16
    if (dev_ctx.GetComputeCapability() >= 70 &&
        std::type_index(typeid(T)) ==
            std::type_index(typeid(platform::float16))) {
      CUDNN_ENFORCE(platform::dynload::cudnnSetConvolutionMathType(
          cudnn_conv_desc, CUDNN_TENSOR_OP_MATH));
      // Currently tensor core is only enabled using this algo
K
Kexin Zhao 已提交
153
      algo = CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM;
154
      half_float = true;
M
minqiyang 已提交
155
      VLOG(5) << "use cudnn_tensor_op_math";
K
Kexin Zhao 已提交
156
    } else {
157 158
      CUDNN_ENFORCE(platform::dynload::cudnnSetConvolutionMathType(
          cudnn_conv_desc, CUDNN_DEFAULT_MATH));
M
minqiyang 已提交
159
      VLOG(5) << "NOT use cudnn_tensor_op_math";
K
Kexin Zhao 已提交
160
    }
161
#endif
K
Kexin Zhao 已提交
162

163 164
    auto handle = dev_ctx.cudnn_handle();
    auto workspace_handle = dev_ctx.cudnn_workspace_handle();
165 166 167 168 169 170 171 172 173
    auto x_dims = framework::vectorize(input->dims());
    auto f_dims = framework::vectorize(filter->dims());
    if ((!exhaustive_search) && (!half_float)) {
      CUDNN_ENFORCE(platform::dynload::cudnnGetConvolutionForwardAlgorithm(
          handle, cudnn_input_desc, cudnn_filter_desc, cudnn_conv_desc,
          cudnn_output_desc, CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT,
          workspace_size_limit, &algo));
      VLOG(3) << "cuDNN forward algo " << algo;
    } else if (exhaustive_search && (!half_float)) {
174 175
      AlgorithmsCache<cudnnConvolutionFwdAlgo_t>& algo_cache =
          ctx.GetKernelConfig<AlgorithmsCache<cudnnConvolutionFwdAlgo_t>>(0);
176

177
      algo = algo_cache.GetAlgorithm(
178 179 180 181
          x_dims, f_dims, strides, paddings, dilations, 0, [&]() {
            int returned_algo_count;
            std::array<cudnnConvolutionFwdAlgoPerf_t, kNUM_CUDNN_FWD_ALGS>
                fwd_perf_stat;
182

183 184 185 186 187 188 189 190 191 192
            auto cudnn_find_func = [&](void* cudnn_workspace) {
              CUDNN_ENFORCE(
                  platform::dynload::cudnnFindConvolutionForwardAlgorithmEx(
                      handle, cudnn_input_desc, input_data, cudnn_filter_desc,
                      filter_data, cudnn_conv_desc, cudnn_output_desc,
                      output_data, kNUM_CUDNN_FWD_ALGS, &returned_algo_count,
                      fwd_perf_stat.data(), cudnn_workspace,
                      workspace_size_limit));
            };
            workspace_handle.RunFuncSync(cudnn_find_func, workspace_size_limit);
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

            VLOG(3) << "Perf result: (algo: stat, time, memory)";
            for (int i = 0; i < returned_algo_count; ++i) {
              const auto& stat = fwd_perf_stat[i];
              VLOG(3) << stat.algo << ": " << stat.status << " " << stat.time
                      << " " << stat.memory;
            }
            return fwd_perf_stat[0].algo;
          });
      VLOG(3) << "choose algo " << algo;
    } else {
      PADDLE_ENFORCE(half_float,
                     "cuDNN exhaustive search doesn't support half float.");
    }

武毅 已提交
208
    // get workspace size able to allocate
W
Wu Yi 已提交
209
    CUDNN_ENFORCE(platform::dynload::cudnnGetConvolutionForwardWorkspaceSize(
武毅 已提交
210 211
        handle, cudnn_input_desc, cudnn_filter_desc, cudnn_conv_desc,
        cudnn_output_desc, algo, &workspace_size_in_bytes));
K
Kexin Zhao 已提交
212 213 214 215 216
    // It is possible for float16 on Volta GPU to allocate more memory than
    // the limit because the algo is overrided to use tensor core.
    PADDLE_ENFORCE_LE(workspace_size_in_bytes, workspace_size_limit,
                      "workspace_size to be allocated exceeds the limit");

217
    // Allocate on GPU memory
218 219 220 221 222 223 224
    Tensor cudnn_workspace =
        ctx.AllocateTmpTensor<int8_t, platform::CUDADeviceContext>(
            framework::make_ddim(
                {static_cast<int64_t>(workspace_size_in_bytes)}),
            dev_ctx);
    void* cudnn_workspace_ptr =
        static_cast<void*>(cudnn_workspace.data<int8_t>());
Z
Zeng Jinle 已提交
225 226 227
    VLOG(2) << "Cudnn workspace size fwd: "
            << static_cast<double>(workspace_size_in_bytes) / (1 << 20)
            << " MB";
武毅 已提交
228
    // ------------------- cudnn conv forward ---------------------
K
update  
Kexin Zhao 已提交
229
    ScalingParamType<T> alpha = 1.0f, beta = 0.0f;
武毅 已提交
230
    for (int i = 0; i < groups; i++) {
231 232 233 234 235
      CUDNN_ENFORCE(platform::dynload::cudnnConvolutionForward(
          handle, &alpha, cudnn_input_desc, input_data + i * group_offset_in,
          cudnn_filter_desc, filter_data + i * group_offset_filter,
          cudnn_conv_desc, algo, cudnn_workspace_ptr, workspace_size_in_bytes,
          &beta, cudnn_output_desc, output_data + i * group_offset_out));
武毅 已提交
236 237 238 239 240
    }
  }
};

template <typename T>
241
class CUDNNConvGradOpKernel : public framework::OpKernel<T> {
武毅 已提交
242 243
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
244
    auto& dev_ctx = ctx.template device_context<platform::CUDADeviceContext>();
武毅 已提交
245
    PADDLE_ENFORCE(platform::is_gpu_place(ctx.GetPlace()),
D
dzhwinter 已提交
246
                   "It must use CUDAPlace.");
武毅 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260
    auto input = ctx.Input<Tensor>("Input");
    auto filter = ctx.Input<Tensor>("Filter");
    auto output_grad = ctx.Input<Tensor>(framework::GradVarName("Output"));
    auto input_grad = ctx.Output<Tensor>(framework::GradVarName("Input"));
    auto filter_grad = ctx.Output<Tensor>(framework::GradVarName("Filter"));

    const T* input_data = input->data<T>();
    const T* output_grad_data = output_grad->data<T>();
    const T* filter_data = filter->data<T>();

    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");
Q
qiaolongfei 已提交
261 262
    int64_t user_workspace_size =
        static_cast<size_t>(ctx.Attr<int>("workspace_size_MB"));
263 264 265 266 267 268 269
    bool exhaustive_search =
        FLAGS_cudnn_exhaustive_search || ctx.Attr<bool>("exhaustive_search");
    if (exhaustive_search && FLAGS_cudnn_deterministic) {
      PADDLE_THROW(
          "Cann't set exhaustive_search True and "
          "FLAGS_cudnn_deterministic True at same time.");
    }
武毅 已提交
270 271 272 273 274 275 276 277 278

    // ------------------- cudnn descriptors ---------------------
    ScopedTensorDescriptor input_desc;
    ScopedTensorDescriptor output_grad_desc;

    ScopedFilterDescriptor filter_desc;
    ScopedFilterDescriptor filter_grad_desc;
    ScopedConvolutionDescriptor conv_desc;
    DataLayout layout = DataLayout::kNCHW;
武毅 已提交
279 280 281 282 283 284 285
    if (input->dims().size() == 5) {
      layout = DataLayout::kNCDHW;
    }

    cudnnConvolutionDescriptor_t cudnn_conv_desc =
        conv_desc.descriptor<T>(paddings, strides, dilations);

武毅 已提交
286
#if CUDNN_VERSION_MIN(7, 0, 1)
武毅 已提交
287 288 289
    // cudnn 7 can support groups, no need to do it mannually
    // FIXME(typhoonzero): find a better way to disable groups
    // rather than setting it to 1.
W
Wu Yi 已提交
290
    CUDNN_ENFORCE(platform::dynload::cudnnSetConvolutionGroupCount(
武毅 已提交
291 292 293
        cudnn_conv_desc, groups));
    groups = 1;
#endif
武毅 已提交
294

C
chengduoZH 已提交
295 296
    cudnnTensorDescriptor_t cudnn_input_desc = input_desc.descriptor<T>(
        layout, framework::vectorize2int(input->dims()), groups);
武毅 已提交
297
    cudnnTensorDescriptor_t cudnn_output_grad_desc =
C
chengduoZH 已提交
298 299 300 301
        output_grad_desc.descriptor<T>(
            layout, framework::vectorize2int(output_grad->dims()), groups);
    cudnnFilterDescriptor_t cudnn_filter_desc = filter_desc.descriptor<T>(
        layout, framework::vectorize2int(filter->dims()), groups);
武毅 已提交
302

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
#if CUDA_VERSION >= 9000 && CUDNN_VERSION_MIN(7, 0, 1)
    // Enable Tensor Core for cudnn backward
    if (dev_ctx.GetComputeCapability() >= 70 &&
        std::type_index(typeid(T)) ==
            std::type_index(typeid(platform::float16))) {
      CUDNN_ENFORCE(platform::dynload::cudnnSetConvolutionMathType(
          cudnn_conv_desc, CUDNN_TENSOR_OP_MATH));
      VLOG(5) << "use cudnn_tensor_op_math for backward";
    } else {
      CUDNN_ENFORCE(platform::dynload::cudnnSetConvolutionMathType(
          cudnn_conv_desc, CUDNN_DEFAULT_MATH));
      VLOG(5) << "NOT use cudnn_tensor_op_math for backward";
    }
#endif

武毅 已提交
318
    int input_channels = input->dims()[1];
武毅 已提交
319 320 321 322 323 324 325 326 327 328 329
    int input_height, input_width, input_depth;
    if (input->dims().size() == 5) {
      input_depth = input->dims()[2];
      input_height = input->dims()[3];
      input_width = input->dims()[4];
    } else {  // dim size is enforced in InferShape
      input_depth = 1;
      input_height = input->dims()[2];
      input_width = input->dims()[3];
    }

武毅 已提交
330
    int output_grad_channels = filter->dims()[0];
武毅 已提交
331 332 333 334 335 336 337 338 339 340
    int output_grad_height, output_grad_width, output_grad_depth;
    if (input->dims().size() == 5) {
      output_grad_depth = output_grad->dims()[2];
      output_grad_height = output_grad->dims()[3];
      output_grad_width = output_grad->dims()[4];
    } else {
      output_grad_depth = 1;
      output_grad_height = output_grad->dims()[2];
      output_grad_width = output_grad->dims()[3];
    }
武毅 已提交
341

武毅 已提交
342 343 344 345
    int group_offset_in =
        input_channels / groups * input_height * input_width * input_depth;
    int group_offset_out = output_grad_channels / groups * output_grad_height *
                           output_grad_width * output_grad_depth;
武毅 已提交
346 347 348 349 350
    int group_offset_filter = filter->numel() / groups;
    // ------------------- cudnn backward algorithm ---------------------
    cudnnConvolutionBwdDataAlgo_t data_algo;
    cudnnConvolutionBwdFilterAlgo_t filter_algo;
    size_t workspace_size_in_bytes = 0, tmp_size = 0;
351
    size_t workspace_size_limit = 0;
352 353
    if (FLAGS_conv_workspace_size_limit > 0 || user_workspace_size > 0) {
      int64_t max_user_size =
354
          std::min(static_cast<int64_t>(FLAGS_conv_workspace_size_limit),
355 356
                   user_workspace_size);
      workspace_size_limit = max_user_size * 1024 * 1024;
武毅 已提交
357 358
    }

359 360 361 362 363 364 365 366 367 368 369
    Tensor cudnn_workspace;
    void* cudnn_workspace_ptr = nullptr;
    if ((input_data || filter_data) && exhaustive_search) {
      cudnn_workspace =
          ctx.AllocateTmpTensor<int8_t, platform::CUDADeviceContext>(
              framework::make_ddim(
                  {static_cast<int64_t>(workspace_size_limit)}),
              dev_ctx);
      cudnn_workspace_ptr = static_cast<void*>(cudnn_workspace.data<int8_t>());
    }

370 371
    auto x_dims = framework::vectorize(input->dims());
    auto f_dims = framework::vectorize(filter->dims());
Q
QI JUN 已提交
372
    auto handle = dev_ctx.cudnn_handle();
武毅 已提交
373
    if (input_grad) {
374 375
      T* input_grad_data = input_grad->mutable_data<T>(ctx.GetPlace());
      if (exhaustive_search) {
376 377 378 379 380
        AlgorithmsCache<cudnnConvolutionBwdDataAlgo_t>& data_algo_cache =
            ctx.GetKernelConfig<AlgorithmsCache<cudnnConvolutionBwdDataAlgo_t>>(
                0);

        data_algo = data_algo_cache.GetAlgorithm(
381 382 383 384 385
            x_dims, f_dims, strides, paddings, dilations, 0, [&]() {
              int returned_algo_count;
              std::array<cudnnConvolutionBwdDataAlgoPerf_t,
                         kNUM_CUDNN_BWD_DATA_ALGS>
                  data_perf_stat;
386 387 388 389 390 391 392 393 394

              CUDNN_ENFORCE(platform::dynload::
                                cudnnFindConvolutionBackwardDataAlgorithmEx(
                                    handle, cudnn_filter_desc, filter_data,
                                    cudnn_output_grad_desc, output_grad_data,
                                    cudnn_conv_desc, cudnn_input_desc,
                                    input_grad_data, kNUM_CUDNN_BWD_DATA_ALGS,
                                    &returned_algo_count, data_perf_stat.data(),
                                    cudnn_workspace_ptr, workspace_size_limit));
395 396 397 398 399 400 401 402 403 404 405 406 407

              VLOG(3) << "Perf result: (algo: stat, time, memory)";
              for (int i = 0; i < returned_algo_count; ++i) {
                const auto& stat = data_perf_stat[i];
                VLOG(3) << stat.algo << ": " << stat.status << " " << stat.time
                        << " " << stat.memory;
              }
              return data_perf_stat[0].algo;
            });
        VLOG(3) << "cuDNN backward data algo " << data_algo;
      } else if (FLAGS_cudnn_deterministic) {
        data_algo = CUDNN_CONVOLUTION_BWD_DATA_ALGO_1;
      } else {
W
Wu Yi 已提交
408
        CUDNN_ENFORCE(
C
chengduoZH 已提交
409 410 411 412 413 414 415 416 417 418 419 420
            platform::dynload::cudnnGetConvolutionBackwardDataAlgorithm(
                handle, cudnn_filter_desc,
                // dyDesc: Handle to the previously initialized input
                // differential
                // tensor descriptor.
                cudnn_output_grad_desc, cudnn_conv_desc,
                // dxDesc: Handle to the previously initialized output tensor
                // descriptor.
                cudnn_input_desc,
                CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT,
                workspace_size_limit, &data_algo));
      }
W
Wu Yi 已提交
421
      CUDNN_ENFORCE(
武毅 已提交
422 423
          platform::dynload::cudnnGetConvolutionBackwardDataWorkspaceSize(
              handle, cudnn_filter_desc, cudnn_output_grad_desc,
武毅 已提交
424
              cudnn_conv_desc, cudnn_input_desc, data_algo, &tmp_size));
武毅 已提交
425 426 427 428
      workspace_size_in_bytes = std::max(workspace_size_in_bytes, tmp_size);
    }

    if (filter_grad) {
429 430
      T* filter_grad_data = filter_grad->mutable_data<T>(ctx.GetPlace());
      if (exhaustive_search) {
431 432 433 434 435
        AlgorithmsCache<cudnnConvolutionBwdFilterAlgo_t>& f_algo_cache =
            ctx.GetKernelConfig<
                AlgorithmsCache<cudnnConvolutionBwdFilterAlgo_t>>(1);

        filter_algo = f_algo_cache.GetAlgorithm(
436 437 438 439 440
            x_dims, f_dims, strides, paddings, dilations, 0, [&]() {
              int returned_algo_count;
              std::array<cudnnConvolutionBwdFilterAlgoPerf_t,
                         kNUM_CUDNN_BWD_FILTER_ALGS>
                  filter_perf_stat;
441 442 443 444 445 446 447 448 449 450

              CUDNN_ENFORCE(
                  platform::dynload::
                      cudnnFindConvolutionBackwardFilterAlgorithmEx(
                          handle, cudnn_input_desc, input_data,
                          cudnn_output_grad_desc, output_grad_data,
                          cudnn_conv_desc, cudnn_filter_desc, filter_grad_data,
                          kNUM_CUDNN_BWD_FILTER_ALGS, &returned_algo_count,
                          filter_perf_stat.data(), cudnn_workspace_ptr,
                          workspace_size_limit));
451 452 453 454 455 456
              return filter_perf_stat[0].algo;
            });
        VLOG(3) << "cuDNN backward filter algo " << filter_algo;
      } else if (FLAGS_cudnn_deterministic) {
        filter_algo = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1;
      } else {
W
Wu Yi 已提交
457
        CUDNN_ENFORCE(
C
chengduoZH 已提交
458 459 460 461 462 463
            platform::dynload::cudnnGetConvolutionBackwardFilterAlgorithm(
                handle, cudnn_input_desc, cudnn_output_grad_desc,
                cudnn_conv_desc, cudnn_filter_desc,
                CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT,
                workspace_size_limit, &filter_algo));
      }
W
Wu Yi 已提交
464
      CUDNN_ENFORCE(
武毅 已提交
465 466 467 468 469
          platform::dynload::cudnnGetConvolutionBackwardFilterWorkspaceSize(
              handle, cudnn_input_desc, cudnn_output_grad_desc, cudnn_conv_desc,
              cudnn_filter_desc, filter_algo, &tmp_size));
      workspace_size_in_bytes = std::max(workspace_size_in_bytes, tmp_size);
    }
470

471 472 473 474 475 476 477 478
    // ------------------- cudnn conv workspace ---------------------
    if (!cudnn_workspace_ptr) {
      cudnn_workspace =
          ctx.AllocateTmpTensor<int8_t, platform::CUDADeviceContext>(
              framework::make_ddim(
                  {static_cast<int64_t>(workspace_size_in_bytes)}),
              dev_ctx);
      cudnn_workspace_ptr = static_cast<void*>(cudnn_workspace.data<int8_t>());
Z
Zeng Jinle 已提交
479 480 481
      VLOG(2) << "Cudnn workspace size bwd: "
              << static_cast<double>(workspace_size_in_bytes) / (1 << 20)
              << " MB";
482 483
    }

武毅 已提交
484
    // ------------------- cudnn conv backward data ---------------------
K
update  
Kexin Zhao 已提交
485
    ScalingParamType<T> alpha = 1.0f, beta = 0.0f;
武毅 已提交
486 487
    if (input_grad) {
      T* input_grad_data = input_grad->mutable_data<T>(ctx.GetPlace());
C
chengduoZH 已提交
488 489
      // Because beta is zero, it is unnecessary to reset input_grad.

武毅 已提交
490
      for (int i = 0; i < groups; i++) {
491 492 493 494 495 496
        CUDNN_ENFORCE(platform::dynload::cudnnConvolutionBackwardData(
            handle, &alpha, cudnn_filter_desc,
            filter_data + i * group_offset_filter, cudnn_output_grad_desc,
            output_grad_data + i * group_offset_out, cudnn_conv_desc, data_algo,
            cudnn_workspace_ptr, workspace_size_in_bytes, &beta,
            cudnn_input_desc, input_grad_data + i * group_offset_in));
武毅 已提交
497 498 499 500 501
      }
    }
    // ------------------- cudnn conv backward filter ---------------------
    if (filter_grad) {
      T* filter_grad_data = filter_grad->mutable_data<T>(ctx.GetPlace());
C
chengduoZH 已提交
502
      // Because beta is zero, it is unnecessary to reset filter_grad.
武毅 已提交
503
      for (int i = 0; i < groups; i++) {
504 505 506 507 508 509
        CUDNN_ENFORCE(platform::dynload::cudnnConvolutionBackwardFilter(
            handle, &alpha, cudnn_input_desc, input_data + i * group_offset_in,
            cudnn_output_grad_desc, output_grad_data + i * group_offset_out,
            cudnn_conv_desc, filter_algo, cudnn_workspace_ptr,
            workspace_size_in_bytes, &beta, cudnn_filter_desc,
            filter_grad_data + i * group_offset_filter));
武毅 已提交
510 511 512 513 514 515 516 517
      }
    }
  }
};

}  // namespace operators
}  // namespace paddle

K
Kexin Zhao 已提交
518 519
namespace plat = paddle::platform;
REGISTER_OP_KERNEL(conv2d, CUDNN, plat::CUDAPlace,
520
                   paddle::operators::CUDNNConvOpKernel<float>,
K
Kexin Zhao 已提交
521
                   paddle::operators::CUDNNConvOpKernel<double>,
K
Kexin Zhao 已提交
522
                   paddle::operators::CUDNNConvOpKernel<plat::float16>);
K
Kexin Zhao 已提交
523
REGISTER_OP_KERNEL(conv2d_grad, CUDNN, plat::CUDAPlace,
524
                   paddle::operators::CUDNNConvGradOpKernel<float>,
C
chengduo 已提交
525 526
                   paddle::operators::CUDNNConvGradOpKernel<double>,
                   paddle::operators::CUDNNConvGradOpKernel<plat::float16>);
527

K
Kexin Zhao 已提交
528
REGISTER_OP_KERNEL(conv3d, CUDNN, plat::CUDAPlace,
529
                   paddle::operators::CUDNNConvOpKernel<float>,
K
Kexin Zhao 已提交
530 531
                   paddle::operators::CUDNNConvOpKernel<double>,
                   paddle::operators::CUDNNConvOpKernel<plat::float16>);
K
Kexin Zhao 已提交
532
REGISTER_OP_KERNEL(conv3d_grad, CUDNN, plat::CUDAPlace,
533
                   paddle::operators::CUDNNConvGradOpKernel<float>,
534
                   paddle::operators::CUDNNConvGradOpKernel<double>);