concat_mkldnn_op.cc 9.4 KB
Newer Older
M
Michal Gallus 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

M
Michal Gallus 已提交
15
#include <memory>
M
Michal Gallus 已提交
16
#include "paddle/fluid/operators/concat_op.h"
17
#include "paddle/fluid/operators/utils.h"
M
Michal Gallus 已提交
18
#include "paddle/fluid/platform/mkldnn_helper.h"
19
#include "paddle/fluid/platform/mkldnn_reuse.h"
M
Michal Gallus 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33

namespace paddle {
namespace operators {

using framework::DataLayout;
using framework::Tensor;
using mkldnn::memory;
using mkldnn::primitive;
using mkldnn::concat;
using mkldnn::stream;
using platform::to_void_cast;

static void EnforceLayouts(const std::vector<const Tensor*> inputs) {
  for (auto* input : inputs) {
34 35 36 37 38 39
    PADDLE_ENFORCE_EQ(
        input->layout(), DataLayout::kMKLDNN,
        platform::errors::InvalidArgument("Wrong layout set for Input tensor"));
    PADDLE_ENFORCE_NE(
        input->format(), MKLDNNMemoryFormat::undef,
        platform::errors::InvalidArgument("Wrong format set for Input tensor"));
M
Michal Gallus 已提交
40 41 42
  }
}

A
Adam 已提交
43 44 45
static memory::desc CreateMemDesc(const Tensor& input,
                                  const memory::data_type& dt) {
  const auto dims = paddle::framework::vectorize<int64_t>(input.dims());
M
Michal Gallus 已提交
46
  const auto format = input.format();
A
Adam 已提交
47 48
  auto mem_desc = memory::desc(dims, dt, format);
  return mem_desc;
M
Michal Gallus 已提交
49 50 51 52 53 54
}

static platform::CPUPlace GetCpuPlace(
    const paddle::framework::ExecutionContext& ctx) {
  auto place = ctx.GetPlace();
  PADDLE_ENFORCE(paddle::platform::is_cpu_place(place),
55
                 platform::errors::InvalidArgument("It must use CPUPlace."));
56
  return BOOST_GET_CONST(platform::CPUPlace, place);
M
Michal Gallus 已提交
57 58
}

M
Michal Gallus 已提交
59
static const mkldnn::engine& GetMKLDNNEngine(
60 61 62
    const paddle::framework::ExecutionContext& ctx) {
  auto& dev_ctx = ctx.template device_context<platform::MKLDNNDeviceContext>();
  return dev_ctx.GetEngine();
M
Michal Gallus 已提交
63
}
M
Michal Gallus 已提交
64

65 66 67 68 69 70 71 72 73 74
// From a multi-input, gather only nonempty inputs
static const std::vector<const Tensor*> ReduceMultiInput(
    const std::vector<const Tensor*>& inputs) {
  std::vector<const Tensor*> reduced(inputs.size());
  auto end_it = std::copy_if(inputs.begin(), inputs.end(), reduced.begin(),
                             [](const Tensor* t) { return t->numel() > 0; });
  reduced.resize(std::distance(reduced.begin(), end_it));
  return reduced;
}

75 76 77 78 79 80 81 82 83
static const std::vector<int> GetDimsForKey(
    const std::vector<const Tensor*>& inputs) {
  auto dims_key = paddle::framework::vectorize<int>(inputs[0]->dims());
  for (auto it = std::next(inputs.begin()); it != inputs.end(); ++it) {
    dims_key.push_back((*it)->dims()[0]);
  }
  return dims_key;
}

M
Michal Gallus 已提交
84 85 86 87 88
template <typename T>
class ConcatPrimitiveFactory {
 public:
  concat::primitive_desc CreateConcatPrimDescriptor(
      const std::vector<const Tensor*> multi_input, Tensor* output,
89 90 91 92
      int concat_axis, const mkldnn::engine& mkldnn_engine,
      const memory::data_type& dt = memory::data_type::f32) {
    CreateSourcesDescriptors(multi_input, mkldnn_engine, dt);
    auto dst_desc = CreateDstMemDescriptor(output, dt);
A
Adam 已提交
93
    return concat::primitive_desc(dst_desc, concat_axis, srcs_d, mkldnn_engine);
M
Michal Gallus 已提交
94
  }
M
Michal Gallus 已提交
95

M
Michal Gallus 已提交
96
  concat CreateConcatPrimitive(const concat::primitive_desc& concat_pd,
A
Adam 已提交
97 98
                               Tensor* output, platform::CPUPlace place,
                               const mkldnn::engine& mkldnn_engine) {
99 100 101 102
    dst_mem = mkldnn::memory(
        concat_pd.dst_desc(), mkldnn_engine,
        output->mutable_data<T>(place, concat_pd.dst_desc().get_size()));

A
Adam 已提交
103
    return concat(concat_pd);
M
Michal Gallus 已提交
104 105
  }

106 107 108 109 110 111 112 113 114 115 116 117 118
  void SetSrcDataHandleByIndex(const std::vector<memory>& srcs, const size_t& i,
                               void* handler) {
    srcs[i].set_data_handle(handler);
  }

