elementwise_mul_mkldnn_op.cc 7.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 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 <mkldnn/include/mkldnn.hpp>
16 17
#include "paddle/fluid/operators/elementwise/elementwise_op.h"
#include "paddle/fluid/operators/elementwise/elementwise_op_function.h"
18

T
tensor-tang 已提交
19
#include "paddle/fluid/operators/jit/kernels.h"
P
peizhilin 已提交
20
#include "paddle/fluid/platform/cpu_info.h"
P
peizhilin 已提交
21
#include "paddle/fluid/platform/mkldnn_helper.h"
22

23
#ifdef PADDLE_WITH_XBYAK
24 25
#include "xbyak/xbyak.h"
#include "xbyak/xbyak_util.h"
26
#endif
27

28 29 30 31
namespace paddle {
namespace operators {

using framework::DataLayout;
32
using mkldnn::memory;
33
using platform::StringToMKLDNNFormat;
34 35

static void UpdateDataFormat(const framework::ExecutionContext& ctx,
36 37
                             framework::Tensor* tensor, const char* attribute) {
  if (ctx.op().HasAttr(attribute)) {
38
    auto format_as_string = ctx.Attr<std::string>(attribute);
39
    auto format = StringToMKLDNNFormat(&format_as_string);
40 41 42 43 44 45
    if (format != memory::format::any) {
      tensor->set_format(format);
    }
  }
}

46 47 48
template <typename T>
static void ReorderInput(framework::Tensor* tensor,
                         const platform::Place& place,
49
                         const mkldnn::engine& engine, bool isFourDim) {
50 51 52 53 54 55
  using platform::to_void_cast;
  auto dims = paddle::framework::vectorize2int(tensor->dims());
  framework::Tensor out_tensor;
  out_tensor.Resize(tensor->dims());
  out_tensor.set_format(isFourDim ? memory::format::nchw : memory::format::nc);
  out_tensor.set_layout(tensor->layout());
56 57 58 59 60 61
  mkldnn::memory input_memory = {
      {{dims, platform::MKLDNNGetDataType<T>(), tensor->format()}, engine},
      to_void_cast<T>(tensor->data<T>())};
  mkldnn::memory output_memory = {
      {{dims, platform::MKLDNNGetDataType<T>(), out_tensor.format()}, engine},
      to_void_cast<T>(out_tensor.mutable_data<T>(place))};
62 63 64 65
  platform::Reorder(input_memory, output_memory);
  tensor->ShareDataWith(out_tensor);
}

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
template <typename T>
class ElementwiseMulMKLDNNKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    using Tensor = framework::Tensor;

    int axis = ctx.Attr<int>("axis");
    auto* x = ctx.Input<Tensor>("X");
    auto* y = ctx.Input<Tensor>("Y");
    auto* z = ctx.Output<Tensor>("Out");
    const T* x_data = x->data<T>();
    const T* y_data = y->data<T>();
    T* z_data = z->mutable_data<T>(ctx.GetPlace());

