conv_mkldnn_op.cc 50.0 KB
Newer Older
A
Adam Osewski 已提交
1
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14

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

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

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

A
Adam Osewski 已提交
15 16
#include <tuple>

17
#include "paddle/fluid/framework/expect.h"
18
#include "paddle/fluid/operators/conv_op.h"
J
Jacek Czaja 已提交
19
#include "paddle/fluid/platform/cpu_info.h"
A
Adam Osewski 已提交
20
#include "paddle/fluid/platform/mkldnn_helper.h"
J
Jacek Czaja 已提交
21
#include "paddle/fluid/platform/mkldnn_reuse.h"
22 23 24

namespace paddle {
namespace operators {
A
Adam Osewski 已提交
25
namespace {
26

27 28 29
inline MKLDNNMemoryFormat GetWeightsFormat(const MKLDNNMemoryFormat format,
                                           const int groups,
                                           const bool is_conv3d) {
Y
Yihua Xu 已提交
30
  if (is_conv3d) {
31
    return (groups == 1) ? format : MKLDNNMemoryFormat::goidhw;
Y
Yihua Xu 已提交
32
  } else {
33
    return (groups == 1) ? format : MKLDNNMemoryFormat::goihw;
Y
Yihua Xu 已提交
34 35 36
  }
}

37 38
static dnnl::memory::data_type GetDstType(bool is_int8,
                                          bool is_bfloat16,
39 40 41 42 43
                                          bool force_fp32_output,
                                          std::string fuse_activation,
                                          bool fuse_residual_conn,
                                          const Tensor* residual_param) {
  auto dst_dt = dnnl::memory::data_type::f32;
44 45
  if (is_int8) {
    dst_dt = (fuse_activation == "relu" || fuse_activation == "relu6")
46 47
                 ? dnnl::memory::data_type::u8
                 : dnnl::memory::data_type::s8;
48
    if (force_fp32_output) {
49
      dst_dt = dnnl::memory::data_type::f32;
50
    }
51
    if (fuse_residual_conn && residual_param) {
52 53
      auto residual_dt = framework::ToMKLDNNDataType(
          framework::TransToProtoVarType(residual_param->dtype()));
54
      if (dst_dt != residual_dt) dst_dt = residual_dt;
55
    }
56 57
  } else {
    if (!force_fp32_output && is_bfloat16) {
58
      dst_dt = dnnl::memory::data_type::bf16;
59
      if (fuse_residual_conn && residual_param) {
60 61
        dst_dt = framework::ToMKLDNNDataType(
            framework::TransToProtoVarType(residual_param->dtype()));
62 63
      }
    }
64 65 66 67
  }
  return dst_dt;
}

68
template <typename T, typename K, typename T_out>
69
class ConvMKLDNNHandlerT
70 71
    : public platform::MKLDNNHandlerT<T,
                                      dnnl::convolution_forward,
72 73
                                      dnnl::convolution_backward_data,
                                      dnnl::convolution_backward_weights> {
74
 public:
A
Adam Osewski 已提交
75
  ConvMKLDNNHandlerT(const framework::ExecutionContext& ctx,
76
                     const platform::MKLDNNDeviceContext& dev_ctx,
77
                     const dnnl::engine mkldnn_engine,
78 79 80 81 82
                     platform::Place cpu_place,
                     const Tensor* input,
                     const Tensor* filter,
                     const Tensor* bias,
                     Tensor* output,
83
                     const std::string& unique_name)
84 85
      : platform::MKLDNNHandlerT<T,
                                 dnnl::convolution_forward,
86 87
                                 dnnl::convolution_backward_data,
                                 dnnl::convolution_backward_weights>(
88 89 90 91 92
            dev_ctx,
            mkldnn_engine,
            cpu_place,
            platform::CreateKey(
                dev_ctx, phi::vectorize(input->dims()), unique_name)) {
93
    if (unlikely(!this->isCached())) {
94
      PADDLE_ENFORCE_EQ(
95 96
          input->layout(),
          framework::DataLayout::kMKLDNN,
97 98
          platform::errors::InvalidArgument(
              "The input tensor's layout should be %d, but got %d.",
99 100 101 102
              framework::DataLayout::kMKLDNN,
              input->layout()));
      PADDLE_ENFORCE_NE(input->format(),
                        MKLDNNMemoryFormat::undef,
103 104
                        platform::errors::InvalidArgument(
                            "Wrong format set for Input tensor"));
105

106
      PADDLE_ENFORCE_EQ(
107 108
          filter->layout(),
          framework::DataLayout::kMKLDNN,
109 110
          platform::errors::InvalidArgument(
              "The Filter tensor's layout should be %d, but got %d.",
111 112 113 114
              framework::DataLayout::kMKLDNN,
              filter->layout()));
      PADDLE_ENFORCE_NE(filter->format(),
                        MKLDNNMemoryFormat::undef,
115 116
                        platform::errors::InvalidArgument(
                            "Wrong format set for Filter tensor"));
K
Krzysztof Binias 已提交
117

118
      PADDLE_ENFORCE_GE(
119 120
          input->dims().size(),
          4,
121 122 123 124 125
          platform::errors::InvalidArgument(
              "Input must be with 4 or 5 dimensions, i.e. NCHW or "
              "NCDHW, but got dimension = %d .",
              input->dims().size()));
      PADDLE_ENFORCE_LE(
126 127
          input->dims().size(),
          5,
128 129 130 131
          platform::errors::InvalidArgument(
              "Input must be with 4 or 5 dimensions, i.e. NCHW or "
              "NCDHW, but got dimension = %d .",
              input->dims().size()));
132

133
      PADDLE_ENFORCE_GE(
134 135
          filter->dims().size(),
          4,
136 137 138 139 140
          platform::errors::InvalidArgument(
              "Filter must be with 4 or 5 dimensions, i.e. OIHW or "
              "OIDHW, but got dimension = %d .",
              filter->dims().size()));
      PADDLE_ENFORCE_LE(
141 142
          filter->dims().size(),
          5,
143 144 145 146
          platform::errors::InvalidArgument(
              "Filter must be with 4 or 5 dimensions, i.e. OIHW or "
              "OIDHW, but got dimension = %d .",
              filter->dims().size()));
147

148 149
      if (bias) {
        PADDLE_ENFORCE_EQ(
150 151
            bias->layout(),
            framework::DataLayout::kMKLDNN,
152 153
            platform::errors::InvalidArgument(
                "The Bias tensor's layout should be %d, but got %d.",
154 155 156 157
                framework::DataLayout::kMKLDNN,
                bias->layout()));
        PADDLE_ENFORCE_NE(bias->format(),
                          MKLDNNMemoryFormat::undef,
158 159
                          platform::errors::InvalidArgument(
                              "Got wrong format for Bias tensor."));
160

161 162
        PADDLE_ENFORCE_EQ(bias->dims().size(),
                          1,
163 164 165 166 167
                          platform::errors::InvalidArgument(
                              "Bias must only have 1 dimension, "
                              "i.e. X, but got dimension = %d .",
                              bias->dims().size()));
      }
F
FDInSky 已提交
168

169 170 171
      const int groups = ctx.Attr<int>("groups");
      const std::string padding_algorithm =
          ctx.Attr<std::string>("padding_algorithm");
F
FDInSky 已提交
172

173
      const auto input_dims = input->dims();
174
      const auto data_dims = phi::slice_ddim(input_dims, 2, input_dims.size());
175 176
      const auto filter_dims = filter->dims();
      const auto filter_data_dims =
177
          phi::slice_ddim(filter_dims, 2, filter_dims.size());
178

179
      const auto ksize = phi::vectorize(filter_data_dims);
180
      const bool is_test = ctx.Attr<bool>("is_test");
181

182 183
      auto strides_temp = ctx.Attr<std::vector<int>>("strides");
      std::vector<int64_t> strides(begin(strides_temp), end(strides_temp));
184

185 186
      auto paddings_temp = ctx.Attr<std::vector<int>>("paddings");
      std::vector<int64_t> paddings(begin(paddings_temp), end(paddings_temp));
A
Adam 已提交
187

188 189 190
      auto dilations_temp = ctx.Attr<std::vector<int>>("dilations");
      std::vector<int64_t> dilations(begin(dilations_temp),
                                     end(dilations_temp));
A
Adam 已提交
191

192 193
      UpdatePaddingAndDilation(
          &paddings, &dilations, padding_algorithm, data_dims, strides, ksize);
A
Adam 已提交
194

195 196 197 198
      std::transform(
          dilations.begin(), dilations.end(), dilations.begin(), [](int64_t i) {
            return i - 1;
          });
199

200
      const auto src_tz = phi::vectorize(input->dims());
201

202
      auto weights_tz = phi::vectorize(filter->dims());
203
      platform::GetGroupConvWeightsTz(weights_tz, groups);
204

205
      const auto dst_tz = phi::vectorize(output->dims());
206

207
      const dnnl::memory::dims stride_dims = strides;
208
      const auto mkldnn_paddings = platform::ToMkldnnPadding(paddings);
209
      const dnnl::memory::dims dilations_dims = dilations;
A
Adam 已提交
210

211 212 213 214
      /* create memory descriptor for convolution without specified format
       * ('any') which lets a primitive (convolution in this case) choose
       * the memory format preferred for best performance
       */
215
      auto chosen_memory_format = MKLDNNMemoryFormat::any;
216
      auto data_type = dnnl::memory::data_type::f32;
217 218
      if (ctx.Attr<std::string>("mkldnn_data_type") == "bfloat16" ||
          std::is_same<T_out, platform::bfloat16>::value)
219
        data_type = dnnl::memory::data_type::bf16;
220

221
      dnnl::memory::desc src_md, weights_md;
A
Adam Osewski 已提交
222 223
      if (platform::is_int8<T>()) {
        src_md = platform::MKLDNNMemDesc(
224 225 226
            src_tz,
            framework::ToMKLDNNDataType(
                framework::TransToProtoVarType(input->dtype())),
A
Adam Osewski 已提交
227 228
            chosen_memory_format);
        weights_md = platform::MKLDNNMemDesc(
229
            weights_tz, dnnl::memory::data_type::s8, chosen_memory_format);
A
Adam Osewski 已提交
230 231 232
      } else {
        src_md =
            platform::MKLDNNMemDesc(src_tz, data_type, chosen_memory_format);
233 234
        weights_md = platform::MKLDNNMemDesc(
            weights_tz, data_type, MKLDNNMemoryFormat::any);
A
Adam Osewski 已提交
235 236
      }

237
      const auto dst_md = platform::MKLDNNMemDesc(
238
          dst_tz, platform::MKLDNNGetDataType<T_out>(), chosen_memory_format);
239 240
      const auto fwd_prop_kind = is_test ? dnnl::prop_kind::forward_inference
                                         : dnnl::prop_kind::forward_training;
241

242
      const dnnl::primitive_attr conv_attr = CreateConvAttrs(ctx);
A
Adam 已提交
243

244
      if (bias) {
245
        auto bias_tz = phi::vectorize(bias->dims());
246
        dnnl::memory::desc bias_md;
A
Adam Osewski 已提交
247 248
        if (platform::is_int8<T>()) {
          bias_md = platform::MKLDNNMemDesc(
249
              bias_tz, dnnl::memory::data_type::s32, MKLDNNMemoryFormat::x);
A
Adam Osewski 已提交
250
        } else {
251 252
          bias_md = platform::MKLDNNMemDesc(
              bias_tz, data_type, MKLDNNMemoryFormat::x);
A
Adam Osewski 已提交
253
        }
254

255
        this->AcquireForwardPrimitiveDescriptor(
256 257 258 259 260 261 262 263 264 265 266
            conv_attr,
            fwd_prop_kind,
            dnnl::algorithm::convolution_direct,
            src_md,
            weights_md,
            bias_md,
            dst_md,
            stride_dims,
            dilations_dims,
            mkldnn_paddings[0],
            mkldnn_paddings[1]);
267
      } else {
268
        this->AcquireForwardPrimitiveDescriptor(
269 270 271 272 273 274 275 276 277 278
            conv_attr,
            fwd_prop_kind,
            dnnl::algorithm::convolution_direct,
            src_md,
            weights_md,
            dst_md,
            stride_dims,
            dilations_dims,
            mkldnn_paddings[0],
            mkldnn_paddings[1]);
279 280 281
      }
    }
  }
282

283 284
  ConvMKLDNNHandlerT(const framework::ExecutionContext& ctx,
                     const platform::MKLDNNDeviceContext& dev_ctx,
285 286 287 288 289 290 291 292 293 294
                     platform::Place cpu_place,
                     const Tensor* in,
                     const Tensor* filter,
                     const Tensor* bias,
                     const Tensor* out_grad,
                     Tensor* filter_grad,
                     Tensor* in_x_grad,
                     const std::string& unique_name)
      : platform::MKLDNNHandlerT<T,
                                 dnnl::convolution_forward,
295 296
                                 dnnl::convolution_backward_data,
                                 dnnl::convolution_backward_weights>(
297 298 299 300 301
            dev_ctx,
            dev_ctx.GetEngine(),
            cpu_place,
            platform::CreateKey(
                dev_ctx, phi::vectorize(in->dims()), unique_name)) {
302
    if (unlikely(!this->isBwdCached())) {
303
      PADDLE_ENFORCE_EQ(
304 305
          in->layout(),
          framework::DataLayout::kMKLDNN,
306 307
          platform::errors::InvalidArgument(
              "The input tensor's layout should be %d, but got %d.",
308 309 310 311
              framework::DataLayout::kMKLDNN,
              in->layout()));
      PADDLE_ENFORCE_NE(in->format(),
                        MKLDNNMemoryFormat::undef,
312 313 314 315
                        platform::errors::InvalidArgument(
                            "Got wrong format for Input tensor."));

      PADDLE_ENFORCE_EQ(
316 317
          filter->layout(),
          framework::DataLayout::kMKLDNN,
318 319
          platform::errors::InvalidArgument(
              "The filter tensor's layout should be %d, but got %d.",
320 321 322 323
              framework::DataLayout::kMKLDNN,
              filter->layout()));
      PADDLE_ENFORCE_NE(filter->format(),
                        MKLDNNMemoryFormat::undef,
324 325 326 327
                        platform::errors::InvalidArgument(
                            "Got wrong format for Filter tensor."));

      PADDLE_ENFORCE_EQ(
328 329
          out_grad->layout(),
          framework::DataLayout::kMKLDNN,
330 331
          platform::errors::InvalidArgument(
              "The output_grad tensor's layout should be %d, but got %d.",
332 333 334 335
              framework::DataLayout::kMKLDNN,
              out_grad->layout()));
      PADDLE_ENFORCE_NE(out_grad->format(),
                        MKLDNNMemoryFormat::undef,
336 337 338 339
                        platform::errors::InvalidArgument(
                            "Wrong format set for output_grad tensor"));

      PADDLE_ENFORCE_EQ(
340 341
          ctx.Attr<bool>("is_test"),
          false,
342 343 344 345 346 347 348 349 350 351 352 353 354 355
          platform::errors::InvalidArgument(
              "is_test attribute should be set to False in training phase."));

      std::vector<int> strides_temp = ctx.Attr<std::vector<int>>("strides");
      std::vector<int64_t> strides(begin(strides_temp), end(strides_temp));

      std::vector<int> paddings_temp = ctx.Attr<std::vector<int>>("paddings");
      std::vector<int64_t> paddings(begin(paddings_temp), end(paddings_temp));

      std::vector<int> dilations_temp = ctx.Attr<std::vector<int>>("dilations");
      std::vector<int64_t> dilations(begin(dilations_temp),
                                     end(dilations_temp));

      auto input_dims = in->dims();
356
      auto data_dims = phi::slice_ddim(input_dims, 2, input_dims.size());
357 358
      auto filter_dims = filter->dims();
      auto filter_data_dims =
359 360
          phi::slice_ddim(filter_dims, 2, filter_dims.size());
      auto ksize = phi::vectorize(filter_data_dims);
361

A
Adam Osewski 已提交
362 363
      std::string padding_algorithm =
          ctx.Attr<std::string>("padding_algorithm");
364 365
      UpdatePaddingAndDilation(
          &paddings, &dilations, padding_algorithm, data_dims, strides, ksize);
366

367 368
      auto src_tz = phi::vectorize(in->dims());
      auto weights_tz = phi::vectorize(filter->dims());
369

A
Adam Osewski 已提交
370
      int groups = ctx.Attr<int>("groups");
371 372
      int g = std::max(groups, 1);
      platform::GetGroupConvWeightsTz(weights_tz, g);
373
      auto dst_tz = phi::vectorize(out_grad->dims());
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395

      /* create memory descriptor for conv backward without specified format
       * ('any') which lets a primitive (conv backward in this case) choose
       * the memory format preferred for best performance
       */
      const auto chosen_memory_format = MKLDNNMemoryFormat::any;
      const auto weights_format = MKLDNNMemoryFormat::any;

      auto src_md = platform::MKLDNNMemDesc(
          src_tz, platform::MKLDNNGetDataType<T>(), chosen_memory_format);
      const auto dst_md = platform::MKLDNNMemDesc(
          dst_tz, platform::MKLDNNGetDataType<T_out>(), chosen_memory_format);
      auto diff_src_md = platform::MKLDNNMemDesc(
          src_tz, platform::MKLDNNGetDataType<T>(), chosen_memory_format);
      auto weights_md = platform::MKLDNNMemDesc(
          weights_tz, platform::MKLDNNGetDataType<T>(), weights_format);
      auto diff_weights_md = platform::MKLDNNMemDesc(
          weights_tz, platform::MKLDNNGetDataType<T>(), weights_format);
      auto diff_dst_md = platform::MKLDNNMemDesc(
          dst_tz, platform::MKLDNNGetDataType<T>(), chosen_memory_format);

      auto mkldnn_paddings = platform::ToMkldnnPadding(paddings);
396 397 398 399
      std::transform(
          dilations.begin(), dilations.end(), dilations.begin(), [](int64_t i) {
            return i - 1;
          });
400
      const dnnl::memory::dims dilations_dims = dilations;
401

402
      const dnnl::memory::dims stride_dims = strides;
403
      // Recreating FWD PD. For training there are no post ops in convolution
404
      dnnl::primitive_attr conv_attr;
405
      if (bias) {
406
        auto bias_tz = phi::vectorize(bias->dims());
407
        dnnl::memory::desc bias_md;
A
Adam Osewski 已提交
408 409
        if (platform::is_int8<T>()) {
          bias_md = platform::MKLDNNMemDesc(
410
              bias_tz, dnnl::memory::data_type::s32, MKLDNNMemoryFormat::x);
A
Adam Osewski 已提交
411 412
        } else {
          bias_md = platform::MKLDNNMemDesc(
413
              bias_tz, dnnl::memory::data_type::f32, MKLDNNMemoryFormat::x);
A
Adam Osewski 已提交
414
        }
415

416
        this->AcquireForwardPrimitiveDescriptor(
417 418 419 420 421 422 423 424 425 426
            conv_attr,
            dnnl::prop_kind::forward_training,
            dnnl::algorithm::convolution_direct,
            src_md,
            weights_md,
            bias_md,
            dst_md,
            stride_dims,
            dilations_dims,
            mkldnn_paddings[0],
427 428
            mkldnn_paddings[1]);
      } else {
429
        this->AcquireForwardPrimitiveDescriptor(
430 431 432 433 434 435 436 437 438
            conv_attr,
            dnnl::prop_kind::forward_training,
            dnnl::algorithm::convolution_direct,
            src_md,
            weights_md,
            dst_md,
            stride_dims,
            dilations_dims,
            mkldnn_paddings[0],
439 440 441
            mkldnn_paddings[1]);
      }

442
      this->AcquireBackwardPrimitiveDescriptor(
443 444 445 446 447 448 449
          dnnl::algorithm::convolution_direct,
          diff_src_md,
          weights_md,
          diff_dst_md,
          strides,
          dilations_dims,
          mkldnn_paddings[0],
450 451
          mkldnn_paddings[1]);

452
      this->AcquireBackwardWeightsPrimitiveDescriptor(
453 454 455 456 457 458 459
          dnnl::algorithm::convolution_direct,
          src_md,
          diff_weights_md,
          diff_dst_md,
          strides,
          dilations_dims,
          mkldnn_paddings[0],
460 461 462 463
          mkldnn_paddings[1]);
    }
  }

464 465 466 467 468 469 470 471 472 473 474 475 476
  std::shared_ptr<std::tuple<float, std::vector<float>>> get_int8_bias_scales(
      const framework::ExecutionContext& ctx) {
    // Get scales int8 bias key
    const std::string key_bs = this->key_ + "@bs";

    // Scales for int8 bias are to be cached to avoid
    // computing them each iteration
    auto bias_scale_tuple =
        std::static_pointer_cast<std::tuple<float, std::vector<float>>>(
            this->dev_ctx_.GetBlob(key_bs));
    if (bias_scale_tuple) return bias_scale_tuple;

    const auto* filter = ctx.Input<Tensor>("Filter");
477
    const auto& weights_tz = phi::vectorize(filter->dims());
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
    const int groups = std::max(ctx.Attr<int>("groups"), 1);

    const auto& scale_weights_data =
        ctx.Attr<std::vector<float>>("Scale_weights");
    const auto& scale_in_data = ctx.Attr<float>("Scale_in");

    bool is_multi_channel = scale_weights_data.size() > 1;
    int mask_reorder = is_multi_channel ? 1 << 0 : 1;

    int count = 1;
    if (is_multi_channel) {
      count *= weights_tz[0];
      if (groups > 1) {
        count *= weights_tz[1];
      }
    }

    bias_scale_tuple =
        std::make_shared<std::tuple<float, std::vector<float>>>(std::make_tuple(
            static_cast<float>(mask_reorder), std::vector<float>(count)));
    for (int i = 0; i < count; i++) {
      std::get<1>(*bias_scale_tuple)[i] = scale_in_data * scale_weights_data[i];
    }

    this->dev_ctx_.SetBlob(key_bs, bias_scale_tuple);

    return bias_scale_tuple;
  }

507
  std::tuple<float, std::vector<float>, float> get_int8_scales(
A
Adam Osewski 已提交
508 509
      const framework::ExecutionContext& ctx) const {
    const auto* filter = ctx.Input<Tensor>("Filter");
510
    const auto& weights_tz = phi::vectorize(filter->dims());
A
Adam Osewski 已提交
511 512 513 514 515 516 517 518 519

    const bool& force_fp32_output = ctx.Attr<bool>("force_fp32_output");
    const bool& fuse_residual_conn = ctx.Attr<bool>("fuse_residual_connection");
    const int groups = std::max(ctx.Attr<int>("groups"), 1);

    const auto& scale_in_data = ctx.Attr<float>("Scale_in");
    const auto& scale_in_eltwise_data = ctx.Attr<float>("Scale_in_eltwise");
    auto scale_weights_data = ctx.Attr<std::vector<float>>("Scale_weights");
    bool is_multi_channel = scale_weights_data.size() > 1;
520
    bool has_activation = !ctx.Attr<std::string>("fuse_activation").empty();
521 522 523 524 525 526 527
    float activation_scale = (!force_fp32_output && has_activation)
                                 ? ctx.Attr<float>("Scale_out")
                                 : 1.0f;

    float scale_out_data = (force_fp32_output || has_activation)
                               ? 1.0f
                               : ctx.Attr<float>("Scale_out");
A
Adam Osewski 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
    float sum_scale =
        fuse_residual_conn ? scale_out_data / scale_in_eltwise_data : 1.0f;
    int count =
        is_multi_channel
            ? (groups > 1 ? (weights_tz)[1] * (weights_tz)[0] : (weights_tz)[0])
            : 1;
    std::vector<float> output_shift_scale(count);

#pragma omp parallel for if (count > 50)
    for (int i = 0; i < count; i++) {
      if (scale_weights_data[i] == 0.0)
        // weights data will contain 0 in some models, then weights
        // scale couldn't be calculated
        output_shift_scale[i] = scale_out_data;
      else
        output_shift_scale[i] =
            static_cast<float>(static_cast<double>(scale_out_data) /
                               (static_cast<double>(scale_in_data) *
                                static_cast<double>(scale_weights_data[i])));
    }

549
    return std::make_tuple(sum_scale, output_shift_scale, activation_scale);
A
Adam Osewski 已提交
550 551
  }

552
  dnnl::primitive_attr CreateConvAttrs(const framework::ExecutionContext& ctx) {
553 554
    dnnl::primitive_attr conv_attr;
    dnnl::post_ops post_operations;
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578

    const std::string fuse_activation =
        ctx.Attr<std::string>("fuse_activation");
    const float fuse_alpha = ctx.Attr<float>("fuse_alpha");
    const float fuse_beta = ctx.Attr<float>("fuse_beta");
    const bool fuse_residual_conn = ctx.Attr<bool>("fuse_residual_connection");

    float sum_scale = 1.0f;
    float activation_scale = 1.0f;
    std::vector<float> output_shift_scale;
    if (platform::is_int8<T>()) {
      if (ctx.HasAttr("Sum_scale")) {
        sum_scale = ctx.Attr<float>("Sum_scale");
        activation_scale = ctx.Attr<float>("Activation_scale");
        output_shift_scale = ctx.Attr<std::vector<float>>("Output_shift_scale");
      } else {
        std::tie(sum_scale, output_shift_scale, activation_scale) =
            get_int8_scales(ctx);
      }

      if (output_shift_scale.size() > 0) {
        int mask = output_shift_scale.size() > 1 ? 1 << 1 : 0;
        conv_attr.set_output_scales(mask, output_shift_scale);
      }
579
    }
580

581 582 583 584 585 586 587 588
    // Fusion with Elementwise layer relies on adding a sum post-operation with
    // the scale parameter. It is assumed that when fuse_residual_connection is
    // true, the output tensor contains the data coming from residual
    // connection. The result of this post_op is:
    // Output = scale * Output + Conv_Out.
    if (fuse_residual_conn) {
      post_operations.append_sum(sum_scale);
    }
589 590

    if (fuse_activation == "hard_sigmoid") {
591 592
      post_operations.append_eltwise(activation_scale,
                                     dnnl::algorithm::eltwise_linear,
593 594 595 596
                                     fuse_alpha,
                                     fuse_beta);
      post_operations.append_eltwise(
          activation_scale, dnnl::algorithm::eltwise_clip, 0.0f, 1.0f);
597 598 599
    } else if (fuse_activation != "") {
      const auto activation_algorithm =
          platform::AcquireActivationAlgorithm(fuse_activation);
600 601
      post_operations.append_eltwise(
          activation_scale, activation_algorithm, fuse_alpha, fuse_beta);
602
    }
603

604 605 606
    conv_attr.set_post_ops(post_operations);
    return conv_attr;
  }
607

608
  std::shared_ptr<dnnl::memory>
609 610 611
  AcquireWeightsMemoryWithReorderFromDataPrimitive(
      const framework::Tensor* filter, const int groups, const bool is_conv3d) {
    const K* filter_data = filter->data<K>();
612
    auto weights_tz = phi::vectorize(filter->dims());
613 614 615
    platform::GetGroupConvWeightsTz(weights_tz, groups);

    auto user_src_md = platform::MKLDNNMemDesc(
616 617
        weights_tz,
        platform::MKLDNNGetDataType<K>(),
618 619 620
        GetWeightsFormat(filter->format(), groups, is_conv3d));

    return this->AcquireMemoryWithReorder(
621 622 623 624 625
        user_src_md,
        this->bwd_pd_->weights_desc(),
        platform::to_void_cast<K>(filter_data),
        "@weights_mem_d_p",
        false);
626 627
  }

628
  std::shared_ptr<dnnl::memory> AcquireSrcMemoryWithReorder(
629
      const framework::Tensor* input) {
630 631 632 633 634
    return this->AcquireMemoryWithReorderPrimitive(input,
                                                   "@src_mem_p_user",
                                                   "@src_mem_p_target",
                                                   "@src_mem_p",
                                                   this->fwd_pd_->src_desc());
635
  }
636

637
  std::shared_ptr<dnnl::memory> AcquireSrcMemoryWithReorderFromWeightsPrimitive(
638
      const framework::Tensor* input) {
639 640 641 642 643
    return this->AcquireMemoryWithReorderPrimitive(input,
                                                   "@src_mem_w_p_user",
                                                   "@src_mem_w_p_target",
                                                   "@src_mem_w_p",
                                                   this->bwd_w_pd_->src_desc());
644 645
  }

646
  std::shared_ptr<dnnl::memory>
647 648 649
  AcquireDiffDstMemoryWithReorderFromWeightsPrimitive(
      const framework::Tensor* out_grad) {
    return this->AcquireMemoryWithReorderPrimitive(
650 651 652 653 654
        out_grad,
        "@diff_dst_mem_w_p_user",
        "@diff_dst_mem_w_p_target",
        "@diff_dst_mem_w_p",
        this->bwd_w_pd_->diff_dst_desc());
655 656
  }

657
  std::shared_ptr<dnnl::memory>
658 659 660
  AcquireDiffDstMemoryWithReorderMemoryFromDataPrimitive(
      const framework::Tensor* out_grad) {
    return this->AcquireMemoryWithReorderPrimitive(
661 662 663 664 665
        out_grad,
        "@diff_dst_mem_p_user",
        "@diff_dst_mem_p_target",
        "@diff_dst_mem_p",
        this->bwd_pd_->diff_dst_desc());
666 667
  }

668
  std::shared_ptr<dnnl::memory> AcquireMemoryWithReorderPrimitive(
669 670 671 672
      const framework::Tensor* in_mem,
      const char* key_mem_user,
      const char* key_mem_target,
      const char* key_mem,
673
      const dnnl::memory::desc& mem_md) {
674 675 676 677 678
    const T* in_mem_data = in_mem->data<T>();
    const std::string user_key_suffix{key_mem_user};
    auto user_mem_p = this->AcquireMemory(user_key_suffix);

    if (!user_mem_p) {
679 680 681 682
      auto user_mem_md =
          platform::MKLDNNMemDesc(phi::vectorize(in_mem->dims()),
                                  platform::MKLDNNGetDataType<T>(),
                                  in_mem->format());
683
      return this->AcquireMemoryWithReorder(
684
          user_mem_md, mem_md, platform::to_void_cast<T>(in_mem_data), key_mem);
685
    } else {
686 687
      const std::string target_key_suffix{key_mem_target};
      const auto target_mem_p = this->AcquireMemory(target_key_suffix);
A
Adam Osewski 已提交
688
      user_mem_p->set_data_handle(platform::to_void_cast<T>(in_mem_data));
689
      if (user_mem_p != target_mem_p) {
690
        this->AcquireReorder(user_mem_p, target_mem_p);
691
      }
692
      return target_mem_p;
693
    }
694 695
  }

696
  std::shared_ptr<dnnl::memory> AcquireWeightsMemoryWithReorder(
697 698 699 700 701
      const framework::Tensor* filter,
      const int groups,
      const bool is_conv3d,
      const bool is_test,
      const std::vector<float>& scale_data = {1.0f},
702
      int mask = 0) {
703 704 705
    // This is workaround to make execution faster, delete
    // if statement after including md inside Tensor
    auto weights_mem_p = this->AcquireMemory("@weights_mem_p_target");
706
    if (is_test && weights_mem_p) {
707
      return weights_mem_p;
708
    } else if (is_test) {
709
      const K* filter_data = filter->data<K>();
710
      auto weights_tz = phi::vectorize(filter->dims());
711
      platform::GetGroupConvWeightsTz(weights_tz, groups);
712 713

      auto user_src_md = platform::MKLDNNMemDesc(
714 715
          weights_tz,
          platform::MKLDNNGetDataType<K>(),
716 717 718
          GetWeightsFormat(filter->format(), groups, is_conv3d));

      return this->AcquireMemoryWithReorder(
719 720 721 722 723 724 725 726
          user_src_md,
          this->fwd_pd_->weights_desc(),
          platform::to_void_cast<K>(filter_data),
          "@weights_mem_p",
          is_test,
          {},
          scale_data,
          mask);
727 728
    } else {
      const T* filter_data = filter->data<T>();
729
      auto weights_tz = phi::vectorize(filter->dims());
730 731 732
      platform::GetGroupConvWeightsTz(weights_tz, groups);

      auto user_src_md = platform::MKLDNNMemDesc(
733 734
          weights_tz,
          platform::MKLDNNGetDataType<T>(),
735 736 737
          GetWeightsFormat(filter->format(), groups, is_conv3d));

      return this->AcquireMemoryWithReorder(
738 739 740 741 742 743 744 745
          user_src_md,
          this->fwd_pd_->weights_desc(),
          platform::to_void_cast<T>(filter_data),
          "@weights_mem_p",
          is_test,
          {},
          scale_data,
          mask);
746
    }
747
  }
748

749
  std::shared_ptr<dnnl::memory> AcquireBiasMemoryWithReorder(
750 751 752 753
      const framework::Tensor* bias,
      const bool is_test,
      const std::vector<float>& scale_data = {1.0f},
      int mask = 0) {
754
    auto bias_mem_p = this->AcquireMemory("@bias_mem_p_target");
755
    if (is_test && bias_mem_p) {
756 757
      return bias_mem_p;
    } else {
758
      // if K is int8 (weights are int8) then biases are int32
759 760
      using K_Bias = typename std::
          conditional<std::is_same<K, int8_t>::value, int32_t, K>::type;
761 762 763 764 765
      if (std::is_same<K_Bias, int32_t>::value &&
          bias->dtype() != phi::DataType::INT32) {
        LOG(ERROR) << "Bias should be of type int32 but is " << bias->dtype();
      }
      const K_Bias* bias_data = bias->data<K_Bias>();
766 767 768 769
      auto user_bias_md =
          platform::MKLDNNMemDesc(phi::vectorize(bias->dims()),
                                  platform::MKLDNNGetDataType<K_Bias>(),
                                  MKLDNNMemoryFormat::x);
770 771

      return this->AcquireMemoryWithReorder(
772 773 774 775 776 777 778 779
          user_bias_md,
          this->fwd_pd_->bias_desc(),
          platform::to_void_cast<K_Bias>(bias_data),
          "@bias_mem_p",
          is_test,
          {},
          scale_data,
          mask);
780
    }
781
  }
782

783
  std::shared_ptr<dnnl::memory> AcquireResidualMemory(
784
      const framework::Tensor* residual_param) {
785
    void* residual_data =
786 787
        framework::TransToProtoVarType(residual_param->dtype()) ==
                framework::DataTypeTrait<T_out>::DataType()
A
Adam Osewski 已提交
788 789
            ? platform::to_void_cast<T_out>(residual_param->data<T_out>())
            : platform::to_void_cast<T>(residual_param->data<T>());
790 791 792 793 794 795
    auto residual_mem_p = this->AcquireMemory("@user_residual_data_mem_p");
    if (residual_mem_p) {
      residual_mem_p->set_data_handle(residual_data);
      return residual_mem_p;
    } else {
      auto user_residual_md = platform::MKLDNNMemDesc(
796
          phi::vectorize(residual_param->dims()),
797 798
          framework::ToMKLDNNDataType(
              framework::TransToProtoVarType(residual_param->dtype())),
799
          residual_param->format());
800

801 802
      return this->AcquireMemoryFromPrimitive(
          user_residual_md, residual_data, "@user_residual_data_mem_p");
803
    }
804 805
  }

806
  std::shared_ptr<dnnl::memory> AcquireDstMemoryWithResidual(
807 808 809 810 811
      framework::Tensor* output, const framework::Tensor* residual_param) {
    std::shared_ptr<dnnl::memory> dst_memory_p;
    if (residual_param->format() !=
        platform::GetMKLDNNFormat(this->fwd_pd_->dst_desc())) {
      auto residual_memory_p = this->AcquireResidualMemory(residual_param);
812
      dst_memory_p = this->template AcquireDstMemory<T_out>(output);
813
      this->AcquireReorder(residual_memory_p, dst_memory_p);
814 815 816 817 818
    } else {
      // Changing ShareDataWith to TensorCopy results in performance drop
      // on ResNet architectures
      // (https://github.com/PaddlePaddle/Paddle/issues/22964)
      output->ShareDataWith(*residual_param);
819
      dst_memory_p = this->template AcquireDstMemory<T_out>(output);
820 821 822 823 824
    }
    return dst_memory_p;
  }
};

A
Adam Osewski 已提交
825 826
}  // anonymous namespace

827
template <typename T, typename K>
A
Adam Osewski 已提交
828
class ConvMKLDNNOpKernel : public framework::OpKernel<T> {
829
 public:
A
Adam Osewski 已提交
830
  void Compute(const framework::ExecutionContext& ctx) const override {
831 832
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()),
                      true,
A
Adam Osewski 已提交
833
                      platform::errors::PreconditionNotMet(
834 835 836
                          "Operator DNNL Conv must use CPUPlace"));
    bool is_INT8 =
        std::is_same<T, int8_t>::value || std::is_same<T, uint8_t>::value;
837 838 839 840 841
    bool is_BFLOAT16 = ctx.Attr<std::string>("mkldnn_data_type") == "bfloat16";
    auto residual_param = ctx.Input<Tensor>("ResidualData");
    bool fuse_residual_conn = ctx.Attr<bool>("fuse_residual_connection");
    std::string fuse_activation = ctx.Attr<std::string>("fuse_activation");
    bool force_fp32_output = ctx.Attr<bool>("force_fp32_output");
842 843 844 845 846 847
    auto dst_dt = GetDstType(is_INT8,
                             is_BFLOAT16,
                             force_fp32_output,
                             fuse_activation,
                             fuse_residual_conn,
                             residual_param);
848
    if (!is_INT8) {
849
      if (dst_dt == dnnl::memory::data_type::f32) {
850
        ComputeFP32<float>(ctx);
851
      } else if (dst_dt == dnnl::memory::data_type::bf16) {
852 853
        ComputeFP32<platform::bfloat16>(ctx);
      }
854
    } else {
855
      if (dst_dt == dnnl::memory::data_type::f32) {
856
        ComputeINT8<float>(ctx);
857
      } else if (dst_dt == dnnl::memory::data_type::u8) {
858
        ComputeINT8<uint8_t>(ctx);
859
      } else if (dst_dt == dnnl::memory::data_type::s8) {
860 861
        ComputeINT8<int8_t>(ctx);
      }
862
    }
863
  }
864

865
  template <typename T_out>
A
Adam Osewski 已提交
866
  void ComputeFP32(const framework::ExecutionContext& ctx) const {
867
    auto& dev_ctx =
A
Adam Osewski 已提交
868
        ctx.template device_context<platform::MKLDNNDeviceContext>();
869
    const auto& mkldnn_engine = dev_ctx.GetEngine();
870

871
    const bool is_test = ctx.Attr<bool>("is_test");
872 873
    const bool is_conv3d = ctx.Attr<std::vector<int>>("strides").size() == 3U;
    const bool fuse_residual_conn = ctx.Attr<bool>("fuse_residual_connection");
874

875 876 877 878 879
    const auto* input = ctx.Input<Tensor>("Input");
    const auto* filter = ctx.Input<Tensor>("Filter");
    const auto* bias =
        ctx.HasInput("Bias") ? ctx.Input<Tensor>("Bias") : nullptr;
    auto* output = ctx.Output<Tensor>("Output");
880

881
    ConvMKLDNNHandlerT<T, K, T_out> handler(
882 883 884 885 886 887 888 889 890
        ctx,
        dev_ctx,
        mkldnn_engine,
        ctx.GetPlace(),
        input,
        filter,
        bias,
        output,
        ctx.InputName("Input") + ctx.InputName("Filter"));
891

892
    auto src_memory_p = handler.AcquireSrcMemoryWithReorder(input);
893

894
    auto weights_memory_p = handler.AcquireWeightsMemoryWithReorder(
895
        filter, ctx.Attr<int>("groups"), is_conv3d, is_test);
896

897 898 899
    std::shared_ptr<dnnl::memory> dst_memory_p;
    if (fuse_residual_conn) {
      auto* residual_param = ctx.Input<Tensor>("ResidualData");
900
      dst_memory_p =
901 902
          handler.AcquireDstMemoryWithResidual(output, residual_param);
    } else {
903
      dst_memory_p = handler.template AcquireDstMemory<T_out>(output);
904
    }
905

906
    auto conv_p = handler.AcquireForwardPrimitive();
A
Adam 已提交
907

908
    std::unordered_map<int, dnnl::memory> args = {
909 910 911
        {DNNL_ARG_SRC, *src_memory_p},
        {DNNL_ARG_WEIGHTS, *weights_memory_p},
        {DNNL_ARG_DST, *dst_memory_p}};
A
Adam 已提交
912

913
    if (bias) {
914
      auto bias_memory_p = handler.AcquireBiasMemoryWithReorder(bias, is_test);
915
      args.insert({DNNL_ARG_BIAS, *bias_memory_p});
916
    }
917

918
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
919
    conv_p->execute(astream, args);
A
Adam 已提交
920
    astream.wait();
921

A
Adam Osewski 已提交
922 923
    output->set_layout(framework::DataLayout::kMKLDNN);
    output->set_format(platform::GetMKLDNNFormat(*dst_memory_p));
924
  }
925

926
  template <typename T_out>
A
Adam Osewski 已提交
927
  void ComputeINT8(const framework::ExecutionContext& ctx) const {
928
    auto& dev_ctx =
A
Adam Osewski 已提交
929
        ctx.template device_context<platform::MKLDNNDeviceContext>();
930 931
    const auto& mkldnn_engine = dev_ctx.GetEngine();

A
Adam Osewski 已提交
932 933 934 935 936
    const std::string& fuse_activation =
        ctx.Attr<std::string>("fuse_activation");
    const bool& fuse_residual_conn = ctx.Attr<bool>("fuse_residual_connection");
    const bool& force_fp32_output = ctx.Attr<bool>("force_fp32_output");
    const bool is_conv3d = ctx.Attr<std::vector<int>>("strides").size() == 3U;
937

938 939
    bool unsigned_output =
        (fuse_activation == "relu" || fuse_activation == "relu6");
940 941
    bool need_s8_to_u8 = false;

A
Adam Osewski 已提交
942
    PADDLE_ENFORCE_NE(
943 944
        is_conv3d,
        true,
A
Adam Osewski 已提交
945 946 947
        platform::errors::Unimplemented(
            "OneDNN int8 convolution does not support 3D inputs currently"));
    PADDLE_ENFORCE_EQ(
948 949
        fuse_residual_conn && force_fp32_output,
        false,
A
Adam Osewski 已提交
950 951
        platform::errors::Unimplemented(
            "residual fusion does not support force output with fp32"));
A
Adam 已提交
952

A
Adam Osewski 已提交
953 954 955 956
    auto* input = ctx.Input<Tensor>("Input");
    auto* filter = ctx.Input<Tensor>("Filter");
    auto* bias = ctx.HasInput("Bias") ? ctx.Input<Tensor>("Bias") : nullptr;
    auto* output = ctx.Output<Tensor>("Output");
957

A
Adam Osewski 已提交
958
    ConvMKLDNNHandlerT<T, K, T_out> handler(
959 960 961 962 963 964 965 966 967
        ctx,
        dev_ctx,
        mkldnn_engine,
        ctx.GetPlace(),
        input,
        filter,
        bias,
        output,
        ctx.InputName("Input") + ctx.InputName("Filter"));
968

A
Adam Osewski 已提交
969
    auto src_memory_p = handler.AcquireSrcMemoryWithReorder(input);
F
FDInSky 已提交
970

A
Adam Osewski 已提交
971 972 973 974 975 976 977
    const auto& scale_weights_data =
        ctx.Attr<std::vector<float>>("Scale_weights");
    const bool is_multi_channel = scale_weights_data.size() > 1;
    const int& groups = ctx.Attr<int>("groups");
    int mask_reorder =
        is_multi_channel ? ((groups != 1) ? (1 << 1) + (1 << 0) : 1 << 0) : 0;
    auto weights_memory_p = handler.AcquireWeightsMemoryWithReorder(
978
        filter, groups, false, true, scale_weights_data, mask_reorder);
979

A
Adam Osewski 已提交
980 981 982
    std::shared_ptr<dnnl::memory> dst_memory_p;
    if (fuse_residual_conn) {
      auto* residual_param = ctx.Input<Tensor>("ResidualData");
983
      PADDLE_ENFORCE_EQ(
984 985
          output->dims(),
          residual_param->dims(),
A
Adam Osewski 已提交
986 987 988 989
          platform::errors::InvalidArgument(
              "Output and elementwise parameter need to have the "
              "same dimension sizes, but got output's dimension = %d"
              " and residual param's dimension =%d .",
990 991
              output->dims().size(),
              residual_param->dims().size()));
992
      dst_memory_p =
A
Adam Osewski 已提交
993 994
          handler.AcquireDstMemoryWithResidual(output, residual_param);
      need_s8_to_u8 = (platform::MKLDNNGetDataType<T_out>() ==
995
                       dnnl::memory::data_type::s8) &&
A
Adam Osewski 已提交
996 997 998 999
                      unsigned_output;
    } else {
      dst_memory_p = handler.template AcquireDstMemory<T_out>(output);
    }
L
lidanqing 已提交
1000

A
Adam Osewski 已提交
1001 1002 1003
    auto conv_p = handler.AcquireForwardPrimitive();

    std::unordered_map<int, dnnl::memory> args = {
1004 1005 1006
        {DNNL_ARG_SRC, *src_memory_p},
        {DNNL_ARG_WEIGHTS, *weights_memory_p},
        {DNNL_ARG_DST, *dst_memory_p}};
A
Adam 已提交
1007

A
Adam Osewski 已提交
1008
    if (bias) {
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
      std::vector<float> bias_scales;
      auto p_scales_tuple =
          std::make_shared<std::tuple<float, std::vector<float>>>(
              std::make_tuple(static_cast<float>(mask_reorder), bias_scales));
      if (ctx.HasAttr("Bias_scales")) {
        bias_scales = ctx.Attr<std::vector<float>>("Bias_scales");
        p_scales_tuple =
            std::make_shared<std::tuple<float, std::vector<float>>>(
                std::make_tuple(static_cast<float>(mask_reorder), bias_scales));
      } else {
        p_scales_tuple = handler.get_int8_bias_scales(ctx);
      }
1021 1022 1023 1024 1025
      auto bias_memory_p =
          handler.AcquireBiasMemoryWithReorder(bias,
                                               true,
                                               std::get<1>(*p_scales_tuple),
                                               std::get<0>(*p_scales_tuple));
1026
      args.insert({DNNL_ARG_BIAS, *bias_memory_p});
1027
    }
A
Adam Osewski 已提交
1028 1029 1030

    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
    conv_p->execute(astream, args);
A
Adam 已提交
1031
    astream.wait();
A
Adam Osewski 已提交
1032

1033
    if (need_s8_to_u8) {
X
xiaolil1 已提交
1034 1035
      output->mutable_data<uint8_t>(ctx.GetPlace());
    }
A
Adam Osewski 已提交
1036 1037 1038

    output->set_layout(framework::DataLayout::kMKLDNN);
    output->set_format(platform::GetMKLDNNFormat(*dst_memory_p));
1039
  }
1040 1041
};

