sum_mkldnn_op.cc 5.8 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
//   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.

/*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 "mkldnn.hpp"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/operators/math/selected_rows_functor.h"
#include "paddle/fluid/operators/sum_op.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/mkldnn_helper.h"

namespace paddle {
namespace operators {

using framework::DataLayout;
using mkldnn::memory;
using mkldnn::primitive;
T
tangwei12 已提交
40
using mkldnn::reorder;
41 42
using mkldnn::stream;
using mkldnn::sum;
T
tangwei12 已提交
43 44 45
using paddle::framework::Tensor;
using paddle::platform::CPUDeviceContext;
using paddle::platform::MKLDNNDeviceContext;
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
using platform::to_void_cast;

template <typename T>
class SumMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
    PADDLE_ENFORCE(paddle::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();
    auto in_vars = ctx.MultiInputVar("X");

    const int N = in_vars.size();
    auto out_var = ctx.OutputVar("Out");
    bool in_place = out_var == in_vars[0];

    if (out_var->IsType<framework::LoDTensor>()) {
      LoDTensor* output = ctx.Output<LoDTensor>("Out");
      T* output_data = output->mutable_data<T>(ctx.GetPlace());

A
Adam 已提交
66
      auto dst_tz = framework::vectorize<int64_t>(output->dims());
67
      auto src_tz = dst_tz;
A
Adam 已提交
68
      MKLDNNMemoryFormat output_format{MKLDNNMemoryFormat::undef};
69
      std::vector<float> scales;
A
Adam 已提交
70
      std::vector<memory::desc> srcs_md;
71 72
      std::vector<mkldnn::memory> srcs_mem;

73 74
      PADDLE_ENFORCE_EQ(in_vars[0]->IsType<LoDTensor>(), true,
                        "Input[0] must be LoDTensors");
75
      auto& input0 = in_vars[0]->Get<LoDTensor>();
76 77
      PADDLE_ENFORCE_EQ(input0.layout(), DataLayout::kMKLDNN,
                        "Wrong layout set for inputs[0] tensor");
A
Adam 已提交
78
      PADDLE_ENFORCE_NE(input0.format(), MKLDNNMemoryFormat::undef,
79
                        "Wrong format set for inputs[0] tensor");
80

81
      MKLDNNMemoryFormat input_format = input0.format();
82

83
      for (int i = 0; i < N; i++) {
84 85
        PADDLE_ENFORCE_EQ(in_vars[i]->IsType<LoDTensor>(), true,
                          "all inputs must be all LoDTensors");
86
        auto& input = in_vars[i]->Get<LoDTensor>();
87 88
        PADDLE_ENFORCE_EQ(input.layout(), DataLayout::kMKLDNN,
                          "Wrong layout set for inputs");
A
Adam 已提交
89
        PADDLE_ENFORCE_NE(input.format(), MKLDNNMemoryFormat::undef,
90
                          "Wrong format set for inputs");
91 92 93 94 95 96 97 98 99

        if (input.numel() == 0) {
          continue;
        }

        const T* input_data = input.data<T>();

        auto src_md =
            memory::desc(src_tz, memory::data_type::f32, input_format);
A
Adam 已提交
100 101
        auto src_mem = memory(src_md, mkldnn_engine, to_void_cast(input_data));
        srcs_md.push_back(src_md);
102 103 104 105 106
        srcs_mem.push_back(src_mem);
        scales.push_back(1.0);
      }

      auto dst_md =
107
          memory::desc(dst_tz, memory::data_type::f32, MKLDNNMemoryFormat::any);
108

A
Adam 已提交
109
      auto sum_pd = sum::primitive_desc(dst_md, scales, srcs_md, mkldnn_engine);
110

111 112
      std::shared_ptr<memory> dst_mem;
      if (in_place) {
A
Adam 已提交
113
        dst_mem.reset(new memory(sum_pd.dst_desc(), mkldnn_engine));
114
      } else {
A
Adam 已提交
115 116
        dst_mem.reset(
            new memory(sum_pd.dst_desc(), mkldnn_engine, output_data));
117 118
      }

A
Adam 已提交
119 120
      auto sum_prim = mkldnn::sum(sum_pd);
      output_format = platform::GetMKLDNNFormat(sum_pd.dst_desc());
121

A
Adam 已提交
122
      std::shared_ptr<mkldnn::reorder> reorder_p;
123 124 125
      std::shared_ptr<memory> target_mem;
      if (in_place) {
        output_format = input_format;
A
Adam 已提交
126 127 128 129 130 131 132 133 134 135
        target_mem.reset(
            new memory({{src_tz}, memory::data_type::f32, output_format},
                       mkldnn_engine, output_data));
        reorder_p = std::make_shared<reorder>(*dst_mem, *target_mem);
      }

      mkldnn::stream astream(mkldnn_engine);
      std::unordered_map<int, memory> args;
      for (size_t i = 0; i < srcs_mem.size(); ++i) {
        args.insert({MKLDNN_ARG_MULTIPLE_SRC + i, srcs_mem.at(i)});
136
      }
A
Adam 已提交
137 138 139 140
      args.insert({MKLDNN_ARG_DST, *dst_mem});

      sum_prim.execute(astream, args);
      astream.wait();
141

A
Adam 已提交
142 143 144 145
      if (in_place) {
        reorder_p->execute(astream, *dst_mem, *target_mem);
        astream.wait();
      }
146

147 148
      output->set_layout(DataLayout::kMKLDNN);
      output->set_format(output_format);
149 150 151
    } else {  // Fallback to naive version
      SumKernel<CPUDeviceContext, T> reference_kernel;
      reference_kernel.Compute(ctx);
152 153 154 155 156 157 158 159 160
    }
  }
};

}  // namespace operators
}  // namespace paddle

REGISTER_OP_KERNEL(sum, MKLDNN, ::paddle::platform::CPUPlace,
                   paddle::operators::SumMKLDNNOpKernel<float>);