conv_mkldnn_op.cc 36.8 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
#include "paddle/phi/core/expect.h"
22

23 24
#include "paddle/phi/core/visit_type.h"

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

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

39 40 41 42 43 44 45
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 phi::DenseTensor* residual_param) {
46
  auto dst_dt = dnnl::memory::data_type::f32;
47 48
  if (is_int8) {
    dst_dt = (fuse_activation == "relu" || fuse_activation == "relu6")
49 50
                 ? dnnl::memory::data_type::u8
                 : dnnl::memory::data_type::s8;
51
    if (force_fp32_output) {
52
      dst_dt = dnnl::memory::data_type::f32;
53
    }
54
    if (fuse_residual_conn && residual_param) {
55 56
      auto residual_dt = framework::ToMKLDNNDataType(
          framework::TransToProtoVarType(residual_param->dtype()));
57
      if (dst_dt != residual_dt) dst_dt = residual_dt;
58
    }
59 60
  } else {
    if (!force_fp32_output && is_bfloat16) {
61
      dst_dt = dnnl::memory::data_type::bf16;
62
      if (fuse_residual_conn && residual_param) {
63 64
        dst_dt = framework::ToMKLDNNDataType(
            framework::TransToProtoVarType(residual_param->dtype()));
65 66
      }
    }
67 68 69 70
  }
  return dst_dt;
}

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

105
      PADDLE_ENFORCE_EQ(
106
          filter->layout(),
107
          phi::DataLayout::kMKLDNN,
108 109
          platform::errors::InvalidArgument(
              "The Filter tensor's layout should be %d, but got %d.",
110
              phi::DataLayout::kMKLDNN,
111
              filter->layout()));
K
Krzysztof Binias 已提交
112

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