1042
template <typename T, typename K>
A
Adam Osewski 已提交
1043
class ConvMKLDNNGradOpKernel : public framework::OpKernel<T> {
1044
 public:
A
Adam Osewski 已提交
1045
  void Compute(const framework::ExecutionContext& ctx) const override {
1046 1047
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()),
                      true,
A
Adam Osewski 已提交
1048
                      platform::errors::PreconditionNotMet(
1049
                          "Operator DNNL ConvGrad must use CPUPlace"));
1050 1051
    auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
1052 1053 1054 1055
    const auto& mkldnn_engine = dev_ctx.GetEngine();

    const Tensor* input = ctx.Input<Tensor>("Input");
    const Tensor* filter = ctx.Input<Tensor>("Filter");
1056 1057
    const Tensor* bias =
        ctx.HasInput("Bias") ? ctx.Input<Tensor>("Bias") : nullptr;
1058 1059 1060 1061 1062 1063 1064
    const Tensor* output_grad =
        ctx.Input<Tensor>(framework::GradVarName("Output"));
    Tensor* input_grad = ctx.Output<Tensor>(framework::GradVarName("Input"));
    Tensor* filter_grad = ctx.Output<Tensor>(framework::GradVarName("Filter"));

    if (!input_grad && !filter_grad) return;