  void SetDstDataHandle(const memory& dst_mem, void* handler) {
    dst_mem.set_data_handle(handler);
  }

  std::vector<memory> GetSrcs() { return srcs; }

  memory GetDst() { return dst_mem.get(); }

M
Michal Gallus 已提交
119
 private:
120 121
  memory::desc CreateDstMemDescriptor(Tensor* output,
                                      const memory::data_type& dt) {
A
Adam 已提交
122
    auto dst_dims = paddle::framework::vectorize<int64_t>(output->dims());
123
    return memory::desc(dst_dims, dt, MKLDNNMemoryFormat::any);
M
Michal Gallus 已提交
124 125 126
  }

  void CreateSourcesDescriptors(const std::vector<const Tensor*> multi_input,
127 128
                                const mkldnn::engine& mkldnn_engine,
                                const memory::data_type& dt) {
M
Michal Gallus 已提交
129
    for (size_t i = 0; i < multi_input.size(); i++) {
A
Adam 已提交
130 131 132 133
      auto mem_desc = CreateMemDesc(*multi_input[i], dt);
      srcs_d.push_back(mem_desc);
      srcs.push_back(memory(mem_desc, mkldnn_engine,
                            to_void_cast(multi_input[i]->data<T>())));
M
Michal Gallus 已提交
134
    }
M
Michal Gallus 已提交
135 136 137
  }

 private:
A
Adam 已提交
138 139
  std::vector<memory::desc> srcs_d;
  std::vector<mkldnn::memory> srcs;
140
  paddle::optional<mkldnn::memory> dst_mem;
141
};
M
Michal Gallus 已提交
142 143 144 145 146

template <typename T>
class ConcatMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
147 148
    // If any of the multiple inputs of concat has an input size of 0, the
    // actual size of the multi_input will change
149
    auto multi_input = ReduceMultiInput(ctx.MultiInput<Tensor>("X"));
M
Michal Gallus 已提交
150 151
    EnforceLayouts(multi_input);
    Tensor* output = ctx.Output<Tensor>("Out");
A
Adam 已提交
152
    int concat_axis = ctx.Attr<int>("axis");
153 154 155 156 157 158
    const int rank = multi_input[0]->dims().size();
    PADDLE_ENFORCE_EQ(
        concat_axis >= -rank && concat_axis < rank, true,
        platform::errors::InvalidArgument(
            "The axis is expected to be in range of [%d, %d), but got %d",
            -rank, rank, concat_axis));
159
    platform::MKLDNNDeviceContext::tls().log_lib_version();
160 161 162 163 164 165 166 167 168 169 170

    if (ctx.HasInput("AxisTensor")) {
      auto* axis_tensor = ctx.Input<Tensor>("AxisTensor");
      concat_axis = GetDataFromTensor(axis_tensor)[0];
      auto out_dims = multi_input[0]->dims();
      for (size_t i = 1; i < multi_input.size(); ++i) {
        out_dims[concat_axis] += multi_input[i]->dims()[concat_axis];
      }
      output->Resize(out_dims);
    }

171 172 173
    if (concat_axis < 0) {
      concat_axis = concat_axis + rank;
    }
174 175 176 177 178 179
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::MKLDNNDeviceContext>();
    auto place = GetCpuPlace(ctx);