128
      PADDLE_ENFORCE_GE(
129 130
          filter->dims().size(),
          4,
131 132 133 134 135
          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(
136 137
          filter->dims().size(),
          5,
138 139 140 141
          platform::errors::InvalidArgument(
              "Filter must be with 4 or 5 dimensions, i.e. OIHW or "
              "OIDHW, but got dimension = %d .",
              filter->dims().size()));
142

143 144
      if (bias) {
        PADDLE_ENFORCE_EQ(
145
            bias->layout(),
146
            phi::DataLayout::kMKLDNN,
147 148
            platform::errors::InvalidArgument(
                "The Bias tensor's layout should be %d, but got %d.",
149
                phi::DataLayout::kMKLDNN,
150
                bias->layout()));
151

152 153
        PADDLE_ENFORCE_EQ(bias->dims().size(),
                          1,
154 155 156 157 158
                          platform::errors::InvalidArgument(
                              "Bias must only have 1 dimension, "
                              "i.e. X, but got dimension = %d .",
                              bias->dims().size()));
      }
F
FDInSky 已提交
159

160 161 162
      const int groups = ctx.Attr<int>("groups");
      const std::string padding_algorithm =
          ctx.Attr<std::string>("padding_algorithm");
F
FDInSky 已提交
163

164
      const auto input_dims = input->dims();
165
      const auto data_dims = phi::slice_ddim(input_dims, 2, input_dims.size());
166 167
      const auto filter_dims = filter->dims();
      const auto filter_data_dims =
168
          phi::slice_ddim(filter_dims, 2, filter_dims.size());
169

170
      const auto ksize = phi::vectorize(filter_data_dims);
171
      const bool is_test = ctx.Attr<bool>("is_test");
172

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

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

179 180 181
      auto dilations_temp = ctx.Attr<std::vector<int>>("dilations");
      std::vector<int64_t> dilations(begin(dilations_temp),
                                     end(dilations_temp));
A
Adam 已提交
182

183 184
      UpdatePaddingAndDilation(
          &paddings, &dilations, padding_algorithm, data_dims, strides, ksize);
A
Adam 已提交
185

186 187 188 189
      std::transform(
          dilations.begin(), dilations.end(), dilations.begin(), [](int64_t i) {
            return i - 1;
          });
190

191
      const auto src_tz = phi::vectorize(input->dims());
192

193
      auto weights_tz = phi::vectorize(filter->dims());
194
      platform::GetGroupConvWeightsTz(weights_tz, groups);
195

196
      const auto dst_tz = phi::vectorize(output->dims());
197

198
      const dnnl::memory::dims stride_dims = strides;
199
      const auto mkldnn_paddings = platform::ToMkldnnPadding(paddings);
200
      const dnnl::memory::dims dilations_dims = dilations;
A
Adam 已提交
201

202 203 204 205
      /* 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
       */
206
      auto chosen_memory_format = MKLDNNMemoryFormat::any;
207
      auto data_type = dnnl::memory::data_type::f32;
208 209
      if (ctx.Attr<std::string>("mkldnn_data_type") == "bfloat16" ||
          std::is_same<T_out, platform::bfloat16>::value)
210
        data_type = dnnl::memory::data_type::bf16;
211

212
      dnnl::memory::desc src_md, weights_md;
A
Adam Osewski 已提交
213 214
      if (platform::is_int8<T>()) {
        src_md = platform::MKLDNNMemDesc(
215 216 217
            src_tz,
            framework::ToMKLDNNDataType(
                framework::TransToProtoVarType(input->dtype())),
A
Adam Osewski 已提交
218 219
            chosen_memory_format);
        weights_md = platform::MKLDNNMemDesc(
220
            weights_tz, dnnl::memory::data_type::s8, chosen_memory_format);
A
Adam Osewski 已提交
221 222 223
      } else {
        src_md =
            platform::MKLDNNMemDesc(src_tz, data_type, chosen_memory_format);
224 225
        weights_md = platform::MKLDNNMemDesc(
            weights_tz, data_type, MKLDNNMemoryFormat::any);
A
Adam Osewski 已提交
226 227
      }

228
      const auto dst_md = platform::MKLDNNMemDesc(
229
          dst_tz, platform::MKLDNNGetDataType<T_out>(), chosen_memory_format);
230 231
      const auto fwd_prop_kind = is_test ? dnnl::prop_kind::forward_inference
                                         : dnnl::prop_kind::forward_training;
232

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

235
      if (bias) {
236
        auto bias_tz = phi::vectorize(bias->dims());
237
        dnnl::memory::desc bias_md;
A
Adam Osewski 已提交
238 239
        if (platform::is_int8<T>()) {
          bias_md = platform::MKLDNNMemDesc(
240
              bias_tz, dnnl::memory::data_type::s32, MKLDNNMemoryFormat::x);
A
Adam Osewski 已提交
241
        } else {
242 243
          bias_md = platform::MKLDNNMemDesc(
              bias_tz, data_type, MKLDNNMemoryFormat::x);
A
Adam Osewski 已提交
244
        }
245

246
        this->AcquireForwardPrimitiveDescriptor(
247 248 249 250 251 252 253 254 255 256 257
            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]);
258
      } else {
259
        this->AcquireForwardPrimitiveDescriptor(
260 261 262 263 264 265 266 267 268 269
            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]);
270 271 272
      }
    }
  }
273

274 275
  ConvMKLDNNHandlerT(const framework::ExecutionContext& ctx,
                     const platform::MKLDNNDeviceContext& dev_ctx,
276
                     platform::Place cpu_place,
277 278 279 280 281 282
                     const phi::DenseTensor* in,
                     const phi::DenseTensor* filter,
                     const phi::DenseTensor* bias,
                     const phi::DenseTensor* out_grad,
                     phi::DenseTensor* filter_grad,
                     phi::DenseTensor* in_x_grad,
283 284 285
                     const std::string& unique_name)
      : platform::MKLDNNHandlerT<T,
                                 dnnl::convolution_forward,