1065 1066
    // TODO(jczaja): Are all tensors really needed?
    ConvMKLDNNHandlerT<T, K, T> handler(
1067 1068 1069 1070 1071 1072 1073 1074 1075
        ctx,
        dev_ctx,
        ctx.GetPlace(),
        input,
        filter,
        bias,
        output_grad,
        filter_grad,
        input_grad,
1076
        ctx.InputName("Input") + ctx.InputName("Filter"));
1077 1078

    // create mkldnn memory from input tensors (data/weights)
1079
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
1080

1081 1082 1083 1084 1085 1086
    if (filter_grad) {
      auto src_memory_p =
          handler.AcquireSrcMemoryWithReorderFromWeightsPrimitive(input);
      auto diff_dst_memory_p =
          handler.AcquireDiffDstMemoryWithReorderFromWeightsPrimitive(
              output_grad);
1087

1088 1089
      // For convoluition with groups write filter grad into
      // oneDNN buffer and then we reorder it into filter_grad tensor
1090
      int g = std::max(ctx.Attr<int>("groups"), 1);
1091
      auto diff_weights_memory_p =
1092 1093
          g > 1 ? handler.AcquireDiffWeightsMemory()
                : handler.AcquireDiffWeightsMemory(filter_grad);
1094

1095
      auto conv_bwd_weights_p = handler.AcquireBackwardWeightsPrimitive();
1096

A
Adam 已提交
1097 1098
      // TODO(grygielski) why no bias_diff?
      conv_bwd_weights_p->execute(
1099 1100 1101 1102
          astream,
          {{DNNL_ARG_SRC, *src_memory_p},
           {DNNL_ARG_DIFF_DST, *diff_dst_memory_p},
           {DNNL_ARG_DIFF_WEIGHTS, *diff_weights_memory_p}});
A
Adam 已提交
1103
      astream.wait();
1104

A
Adam Osewski 已提交
1105
      filter_grad->set_layout(framework::DataLayout::kMKLDNN);
1106 1107
      // in OneDNN groups in convolution are treated as separate dimension
      // which is not the case in paddlepaddle
A
Adam Osewski 已提交
1108
      auto filter_fmt = platform::GetMKLDNNFormat(*diff_weights_memory_p);
1109 1110 1111 1112

      // For convolution with groups convert from blocked to NCHW
      // otherwise there will be problems in next operators working on this data
      if (g > 1) {
1113 1114
        dnnl::memory::data_type in_type = framework::ToMKLDNNDataType(
            framework::TransToProtoVarType(filter->dtype()));
1115 1116
        // for 3d conv with groups (six dimensional data reorder to goidhw)
        // for 2d conv with groups (five dimensional data reorder to goihw)
1117
        // auto weights_tz = phi::vectorize(filter->dims());
1118 1119

        auto weights_tz = diff_weights_memory_p->get_desc().dims();
1120 1121 1122
        dnnl::memory::format_tag out_format =
            weights_tz.size() == 6 ? dnnl::memory::format_tag::goidhw
                                   : dnnl::memory::format_tag::goihw;
1123
        platform::ReorderMKLDNNHandler handler(
1124 1125 1126 1127
            weights_tz,
            framework::TransToProtoVarType(filter->dtype()),
            in_type,
            mkldnn_engine);
1128 1129 1130 1131 1132 1133
        auto reorder_dst_memory_p =
            handler.AcquireDstMemory(filter_grad, out_format, ctx.GetPlace());

        auto reorder_p =
            handler.AcquireReorder(reorder_dst_memory_p, diff_weights_memory_p);

1134
        {
C
chenjian 已提交
1135
          platform::RecordEvent record_reorder(
1136 1137 1138
              "int_reorder",
              platform::TracerEventType::UserDefined,
              2,
C
chenjian 已提交
1139
              platform::EventRole::kUniqueOp);
1140 1141
          reorder_p->execute(
              astream, *diff_weights_memory_p, *reorder_dst_memory_p);
1142 1143
          astream.wait();
        }
1144 1145 1146 1147

        // So here we have a data in goihw , which can be interpreted as OIHW
        // (OIDHW for conv3d)
        // because filter_grad shape is set for OIHW (OIDHW for conv3d)
1148 1149 1150
        dnnl::memory::format_tag target_format =
            weights_tz.size() == 6 ? dnnl::memory::format_tag::oidhw
                                   : dnnl::memory::format_tag::oihw;
1151 1152 1153 1154
        filter_grad->set_format(target_format);
      } else {
        filter_grad->set_format(filter_fmt);
      }
1155 1156
    }
    if (input_grad) {
1157 1158
      auto weights_memory_p =
          handler.AcquireWeightsMemoryWithReorderFromDataPrimitive(
1159 1160
              filter,
              ctx.Attr<int>("groups"),
1161
              ctx.Attr<std::vector<int>>("strides").size() == 3U);
1162

1163 1164 1165 1166
      auto diff_dst_memory_p =
          handler.AcquireDiffDstMemoryWithReorderMemoryFromDataPrimitive(
              output_grad);
      auto diff_src_memory_p = handler.AcquireDiffSrcMemory(input_grad);
1167

1168
      auto conv_bwd_data_p = handler.AcquireBackwardPrimitive();
1169

A
Adam 已提交
1170
      conv_bwd_data_p->execute(astream,
1171 1172 1173
                               {{DNNL_ARG_WEIGHTS, *weights_memory_p},
                                {DNNL_ARG_DIFF_DST, *diff_dst_memory_p},
                                {DNNL_ARG_DIFF_SRC, *diff_src_memory_p}});
A
Adam 已提交
1174
      astream.wait();
1175

A
Adam Osewski 已提交
1176 1177
      input_grad->set_layout(framework::DataLayout::kMKLDNN);
      input_grad->set_format(platform::GetMKLDNNFormat(*diff_src_memory_p));
1178
    }
