fc_mkldnn_op.cc 25.3 KB
Newer Older
M
mozga-intel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

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

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

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

15
#include <memory>
W
wanghuancoder 已提交
16

17
#include "paddle/fluid/framework/op_registry.h"
18
#include "paddle/fluid/operators/fc_op.h"
M
mozga-intel 已提交
19
#include "paddle/fluid/platform/mkldnn_helper.h"
20
#include "paddle/fluid/platform/profiler/event_tracing.h"
21
#include "paddle/phi/backends/onednn/onednn_reuse.h"
22

M
mozga-intel 已提交
23 24 25
namespace paddle {
namespace operators {

26 27 28 29 30
using dnnl::inner_product_forward;
using dnnl::memory;
using dnnl::primitive;
using dnnl::prop_kind;
using dnnl::stream;
31 32
using framework::DDim;
using framework::ExecutionContext;
33
using phi::OneDNNContext;
34 35
using phi::funcs::OneDNNGetDataType;
using phi::funcs::to_void_cast;
36

37 38 39 40 41 42 43
struct InnerProductCache {
  dnnl::inner_product_forward inner_product_p;
  dnnl::memory src_mem;
  dnnl::memory weights_mem;
  dnnl::memory bias_mem;
  dnnl::memory dst_mem;
};
M
Michał Gallus 已提交
44
template <typename T_in, typename T_w, typename T_out>
45
class FCMKLDNNHandler
46 47
    : public phi::funcs::OneDNNHandlerNoCachingT<T_in,
                                                 dnnl::inner_product_forward> {
M
mozga-intel 已提交
48
 public:
49
  FCMKLDNNHandler(const paddle::framework::ExecutionContext& ctx,
50
                  const OneDNNContext& dev_ctx,
51 52 53 54
                  const phi::DenseTensor* x,
                  const phi::DenseTensor* weights,
                  const phi::DenseTensor* bias,
                  phi::DenseTensor* out,
55
                  const int in_num_col_dims,
56
                  dnnl::engine onednn_engine,
57
                  platform::Place cpu_place)
58
      : phi::funcs::OneDNNHandlerNoCachingT<T_in, dnnl::inner_product_forward>(
59
            onednn_engine, cpu_place),
60 61 62 63 64 65 66 67 68
        dev_ctx_(dev_ctx) {
    this->memory_key_ = ctx.InputName("W");

    auto x_vec_dims = phi::vectorize(x->dims());
    auto weights_vec_dims = phi::vectorize(weights->dims());

    int MB = 1;
    for (int i = 0; i < in_num_col_dims; ++i) {
      MB *= x_vec_dims[i];
69 70
    }

71 72 73
    int IC = 1;
    for (size_t i = in_num_col_dims; i < x_vec_dims.size(); ++i) {
      IC *= x_vec_dims[i];
74
    }
75

76
    int OC = weights_vec_dims[1];
M
mozga-intel 已提交
77

78
    dnnl::memory::desc bias_md;
79

80
    auto src_md = dnnl::memory::desc(
81
        {MB, IC}, OneDNNGetDataType<T_in>(), dnnl::memory::format_tag::any);
82
    auto weights_md = dnnl::memory::desc(
83
        {OC, IC}, OneDNNGetDataType<T_w>(), dnnl::memory::format_tag::any);
84
    auto dst_md = dnnl::memory::desc(
85
        {MB, OC}, OneDNNGetDataType<T_out>(), dnnl::memory::format_tag::any);
86 87
    if (bias) {
      bias_md = dnnl::memory::desc({bias->numel()},
88
                                   OneDNNGetDataType<float>(),
89 90
                                   dnnl::memory::format_tag::a);
    }
91

92
    const auto attrs = CreateFCAttrs(ctx);
A
Adam 已提交
93

94 95 96 97 98 99
    this->AcquireForwardPrimitiveDescriptor(attrs,
                                            prop_kind::forward_inference,
                                            src_md,
                                            weights_md,
                                            bias_md,
                                            dst_md);
M
mozga-intel 已提交
100 101
  }

102
 private:
103 104 105
  dnnl::primitive_attr CreateFCAttrs(const ExecutionContext& ctx) {
    dnnl::primitive_attr attributes;
    dnnl::post_ops post_operations;
106

107 108
    float sum_scale = 1.0f;
    float activation_scale = 1.0f;
109
    if (phi::funcs::is_int8<T_w>()) {
110 111 112
      std::vector<float> output_shift_scale;
      std::tie(output_shift_scale, sum_scale, activation_scale) =
          GetOutputScales(ctx);
113
      int mask = CreateMask(1, output_shift_scale.size() > 1);
114
      attributes.set_output_scales(mask, output_shift_scale);
115
    }
116

117 118
    if (ctx.HasAttr("fuse_residual_connection") &&
        ctx.Attr<bool>("fuse_residual_connection")) {
119
      post_operations.append_sum(sum_scale);
120
    }
M
mozga-intel 已提交
121

122 123 124
    // ReLU from "fc_fuse_pass"
    if (ctx.Attr<std::string>("activation_type") == "relu") {
      post_operations.append_eltwise(
125
          activation_scale, dnnl::algorithm::eltwise_relu, 0.0f, 0.0f);
126
    }
127
    AppendActivation(ctx, post_operations, activation_scale);
128

129 130 131 132 133 134
    if (ctx.HasAttr("fused_output_scale")) {
      float scale_alpha = ctx.Attr<float>("fused_output_scale");
      post_operations.append_eltwise(
          1.0, dnnl::algorithm::eltwise_linear, scale_alpha, 0.0f);
    }

135 136
    attributes.set_post_ops(post_operations);
    return attributes;
137 138
  }

M
Michał Gallus 已提交
139 140
  // Compute the bias scales so that its values correspond to the
  // scale of data being an output of weights and input multiplication
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  std::vector<float> GetBiasScales(const framework::ExecutionContext& ctx) {
    if (ctx.HasAttr("Bias_scales")) {
      return ctx.Attr<std::vector<float>>("Bias_scales");
    } else {
      const float scale_in = ctx.Attr<float>("Scale_in");
      const auto& scale_weights = ctx.Attr<std::vector<float>>("Scale_weights");
      std::vector<float> bias_scales(scale_weights.size());

      for (size_t i = 0; i < bias_scales.size(); ++i) {
        if (scale_weights[i] == 0.0)
          bias_scales[i] = 1.0f;
        else
          bias_scales[i] = scale_in * scale_weights[i];
      }
      return bias_scales;
M
Michał Gallus 已提交
156 157 158
    }
  }

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
  void AppendActivation(const ExecutionContext& ctx,
                        dnnl::post_ops& post_ops,  // NOLINT
                        float activation_scale = 1.0f) {
    const auto invalid_attribute =
        ctx.HasAttr("fuse_activation")
            ? ctx.Attr<std::string>("fuse_activation").empty()
            : true;
    if (invalid_attribute) return;

    const auto fuse_activation = ctx.Attr<std::string>("fuse_activation");
    const auto fuse_alpha =
        ctx.HasAttr("fuse_alpha") ? ctx.Attr<float>("fuse_alpha") : 0.0f;
    const auto fuse_beta =
        ctx.HasAttr("fuse_beta") ? ctx.Attr<float>("fuse_beta") : 0.0f;

    if (fuse_activation == "hard_sigmoid") {
      post_ops.append_eltwise(activation_scale,
                              dnnl::algorithm::eltwise_linear,
                              fuse_alpha,
                              fuse_beta);
      post_ops.append_eltwise(
          activation_scale, dnnl::algorithm::eltwise_clip, 0.0f, 1.0f);
    } else {
      const std::unordered_map<std::string, dnnl::algorithm> activation_map = {
          {"abs", dnnl::algorithm::eltwise_abs},
          {"clip", dnnl::algorithm::eltwise_clip},
          {"gelu", dnnl::algorithm::eltwise_gelu_erf},
          {"gelu_erf", dnnl::algorithm::eltwise_gelu_erf},
          {"gelu_tanh", dnnl::algorithm::eltwise_gelu_tanh},
          {"hard_swish", dnnl::algorithm::eltwise_hardswish},
          {"leaky_relu", dnnl::algorithm::eltwise_relu},
          {"mish", dnnl::algorithm::eltwise_mish},
          {"relu", dnnl::algorithm::eltwise_relu},
          {"relu6", dnnl::algorithm::eltwise_bounded_relu},
          {"sigmoid", dnnl::algorithm::eltwise_logistic},
          {"sqrt", dnnl::algorithm::eltwise_sqrt},
          {"swish", dnnl::algorithm::eltwise_swish},
          {"tanh", dnnl::algorithm::eltwise_tanh}};

      const auto& activation_type = activation_map.find(fuse_activation);

      PADDLE_ENFORCE_NE(
          activation_type,
          activation_map.end(),
          platform::errors::InvalidArgument(
              "Activation '%s' not found in oneDNN algorithms mapper",
              fuse_activation));

      post_ops.append_eltwise(
          activation_scale, activation_type->second, fuse_alpha, fuse_beta);
    }
  }

M
Michał Gallus 已提交
212 213 214 215 216
  // Correct output scale, to take into account scaling of input and weights
  // Since the data that comes out of input and weight multiplication is
  // scaled with its own scales, this data needs to be divided by
  // those scales to normalise them back to what their floating-point range
  // was. Then we multiply them by desired output scale we want on the output.
217
  std::tuple<std::vector<float>, float, float> GetOutputScales(
218
      const ExecutionContext& ctx) {
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    if (ctx.HasAttr("Sum_scale")) {
      return std::make_tuple(ctx.Attr<std::vector<float>>("Output_shift_scale"),
                             ctx.Attr<float>("Sum_scale"),
                             ctx.Attr<float>("Activation_scale"));
    } else {
      auto scale_in_data = ctx.Attr<float>("Scale_in");
      auto scale_weights_data = ctx.Attr<std::vector<float>>("Scale_weights");
      bool has_activation = !ctx.Attr<std::string>("activation_type").empty();
      bool force_fp32_output = ctx.Attr<bool>("force_fp32_output");
      bool fuse_residual_conn = ctx.HasAttr("fuse_residual_connection") &&
                                ctx.Attr<bool>("fuse_residual_connection");
      auto scale_in_eltwise_data = ctx.HasAttr("Scale_in_eltwise")
                                       ? ctx.Attr<float>("Scale_in_eltwise")
                                       : 1.0f;

      // If the output will be in floats, we don't multiply by scale_out.

      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");
      float sum_scale =
          fuse_residual_conn ? scale_out_data / scale_in_eltwise_data : 1.0f;
      const size_t weight_scales_num = scale_weights_data.size();

      for (size_t i = 0; i < weight_scales_num; ++i) {
        if (scale_weights_data[i] == 0.0)
          scale_weights_data[i] = scale_out_data;
        else
          scale_weights_data[i] =
              scale_out_data / (scale_in_data * scale_weights_data[i]);
      }
      return std::make_tuple(scale_weights_data, sum_scale, activation_scale);
M
Michał Gallus 已提交
254 255 256 257 258 259 260 261 262 263 264
    }
  }

  // Computing MKL-DNN's scaling mask which determines along which dimension
  // slice should the scaling be applied. For more data plase refer to:
  // https://intel.github.io/mkl-dnn/group__c__api__attributes.html
  // Section dnnl_status_t DNNL_API dnnl_primitive_attr_set_output_scales
  int CreateMask(int slice_dimension, bool is_multi_channel_quantizied) {
    return is_multi_channel_quantizied ? 1 << slice_dimension : 0;
  }

265 266 267 268 269 270
  std::shared_ptr<dnnl::memory> AcquireMemoryWithReorderAndAttrs(
      const dnnl::memory::desc& user_md,
      const dnnl::memory::desc& target_md,
      void* ptr,
      const dnnl::primitive_attr& attrs) {
    std::shared_ptr<dnnl::memory> target_memory_p;
M
Michał Gallus 已提交
271

272 273 274 275 276
    auto user_memory_p =
        std::make_shared<dnnl::memory>(user_md, this->engine_, ptr);
    target_memory_p = std::make_shared<dnnl::memory>(target_md, this->engine_);
    auto reorder_p = std::make_shared<dnnl::reorder>(
        *user_memory_p, *target_memory_p, attrs);
M
Michał Gallus 已提交
277

278
    auto& astream = OneDNNContext::tls().get_stream();
279 280 281 282 283 284 285 286 287 288 289
    {
      platform::RecordEvent record_reorder(
          "int_reorder",
          platform::TracerEventType::UserDefined,
          1,
          platform::EventRole::kUniqueOp);
      reorder_p->execute(
          astream,
          {{DNNL_ARG_FROM, *user_memory_p}, {DNNL_ARG_TO, *target_memory_p}});
      astream.wait();
    }
M
Michał Gallus 已提交
290

291 292
    return target_memory_p;
  }
293

294
  std::string memory_key_;
295
  const OneDNNContext& dev_ctx_;
M
Michał Gallus 已提交
296

297
 public:
298 299
  std::shared_ptr<dnnl::memory> AcquireSrcMemoryWithReorder(
      const phi::DenseTensor* x) {
300 301 302 303 304 305 306
    const T_in* x_data = x->data<T_in>();

    auto user_md = x->mem_desc();
    if (x->dims().size() != 2) {
      // reshape restrictions are always satisfied because in case of 3 or 4 dim
      // input, plain layout is enforced
      user_md = user_md.reshape(this->fwd_pd_->src_desc().dims());
M
Michał Gallus 已提交
307 308
    }

309 310
    return this->AcquireMemoryWithReorder(
        user_md, this->fwd_pd_->src_desc(), to_void_cast<T_in>(x_data));
311
  }
M
mozga-intel 已提交
312

313
  std::shared_ptr<dnnl::memory> AcquireBiasMemoryWithReorder(
314
      const framework::ExecutionContext& ctx, const phi::DenseTensor* bias) {
315 316
    const float* bias_data = bias->data<float>();

317
    if (phi::funcs::is_int8<T_w>() == false) {
318 319 320 321 322 323 324 325 326
      // for BF16/FP32 bias is 1D and has no scales, so reorder is not needed
      return this->AcquireMemoryFromPrimitive(this->fwd_pd_->bias_desc(),
                                              to_void_cast<float>(bias_data));
    } else {
      const std::string bias_key = this->memory_key_ + "@bias";
      auto memory_p = std::static_pointer_cast<dnnl::memory>(
          this->dev_ctx_.GetBlob(bias_key));

      if (!memory_p) {
327
        const auto& scale_data = GetBiasScales(ctx);
328 329 330 331 332 333
        dnnl::primitive_attr attrs;

        int mask = CreateMask(0, scale_data.size() > 1);
        attrs.set_output_scales(mask, scale_data);

        auto user_md = dnnl::memory::desc({bias->dims()[0]},
334
                                          OneDNNGetDataType<float>(),
335 336 337 338 339 340 341
                                          dnnl::memory::format_tag::a);

        memory_p = this->AcquireMemoryWithReorderAndAttrs(
            user_md,
            this->fwd_pd_->bias_desc(),
            to_void_cast<float>(bias_data),
            attrs);
342
        this->dev_ctx_.SetBlob(bias_key, memory_p);
343 344 345 346 347 348
      }
      return memory_p;
    }
  }

  std::shared_ptr<dnnl::memory> AcquireWeightsMemoryWithReorder(
349
      const phi::DenseTensor* weights, const std::vector<float>& scale_data) {
350 351 352
    const std::string weights_key = this->memory_key_ + "@weights";
    auto memory_p = std::static_pointer_cast<dnnl::memory>(
        this->dev_ctx_.GetBlob(weights_key));
M
mozga-intel 已提交
353

354 355 356 357 358
    if (!memory_p) {
      const float* weights_data = weights->data<float>();
      auto weights_dims = this->fwd_pd_->weights_desc().dims();

      auto user_md = dnnl::memory::desc(weights_dims,
359
                                        OneDNNGetDataType<float>(),
360 361
                                        dnnl::memory::format_tag::io);

362
      if (phi::funcs::is_int8<T_w>()) {
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
        dnnl::primitive_attr attrs;
        int mask = CreateMask(0, scale_data.size() > 1);
        attrs.set_output_scales(mask, scale_data);

        memory_p = this->AcquireMemoryWithReorderAndAttrs(
            user_md,
            this->fwd_pd_->weights_desc(),
            to_void_cast<float>(weights_data),
            attrs);
      } else {
        memory_p =
            this->AcquireMemoryWithReorder(user_md,
                                           this->fwd_pd_->weights_desc(),
                                           to_void_cast<float>(weights_data));
      }

      this->dev_ctx_.SetBlob(weights_key, memory_p);
    }
    return memory_p;
382
  }
M
mozga-intel 已提交
383

384
  std::shared_ptr<dnnl::memory> AcquireCustomDstMemory(
385
      const ExecutionContext& ctx, phi::DenseTensor* out) {
386 387
    if (ctx.HasAttr("fuse_residual_connection") &&
        ctx.Attr<bool>("fuse_residual_connection")) {
388
      auto* residual_param = ctx.Input<phi::DenseTensor>("ResidualData");
389 390

      PADDLE_ENFORCE_EQ(
391
          out->dims(),
392
          residual_param->dims(),
393 394 395 396
          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 .",
397
              out->dims().size(),
398
              residual_param->dims().size()));
399

400
      out->ShareDataWith(*residual_param);
401
    }
402
    return this->template AcquireDstMemory<T_out>(out);
403 404
  }  // namespace operators
};   // namespace paddle
405

406 407 408 409 410 411 412 413 414 415
#define IF_CHANGE_FC_TW_TYPENAME(condition, ...) \
  if (condition) {                               \
    using T_w = int8_t;                          \
    __VA_ARGS__();                               \
  } else {                                       \
    using T_w = T_in;                            \
    __VA_ARGS__();                               \
  }

template <typename T_in>
416 417 418 419 420
class FCMKLDNNKernel : public framework::OpKernel<T_in> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    bool force_fp32_output = ctx.Attr<bool>("force_fp32_output");
    bool fuse_relu = ctx.Attr<std::string>("activation_type") == "relu";
421

422 423 424
    IF_CHANGE_FC_TW_TYPENAME((std::is_same<T_in, uint8_t>::value), ([&] {
                               if (force_fp32_output) {
                                 this->RunKernel<float, T_w>(ctx);
425
                               } else if (phi::funcs::is_int8<T_in>()) {
426 427 428 429 430 431 432 433 434
                                 if (fuse_relu) {
                                   this->RunKernel<uint8_t, T_w>(ctx);
                                 } else {
                                   this->RunKernel<int8_t, T_w>(ctx);
                                 }
                               } else {
                                 this->RunKernel<T_in, T_w>(ctx);
                               }
                             }));
435 436
  }