286 287
                                 dnnl::convolution_backward_data,
                                 dnnl::convolution_backward_weights>(
288 289 290 291 292
            dev_ctx,
            dev_ctx.GetEngine(),
            cpu_place,
            platform::CreateKey(
                dev_ctx, phi::vectorize(in->dims()), unique_name)) {
293
    if (unlikely(!this->isBwdCached())) {
294
      PADDLE_ENFORCE_EQ(
295
          in->layout(),
296
          phi::DataLayout::kMKLDNN,
297 298
          platform::errors::InvalidArgument(
              "The input tensor's layout should be %d, but got %d.",
299
              phi::DataLayout::kMKLDNN,
300
              in->layout()));
301 302

      PADDLE_ENFORCE_EQ(
303
          filter->layout(),
304
          phi::DataLayout::kMKLDNN,
305 306
          platform::errors::InvalidArgument(
              "The filter tensor's layout should be %d, but got %d.",
307
              phi::DataLayout::kMKLDNN,
308
              filter->layout()));
309 310

      PADDLE_ENFORCE_EQ(
311
          out_grad->layout(),
312
          phi::DataLayout::kMKLDNN,
313 314
          platform::errors::InvalidArgument(
              "The output_grad tensor's layout should be %d, but got %d.",
315
              phi::DataLayout::kMKLDNN,
316
              out_grad->layout()));
317 318

      PADDLE_ENFORCE_EQ(
319 320
          ctx.Attr<bool>("is_test"),
          false,
321 322 323 324 325 326 327 328 329 330 331 332 333 334
          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();
335
      auto data_dims = phi::slice_ddim(input_dims, 2, input_dims.size());
336 337
      auto filter_dims = filter->dims();
      auto filter_data_dims =
338 339
          phi::slice_ddim(filter_dims, 2, filter_dims.size());
      auto ksize = phi::vectorize(filter_data_dims);
340

A
Adam Osewski 已提交
341 342
      std::string padding_algorithm =
          ctx.Attr<std::string>("padding_algorithm");
343 344
      UpdatePaddingAndDilation(
          &paddings, &dilations, padding_algorithm, data_dims, strides, ksize);
345

346 347
      auto src_tz = phi::vectorize(in->dims());
      auto weights_tz = phi::vectorize(filter->dims());
348

A
Adam Osewski 已提交
349
      int groups = ctx.Attr<int>("groups");
350 351
      int g = std::max(groups, 1);
      platform::GetGroupConvWeightsTz(weights_tz, g);
352
      auto dst_tz = phi::vectorize(out_grad->dims());
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374

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

381
      const dnnl::memory::dims stride_dims = strides;
382
      // Recreating FWD PD. For training there are no post ops in convolution
383
      dnnl::primitive_attr conv_attr;
384
      if (bias) {
385
        auto bias_tz = phi::vectorize(bias->dims());
386
        dnnl::memory::desc bias_md;
A
Adam Osewski 已提交
387 388
        if (platform::is_int8<T>()) {
          bias_md = platform::MKLDNNMemDesc(
389
              bias_tz, dnnl::memory::data_type::s32, MKLDNNMemoryFormat::x);
A
Adam Osewski 已提交
390 391
        } else {
          bias_md = platform::MKLDNNMemDesc(
392
              bias_tz, dnnl::memory::data_type::f32, MKLDNNMemoryFormat::x);
A
Adam Osewski 已提交
393
        }
394

395
        this->AcquireForwardPrimitiveDescriptor(
396 397 398 399 400 401 402 403 404 405
            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],
406 407
            mkldnn_paddings[1]);
      } else {
408
        this->AcquireForwardPrimitiveDescriptor(
409 410 411 412 413 414 415 416 417
            conv_attr,
            dnnl::prop_kind::forward_training,
            dnnl::algorithm::convolution_direct,
            src_md,
            weights_md,
            dst_md,
            stride_dims,
            dilations_dims,
            mkldnn_paddings[0],
418 419 420
            mkldnn_paddings[1]);
      }

421
      this->AcquireBackwardPrimitiveDescriptor(
422 423 424 425 426 427 428
          dnnl::algorithm::convolution_direct,
          diff_src_md,
          weights_md,
          diff_dst_md,
          strides,
          dilations_dims,
          mkldnn_paddings[0],
429 430
          mkldnn_paddings[1]);

431
      this->AcquireBackwardWeightsPrimitiveDescriptor(
432 433 434 435 436 437 438
          dnnl::algorithm::convolution_direct,
          src_md,
          diff_weights_md,
          diff_dst_md,
          strides,
          dilations_dims,
          mkldnn_paddings[0],
439 440 441 442
          mkldnn_paddings[1]);
    }
  }