X
xiaolil1 已提交
1179
  }
1180
};
1181

1182 1183 1184 1185 1186
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

1187 1188 1189 1190
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv2d,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    FP32,
X
Xin Pan 已提交
1191
                                    ops::kConvMKLDNNFP32,
1192
                                    ops::ConvMKLDNNOpKernel<float, float>);
1193

1194
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(
1195 1196 1197 1198 1199
    conv2d,
    MKLDNN,
    ::paddle::platform::CPUPlace,
    BF16,
    ops::kConvMKLDNNFP32,
1200 1201
    ops::ConvMKLDNNOpKernel<paddle::platform::bfloat16, float>);

1202 1203 1204 1205
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv2d,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    U8,
1206
                                    ops::kConvMKLDNNINT8,
1207
                                    ops::ConvMKLDNNOpKernel<uint8_t, float>);
1208

1209 1210 1211 1212
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv2d,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    U8WS8,
1213 1214 1215
                                    ops::kConvMKLDNNINT8WS8,
                                    ops::ConvMKLDNNOpKernel<uint8_t, int8_t>);

1216 1217 1218 1219
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv2d,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    S8,
1220
                                    ops::kConvMKLDNNINT8,
1221
                                    ops::ConvMKLDNNOpKernel<int8_t, float>);