437 438
  void PrepareSrcMem(const std::shared_ptr<inner_product_forward>& fc_p,
                     const std::shared_ptr<dnnl::memory>& src_mem,
439
                     const phi::DenseTensor* x,
440 441 442 443 444 445
                     const dnnl::engine& engine) const {
    auto x_md = x->mem_desc().reshape(src_mem->get_desc().dims());
    if (x_md != src_mem->get_desc()) {
      dnnl::memory x_mem(x_md, engine, to_void_cast<T_in>(x->data<T_in>()));
      auto reorder_p = dnnl::reorder(x_mem, *src_mem);

446
      auto& astream = OneDNNContext::tls().get_stream();
447 448 449 450 451 452 453
      reorder_p.execute(astream, x_mem, *src_mem);
      astream.wait();
    } else {
      src_mem->set_data_handle(to_void_cast<T_in>(x->data<T_in>()));
    }
  }

454 455 456 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 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
  void SetOutMemDescWithUnsqueeze2FuseSupport(
      const framework::ExecutionContext& ctx,
      phi::DenseTensor* out,
      const dnnl::memory::desc& out_md) const {
    const std::vector<int>& fused_unsqueeze2_axes =
        ctx.Attr<std::vector<int>>("fused_unsqueeze2_axes");
    const std::vector<int64_t>& op_tz = out_md.dims();
    std::vector<int64_t> unsqueezed_op_tz(
        op_tz.size() + fused_unsqueeze2_axes.size(), 0);

    for (const auto& axis : fused_unsqueeze2_axes) {
      int positive_axis = axis < 0 ? unsqueezed_op_tz.size() + axis : axis;
      unsqueezed_op_tz[positive_axis] = 1;
    }

    int j = 0;
    for (size_t i = 0; i < unsqueezed_op_tz.size(); ++i) {
      if (unsqueezed_op_tz[i] == 0) {
        unsqueezed_op_tz[i] = op_tz[j++];
      }
    }
    out->set_mem_desc(out_md.reshape(unsqueezed_op_tz));
    out->Resize(phi::make_ddim(unsqueezed_op_tz));
  }

  void SetOutMemDescWithReshape2FuseSupport(
      const framework::ExecutionContext& ctx,
      phi::DenseTensor* out,
      const dnnl::memory::desc& out_md) const {
    std::vector<int64_t> fused_reshape2_shape(
        ctx.Attr<std::vector<int>>("fused_reshape2_shape").begin(),
        ctx.Attr<std::vector<int>>("fused_reshape2_shape").end());

    const int out_shape_numel = out->numel();
    const int new_shape_numel = std::accumulate(fused_reshape2_shape.begin(),
                                                fused_reshape2_shape.end(),
                                                1,
                                                std::multiplies<int64_t>());

    for (size_t i = 0; i < fused_reshape2_shape.size(); ++i) {
      if (fused_reshape2_shape[i] == -1) {
        fused_reshape2_shape[i] = -out_shape_numel / new_shape_numel;
        break;
      }
    }

    out->set_mem_desc(out_md.reshape(fused_reshape2_shape));
    out->Resize(phi::make_ddim(fused_reshape2_shape));
  }

  void SetOutMemDescWithLogicalLayoutFusesSupport(
      const framework::ExecutionContext& ctx,
      phi::DenseTensor* out,
      const dnnl::memory::desc& out_md) const {
    if (ctx.HasAttr("fused_unsqueeze2_axes")) {
      SetOutMemDescWithUnsqueeze2FuseSupport(ctx, out, out_md);
    } else if (ctx.HasAttr("fused_reshape2_shape")) {
      SetOutMemDescWithReshape2FuseSupport(ctx, out, out_md);
    } else if (ctx.HasAttr("fused_squeeze2_axes")) {
      out->set_mem_desc(out_md);
      out->Resize(phi::make_ddim(out_md.dims()));
    } else {
      out->set_mem_desc(out_md);
    }
  }