443 444 445 446 447 448 449 450 451 452 453 454
  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;

455
    const auto* filter = ctx.Input<phi::DenseTensor>("Filter");
456
    const auto& weights_tz = phi::vectorize(filter->dims());
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
    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;
  }

486
  std::tuple<float, std::vector<float>, float> get_int8_scales(
A
Adam Osewski 已提交
487
      const framework::ExecutionContext& ctx) const {
488
    const auto* filter = ctx.Input<phi::DenseTensor>("Filter");
489
    const auto& weights_tz = phi::vectorize(filter->dims());
A
Adam Osewski 已提交
490 491 492 493 494 495 496 497 498

    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;
499
    bool has_activation = !ctx.Attr<std::string>("fuse_activation").empty();
500 501 502 503 504 505 506
    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 已提交
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
    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])));
    }

528
    return std::make_tuple(sum_scale, output_shift_scale, activation_scale);
A
Adam Osewski 已提交
529 530
  }

531
  dnnl::primitive_attr CreateConvAttrs(const framework::ExecutionContext& ctx) {
532 533
    dnnl::primitive_attr conv_attr;
    dnnl::post_ops post_operations;
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553

    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);
      }
554
    }
555

556 557 558 559 560 561 562 563
    // 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);
    }
564

565
    platform::AppendActivation(ctx, post_operations, activation_scale);
566

567 568 569
    conv_attr.set_post_ops(post_operations);
    return conv_attr;
  }
570

571
  std::shared_ptr<dnnl::memory>
572
  AcquireWeightsMemoryWithReorderFromDataPrimitive(
573
      const phi::DenseTensor* filter, const int groups, const bool is_conv3d) {
574
    const K* filter_data = filter->data<K>();
575
    auto weights_tz = phi::vectorize(filter->dims());
576 577
    platform::GetGroupConvWeightsTz(weights_tz, groups);

578 579 580 581
    auto user_src_md =
        platform::MKLDNNMemDesc(weights_tz,
                                platform::MKLDNNGetDataType<K>(),
                                GetWeightsFormat(groups, is_conv3d));
582 583

    return this->AcquireMemoryWithReorder(
584 585 586 587 588
        user_src_md,
        this->bwd_pd_->weights_desc(),
        platform::to_void_cast<K>(filter_data),
        "@weights_mem_d_p",
        false);
589 590
  }

591
  std::shared_ptr<dnnl::memory> AcquireSrcMemoryWithReorder(
592
      const phi::DenseTensor* input) {
593 594 595 596 597
    return this->AcquireMemoryWithReorderPrimitive(input,
                                                   "@src_mem_p_user",
                                                   "@src_mem_p_target",
                                                   "@src_mem_p",
                                                   this->fwd_pd_->src_desc());
598
  }
599

600
  std::shared_ptr<dnnl::memory> AcquireSrcMemoryWithReorderFromWeightsPrimitive(
601
      const phi::DenseTensor* input) {
602 603 604 605 606
    return this->AcquireMemoryWithReorderPrimitive(input,
                                                   "@src_mem_w_p_user",
                                                   "@src_mem_w_p_target",
                                                   "@src_mem_w_p",
                                                   this->bwd_w_pd_->src_desc());
607 608
  }

609
  std::shared_ptr<dnnl::memory>
610
  AcquireDiffDstMemoryWithReorderFromWeightsPrimitive(
611
      const phi::DenseTensor* out_grad) {
612
    return this->AcquireMemoryWithReorderPrimitive(
613 614 615 616 617
        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());
618 619
  }

620
  std::shared_ptr<dnnl::memory>
621
  AcquireDiffDstMemoryWithReorderMemoryFromDataPrimitive(
622
      const phi::DenseTensor* out_grad) {
623
    return this->AcquireMemoryWithReorderPrimitive(
624 625 626 627 628
        out_grad,
        "@diff_dst_mem_p_user",
        "@diff_dst_mem_p_target",
        "@diff_dst_mem_p",
        this->bwd_pd_->diff_dst_desc());
629 630
  }

