conv_mkldnn_op.cc 43.2 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/operators/conv_op.h"
J
Jacek Czaja 已提交
18
#include "paddle/fluid/platform/cpu_info.h"
A
Adam Osewski 已提交
19
#include "paddle/fluid/platform/mkldnn_helper.h"
J
Jacek Czaja 已提交
20
#include "paddle/fluid/platform/mkldnn_reuse.h"
21 22 23

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

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

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

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

92
      PADDLE_ENFORCE_EQ(
A
Adam Osewski 已提交
93
          filter->layout(), framework::DataLayout::kMKLDNN,
94 95
          platform::errors::InvalidArgument(
              "The Filter tensor's layout should be %d, but got %d.",
A
Adam Osewski 已提交
96
              framework::DataLayout::kMKLDNN, filter->layout()));
97 98 99
      PADDLE_ENFORCE_NE(filter->format(), MKLDNNMemoryFormat::undef,
                        platform::errors::InvalidArgument(
                            "Wrong format set for Filter tensor"));
K
Krzysztof Binias 已提交
100

101 102 103 104 105 106 107 108 109 110 111 112
      PADDLE_ENFORCE_GE(
          input->dims().size(), 4,
          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(
          input->dims().size(), 5,
          platform::errors::InvalidArgument(
              "Input must be with 4 or 5 dimensions, i.e. NCHW or "
              "NCDHW, but got dimension = %d .",
              input->dims().size()));
113

114 115 116 117 118 119 120 121 122 123 124 125
      PADDLE_ENFORCE_GE(
          filter->dims().size(), 4,
          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(
          filter->dims().size(), 5,
          platform::errors::InvalidArgument(
              "Filter must be with 4 or 5 dimensions, i.e. OIHW or "
              "OIDHW, but got dimension = %d .",
              filter->dims().size()));
126

127 128
      if (bias) {
        PADDLE_ENFORCE_EQ(
A
Adam Osewski 已提交
129
            bias->layout(), framework::DataLayout::kMKLDNN,
130 131
            platform::errors::InvalidArgument(
                "The Bias tensor's layout should be %d, but got %d.",
A
Adam Osewski 已提交
132
                framework::DataLayout::kMKLDNN, bias->layout()));
133 134 135
        PADDLE_ENFORCE_NE(bias->format(), MKLDNNMemoryFormat::undef,
                          platform::errors::InvalidArgument(
                              "Got wrong format for Bias tensor."));
136

137 138 139 140 141 142
        PADDLE_ENFORCE_EQ(bias->dims().size(), 1,
                          platform::errors::InvalidArgument(
                              "Bias must only have 1 dimension, "
                              "i.e. X, but got dimension = %d .",
                              bias->dims().size()));
      }
F
FDInSky 已提交
143

144 145 146 147 148 149 150 151 152
      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");
      const int groups = ctx.Attr<int>("groups");
      const std::string padding_algorithm =
          ctx.Attr<std::string>("padding_algorithm");
F
FDInSky 已提交
153

154 155 156 157 158 159
      const auto input_dims = input->dims();
      const auto data_dims =
          framework::slice_ddim(input_dims, 2, input_dims.size());
      const auto filter_dims = filter->dims();
      const auto filter_data_dims =
          framework::slice_ddim(filter_dims, 2, filter_dims.size());
160

161
      const auto ksize = framework::vectorize(filter_data_dims);
162
      const bool is_test = ctx.Attr<bool>("is_test");
163

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

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

170 171 172
      auto dilations_temp = ctx.Attr<std::vector<int>>("dilations");
      std::vector<int64_t> dilations(begin(dilations_temp),
                                     end(dilations_temp));
A
Adam 已提交
173

174 175
      UpdatePaddingAndDilation(&paddings, &dilations, padding_algorithm,
                               data_dims, strides, ksize);
A
Adam 已提交
176

177 178
      std::transform(dilations.begin(), dilations.end(), dilations.begin(),
                     [](int64_t i) { return i - 1; });
179

A
Adam Osewski 已提交
180
      const auto src_tz = framework::vectorize(input->dims());
181

A
Adam Osewski 已提交
182
      auto weights_tz = framework::vectorize(filter->dims());
183
      platform::GetGroupConvWeightsTz(weights_tz, groups);
184

A
Adam Osewski 已提交
185
      const auto dst_tz = framework::vectorize(output->dims());
186

187
      const dnnl::memory::dims stride_dims = strides;
188
      const auto mkldnn_paddings = platform::ToMkldnnPadding(paddings);
189
      const dnnl::memory::dims dilations_dims = dilations;
A
Adam 已提交
190

191 192 193 194
      /* 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
       */
195
      auto chosen_memory_format = MKLDNNMemoryFormat::any;
196
      auto data_type = dnnl::memory::data_type::f32;
197 198
      if (ctx.Attr<std::string>("mkldnn_data_type") == "bfloat16" ||
          std::is_same<T_out, platform::bfloat16>::value)
199
        data_type = dnnl::memory::data_type::bf16;
200

201
      dnnl::memory::desc src_md, weights_md;
A
Adam Osewski 已提交
202 203 204 205 206
      if (platform::is_int8<T>()) {
        src_md = platform::MKLDNNMemDesc(
            src_tz, framework::ToMKLDNNDataType(input->type()),
            chosen_memory_format);
        weights_md = platform::MKLDNNMemDesc(
207
            weights_tz, dnnl::memory::data_type::s8, chosen_memory_format);
A
Adam Osewski 已提交
208 209 210 211 212 213 214
      } else {
        src_md =
            platform::MKLDNNMemDesc(src_tz, data_type, chosen_memory_format);
        weights_md = platform::MKLDNNMemDesc(weights_tz, data_type,
                                             MKLDNNMemoryFormat::any);
      }

215
      const auto dst_md = platform::MKLDNNMemDesc(
216
          dst_tz, platform::MKLDNNGetDataType<T_out>(), chosen_memory_format);
217 218
      const auto fwd_prop_kind = is_test ? dnnl::prop_kind::forward_inference
                                         : dnnl::prop_kind::forward_training;
219

J
jakpiase 已提交
220
      float sum_scale = 1.0f;
A
Adam Osewski 已提交
221
      std::vector<float> output_shift_scale;
J
jakpiase 已提交
222 223
      if (platform::is_int8<T>())
        std::tie(sum_scale, output_shift_scale) = get_int8_scales(ctx);
A
Adam Osewski 已提交
224

225
      const dnnl::primitive_attr conv_attr = CreatePostOps(
A
Adam Osewski 已提交
226 227
          fuse_activation, fuse_alpha, fuse_beta, fuse_residual_conn,
          output_shift_scale, sum_scale);  // for INT8 only!
A
Adam 已提交
228

229 230
      if (bias) {
        auto bias_tz = framework::vectorize(bias->dims());
231
        dnnl::memory::desc bias_md;
A
Adam Osewski 已提交
232 233
        if (platform::is_int8<T>()) {
          bias_md = platform::MKLDNNMemDesc(
234
              bias_tz, dnnl::memory::data_type::s32, MKLDNNMemoryFormat::x);
A
Adam Osewski 已提交
235 236 237 238
        } else {
          bias_md = platform::MKLDNNMemDesc(bias_tz, data_type,
                                            MKLDNNMemoryFormat::x);
        }
239

240
        this->AcquireForwardPrimitiveDescriptor(
241
            conv_attr, fwd_prop_kind, dnnl::algorithm::convolution_direct,
242
            src_md, weights_md, bias_md, dst_md, stride_dims, dilations_dims,
243 244
            mkldnn_paddings[0], mkldnn_paddings[1]);
      } else {
245
        this->AcquireForwardPrimitiveDescriptor(
246
            conv_attr, fwd_prop_kind, dnnl::algorithm::convolution_direct,
247 248
            src_md, weights_md, dst_md, stride_dims, dilations_dims,
            mkldnn_paddings[0], mkldnn_paddings[1]);
249 250 251
      }
    }
  }