520
  template <typename T_out, typename T_w>
521
  void RunKernel(const framework::ExecutionContext& ctx) const {
522
    const auto& dev_ctx = ctx.template device_context<OneDNNContext>();
523
    const auto& onednn_engine = dev_ctx.GetEngine();
524

525
    const auto* x = ctx.Input<phi::DenseTensor>("Input");
526 527
    const auto* weights = ctx.Input<phi::DenseTensor>("W");
    const auto* bias = ctx.Input<phi::DenseTensor>("Bias");
528
    auto out = ctx.Output<phi::DenseTensor>("Out");
529 530 531

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

532 533 534 535 536 537 538 539
    std::shared_ptr<dnnl::inner_product_forward> fc_p;
    std::shared_ptr<dnnl::memory> src_memory_p;
    std::shared_ptr<dnnl::memory> weights_memory_p;
    std::shared_ptr<dnnl::memory> bias_memory_p;
    std::shared_ptr<dnnl::memory> dst_memory_p;

    std::string cache_key;
    cache_key.reserve(64);
540
    cache_key = phi::funcs::ExtendKeyWithThreadInfoIfNeeded(
541
        dev_ctx,
542 543 544 545
        phi::funcs::CreateKey(dev_ctx,
                              ctx.InputName("Input"),
                              ctx.InputName("W"),
                              phi::vectorize(x->dims())));
546 547 548 549

    auto inner_product_cache =
        std::static_pointer_cast<InnerProductCache>(dev_ctx.GetBlob(cache_key));

550 551
    RecomputeOutputDims(ctx, x, weights, out);

552 553 554 555 556
    if (inner_product_cache) {
      fc_p = std::make_shared<dnnl::inner_product_forward>(
          inner_product_cache->inner_product_p);
      src_memory_p =
          std::make_shared<dnnl::memory>(inner_product_cache->src_mem);
557
      PrepareSrcMem(fc_p, src_memory_p, x, onednn_engine);
558 559 560 561 562 563 564 565

      weights_memory_p =
          std::make_shared<dnnl::memory>(inner_product_cache->weights_mem);

      dst_memory_p =
          std::make_shared<dnnl::memory>(inner_product_cache->dst_mem);
      if (ctx.HasAttr("fuse_residual_connection") &&
          ctx.Attr<bool>("fuse_residual_connection")) {
566
        auto* residual_param = ctx.Input<phi::DenseTensor>("ResidualData");
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
        out->ShareDataWith(*residual_param);
      }
      auto out_ptr = out->mutable_data<T_out>(
          ctx.GetPlace(), dst_memory_p->get_desc().get_size());
      dst_memory_p->set_data_handle(out_ptr);

      if (bias) {
        bias_memory_p =
            std::make_shared<dnnl::memory>(inner_product_cache->bias_mem);
      }
    } else {
      auto in_col_dims = ctx.Attr<int>("in_num_col_dims");

      FCMKLDNNHandler<T_in, T_w, T_out> handler(ctx,
                                                dev_ctx,
                                                x,
                                                weights,
                                                bias,
                                                out,
                                                in_col_dims,
587
                                                onednn_engine,
588 589 590 591 592 593 594 595
                                                ctx.GetPlace());

      src_memory_p = handler.AcquireSrcMemoryWithReorder(x);
      weights_memory_p =
          handler.AcquireWeightsMemoryWithReorder(weights, scale_weights);
      dst_memory_p = handler.AcquireCustomDstMemory(ctx, out);

      if (bias) {
596
        bias_memory_p = handler.AcquireBiasMemoryWithReorder(ctx, bias);
597 598 599 600 601
      }

      fc_p = handler.AcquireForwardPrimitive();
    }

602
    auto& astream = OneDNNContext::tls().get_stream();
603 604 605 606 607 608 609 610 611 612 613 614 615

    std::unordered_map<int, dnnl::memory> fc_args = {
        {DNNL_ARG_SRC, *src_memory_p},
        {DNNL_ARG_WEIGHTS, *weights_memory_p},
        {DNNL_ARG_DST, *dst_memory_p}};

    if (bias) {
      fc_args.insert({DNNL_ARG_BIAS, *bias_memory_p});
    }

    fc_p->execute(astream, fc_args);
    astream.wait();

616 617 618 619 620 621 622 623 624 625 626 627
    if (!inner_product_cache) {
      auto ip_cache = std::make_shared<InnerProductCache>();
      ip_cache->inner_product_p = *fc_p;
      ip_cache->src_mem = *src_memory_p;
      ip_cache->weights_mem = *weights_memory_p;
      ip_cache->dst_mem = *dst_memory_p;
      if (bias) {
        ip_cache->bias_mem = *bias_memory_p;
      }
      dev_ctx.SetBlob(cache_key, ip_cache);
    }

628
    SetOutMemDescWithLogicalLayoutFusesSupport(
629 630
        ctx,
        out,
631
        dst_memory_p->get_desc().reshape(phi::vectorize(out->dims())));
632
  }