631
  std::shared_ptr<dnnl::memory> AcquireMemoryWithReorderPrimitive(
632
      const phi::DenseTensor* in_mem,
633 634 635
      const char* key_mem_user,
      const char* key_mem_target,
      const char* key_mem,
636
      const dnnl::memory::desc& mem_md) {
637 638 639 640 641
    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) {
642
      return this->AcquireMemoryWithReorder(
643 644 645 646
          in_mem->mem_desc(),
          mem_md,
          platform::to_void_cast<T>(in_mem_data),
          key_mem);
647
    } else {
648 649
      const std::string target_key_suffix{key_mem_target};
      const auto target_mem_p = this->AcquireMemory(target_key_suffix);
A
Adam Osewski 已提交
650
      user_mem_p->set_data_handle(platform::to_void_cast<T>(in_mem_data));
651
      if (user_mem_p != target_mem_p) {
652
        this->AcquireReorder(user_mem_p, target_mem_p);
653
      }
654
      return target_mem_p;
655
    }
656 657
  }

658
  std::shared_ptr<dnnl::memory> AcquireWeightsMemoryWithReorder(
659
      const phi::DenseTensor* filter,
660 661 662 663
      const int groups,
      const bool is_conv3d,
      const bool is_test,
      const std::vector<float>& scale_data = {1.0f},
664
      int mask = 0) {
665 666 667
    // 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");
668
    if (is_test && weights_mem_p) {
669
      return weights_mem_p;
670
    } else if (is_test) {
671
      const K* filter_data = filter->data<K>();
672
      auto weights_tz = phi::vectorize(filter->dims());
673
      platform::GetGroupConvWeightsTz(weights_tz, groups);
674

675 676 677 678
      auto user_src_md =
          platform::MKLDNNMemDesc(weights_tz,
                                  platform::MKLDNNGetDataType<K>(),
                                  GetWeightsFormat(groups, is_conv3d));
679 680

      return this->AcquireMemoryWithReorder(
681 682 683 684 685 686 687 688
          user_src_md,
          this->fwd_pd_->weights_desc(),
          platform::to_void_cast<K>(filter_data),
          "@weights_mem_p",
          is_test,
          {},
          scale_data,
          mask);
689 690
    } else {
      const T* filter_data = filter->data<T>();
691
      auto weights_tz = phi::vectorize(filter->dims());
692 693
      platform::GetGroupConvWeightsTz(weights_tz, groups);

694 695 696 697
      auto user_src_md =
          platform::MKLDNNMemDesc(weights_tz,
                                  platform::MKLDNNGetDataType<T>(),
                                  GetWeightsFormat(groups, is_conv3d));
698 699

      return this->AcquireMemoryWithReorder(
700 701 702 703 704 705 706 707
          user_src_md,
          this->fwd_pd_->weights_desc(),
          platform::to_void_cast<T>(filter_data),
          "@weights_mem_p",
          is_test,
          {},
          scale_data,
          mask);
708
    }
709
  }
710

711
  std::shared_ptr<dnnl::memory> AcquireBiasMemoryWithReorder(
712
      const phi::DenseTensor* bias,
713 714 715
      const bool is_test,
      const std::vector<float>& scale_data = {1.0f},
      int mask = 0) {
716
    auto bias_mem_p = this->AcquireMemory("@bias_mem_p_target");
717
    if (is_test && bias_mem_p) {
718 719
      return bias_mem_p;
    } else {
720
      // if K is int8 (weights are int8) then biases are int32
721 722
      using K_Bias = typename std::
          conditional<std::is_same<K, int8_t>::value, int32_t, K>::type;
723 724 725 726 727
      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>();
728 729

      return this->AcquireMemoryWithReorder(
730
          bias->mem_desc(),
731 732 733 734 735 736 737
          this->fwd_pd_->bias_desc(),
          platform::to_void_cast<K_Bias>(bias_data),
          "@bias_mem_p",
          is_test,
          {},
          scale_data,
          mask);
738
    }
739
  }
740