252

253 254 255 256 257 258
  ConvMKLDNNHandlerT(const framework::ExecutionContext& ctx,
                     const platform::MKLDNNDeviceContext& dev_ctx,
                     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)
259 260 261
      : platform::MKLDNNHandlerT<T, dnnl::convolution_forward,
                                 dnnl::convolution_backward_data,
                                 dnnl::convolution_backward_weights>(
262 263
            dev_ctx, dev_ctx.GetEngine(), cpu_place,
            platform::CreateKey(dev_ctx, framework::vectorize(in->dims()),
264
                                unique_name)) {
265 266
    if (!this->isBwdCached()) {
      PADDLE_ENFORCE_EQ(
A
Adam Osewski 已提交
267
          in->layout(), framework::DataLayout::kMKLDNN,
268 269
          platform::errors::InvalidArgument(
              "The input tensor's layout should be %d, but got %d.",
A
Adam Osewski 已提交
270
              framework::DataLayout::kMKLDNN, in->layout()));
271 272 273 274 275
      PADDLE_ENFORCE_NE(in->format(), MKLDNNMemoryFormat::undef,
                        platform::errors::InvalidArgument(
                            "Got wrong format for Input tensor."));

      PADDLE_ENFORCE_EQ(
A
Adam Osewski 已提交
276
          filter->layout(), framework::DataLayout::kMKLDNN,
277 278
          platform::errors::InvalidArgument(
              "The filter tensor's layout should be %d, but got %d.",
A
Adam Osewski 已提交
279
              framework::DataLayout::kMKLDNN, filter->layout()));
280 281 282 283 284
      PADDLE_ENFORCE_NE(filter->format(), MKLDNNMemoryFormat::undef,
                        platform::errors::InvalidArgument(
                            "Got wrong format for Filter tensor."));

      PADDLE_ENFORCE_EQ(
A
Adam Osewski 已提交
285
          out_grad->layout(), framework::DataLayout::kMKLDNN,
286 287
          platform::errors::InvalidArgument(
              "The output_grad tensor's layout should be %d, but got %d.",
A
Adam Osewski 已提交
288
              framework::DataLayout::kMKLDNN, out_grad->layout()));
289 290 291 292 293
      PADDLE_ENFORCE_NE(out_grad->format(), MKLDNNMemoryFormat::undef,
                        platform::errors::InvalidArgument(
                            "Wrong format set for output_grad tensor"));

      PADDLE_ENFORCE_EQ(
294
          ctx.Attr<bool>("is_test"), false,
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
          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();
      auto data_dims = framework::slice_ddim(input_dims, 2, input_dims.size());
      auto filter_dims = filter->dims();
      auto filter_data_dims =
          framework::slice_ddim(filter_dims, 2, filter_dims.size());
      auto ksize = framework::vectorize(filter_data_dims);

A
Adam Osewski 已提交
315 316
      std::string padding_algorithm =
          ctx.Attr<std::string>("padding_algorithm");
317 318 319 320 321 322
      UpdatePaddingAndDilation(&paddings, &dilations, padding_algorithm,
                               data_dims, strides, ksize);

      auto src_tz = framework::vectorize(in->dims());
      auto weights_tz = framework::vectorize(filter->dims());

A
Adam Osewski 已提交
323
      int groups = ctx.Attr<int>("groups");
324 325
      int g = std::max(groups, 1);
      platform::GetGroupConvWeightsTz(weights_tz, g);
A
Adam Osewski 已提交
326
      auto dst_tz = framework::vectorize(out_grad->dims());
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

      /* 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);
      std::transform(dilations.begin(), dilations.end(), dilations.begin(),
                     [](int64_t i) { return i - 1; });
351
      const dnnl::memory::dims dilations_dims = dilations;
352

353
      const dnnl::memory::dims stride_dims = strides;
354
      // Recreating FWD PD. For training there are no post ops in convolution
355
      dnnl::primitive_attr conv_attr;
356 357
      if (bias) {
        auto bias_tz = framework::vectorize(bias->dims());
358
        dnnl::memory::desc bias_md;
A
Adam Osewski 已提交
359 360
        if (platform::is_int8<T>()) {
          bias_md = platform::MKLDNNMemDesc(
361
              bias_tz, dnnl::memory::data_type::s32, MKLDNNMemoryFormat::x);
A
Adam Osewski 已提交
362 363
        } else {
          bias_md = platform::MKLDNNMemDesc(
364
              bias_tz, dnnl::memory::data_type::f32, MKLDNNMemoryFormat::x);
A
Adam Osewski 已提交
365
        }
366

367
        this->AcquireForwardPrimitiveDescriptor(
368
            conv_attr, dnnl::prop_kind::forward_training,
369 370 371 372
            dnnl::algorithm::convolution_direct, src_md, weights_md, bias_md,
            dst_md, stride_dims, dilations_dims, mkldnn_paddings[0],
            mkldnn_paddings[1]);
      } else {
373
        this->AcquireForwardPrimitiveDescriptor(
374
            conv_attr, dnnl::prop_kind::forward_training,
375 376 377 378 379
            dnnl::algorithm::convolution_direct, src_md, weights_md, dst_md,
            stride_dims, dilations_dims, mkldnn_paddings[0],
            mkldnn_paddings[1]);
      }

380
      this->AcquireBackwardPrimitiveDescriptor(
381
          dnnl::algorithm::convolution_direct, diff_src_md, weights_md,
382 383 384
          diff_dst_md, strides, dilations_dims, mkldnn_paddings[0],
          mkldnn_paddings[1]);

385
      this->AcquireBackwardWeightsPrimitiveDescriptor(
386
          dnnl::algorithm::convolution_direct, src_md, diff_weights_md,
387 388 389 390 391
          diff_dst_md, strides, dilations_dims, mkldnn_paddings[0],
          mkldnn_paddings[1]);
    }
  }

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
  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");
    const auto& weights_tz = framework::vectorize(filter->dims());
    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;
  }

A
Adam Osewski 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
  std::tuple<float, std::vector<float>> get_int8_scales(
      const framework::ExecutionContext& ctx) const {
    const auto* filter = ctx.Input<Tensor>("Filter");
    const auto& weights_tz = framework::vectorize(filter->dims());

    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;
    auto scale_out_data =
        force_fp32_output ? 1.0f : ctx.Attr<float>("Scale_out");
    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])));
    }

    return std::make_tuple(sum_scale, output_shift_scale);
  }

474
  dnnl::primitive_attr CreatePostOps(
475 476 477
      std::string fuse_activation, float fuse_alpha, float fuse_beta,
      bool fuse_residual_conn, const std::vector<float> output_shift_scale = {},
      float sum_scale = 1.0f) {
478 479
    dnnl::primitive_attr conv_attr;
    dnnl::post_ops post_operations;
480 481 482 483
    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);
    }
484

485 486 487 488 489 490 491 492 493 494
    // 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);
    }
    // Fusion with ReLU layer is executed through the PostOps feature. Create a
    // PostOps object and configure it to execute an eltwise relu operation.
495
    constexpr float scale = 1.0f;
496
    if (fuse_activation == "relu" || fuse_activation == "leaky_relu") {
497
      post_operations.append_eltwise(scale, dnnl::algorithm::eltwise_relu,
498 499
                                     fuse_alpha, fuse_beta);
    } else if (fuse_activation == "relu6") {
500 501
      post_operations.append_eltwise(
          scale, dnnl::algorithm::eltwise_bounded_relu, fuse_alpha, fuse_beta);
502
    } else if (fuse_activation == "swish") {
503
      post_operations.append_eltwise(scale, dnnl::algorithm::eltwise_swish,
504
                                     fuse_alpha, fuse_beta);
J
jakpiase 已提交
505
    } else if (fuse_activation == "hard_swish") {
506 507
      post_operations.append_eltwise(scale, dnnl::algorithm::eltwise_hardswish,
                                     fuse_alpha, fuse_beta);
508
    } else if (fuse_activation == "hard_sigmoid") {
509
      post_operations.append_eltwise(scale, dnnl::algorithm::eltwise_linear,
510
                                     fuse_alpha, fuse_beta);
511 512
      post_operations.append_eltwise(scale, dnnl::algorithm::eltwise_clip, 0.0f,
                                     1.0f);
513 514 515 516
    }
    conv_attr.set_post_ops(post_operations);
    return conv_attr;
  }
517

518
  std::shared_ptr<dnnl::memory>
519 520 521 522 523 524 525 526 527 528 529 530
  AcquireWeightsMemoryWithReorderFromDataPrimitive(
      const framework::Tensor* filter, const int groups, const bool is_conv3d) {
    const K* filter_data = filter->data<K>();
    auto weights_tz = framework::vectorize(filter->dims());
    platform::GetGroupConvWeightsTz(weights_tz, groups);

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

    return this->AcquireMemoryWithReorder(
        user_src_md, this->bwd_pd_->weights_desc(),
A
Adam Osewski 已提交
531
        platform::to_void_cast<K>(filter_data), "@weights_mem_d_p", false);
532 533
  }

534
  std::shared_ptr<dnnl::memory> AcquireSrcMemoryWithReorder(
535
      const framework::Tensor* input) {
536 537 538 539
    return this->AcquireMemoryWithReorderPrimitive(
        input, "@src_mem_p_user", "@src_mem_p_target", "@src_mem_p",
        this->fwd_pd_->src_desc());
  }
540

541
  std::shared_ptr<dnnl::memory> AcquireSrcMemoryWithReorderFromWeightsPrimitive(
542 543 544 545 546 547
      const framework::Tensor* input) {
    return this->AcquireMemoryWithReorderPrimitive(
        input, "@src_mem_w_p_user", "@src_mem_w_p_target", "@src_mem_w_p",
        this->bwd_w_pd_->src_desc());
  }

548
  std::shared_ptr<dnnl::memory>
549 550 551 552 553 554 555
  AcquireDiffDstMemoryWithReorderFromWeightsPrimitive(
      const framework::Tensor* out_grad) {
    return this->AcquireMemoryWithReorderPrimitive(
        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());
  }

556
  std::shared_ptr<dnnl::memory>
557 558 559 560 561 562 563
  AcquireDiffDstMemoryWithReorderMemoryFromDataPrimitive(
      const framework::Tensor* out_grad) {
    return this->AcquireMemoryWithReorderPrimitive(
        out_grad, "@diff_dst_mem_p_user", "@diff_dst_mem_p_target",
        "@diff_dst_mem_p", this->bwd_pd_->diff_dst_desc());
  }

564
  std::shared_ptr<dnnl::memory> AcquireMemoryWithReorderPrimitive(
565 566
      const framework::Tensor* in_mem, const char* key_mem_user,
      const char* key_mem_target, const char* key_mem,
567
      const dnnl::memory::desc& mem_md) {
568 569 570 571 572 573 574 575
    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) {
      auto user_mem_md = platform::MKLDNNMemDesc(
          framework::vectorize(in_mem->dims()),
          platform::MKLDNNGetDataType<T>(), in_mem->format());
576
      return this->AcquireMemoryWithReorder(
577
          user_mem_md, mem_md, platform::to_void_cast<T>(in_mem_data), key_mem);
578
    } else {
579 580
      const std::string target_key_suffix{key_mem_target};
      const auto target_mem_p = this->AcquireMemory(target_key_suffix);
A
Adam Osewski 已提交
581
      user_mem_p->set_data_handle(platform::to_void_cast<T>(in_mem_data));
582
      if (user_mem_p != target_mem_p) {
583
        this->AcquireReorder(user_mem_p, target_mem_p);
584
      }
585
      return target_mem_p;
586
    }
587 588
  }

589
  std::shared_ptr<dnnl::memory> AcquireWeightsMemoryWithReorder(
590
      const framework::Tensor* filter, const int groups, const bool is_conv3d,
591 592
      const bool is_test, const std::vector<float>& scale_data = {1.0f},
      int mask = 0) {
593 594 595
    // 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");
596
    if (is_test && weights_mem_p) {
597 598
      return weights_mem_p;
    } else {
599
      const K* filter_data = filter->data<K>();
600
      auto weights_tz = framework::vectorize(filter->dims());
601
      platform::GetGroupConvWeightsTz(weights_tz, groups);
602 603

      auto user_src_md = platform::MKLDNNMemDesc(
604
          weights_tz, platform::MKLDNNGetDataType<K>(),
605 606 607 608
          GetWeightsFormat(filter->format(), groups, is_conv3d));

      return this->AcquireMemoryWithReorder(
          user_src_md, this->fwd_pd_->weights_desc(),
609 610
          platform::to_void_cast<K>(filter_data), "@weights_mem_p", is_test, {},
          scale_data, mask);
611
    }
612
  }
613

614
  std::shared_ptr<dnnl::memory> AcquireBiasMemoryWithReorder(
615
      const framework::Tensor* bias, const bool is_test,
A
Adam Osewski 已提交
616
      const std::vector<float>& scale_data = {1.0f}, int mask = 0) {
617
    auto bias_mem_p = this->AcquireMemory("@bias_mem_p_target");
618
    if (is_test && bias_mem_p) {
619 620 621 622 623 624 625 626
      return bias_mem_p;
    } else {
      const K* bias_data = bias->data<K>();
      auto user_bias_md = platform::MKLDNNMemDesc(
          framework::vectorize(bias->dims()), platform::MKLDNNGetDataType<K>(),
          MKLDNNMemoryFormat::x);

      return this->AcquireMemoryWithReorder(
A
Adam Osewski 已提交
627
          user_bias_md, this->fwd_pd_->bias_desc(),
628
          platform::to_void_cast<K>(bias_data), "@bias_mem_p", is_test, {},
A
Adam Osewski 已提交
629
          scale_data, mask);
630
    }
631
  }
632

633
  std::shared_ptr<dnnl::memory> AcquireResidualMemory(
634
      const framework::Tensor* residual_param) {
635 636
    void* residual_data =
        residual_param->type() == framework::DataTypeTrait<T_out>::DataType()
A
Adam Osewski 已提交
637 638
            ? platform::to_void_cast<T_out>(residual_param->data<T_out>())
            : platform::to_void_cast<T>(residual_param->data<T>());
639 640 641 642 643 644 645 646 647
    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(
          framework::vectorize(residual_param->dims()),
          framework::ToMKLDNNDataType(residual_param->type()),
          residual_param->format());
648

649 650 651
      return this->AcquireMemoryFromPrimitive(user_residual_md, residual_data,
                                              "@user_residual_data_mem_p");
    }
652 653
  }

654
  std::shared_ptr<dnnl::memory> AcquireDstMemoryWithResidual(
655 656 657 658 659
      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);
660
      dst_memory_p = this->template AcquireDstMemory<T_out>(output);
661
      this->AcquireReorder(residual_memory_p, dst_memory_p);
662 663 664 665 666
    } else {
      // Changing ShareDataWith to TensorCopy results in performance drop
      // on ResNet architectures
      // (https://github.com/PaddlePaddle/Paddle/issues/22964)
      output->ShareDataWith(*residual_param);
667
      dst_memory_p = this->template AcquireDstMemory<T_out>(output);
668 669 670 671 672
    }
    return dst_memory_p;
  }
};

A
Adam Osewski 已提交
673 674
}  // anonymous namespace

675
template <typename T, typename K>
A
Adam Osewski 已提交
676
class ConvMKLDNNOpKernel : public framework::OpKernel<T> {
677
 public:
A
Adam Osewski 已提交
678
  void Compute(const framework::ExecutionContext& ctx) const override {
679
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
A
Adam Osewski 已提交
680
                      platform::errors::PreconditionNotMet(
681 682 683
                          "Operator DNNL Conv must use CPUPlace"));
    bool is_INT8 =
        std::is_same<T, int8_t>::value || std::is_same<T, uint8_t>::value;
684 685 686 687 688 689 690 691
    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");
    auto dst_dt =
        GetDstType(is_INT8, is_BFLOAT16, force_fp32_output, fuse_activation,
                   fuse_residual_conn, residual_param);
692
    if (!is_INT8) {
693
      if (dst_dt == dnnl::memory::data_type::f32) {
694
        ComputeFP32<float>(ctx);
695
      } else if (dst_dt == dnnl::memory::data_type::bf16) {
696 697
        ComputeFP32<platform::bfloat16>(ctx);
      }
698
    } else {
699
      if (dst_dt == dnnl::memory::data_type::f32) {
700
        ComputeINT8<float>(ctx);
701
      } else if (dst_dt == dnnl::memory::data_type::u8) {
702
        ComputeINT8<uint8_t>(ctx);
703
      } else if (dst_dt == dnnl::memory::data_type::s8) {
704 705
        ComputeINT8<int8_t>(ctx);
      }
706
    }
707
  }
708

709
  template <typename T_out>
A
Adam Osewski 已提交
710
  void ComputeFP32(const framework::ExecutionContext& ctx) const {
711
    auto& dev_ctx =
A
Adam Osewski 已提交
712
        ctx.template device_context<platform::MKLDNNDeviceContext>();
713
    const auto& mkldnn_engine = dev_ctx.GetEngine();
714

715
    const bool is_test = ctx.Attr<bool>("is_test");
716 717
    const bool is_conv3d = ctx.Attr<std::vector<int>>("strides").size() == 3U;
    const bool fuse_residual_conn = ctx.Attr<bool>("fuse_residual_connection");
718

719 720 721 722 723
    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");
724

725
    ConvMKLDNNHandlerT<T, K, T_out> handler(
726 727
        ctx, dev_ctx, mkldnn_engine, ctx.GetPlace(), input, filter, bias,
        output, ctx.InputName("Input") + ctx.InputName("Filter"));
728

729
    auto src_memory_p = handler.AcquireSrcMemoryWithReorder(input);
730

731
    auto weights_memory_p = handler.AcquireWeightsMemoryWithReorder(
732
        filter, ctx.Attr<int>("groups"), is_conv3d, is_test);
733

734 735 736
    std::shared_ptr<dnnl::memory> dst_memory_p;
    if (fuse_residual_conn) {
      auto* residual_param = ctx.Input<Tensor>("ResidualData");
737
      dst_memory_p =
738 739
          handler.AcquireDstMemoryWithResidual(output, residual_param);
    } else {
740
      dst_memory_p = handler.template AcquireDstMemory<T_out>(output);
741
    }
742

743
    auto conv_p = handler.AcquireForwardPrimitive();
A
Adam 已提交
744

745
    std::unordered_map<int, dnnl::memory> args = {
746 747 748
        {DNNL_ARG_SRC, *src_memory_p},
        {DNNL_ARG_WEIGHTS, *weights_memory_p},
        {DNNL_ARG_DST, *dst_memory_p}};
A
Adam 已提交
749

750
    if (bias) {
751
      auto bias_memory_p = handler.AcquireBiasMemoryWithReorder(bias, is_test);
752
      args.insert({DNNL_ARG_BIAS, *bias_memory_p});
753
    }
754

755
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
756
    conv_p->execute(astream, args);
A
Adam 已提交
757
    astream.wait();
758

A
Adam Osewski 已提交
759 760
    output->set_layout(framework::DataLayout::kMKLDNN);
    output->set_format(platform::GetMKLDNNFormat(*dst_memory_p));
761
  }
762

763
  template <typename T_out>
A
Adam Osewski 已提交
764
  void ComputeINT8(const framework::ExecutionContext& ctx) const {
765
    auto& dev_ctx =
A
Adam Osewski 已提交
766
        ctx.template device_context<platform::MKLDNNDeviceContext>();
767 768
    const auto& mkldnn_engine = dev_ctx.GetEngine();

A
Adam Osewski 已提交
769 770 771 772 773
    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;
774

775 776
    bool unsigned_output =
        (fuse_activation == "relu" || fuse_activation == "relu6");
777 778
    bool need_s8_to_u8 = false;

A
Adam Osewski 已提交
779 780 781 782 783 784 785 786
    PADDLE_ENFORCE_NE(
        is_conv3d, true,
        platform::errors::Unimplemented(
            "OneDNN int8 convolution does not support 3D inputs currently"));
    PADDLE_ENFORCE_EQ(
        fuse_residual_conn && force_fp32_output, false,
        platform::errors::Unimplemented(
            "residual fusion does not support force output with fp32"));
A
Adam 已提交
787

A
Adam Osewski 已提交
788 789 790 791
    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");
792

A
Adam Osewski 已提交
793 794 795
    ConvMKLDNNHandlerT<T, K, T_out> handler(
        ctx, dev_ctx, mkldnn_engine, ctx.GetPlace(), input, filter, bias,
        output, ctx.InputName("Input") + ctx.InputName("Filter"));
796

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

A
Adam Osewski 已提交
799 800 801 802
    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");
803
    const bool& is_test = ctx.Attr<bool>("is_test");
A
Adam Osewski 已提交
804 805 806
    int mask_reorder =
        is_multi_channel ? ((groups != 1) ? (1 << 1) + (1 << 0) : 1 << 0) : 0;
    auto weights_memory_p = handler.AcquireWeightsMemoryWithReorder(
807
        filter, groups, false, is_test, scale_weights_data, mask_reorder);
808

A
Adam Osewski 已提交
809 810 811
    std::shared_ptr<dnnl::memory> dst_memory_p;
    if (fuse_residual_conn) {
      auto* residual_param = ctx.Input<Tensor>("ResidualData");
812
      PADDLE_ENFORCE_EQ(
A
Adam Osewski 已提交
813 814 815 816 817 818
          output->dims(), residual_param->dims(),
          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 .",
              output->dims().size(), residual_param->dims().size()));
819
      dst_memory_p =
A
Adam Osewski 已提交
820 821
          handler.AcquireDstMemoryWithResidual(output, residual_param);
      need_s8_to_u8 = (platform::MKLDNNGetDataType<T_out>() ==
822
                       dnnl::memory::data_type::s8) &&
A
Adam Osewski 已提交
823 824 825 826
                      unsigned_output;
    } else {
      dst_memory_p = handler.template AcquireDstMemory<T_out>(output);
    }
L
lidanqing 已提交
827

A
Adam Osewski 已提交
828 829 830
    auto conv_p = handler.AcquireForwardPrimitive();

    std::unordered_map<int, dnnl::memory> args = {
831 832 833
        {DNNL_ARG_SRC, *src_memory_p},
        {DNNL_ARG_WEIGHTS, *weights_memory_p},
        {DNNL_ARG_DST, *dst_memory_p}};
A
Adam 已提交
834

A
Adam Osewski 已提交
835
    if (bias) {
836
      auto p_scales_tuple = handler.get_int8_bias_scales(ctx);
A
Adam 已提交
837

A
Adam Osewski 已提交
838
      auto bias_memory_p = handler.AcquireBiasMemoryWithReorder(
839 840
          bias, is_test, std::get<1>(*p_scales_tuple),
          std::get<0>(*p_scales_tuple));
841
      args.insert({DNNL_ARG_BIAS, *bias_memory_p});
842
    }
A
Adam Osewski 已提交
843 844 845

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

848
    if (need_s8_to_u8) {
X
xiaolil1 已提交
849 850
      output->mutable_data<uint8_t>(ctx.GetPlace());
    }
A
Adam Osewski 已提交
851 852 853

    output->set_layout(framework::DataLayout::kMKLDNN);
    output->set_format(platform::GetMKLDNNFormat(*dst_memory_p));
854
  }
855 856
};

857
template <typename T, typename K>
A
Adam Osewski 已提交
858
class ConvMKLDNNGradOpKernel : public framework::OpKernel<T> {
859
 public:
A
Adam Osewski 已提交
860
  void Compute(const framework::ExecutionContext& ctx) const override {
861
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()), true,
A
Adam Osewski 已提交
862
                      platform::errors::PreconditionNotMet(
863
                          "Operator DNNL ConvGrad must use CPUPlace"));
864 865
    auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
866 867 868 869
    const auto& mkldnn_engine = dev_ctx.GetEngine();

    const Tensor* input = ctx.Input<Tensor>("Input");
    const Tensor* filter = ctx.Input<Tensor>("Filter");
870 871
    const Tensor* bias =
        ctx.HasInput("Bias") ? ctx.Input<Tensor>("Bias") : nullptr;
872 873 874 875 876 877 878
    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;

879 880 881 882 883
    // TODO(jczaja): Are all tensors really needed?
    ConvMKLDNNHandlerT<T, K, T> handler(
        ctx, dev_ctx, ctx.GetPlace(), input, filter, bias, output_grad,
        filter_grad, input_grad,
        ctx.InputName("Input") + ctx.InputName("Filter"));
884 885

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

888 889 890 891 892 893
    if (filter_grad) {
      auto src_memory_p =
          handler.AcquireSrcMemoryWithReorderFromWeightsPrimitive(input);
      auto diff_dst_memory_p =
          handler.AcquireDiffDstMemoryWithReorderFromWeightsPrimitive(
              output_grad);
894

895 896
      // For convoluition with groups write filter grad into
      // oneDNN buffer and then we reorder it into filter_grad tensor
897
      int g = std::max(ctx.Attr<int>("groups"), 1);
898
      auto diff_weights_memory_p =
899 900
          g > 1 ? handler.AcquireDiffWeightsMemory()
                : handler.AcquireDiffWeightsMemory(filter_grad);
901

902
      auto conv_bwd_weights_p = handler.AcquireBackwardWeightsPrimitive();
903

A
Adam 已提交
904 905
      // TODO(grygielski) why no bias_diff?
      conv_bwd_weights_p->execute(
906 907 908
          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 已提交
909
      astream.wait();
910

A
Adam Osewski 已提交
911
      filter_grad->set_layout(framework::DataLayout::kMKLDNN);
912 913
      // in OneDNN groups in convolution are treated as separate dimension
      // which is not the case in paddlepaddle
A
Adam Osewski 已提交
914
      auto filter_fmt = platform::GetMKLDNNFormat(*diff_weights_memory_p);
915 916 917 918

      // For convolution with groups convert from blocked to NCHW
      // otherwise there will be problems in next operators working on this data
      if (g > 1) {
919
        dnnl::memory::data_type in_type =
A
Adam Osewski 已提交
920
            framework::ToMKLDNNDataType(filter->type());
921 922
        // for 3d conv with groups (six dimensional data reorder to goidhw)
        // for 2d conv with groups (five dimensional data reorder to goihw)
A
Adam Osewski 已提交
923
        // auto weights_tz = framework::vectorize(filter->dims());
924 925

        auto weights_tz = diff_weights_memory_p->get_desc().dims();
926 927 928
        dnnl::memory::format_tag out_format =
            weights_tz.size() == 6 ? dnnl::memory::format_tag::goidhw
                                   : dnnl::memory::format_tag::goihw;
929 930
        platform::ReorderMKLDNNHandler handler(weights_tz, filter->type(),
                                               in_type, mkldnn_engine);
931 932 933 934 935 936
        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);

937 938 939 940 941 942 943
        {
          platform::RecordEvent record_reorder("int_reorder",
                                               platform::EventRole::kUniqueOp);
          reorder_p->execute(astream, *diff_weights_memory_p,
                             *reorder_dst_memory_p);
          astream.wait();
        }
944 945 946 947

        // 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)
948 949 950
        dnnl::memory::format_tag target_format =
            weights_tz.size() == 6 ? dnnl::memory::format_tag::oidhw
                                   : dnnl::memory::format_tag::oihw;
951 952 953 954
        filter_grad->set_format(target_format);
      } else {
        filter_grad->set_format(filter_fmt);
      }
955 956
    }
    if (input_grad) {
957 958 959 960
      auto weights_memory_p =
          handler.AcquireWeightsMemoryWithReorderFromDataPrimitive(
              filter, ctx.Attr<int>("groups"),
              ctx.Attr<std::vector<int>>("strides").size() == 3U);
961

962 963 964 965
      auto diff_dst_memory_p =
          handler.AcquireDiffDstMemoryWithReorderMemoryFromDataPrimitive(
              output_grad);
      auto diff_src_memory_p = handler.AcquireDiffSrcMemory(input_grad);
966

967
      auto conv_bwd_data_p = handler.AcquireBackwardPrimitive();
968

A
Adam 已提交
969
      conv_bwd_data_p->execute(astream,
970 971 972
                               {{DNNL_ARG_WEIGHTS, *weights_memory_p},
                                {DNNL_ARG_DIFF_DST, *diff_dst_memory_p},
                                {DNNL_ARG_DIFF_SRC, *diff_src_memory_p}});
A
Adam 已提交
973
      astream.wait();
974

A
Adam Osewski 已提交
975 976
      input_grad->set_layout(framework::DataLayout::kMKLDNN);
      input_grad->set_format(platform::GetMKLDNNFormat(*diff_src_memory_p));
977
    }
X
xiaolil1 已提交
978
  }
979
};
980

981 982 983 984 985
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

X
Xin Pan 已提交
986 987 988
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv2d, MKLDNN,
                                    ::paddle::platform::CPUPlace, FP32,
                                    ops::kConvMKLDNNFP32,
989
                                    ops::ConvMKLDNNOpKernel<float, float>);
990

991 992 993 994
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(
    conv2d, MKLDNN, ::paddle::platform::CPUPlace, BF16, ops::kConvMKLDNNFP32,
    ops::ConvMKLDNNOpKernel<paddle::platform::bfloat16, float>);

995 996
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv2d, MKLDNN,
                                    ::paddle::platform::CPUPlace, U8,
997
                                    ops::kConvMKLDNNINT8,
998
                                    ops::ConvMKLDNNOpKernel<uint8_t, float>);
999 1000 1001

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv2d, MKLDNN,
                                    ::paddle::platform::CPUPlace, S8,
1002
                                    ops::kConvMKLDNNINT8,
1003
                                    ops::ConvMKLDNNOpKernel<int8_t, float>);
X
Xin Pan 已提交
1004 1005 1006 1007

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv2d_grad, MKLDNN,
                                    ::paddle::platform::CPUPlace, FP32,
                                    ops::kConvMKLDNNFP32,
1008
                                    ops::ConvMKLDNNGradOpKernel<float, float>);
1009 1010 1011 1012

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv3d, MKLDNN,
                                    ::paddle::platform::CPUPlace, FP32,
                                    ops::kConvMKLDNNFP32,
1013
                                    ops::ConvMKLDNNOpKernel<float, float>);
1014 1015 1016 1017

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(conv3d_grad, MKLDNN,
                                    ::paddle::platform::CPUPlace, FP32,
                                    ops::kConvMKLDNNFP32,
1018
                                    ops::ConvMKLDNNGradOpKernel<float, float>);