mul_mkldnn_op.cc 16.2 KB
Newer Older
P
Physher 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
/* Copyright (c) 2019 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. */

#include <string>
#include <vector>
#include "paddle/fluid/framework/data_layout_transform.h"
#include "paddle/fluid/memory/malloc.h"
#include "paddle/fluid/operators/mul_op.h"
#include "paddle/fluid/platform/mkldnn_helper.h"
#include "paddle/fluid/platform/mkldnn_reuse.h"

namespace paddle {
namespace operators {

using framework::DataLayout;
using framework::DDim;
using framework::ExecutionContext;
using framework::Tensor;
using mkldnn::inner_product_forward;
using mkldnn::memory;
using mkldnn::prop_kind;
using mkldnn::stream;
using platform::MKLDNNDeviceContext;
using platform::to_void_cast;

template <typename XT, typename YT, typename OT>
class MulPrimitiveFactory {
 public:
  explicit MulPrimitiveFactory(const mkldnn::engine &engine)
      : engine_(engine) {}

  virtual ~MulPrimitiveFactory() {}

  virtual inner_product_forward CreateMulPrimitive(
      const Tensor *input_x, const Tensor *input_y, Tensor *output,
      const ExecutionContext &ctx) {
    /* check format and reorder if need */
    int x_num_col_dims = ctx.Attr<int>("x_num_col_dims");
    int y_num_col_dims = ctx.Attr<int>("y_num_col_dims");

    auto x_matrix = UpdateDataFormat<XT>(input_x, x_num_col_dims, ctx);
    auto y_matrix = UpdateDataFormat<YT>(input_y, y_num_col_dims, ctx);

    auto output_dim = output->dims();
    if (output_dim.size() != 2) {
      output->Resize({x_matrix.dims()[0], y_matrix.dims()[1]});
    }

    if (mul_) {
      UpdateDataPointers(ctx, output, &x_matrix);
A
Adam 已提交
62
      Execute();
P
Physher 已提交
63 64 65
      return *mul_;
    }

66
    auto src_desc = CreateMemDescriptor<XT>(&x_matrix, MKLDNNMemoryFormat::nc);
P
Physher 已提交
67 68
    x_input_ = CreateMemory<XT>(src_desc, &x_matrix);
    y_input_ = TransposeInputY(&y_matrix);
69
    auto dst_desc = CreateMemDescriptor<OT>(output, MKLDNNMemoryFormat::any);
P
Physher 已提交
70 71

    mul_ = CreateMulPrimitive(*x_input_, *y_input_, dst_desc, output, ctx);
A
Adam 已提交
72
    Execute();
P
Physher 已提交
73 74 75
    return *mul_;
  }

A
Adam 已提交
76 77 78 79 80 81 82 83
  void Execute() {
    mkldnn::stream astream(engine_);
    (*mul_).execute(astream, {{MKLDNN_ARG_SRC, *x_input_},
                              {MKLDNN_ARG_WEIGHTS, *y_input_},
                              {MKLDNN_ARG_DST, *output_}});
    astream.wait();
  }

P
Physher 已提交
84 85 86 87 88 89
 protected:
  template <typename T>
  Tensor UpdateDataFormat(const Tensor *data, int num_col_dims,
                          const ExecutionContext &ctx) {
    Tensor x_tmp;
    Tensor data_matrix;
90 91
    MKLDNNMemoryFormat src_fmt = data->format();
    MKLDNNMemoryFormat dst_fmt;
P
Physher 已提交
92 93 94
    auto src_mdesc = CreateMemDescriptor<T>(data, src_fmt);

    if ((data->dims().size() == 4 &&
95
         src_fmt != (dst_fmt = MKLDNNMemoryFormat::nchw)) ||
P
Physher 已提交
96
        (data->dims().size() == 5 &&
97
         src_fmt != (dst_fmt = MKLDNNMemoryFormat::ncdhw))) {
P
Physher 已提交
98 99 100 101 102 103 104
      auto dst_mdesc = CreateMemDescriptor<T>(data, dst_fmt);
      x_tmp.mutable_data<T>(ctx.GetPlace(), data->memory_size());

      Reorder(src_mdesc, dst_mdesc, to_void_cast<T>(data->data<T>()),
              to_void_cast<T>(x_tmp.data<T>()));

      x_tmp.Resize(data->dims());
A
Adam 已提交
105
      x_tmp.set_format(platform::GetMKLDNNFormat(dst_mdesc));
P
Physher 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118
      data_matrix = framework::ReshapeToMatrix(x_tmp, num_col_dims);
    } else {
      data_matrix = framework::ReshapeToMatrix(*data, num_col_dims);
    }

    return data_matrix;
  }

