elementwise_add_mkldnn_op.cc 6.7 KB
Newer Older
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
/* 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_add_op.h"
#include "paddle/fluid/operators/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();
50
    auto y_dims_untrimed = y->dims();
51 52 53 54
    auto z_dims = z->dims();

    // Execute default elementwise_add operator when
    // broadcast operations need to performed.
55
    if (x_dims != y_dims_untrimed) {
56 57 58 59 60 61 62 63 64
      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);

65
      axis = (axis == -1 ? x_dims.size() - y_dims_untrimed.size() : axis);
66 67 68
      PADDLE_ENFORCE(axis >= 0 && axis < x_dims.size(),
                     "Axis should be in range [0, x_dims)");

69
      auto y_dims = trim_trailing_singular_dims(y_dims_untrimed);
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
      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,
P
Paweł Żelazko 已提交
88
                     "Wrong layout/format set for Y tensor");
89 90

      std::vector<int> src_x_tz = framework::vectorize2int(x_dims);
91
      std::vector<int> src_y_tz = framework::vectorize2int(y_dims_untrimed);
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
      std::vector<int> dst_tz = framework::vectorize2int(z_dims);

      std::vector<memory::primitive_desc> srcs_pd;
      std::vector<memory> srcs;
      std::vector<float> scales = {1.0f, 1.0f};

      auto src_x_pd = memory::primitive_desc(
          {{src_x_tz}, memory::data_type::f32, x->format()}, mkldnn_engine);
      auto src_y_pd = memory::primitive_desc(
          {{src_y_tz}, memory::data_type::f32, y->format()}, mkldnn_engine);
      auto src_x_memory =
          memory(src_x_pd, paddle::platform::to_void_cast(x_data));
      auto src_y_memory =
          memory(src_y_pd, paddle::platform::to_void_cast(y_data));

      srcs_pd.push_back(src_x_pd);
      srcs_pd.push_back(src_y_pd);
      srcs.push_back(src_x_memory);
      srcs.push_back(src_y_memory);

      auto dst_md =
          memory::desc({dst_tz}, memory::data_type::f32, memory::format::any);

      // create primitive descriptor for sum
      auto sum_pd = sum::primitive_desc(dst_md, scales, srcs_pd);

      // create mkldnn memory for dst
      memory dst_memory = memory(sum_pd.dst_primitive_desc(), z_data);

      std::vector<primitive::at> inputs;
      inputs.push_back(srcs[0]);
      inputs.push_back(srcs[1]);

      // create sum primitive
      auto sum_prim = sum(sum_pd, inputs, dst_memory);

      std::vector<primitive> pipeline;
      pipeline.push_back(sum_prim);
      stream(stream::kind::eager).submit(pipeline).wait();

      z->set_layout(DataLayout::kMKLDNN);
      z->set_format(
          (memory::format)dst_memory.get_primitive_desc().desc().data.format);
    }
  }
};

template <typename T>
140
class EltwiseAddMKLDNNGradKernel : public ElemwiseGradKernel<T> {
141 142
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
143
    ElemwiseGradKernel<T>::Compute(ctx);
144 145 146 147 148 149
    using Tensor = framework::Tensor;

    auto* dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto* dx = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto* dy = ctx.Output<Tensor>(framework::GradVarName("Y"));
    int axis = ctx.Attr<int>("axis");
150 151 152 153
    // skip out, x, y,
    // dout length is larger or equal than dx, dy.
    auto* out = dout;
    auto *x = dout, *y = dout;
154 155 156 157 158 159

    auto set_mkldnn_format = [](Tensor* in, const Tensor* out) {
      in->set_layout(DataLayout::kMKLDNN);
      in->set_format(out->format());
    };

160 161 162 163 164 165 166 167 168 169 170 171 172 173
    if (dx != nullptr && dy != nullptr && dx->dims() == dy->dims()) {
      if (dx->dims() == dy->dims()) {
        auto blas = math::GetBlas<paddle::platform::CPUDeviceContext, T>(ctx);
        if (dx) {
          blas.VCOPY(dout->numel(), dout->data<T>(),
                     dx->mutable_data<T>(ctx.GetPlace()));
          set_mkldnn_format(dx, dout);
        }

        if (dy) {
          blas.VCOPY(dout->numel(), dout->data<T>(),
                     dy->mutable_data<T>(ctx.GetPlace()));
          set_mkldnn_format(dy, dout);
        }
174 175 176
      }
    } else {
      // Execute default kernel when broadcast is needed
177 178
      ElemwiseExplicitGradCompute<paddle::platform::CPUDeviceContext, T,
                                  IdentityGrad<T>, IdentityGrad<T>>(
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
          ctx, *x, *y, *out, *dout, axis, dx, dy, IdentityGrad<T>(),
          IdentityGrad<T>());
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_KERNEL(elementwise_add, MKLDNN, ::paddle::platform::CPUPlace,
                   ops::EltwiseAddMKLDNNKernel<float>)

REGISTER_OP_KERNEL(elementwise_add_grad, MKLDNN, ::paddle::platform::CPUPlace,
                   ops::EltwiseAddMKLDNNGradKernel<float>)