741
  std::shared_ptr<dnnl::memory> AcquireResidualMemory(
742
      const phi::DenseTensor* residual_param) {
743
    void* residual_data =
744 745
        framework::TransToProtoVarType(residual_param->dtype()) ==
                framework::DataTypeTrait<T_out>::DataType()
A
Adam Osewski 已提交
746 747
            ? platform::to_void_cast<T_out>(residual_param->data<T_out>())
            : platform::to_void_cast<T>(residual_param->data<T>());
748 749 750 751 752
    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 {
753 754 755
      return this->AcquireMemoryFromPrimitive(residual_param->mem_desc(),
                                              residual_data,
                                              "@user_residual_data_mem_p");
756
    }
757 758
  }

759
  std::shared_ptr<dnnl::memory> AcquireDstMemoryWithResidual(
760
      phi::DenseTensor* output, const phi::DenseTensor* residual_param) {
761
    std::shared_ptr<dnnl::memory> dst_memory_p;
762
    if (residual_param->mem_desc() != this->fwd_pd_->dst_desc()) {
763
      auto residual_memory_p = this->AcquireResidualMemory(residual_param);
764
      dst_memory_p = this->template AcquireDstMemory<T_out>(output);
765
      this->AcquireReorder(residual_memory_p, dst_memory_p);
766 767 768 769 770
    } else {
      // Changing ShareDataWith to TensorCopy results in performance drop
      // on ResNet architectures
      // (https://github.com/PaddlePaddle/Paddle/issues/22964)
      output->ShareDataWith(*residual_param);
771
      dst_memory_p = this->template AcquireDstMemory<T_out>(output);
772 773 774 775 776
    }
    return dst_memory_p;
  }
};

A
Adam Osewski 已提交
777 778
}  // anonymous namespace

779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
#define PD_VISIT_FLOAT_AND_BF16_TYPES(TYPE, NAME, ...)                    \
  [&] {                                                                   \
    const auto& __dtype__ = TYPE;                                         \
    switch (__dtype__) {                                                  \
      PD_PRIVATE_CASE_TYPE(                                               \
          NAME, ::paddle::DataType::FLOAT32, float, __VA_ARGS__)          \
      PD_PRIVATE_CASE_TYPE(NAME,                                          \
                           ::paddle::DataType::BFLOAT16,                  \
                           ::phi::dtype::bfloat16,                        \
                           __VA_ARGS__)                                   \
      default:                                                            \
        PD_THROW("function " #NAME " is not implemented for data type `", \
                 __dtype__,                                               \
                 "`");                                                    \
    }                                                                     \
  }()