  void UpdateDataPointers(const ExecutionContext &ctx, Tensor *out,
                          const Tensor *in) {
    x_input_->set_data_handle(to_void_cast<XT>(in->data<XT>()));
    output_->set_data_handle(out->mutable_data<OT>(ctx.GetPlace()));

A
Adam 已提交
119
    if (out->format() == MKLDNNMemoryFormat::undef) {
A
Adam 已提交
120
      auto output_format = platform::GetMKLDNNFormat(*output_);
121
      out->set_format((MKLDNNMemoryFormat)output_format);
P
Physher 已提交
122 123 124 125 126
    }
  }

  template <typename T>
  memory::desc CreateMemDescriptor(
127
      const Tensor *tensor, MKLDNNMemoryFormat format,
P
Physher 已提交
128
      memory::data_type type = platform::MKLDNNGetDataType<T>()) {
A
Adam 已提交
129
    auto dims = framework::vectorize<int64_t>(tensor->dims());
P
Physher 已提交
130 131 132 133 134
    return platform::MKLDNNMemDesc(dims, type, format);
  }

  template <typename T>
  memory::desc CreateMemDescriptor(
A
Adam 已提交
135
      const std::vector<int64_t> &dims, MKLDNNMemoryFormat format,
P
Physher 已提交
136 137 138 139 140 141
      memory::data_type type = platform::MKLDNNGetDataType<T>()) {
    return platform::MKLDNNMemDesc(dims, type, format);
  }

  template <typename T>
  memory CreateMemory(const memory::desc &desc, const Tensor *tensor) {
A
Adam 已提交
142
    return memory(desc, engine_, to_void_cast<T>(tensor->data<T>()));
P
Physher 已提交
143 144 145 146 147
  }

  memory CreateDstMemory(
      const inner_product_forward::primitive_desc &mul_prim_desc,
      const ExecutionContext &ctx, Tensor *output) {
A
Adam 已提交
148 149
    auto dst_desc = mul_prim_desc.dst_desc();
    auto buffer_size = dst_desc.get_size();
P
Physher 已提交
150 151

    OT *output_data = output->mutable_data<OT>(ctx.GetPlace(), buffer_size);
A
Adam 已提交
152 153
    output->set_format(paddle::platform::GetMKLDNNFormat(dst_desc));
    return memory(dst_desc, engine_, to_void_cast<OT>(output_data));
P
Physher 已提交
154 155 156 157
  }

  memory Reorder(const memory::desc &src_desc, const memory::desc &dst_desc,
                 void *src_data, void *dst_data = NULL) {
A
Adam 已提交
158 159 160
    auto src_mem = memory(src_desc, engine_, src_data);
    auto dst_mem = dst_data ? memory(dst_desc, engine_, dst_data)
                            : memory(dst_desc, engine_);
P
Physher 已提交
161 162

    auto reorder = mkldnn::reorder(src_mem, dst_mem);
A
Adam 已提交
163 164 165 166

    mkldnn::stream astream(engine_);
    reorder.execute(astream, src_mem, dst_mem);
    astream.wait();
P
Physher 已提交
167 168 169 170 171

    return dst_mem;
  }

  memory TransposeInputY(const Tensor *input_y) {
A
Adam 已提交
172
    auto dims = framework::vectorize<int64_t>(input_y->dims());
P
Physher 已提交
173
    std::swap(dims[0], dims[1]);  // Correct output dimensions
174 175
    auto src_desc = CreateMemDescriptor<YT>(dims, MKLDNNMemoryFormat::io);
    auto dst_desc = CreateMemDescriptor<YT>(dims, MKLDNNMemoryFormat::oi);
P
Physher 已提交
176 177 178 179 180 181 182 183
    return Reorder(src_desc, dst_desc, to_void_cast<YT>(input_y->data<YT>()));
  }