X
Xin Pan 已提交
1222

1223 1224 1225 1226
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv2d,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    S8WS8,
1227 1228 1229
                                    ops::kConvMKLDNNINT8WS8,
                                    ops::ConvMKLDNNOpKernel<int8_t, int8_t>);

1230 1231 1232 1233
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv2d_grad,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    FP32,
X
Xin Pan 已提交
1234
                                    ops::kConvMKLDNNFP32,
1235
                                    ops::ConvMKLDNNGradOpKernel<float, float>);
1236

1237
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(
1238 1239 1240 1241
    conv2d_grad,
    MKLDNN,
    ::paddle::platform::CPUPlace,
    BF16,
1242
    ops::kConvMKLDNNFP32,
1243 1244
    ops::ConvMKLDNNGradOpKernel<paddle::platform::bfloat16,
                                paddle::platform::bfloat16>);
1245

1246 1247 1248 1249
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(depthwise_conv2d,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    FP32,
1250 1251 1252 1253
                                    ops::kConvMKLDNNFP32,
                                    ops::ConvMKLDNNOpKernel<float, float>);

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(
1254 1255 1256 1257
    depthwise_conv2d,
    MKLDNN,
    ::paddle::platform::CPUPlace,
    BF16,
1258 1259 1260
    ops::kConvMKLDNNFP32,
    ops::ConvMKLDNNOpKernel<paddle::platform::bfloat16, float>);