template <typename T>
A
Adam Osewski 已提交
797
class ConvMKLDNNGradOpKernel : public framework::OpKernel<T> {
798
 public:
A
Adam Osewski 已提交
799
  void Compute(const framework::ExecutionContext& ctx) const override {
800 801
    PADDLE_ENFORCE_EQ(platform::is_cpu_place(ctx.GetPlace()),
                      true,
A
Adam Osewski 已提交
802
                      platform::errors::PreconditionNotMet(
803
                          "Operator DNNL ConvGrad must use CPUPlace"));
804 805
    auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
806 807
    const auto& mkldnn_engine = dev_ctx.GetEngine();

808 809 810 811 812 813 814 815 816 817
    const phi::DenseTensor* input = ctx.Input<phi::DenseTensor>("Input");
    const phi::DenseTensor* filter = ctx.Input<phi::DenseTensor>("Filter");
    const phi::DenseTensor* bias =
        ctx.HasInput("Bias") ? ctx.Input<phi::DenseTensor>("Bias") : nullptr;
    const phi::DenseTensor* output_grad =
        ctx.Input<phi::DenseTensor>(framework::GradVarName("Output"));
    phi::DenseTensor* input_grad =
        ctx.Output<phi::DenseTensor>(framework::GradVarName("Input"));
    phi::DenseTensor* filter_grad =
        ctx.Output<phi::DenseTensor>(framework::GradVarName("Filter"));
818 819 820

    if (!input_grad && !filter_grad) return;

821 822 823 824 825 826 827 828
    PD_VISIT_FLOAT_AND_BF16_TYPES(
        filter->dtype(), "ConvMKLDNNHandlerT", ([&] {
          // TODO(jczaja): Are all tensors really needed?
          ConvMKLDNNHandlerT<T, data_t, T> handler(
              ctx,
              dev_ctx,
              ctx.GetPlace(),
              input,
829
              filter,
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
              bias,
              output_grad,
              filter_grad,
              input_grad,
              ctx.InputName("Input") + ctx.InputName("Filter"));

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

          if (filter_grad) {
            auto src_memory_p =
                handler.AcquireSrcMemoryWithReorderFromWeightsPrimitive(input);
            auto diff_dst_memory_p =
                handler.AcquireDiffDstMemoryWithReorderFromWeightsPrimitive(
                    output_grad);

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

            auto conv_bwd_weights_p = handler.AcquireBackwardWeightsPrimitive();

            conv_bwd_weights_p->execute(
                astream,
                {{DNNL_ARG_SRC, *src_memory_p},
                 {DNNL_ARG_DIFF_DST, *diff_dst_memory_p},
                 {DNNL_ARG_DIFF_WEIGHTS, *diff_weights_memory_p}});
            astream.wait();

            // For convolution with groups convert from blocked to NCHW
            // otherwise there will be problems in next operators working on
            // this data
            if (g > 1) {
              // in OneDNN groups in convolution are treated as separate
              // dimension which is not the case in paddlepaddle

              dnnl::memory::data_type in_type = framework::ToMKLDNNDataType(
                  framework::TransToProtoVarType(filter->dtype()));
              // for 3d conv with groups (six dimensional data reorder to
              // goidhw) for 2d conv with groups (five dimensional data reorder
              // to goihw) auto weights_tz = phi::vectorize(filter->dims());

              auto weights_tz = diff_weights_memory_p->get_desc().dims();
              dnnl::memory::format_tag out_format =
                  weights_tz.size() == 6 ? dnnl::memory::format_tag::goidhw
                                         : dnnl::memory::format_tag::goihw;
              platform::ReorderMKLDNNHandler handler(
                  weights_tz,
                  framework::TransToProtoVarType(filter->dtype()),
                  in_type,
                  mkldnn_engine);
              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);

              {
                platform::RecordEvent record_reorder(
                    "int_reorder",
                    platform::TracerEventType::UserDefined,
                    2,
                    platform::EventRole::kUniqueOp);
                reorder_p->execute(
                    astream, *diff_weights_memory_p, *reorder_dst_memory_p);
                astream.wait();
              }

              // 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)
              dnnl::memory::format_tag target_format =
                  weights_tz.size() == 6 ? dnnl::memory::format_tag::oidhw
                                         : dnnl::memory::format_tag::oihw;
              filter_grad->set_mem_desc(dnnl::memory::desc(
                  phi::vectorize<int64_t>(filter_grad->dims()),
                  in_type,
                  target_format));
            } else {
              filter_grad->set_mem_desc(diff_weights_memory_p->get_desc());
            }
          }
          if (input_grad) {
            auto weights_memory_p =
                handler.AcquireWeightsMemoryWithReorderFromDataPrimitive(
                    filter,
                    ctx.Attr<int>("groups"),
                    ctx.Attr<std::vector<int>>("strides").size() == 3U);

            auto diff_dst_memory_p =
                handler.AcquireDiffDstMemoryWithReorderMemoryFromDataPrimitive(
                    output_grad);
            auto diff_src_memory_p = handler.AcquireDiffSrcMemory(input_grad);

            auto conv_bwd_data_p = handler.AcquireBackwardPrimitive();

            conv_bwd_data_p->execute(astream,
                                     {{DNNL_ARG_WEIGHTS, *weights_memory_p},
                                      {DNNL_ARG_DIFF_DST, *diff_dst_memory_p},
                                      {DNNL_ARG_DIFF_SRC, *diff_src_memory_p}});
            astream.wait();

            input_grad->set_mem_desc(diff_src_memory_p->get_desc());
          }
        }));
X
xiaolil1 已提交
938
  }
939
};
940

941 942 943 944 945
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

946 947 948 949 950 951 952 953 954 955
REGISTER_OP_KERNEL(depthwise_conv2d_grad,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
                   ops::ConvMKLDNNGradOpKernel<float>,
                   ops::ConvMKLDNNGradOpKernel<paddle::platform::bfloat16>);

REGISTER_OP_KERNEL(conv3d_grad,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
                   ops::ConvMKLDNNGradOpKernel<float>);