  inner_product_forward CreateMulPrimitive(const memory &x_memory,
                                           const memory &y_memory,
                                           const memory::desc &dst_desc,
                                           Tensor *output,
                                           const ExecutionContext &ctx) {
A
Adam 已提交
184 185
    const auto y_desc = y_memory.get_desc();
    const auto x_desc = x_memory.get_desc();
P
Physher 已提交
186 187 188 189

    auto mul_prim_desc = CreateMulPrimDesc(x_desc, y_desc, dst_desc);
    output_ = CreateDstMemory(mul_prim_desc, ctx, output);

A
Adam 已提交
190
    return inner_product_forward(mul_prim_desc);
P
Physher 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  }

  inner_product_forward::primitive_desc CreateMulPrimDesc(
      const memory::desc &x_desc, const memory::desc &y_desc,
      const memory::desc &dst_desc) {
    auto mul_desc = inner_product_forward::desc(prop_kind::forward, x_desc,
                                                y_desc, dst_desc);

    return inner_product_forward::primitive_desc(mul_desc, engine_);
  }

 protected:
  const mkldnn::engine &engine_;
  boost::optional<memory> x_input_;
  boost::optional<memory> y_input_;
  boost::optional<memory> output_;
  boost::optional<inner_product_forward> mul_;
};  // namespace operators

template <typename XT, typename YT, typename OT>
class QuantMulPrimitiveFactory : public MulPrimitiveFactory<XT, YT, OT> {
 public:
  using MulPrimitiveFactory<XT, YT, OT>::MulPrimitiveFactory;

  virtual inner_product_forward CreateMulPrimitive(
      const Tensor *x_input, const Tensor *y_input, Tensor *output,
      const ExecutionContext &ctx) {
    /* check data format and reorder if need */
    int x_num_col_dims = ctx.Attr<int>("x_num_col_dims");
    int y_num_col_dims = ctx.Attr<int>("y_num_col_dims");
    auto scale_y = ctx.Attr<std::vector<float>>("scale_y");

223 224 225 226 227 228 229 230
    // TODO(intel-minghui) : Remove the restriction that only supports Input(Y)
    // as weights
    bool enforce = std::is_same<YT, float>::value;
    PADDLE_ENFORCE(
        enforce == true,
        "Input(Y) supposed to be fp32 data type since only fp32 data type is "
        "supported in the current design of MKLDNN INT8.");

P
Physher 已提交
231 232 233 234 235 236 237 238 239 240 241 242
    auto x_matrix =
        this->template UpdateDataFormat<XT>(x_input, x_num_col_dims, ctx);
    auto y_matrix =
        this->template UpdateDataFormat<YT>(y_input, y_num_col_dims, ctx);

    auto output_dim = output->dims();
    if (output_dim.size() != 2) {
      output->Resize({x_matrix.dims()[0], y_matrix.dims()[1]});
    }

    if (this->mul_) {
      this->UpdateDataPointers(ctx, output, &x_matrix);
A
Adam 已提交
243
      this->Execute();
P
Physher 已提交
244 245 246
      return *(this->mul_);
    }

247 248
    auto src_desc = this->template CreateMemDescriptor<XT>(
        &x_matrix, MKLDNNMemoryFormat::nc);
P
Physher 已提交
249 250 251 252 253 254
    this->x_input_ = this->template CreateMemory<XT>(src_desc, &x_matrix);

    const auto trans_y = this->TransposeInputY(&y_matrix);
    this->y_input_ = QuantInputY(trans_y, scale_y);

    auto dst_desc =
255
        this->template CreateMemDescriptor<OT>(output, MKLDNNMemoryFormat::any);
P
Physher 已提交
256 257 258

    this->mul_ = CreateMulPrimitive(*(this->x_input_), *(this->y_input_),
                                    dst_desc, output, ctx);
A
Adam 已提交
259
    this->Execute();
P
Physher 已提交
260 261 262 263 264 265 266 267 268 269
    return *(this->mul_);
  }