    auto x_dims = x->dims();
    auto y_dims_untrimmed = y->dims();
82
    auto x_int_dims = paddle::framework::vectorize2int(x_dims);
83

84 85
    UpdateDataFormat(ctx, const_cast<Tensor*>(x), "x_data_format");
    UpdateDataFormat(ctx, const_cast<Tensor*>(y), "y_data_format");
86

P
peizhilin 已提交
87
    const bool is_avx512_enabled = platform::MayIUse(platform::avx512f);
88 89 90
    const bool are_dims_divisable = !(x_int_dims[1] % 16);
    const bool is_x_format_correct = x->format() == memory::format::nChw16c;
    const bool is_y_format_correct = y->format() == memory::format::nc;
91 92
    if (is_x_format_correct && is_y_format_correct && are_dims_divisable &&
        is_avx512_enabled) {
93 94
      int pre, n, post;
      get_mid_dims(x_dims, y_dims_untrimmed, axis, &pre, &n, &post);
95

96 97 98 99 100
      if (post == 1) {
        PADDLE_THROW("Not implemented when post is 1");
      } else {
        // Just check whether it works for RE-Resnext.
        PADDLE_ENFORCE_EQ(x_dims.size(), 4, "X should have 4 dimensions");
101

102 103 104 105
        int n = x_dims[0];
        int c = x_dims[1];
        int h = x_dims[2];
        int w = x_dims[3];
106

107 108
        PADDLE_ENFORCE(y_dims_untrimmed[0] == n && y_dims_untrimmed[1] == c,
                       "Y should be in nc format");
109

110 111
        constexpr int simd_width = 16;
        int C = c / simd_width;
112

113 114 115 116
        auto multiply =
            jit::KernelFuncs<jit::kNCHW16CMulNC, jit::NCHW16CMulNCTuples<T>,
                             platform::CPUPlace>::Cache()
                .At(0);
117
#pragma omp parallel for collapse(2)
118 119 120
        for (int ni = 0; ni < n; ni++) {
          for (int ci = 0; ci < C; ci++) {
            auto ptr_x =
121
                x_data + ni * C * h * w * simd_width + ci * h * w * simd_width;
122

123 124
            auto ptr_y = y_data + ni * C * simd_width + ci * simd_width;
            auto ptr_z =
125
                z_data + ni * C * h * w * simd_width + ci * h * w * simd_width;
126

T
tensor-tang 已提交
127
            multiply(ptr_x, ptr_y, ptr_z, h, w);
128 129 130
          }
        }
      }
131 132 133

      z->set_layout(DataLayout::kMKLDNN);
      z->set_format(x->format());
134 135
    } else {
      // Fallback to naive version:
136
      const bool are_inputs_in_same_format = x->format() == y->format();
137
      const bool is_x_nchw = x->format() == memory::format::nchw;
138
      const bool is_x_nc = x->format() == memory::format::nc;
139
      const bool is_x_x = x->format() == memory::format::x;
140
      const bool is_y_nchw = y->format() == memory::format::nchw;
141
      const bool is_y_nc = y->format() == memory::format::nc;
142
      const bool is_y_x = y->format() == memory::format::x;
143
      if (!are_inputs_in_same_format) {
144 145 146
        using platform::MKLDNNDeviceContext;
        auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
        const auto& mkldnn_engine = dev_ctx.GetEngine();
147
        if (!(is_x_nchw || is_x_nc || is_x_x))
148
          ReorderInput<T>(const_cast<Tensor*>(x), ctx.GetPlace(), mkldnn_engine,
149
                          x->dims().size() == 4);
150
        if (!(is_y_nchw || is_y_nc || is_y_x))
151
          ReorderInput<T>(const_cast<Tensor*>(y), ctx.GetPlace(), mkldnn_engine,
152
                          y->dims().size() == 4);
153 154
      }

155 156 157 158 159 160 161 162
      auto mul_func = [](T a, T b) -> T { return a * b; };

      TransformFunctor<decltype(mul_func), T,
                       paddle::platform::CPUDeviceContext, T>
          functor(
              x, y, z,
              ctx.template device_context<paddle::platform::CPUDeviceContext>(),
              mul_func);
163

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
      axis = (axis == -1 ? x_dims.size() - y_dims_untrimmed.size() : axis);
      PADDLE_ENFORCE(axis >= 0 && axis < x_dims.size(),
                     "Axis should be in range [0, x_dims)");

      auto y_dims = trim_trailing_singular_dims(y_dims_untrimmed);
      axis = (y_dims.size() == 0) ? x_dims.size() : axis;

      int pre, n, post;
      get_mid_dims(x_dims, y_dims, axis, &pre, &n, &post);

      if (post == 1) {
        functor.RunRowWise(n, pre);
      } else {
        functor.RunMidWise(n, pre, post);
      }
179 180 181 182 183 184 185 186 187 188 189 190
      z->set_layout(DataLayout::kMKLDNN);
      z->set_format(x->format());
    }
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_KERNEL(elementwise_mul, MKLDNN, ::paddle::platform::CPUPlace,
                   ops::ElementwiseMulMKLDNNKernel<float>)