1261 1262 1263 1264
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(depthwise_conv2d,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    U8,
1265 1266 1267
                                    ops::kConvMKLDNNINT8,
                                    ops::ConvMKLDNNOpKernel<uint8_t, float>);

1268 1269 1270 1271
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(depthwise_conv2d,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    S8,
1272 1273 1274
                                    ops::kConvMKLDNNINT8,
                                    ops::ConvMKLDNNOpKernel<int8_t, float>);

1275 1276 1277 1278
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(depthwise_conv2d_grad,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    FP32,
1279 1280 1281 1282
                                    ops::kConvMKLDNNFP32,
                                    ops::ConvMKLDNNGradOpKernel<float, float>);

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(
1283 1284 1285 1286
    depthwise_conv2d_grad,
    MKLDNN,
    ::paddle::platform::CPUPlace,
    BF16,
1287 1288 1289
    ops::kConvMKLDNNFP32,
    ops::ConvMKLDNNGradOpKernel<paddle::platform::bfloat16, float>);

1290 1291 1292 1293
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv3d,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    FP32,
1294
                                    ops::kConvMKLDNNFP32,
1295
                                    ops::ConvMKLDNNOpKernel<float, float>);
1296

1297 1298 1299 1300
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv3d_grad,
                                    MKLDNN,
                                    ::paddle::platform::CPUPlace,
                                    FP32,
1301
                                    ops::kConvMKLDNNFP32,
1302
                                    ops::ConvMKLDNNGradOpKernel<float, float>);