  memory ReorderWithScale(const memory::desc &src_desc,
                          const memory::desc &dst_desc, void *src_data,
                          const std::vector<float> &scale) {
    auto mask = scale.size() > 1 ? 1 : 0;
    mkldnn::primitive_attr attr;
    attr.set_output_scales(mask, scale);

A
Adam 已提交
270 271 272 273
    auto src_mem = memory(src_desc, this->engine_, src_data);
    auto dst_mem = memory(dst_desc, this->engine_);

    auto reorder_pd = mkldnn::reorder::primitive_desc(src_mem, dst_mem, attr);
P
Physher 已提交
274

A
Adam 已提交
275
    auto reorder = mkldnn::reorder(reorder_pd);
P
Physher 已提交
276

A
Adam 已提交
277 278 279
    mkldnn::stream astream(this->engine_);
    reorder.execute(astream, src_mem, dst_mem);
    astream.wait();
P
Physher 已提交
280 281 282 283 284

    return dst_mem;
  }

  memory QuantInputY(memory input_y, const std::vector<float> &scale_y) {
A
Adam 已提交
285 286 287
    const auto &dims = input_y.get_desc().data.dims;
    auto ndims = input_y.get_desc().data.ndims;
    auto y_dims = std::vector<int64_t>(dims, dims + ndims);
P
Physher 已提交
288 289

    auto user_y_desc =
290 291 292
        this->template CreateMemDescriptor<YT>(y_dims, MKLDNNMemoryFormat::oi);
    auto y_desc = this->template CreateMemDescriptor<int8_t>(
        y_dims, MKLDNNMemoryFormat::oi);
P
Physher 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

    return ReorderWithScale(user_y_desc, y_desc, input_y.get_data_handle(),
                            scale_y);
  }

  mkldnn::primitive_attr CreateMulAttr(const ExecutionContext &ctx,
                                       bool force_fp32_output) {
    mkldnn::primitive_attr mul_attr;

    auto scale_y_data = ctx.Attr<std::vector<float>>("scale_y");
    auto scale_x_data = ctx.Attr<float>("scale_x");
    auto scale_out_data =
        force_fp32_output ? 1.0f : ctx.Attr<float>("scale_out");

    bool is_multi_channel = scale_y_data.size() > 1;
    int count = is_multi_channel ? scale_y_data.size() : 1;
    std::vector<float> output_shift_scale(count);
    for (int i = 0; i < count; i++) {
      if (scale_y_data[i] == 0.0)
        output_shift_scale[i] = scale_out_data;
      else
        output_shift_scale[i] =
            scale_out_data / (scale_x_data * scale_y_data[i]);
    }
    int mul_mask = is_multi_channel ? 1 : 0;
    mul_attr.set_output_scales(mul_mask, output_shift_scale);

    return mul_attr;
  }

  inner_product_forward CreateMulPrimitive(const memory &x_memory,
                                           const memory &y_memory,
                                           const memory::desc &dst_desc,
                                           Tensor *output,
                                           const ExecutionContext &ctx) {
A
Adam 已提交
328 329
    const auto x_desc = x_memory.get_desc();
    const auto y_desc = y_memory.get_desc();
P
Physher 已提交
330 331 332 333 334 335 336
    bool force_fp32_output = ctx.Attr<bool>("force_fp32_output");

    mkldnn::primitive_attr mul_attr = CreateMulAttr(ctx, force_fp32_output);
    auto mul_prim_desc = CreateMulPrimDesc(x_desc, y_desc, dst_desc, mul_attr);

    this->output_ = this->CreateDstMemory(mul_prim_desc, ctx, output);

A
Adam 已提交
337
    return inner_product_forward(mul_prim_desc);
P
Physher 已提交
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
  }

