<commit_before>/* 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. */

#include "paddle/fluid/memory/memcpy.h"
#include "paddle/fluid/operators/elementwise/elementwise_add_op.h"
#include "paddle/fluid/operators/elementwise/elementwise_op_function.h"

#include "paddle/fluid/platform/mkldnn_helper.h"

namespace paddle {
namespace operators {

using framework::DataLayout;
using framework::Tensor;
using mkldnn::memory;
using mkldnn::reorder;
using mkldnn::primitive;
using mkldnn::stream;
using mkldnn::sum;

template <typename T>
class EltwiseAddMKLDNNKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
    const auto& mkldnn_engine = dev_ctx.GetEngine();

    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());

    int axis = ctx.Attr<int>("axis");

    auto x_dims = x->dims();
    auto y_dims_untrimed = y->dims();
    auto z_dims = z->dims();

    // Execute default elementwise_add operator when
    // broadcast operations need to performed.
    if (x_dims != y_dims_untrimed) {
      auto sum_func = [](T a, T b) -> T { return a + b; };

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

      axis = (axis == -1 ? x_dims.size() - y_dims_untrimed.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_untrimed);
      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);
      }
      z->set_layout(DataLayout::kMKLDNN);
      z->set_format(x->format());
    } else {
      PADDLE_ENFORCE(x->layout() == DataLayout::kMKLDNN &&
                         x->format() != memory::format::format_undef,
                     "Wrong layout/format set for X tensor");
      PADDLE_ENFORCE(y->layout() == DataLayout::kMKLDNN &&
                         y->format() != memory::format::format_undef,
                     "Wrong layout/format set for Y tensor");

      std::vector<int> src_x_tz = framework::vectorize2int(x_dims);
      std::vector<int> src_y_tz = framework::vectorize2int(y_dims_untrimed);<commit_msg>Fix the format issue when 'X' is not nchw. (#17833)<commit_after>/* 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. */

#include "paddle/fluid/memory/memcpy.h"
#include "paddle/fluid/operators/elementwise/elementwise_add_op.h"
#include "paddle/fluid/operators/elementwise/elementwise_op_function.h"

#include "paddle/fluid/framework/data_layout_transform.h"
#include "paddle/fluid/platform/mkldnn_helper.h"

namespace paddle {
namespace operators {

using framework::DataLayout;
using framework::Tensor;
using mkldnn::memory;
using mkldnn::reorder;
using mkldnn::primitive;
using mkldnn::stream;
using mkldnn::sum;

template <typename T>
class EltwiseAddMKLDNNKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
    const auto& mkldnn_engine = dev_ctx.GetEngine();

    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());

    int axis = ctx.Attr<int>("axis");

    auto x_dims = x->dims();
    auto y_dims_untrimed = y->dims();
    auto z_dims = z->dims();

    // Execute default elementwise_add operator when
    // broadcast operations need to performed.
    if (x_dims != y_dims_untrimed) {
      Tensor _x;
      mkldnn::memory::format format;
      std::vector<int> src_x_tz = framework::vectorize2int(x_dims);

      if ((src_x_tz.size() == 3 &&
           x->format() != (format = memory::format::ncw)) ||
          (src_x_tz.size() == 4 &&
           x->format() != (format = memory::format::nchw)) ||
          (src_x_tz.size() == 5 &&
           x->format() != (format = memory::format::ncdhw))) {
        _x.Resize(x_dims);
        auto user_x_memory_pd = memory::primitive_desc(
            {{src_x_tz}, memory::data_type::f32, x->format()}, mkldnn_engine);
        auto x_memory_pd = memory::primitive_desc(
            {{src_x_tz}, memory::data_type::f32, format}, mkldnn_engine);
        auto size = x_memory_pd.get_size();
        _x.mutable_data<T>(ctx.GetPlace(), paddle::memory::Allocator::kDefault,
                           size);
        auto user_x_memory =
            memory(user_x_memory_pd, paddle::platform::to_void_cast<T>(x_data));
        auto x_memory = memory(x_memory_pd,
                               paddle::platform::to_void_cast<T>(_x.data<T>()));

        auto x_reorder = reorder(user_x_memory, x_memory);

        std::vector<primitive> pipeline;
        pipeline.push_back(x_reorder);
        stream(stream::kind::eager).submit(pipeline).wait();
      } else {
        format = x->format();
        _x.ShareDataWith(*x);
      }

      auto sum_func = [](T a, T b) -> T { return a + b; };

      TransformFunctor<decltype(sum_func), T,
                       paddle::platform::CPUDeviceContext, T>
          functor(
              &_x, y, z,
              ctx.template device_context<paddle::platform::CPUDeviceContext>(),
              sum_func);

      axis = (axis == -1 ? x_dims.size() - y_dims_untrimed.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_untrimed);
      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);
      }
      z->set_layout(DataLayout::kMKLDNN);
      z->set_format(format);
    } else {
      PADDLE_ENFORCE(x->layout() == DataLayout::kMKLDNN &&
                         x->format() != memory::format::format_undef,
                     "Wrong layout/format set for X tensor");
      PADDLE_ENFORCE(y->layout() == DataLayout::kMKLDNN &&
                         y->format() != memory::format::format_undef,
                     "Wrong layout/format set for Y tensor");

      std::vector<int> src_x_tz = framework::vectorize2int(x_dims);
      std::vector<int> src_y_tz = framework::vectorize2int(y_dims_untrimed);
{'fraction_non_alphanumeric': 0.13492354740061163, 'fraction_numerical': 0.0052599388379204895, 'mean_word_length': 3.0475247524752476, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 71, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3634622', 'n_tokens_mistral': 2679, 'n_tokens_neox': 2651, 'n_words': 622}