    memory::data_type dt =
        paddle::framework::ToMKLDNNDataType(multi_input[0]->type());
M
Michal Gallus 已提交
180 181

    ConcatPrimitiveFactory<T> prim_creator;
182 183 184
    std::string key =
        platform::CreateKey(dev_ctx, GetDimsForKey(multi_input),
                            multi_input.size(), ctx.OutputName("Out"), dt);
185
    key = platform::ExtendKeyWithThreadInfoIfNeeded(dev_ctx, key);
A
Adam 已提交
186

187 188 189 190 191 192 193 194 195 196
    const std::string key_prim = key + "@concat_p";
    const std::string key_concat_pd = key + "@concat_pd";
    const std::string key_srcs = key + "@concat_srcs";
    const std::string key_dst = key + "@concat_dst";

    std::shared_ptr<concat::primitive_desc> concat_pd;
    std::shared_ptr<std::vector<memory>> srcs;
    std::shared_ptr<memory> dst_mem;
    auto concat_p = std::static_pointer_cast<concat>(dev_ctx.GetBlob(key_prim));

A
Adam 已提交
197
    const auto& mkldnn_engine = dev_ctx.GetEngine();
198 199
    if (concat_p == nullptr) {
      concat_pd = std::make_shared<concat::primitive_desc>(
A
Adam 已提交
200 201 202 203
          prim_creator.CreateConcatPrimDescriptor(
              multi_input, output, concat_axis, mkldnn_engine, dt));
      concat_p = std::make_shared<concat>(prim_creator.CreateConcatPrimitive(
          *concat_pd, output, place, mkldnn_engine));
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
      srcs = std::make_shared<std::vector<memory>>(prim_creator.GetSrcs());
      dst_mem = std::make_shared<memory>(prim_creator.GetDst());
      dev_ctx.SetBlob(key_prim, concat_p);
      dev_ctx.SetBlob(key_concat_pd, concat_pd);
      dev_ctx.SetBlob(key_srcs, srcs);
      dev_ctx.SetBlob(key_dst, dst_mem);
    } else {
      srcs = std::static_pointer_cast<std::vector<memory>>(
          dev_ctx.GetBlob(key_srcs));
      dst_mem = std::static_pointer_cast<memory>(dev_ctx.GetBlob(key_dst));
      concat_pd = std::static_pointer_cast<concat::primitive_desc>(
          dev_ctx.GetBlob(key_concat_pd));
      for (size_t i = 0; i < multi_input.size(); i++) {
        prim_creator.SetSrcDataHandleByIndex(
            *srcs, i, to_void_cast<T>(multi_input[i]->data<T>()));
      }
220 221 222
      prim_creator.SetDstDataHandle(
          *dst_mem,
          output->mutable_data<T>(place, concat_pd->dst_desc().get_size()));
223 224
    }

225
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
A
Adam 已提交
226 227 228 229 230 231 232 233
    std::unordered_map<int, memory> args;
    for (size_t i = 0; i < multi_input.size(); ++i) {
      args.insert({MKLDNN_ARG_MULTIPLE_SRC + i, (*srcs).at(i)});
    }
    args.insert({MKLDNN_ARG_DST, *dst_mem});

    concat_p->execute(astream, args);
    astream.wait();
M
Michal Gallus 已提交
234

235
    output->set_layout(DataLayout::kMKLDNN);
A
Adam 已提交
236
    output->set_format(platform::GetMKLDNNFormat(*dst_mem));
M
Michal Gallus 已提交
237 238 239 240 241 242 243 244
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_KERNEL(concat, MKLDNN, ::paddle::platform::CPUPlace,
245
                   ops::ConcatMKLDNNOpKernel<float>,
246
                   ops::ConcatMKLDNNOpKernel<paddle::platform::bfloat16>,
247 248
                   ops::ConcatMKLDNNOpKernel<int8_t>,
                   ops::ConcatMKLDNNOpKernel<uint8_t>);