  inner_product_forward::primitive_desc CreateMulPrimDesc(
      const memory::desc &x_desc, const memory::desc &y_desc,
      const memory::desc &dst_desc, const mkldnn::primitive_attr &mul_attr) {
    const auto &mul_desc = inner_product_forward::desc(
        prop_kind::forward, x_desc, y_desc, dst_desc);

    return inner_product_forward::primitive_desc(mul_desc, mul_attr,
                                                 this->engine_);
  }
};

/* OT: output data type */
template <typename XT, typename YT, typename OT>
std::shared_ptr<MulPrimitiveFactory<XT, YT, OT>> GetPrimitiveFactory(
    const MKLDNNDeviceContext &dev_ctx, const ExecutionContext &ctx,
    const Tensor *input_x, const Tensor *input_y,
    const mkldnn::engine &mkldnn_engine, bool enable_quant) {
357
  const std::string key = platform::CreateKey(
A
Adam 已提交
358 359
      input_x->type(), framework::vectorize(input_x->dims()), input_y->type(),
      framework::vectorize(input_y->dims()), ctx.OutputName("Out"));
P
Physher 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 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

  auto prim_creator = std::static_pointer_cast<MulPrimitiveFactory<XT, YT, OT>>(
      dev_ctx.GetBlob(key));

  if (prim_creator == nullptr) {
    prim_creator =
        enable_quant
            ? std::make_shared<QuantMulPrimitiveFactory<XT, YT, OT>>(
                  mkldnn_engine)
            : std::make_shared<MulPrimitiveFactory<XT, YT, OT>>(mkldnn_engine);
    dev_ctx.SetBlob(key, prim_creator);
  }

  return prim_creator;
}

template <typename XT, typename YT>
inner_product_forward GetMulPrimitive(const MKLDNNDeviceContext &dev_ctx,
                                      const ExecutionContext &ctx,
                                      const Tensor *input_x,
                                      const Tensor *input_y, Tensor *output,
                                      const mkldnn::engine &mkldnn_engine) {
  bool enable_quant =
      std::is_same<XT, int8_t>::value || std::is_same<XT, uint8_t>::value;
  bool force_fp32_output = ctx.Attr<bool>("force_fp32_output");

  if (enable_quant && !force_fp32_output) {
    return GetPrimitiveFactory<XT, YT, int8_t>(dev_ctx, ctx, input_x, input_y,
                                               mkldnn_engine, enable_quant)
        ->CreateMulPrimitive(input_x, input_y, output, ctx);

  } else {
    return GetPrimitiveFactory<XT, YT, float>(dev_ctx, ctx, input_x, input_y,
                                              mkldnn_engine, enable_quant)
        ->CreateMulPrimitive(input_x, input_y, output, ctx);
  }
}

/* XT: input x data type, YT: input y data type */
template <typename XT, typename YT>
class MulMKLDNNKernel : public framework::OpKernel<XT> {
 public:
  void Compute(const ExecutionContext &ctx) const override {
    PADDLE_ENFORCE(platform::is_cpu_place(ctx.GetPlace()),
                   "It must use CPUPlace.");

    auto &dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
    const auto &mkldnn_engine = dev_ctx.GetEngine();

    const Tensor *x = ctx.Input<Tensor>("X");
    const Tensor *y = ctx.Input<Tensor>("Y");
    Tensor *out = ctx.Output<Tensor>("Out");
    auto out_dims = out->dims();

    auto mul = GetMulPrimitive<XT, YT>(dev_ctx, ctx, x, y, out, mkldnn_engine);

    if (out_dims.size() != 2) {
      out->Resize(out_dims);
    }
    out->set_layout(DataLayout::kMKLDNN);
A
Adam 已提交
420 421
    out->set_format(platform::MKLDNNFormatForSize(out_dims.size(),
                                                  MKLDNNMemoryFormat::nchw));
P
Physher 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(mul, MKLDNN, ::paddle::platform::CPUPlace,
                                    U8, ops::kMULMKLDNNINT8,
                                    ops::MulMKLDNNKernel<uint8_t, float>);

REGISTER_OP_KERNEL_WITH_CUSTOM_TYPE(mul, MKLDNN, ::paddle::platform::CPUPlace,
                                    S8, ops::kMULMKLDNNINT8,
                                    ops::MulMKLDNNKernel<int8_t, float>);

REGISTER_OP_KERNEL(mul, MKLDNN, ::paddle::platform::CPUPlace,
                   ops::MulMKLDNNKernel<uint8_t, float>);