M
mozga-intel 已提交
633

634
  void RecomputeOutputDims(const ExecutionContext& ctx,
635
                           const phi::DenseTensor* x,
636
                           const phi::DenseTensor* weights,
637
                           phi::DenseTensor* out) const {
L
luotao1 已提交
638
    int in_num_col_dims = ctx.Attr<int>("in_num_col_dims");
639
    bool padding_weights = ctx.Attr<bool>("padding_weights");
640 641
    PADDLE_ENFORCE_EQ(padding_weights,
                      false,
642 643
                      platform::errors::PermissionDenied(
                          "Weight padding in fc can not be used in MKLDNN."));
L
luotao1 已提交
644
    std::vector<int64_t> output_dims;
645 646
    FCOutputSize(x->dims(),
                 weights->dims(),
647 648
                 output_dims,
                 in_num_col_dims,
649
                 padding_weights);
650 651
    out->Resize(phi::make_ddim(output_dims));
    out->set_lod(x->lod());
652 653
  }
};
M
mozga-intel 已提交
654 655 656 657

}  // namespace operators
}  // namespace paddle

M
Michał Gallus 已提交
658 659 660 661
// Weights of FC are by default stored using fp32, template argument of weight
// data type implies their destination data type. (What's eventually going to
// be used during computations of kernel).
namespace ops = paddle::operators;
662 663 664

REGISTER_OP_KERNEL(fc,
                   MKLDNN,
665
                   ::phi::CPUPlace,
666 667 668 669
                   ops::FCMKLDNNKernel<float>,
                   ops::FCMKLDNNKernel<paddle::platform::bfloat16>,
                   ops::FCMKLDNNKernel<uint8_t>,
                   ops::FCMKLDNNKernel<int8_t>);