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>
16

M
Michal Gallus 已提交
17
#include "paddle/fluid/operators/concat_op.h"
18
#include "paddle/fluid/operators/utils.h"
M
Michal Gallus 已提交
19
#include "paddle/fluid/platform/mkldnn_helper.h"
20
#include "paddle/fluid/platform/mkldnn_reuse.h"
M
Michal Gallus 已提交
21 22 23 24

namespace paddle {
namespace operators {

25
using dnnl::concat;
26 27 28
using dnnl::memory;
using dnnl::primitive;
using dnnl::stream;
29 30 31
using framework::DataLayout;
using framework::LoDTensor;
using framework::Tensor;
M
Michal Gallus 已提交
32 33
using platform::to_void_cast;

34 35 36 37 38
template <typename T>
class ConcatMKLDNNHandler
    : public platform::MKLDNNHandlerNoCachingT<T, dnnl::concat> {
 public:
  ConcatMKLDNNHandler(const framework::ExecutionContext& ctx,
39
                      const dnnl::engine mkldnn_engine,
40 41
                      const std::vector<const Tensor*>& inputs,
                      Tensor* output)
42 43 44 45 46
      : platform::MKLDNNHandlerNoCachingT<T, dnnl::concat>(mkldnn_engine,
                                                           ctx.GetPlace()) {
    int concat_axis = ctx.Attr<int>("axis");
    const int rank = inputs[0]->dims().size();
    PADDLE_ENFORCE_EQ(
47 48
        concat_axis >= -rank && concat_axis < rank,
        true,
49 50
        platform::errors::InvalidArgument(
            "The axis is expected to be in range of [%d, %d), but got %d",
51 52 53
            -rank,
            rank,
            concat_axis));
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

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

    if (concat_axis < 0) {
      concat_axis = concat_axis + rank;
    }

69 70
    memory::data_type dt = framework::ToMKLDNNDataType(
        framework::TransToProtoVarType(inputs[0]->dtype()));
71 72 73 74 75
    std::vector<memory::desc> srcs_md;
    srcs_md.reserve(inputs.size());

    // Create memory descriptors for each of inputs
    for (size_t i = 0; i < inputs.size(); ++i) {
76
      srcs_md.push_back(inputs[i]->mem_desc());
77 78
    }

79
    auto dst_dims = phi::vectorize<int64_t>(output->dims());
80 81 82 83 84 85 86 87 88 89 90 91

    dnnl::memory::desc dst_md;

    // if concat is being used as a stack op(all source memories dims on
    // concat_axis are equal to 1), then it may choose a non-optimal memory
    // format tag for destination, because concat primitive is chosing it based
    // on source memory descriptors and f.e.200x1x10 can be described as both
    // abc and bac and both would be using exact same physical layout, but in
    // that scenario bac will be chosen for destination no matter which
    // formats are being set in inputs. In that scenario we are enforcing using
    // a dense format, because it is the most common one and should be the best
    // in terms of the performance
92 93
    const auto src0_tz = srcs_md[0].dims();
    if (std::find(src0_tz.begin(), src0_tz.end(), 1) != src0_tz.end()) {
94 95 96 97 98
      dst_md = memory::desc(
          dst_dims, dt, platform::GetPlainMKLDNNFormat(dst_dims.size()));
    } else {
      dst_md = memory::desc(dst_dims, dt, MKLDNNMemoryFormat::any);
    }
99 100 101 102 103 104 105

    this->AcquireForwardPrimitiveDescriptor(dst_md, concat_axis, srcs_md);
  }

  // (jczaja) concat oneDNN prim is not having .desc attribute so
  // we cannot use base AcquireForwardPrimitiveDescriptor
  void AcquireForwardPrimitiveDescriptor(
106 107
      const memory::desc& dst_md,
      const int concat_axis,
108 109 110 111 112
      const std::vector<memory::desc>& srcs_md) {
    this->fwd_pd_.reset(new dnnl::concat::primitive_desc(
        dst_md, concat_axis, srcs_md, this->engine_));
  }

113
  std::shared_ptr<dnnl::memory> AcquireSrcMemory(const Tensor& input, int i) {
114 115 116 117 118 119
    const T* input_data = input.data<T>();
    return this->AcquireMemoryFromPrimitive(this->fwd_pd_->src_desc(i),
                                            to_void_cast<T>(input_data));
  }
};

M
Michal Gallus 已提交
120 121
static void EnforceLayouts(const std::vector<const Tensor*> inputs) {
  for (auto* input : inputs) {
122
    PADDLE_ENFORCE_EQ(
123 124
        input->layout(),
        DataLayout::kMKLDNN,
125
        platform::errors::InvalidArgument("Wrong layout set for Input tensor"));
M
Michal Gallus 已提交
126 127 128
  }
}

129 130 131 132
// 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());
133 134 135 136
  auto end_it = std::copy_if(
      inputs.begin(), inputs.end(), reduced.begin(), [](const Tensor* t) {
        return t->numel() > 0;
      });
137 138 139 140
  reduced.resize(std::distance(reduced.begin(), end_it));
  return reduced;
}

M
Michal Gallus 已提交
141 142 143 144
template <typename T>
class ConcatMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
145 146 147
    auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
    const auto& mkldnn_engine = dev_ctx.GetEngine();
148 149
    // If any of the multiple inputs of concat has an input size of 0, the
    // actual size of the multi_input will change
150
    auto multi_input = ReduceMultiInput(ctx.MultiInput<Tensor>("X"));
M
Michal Gallus 已提交
151 152
    EnforceLayouts(multi_input);
    Tensor* output = ctx.Output<Tensor>("Out");
153

154
    ConcatMKLDNNHandler<T> handler(ctx, mkldnn_engine, multi_input, output);
155

156 157
    std::vector<std::shared_ptr<memory>> srcs;
    srcs.reserve(multi_input.size());
A
Adam 已提交
158

159 160
    auto dst_mem = handler.AcquireDstMemory(output);
    auto concat_p = handler.AcquireForwardPrimitive();
161

162
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
A
Adam 已提交
163 164
    std::unordered_map<int, memory> args;
    for (size_t i = 0; i < multi_input.size(); ++i) {
165
      srcs.push_back(handler.AcquireSrcMemory(*(multi_input[i]), i));
166
      args.insert({DNNL_ARG_MULTIPLE_SRC + i, *(srcs.at(i))});
A
Adam 已提交
167
    }
168
    args.insert({DNNL_ARG_DST, *dst_mem});
A
Adam 已提交
169 170 171

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

173
    output->set_mem_desc(dst_mem->get_desc());
M
Michal Gallus 已提交
174 175
  }
};
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204

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

    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();

    auto out_var_names = ctx.OutputNames(framework::GradVarName("X"));

    const auto x = ctx.MultiInput<LoDTensor>("X");
    const auto* dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto dx = ctx.MultiOutput<LoDTensor>(framework::GradVarName("X"));

    for (size_t i = 0; i < dx.size(); ++i) {
      if (dx[i] != nullptr) {
        dx[i]->set_lod(x[i]->lod());
      }
    }

    int axis = ctx.Attr<int>("axis");
    if (ctx.HasInput("AxisTensor")) {
      auto* axis_tensor = ctx.Input<Tensor>("AxisTensor");
      axis = GetDataFromTensor<int>(axis_tensor)[0];
    }

205
    auto dout_vec_dims = phi::vectorize(dout->dims());
206 207 208 209 210

    axis = ComputeAxis(axis, dout_vec_dims.size());

    std::vector<int64_t> offset(dout_vec_dims.size(), 0);

211 212 213
    dnnl::memory::data_type dout_type = framework::ToMKLDNNDataType(
        framework::TransToProtoVarType(dout->dtype()));
    platform::ReorderMKLDNNHandler reorder_handler(
214 215 216
        dout_vec_dims,
        framework::TransToProtoVarType(dout->dtype()),
        dout_type,
217
        onednn_engine);
218
    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
219
        dout->mem_desc(), platform::to_void_cast(dout->data<T>()));
220 221 222 223

    for (size_t i = 0; i < dx.size(); ++i) {
      if (out_var_names[i] != framework::kEmptyVarName &&
          dx[i]->numel() != 0UL) {
224
        auto dx_vec_dims = phi::vectorize(dx[i]->dims());
225 226 227 228
        auto slice_mem_p = reorder_handler.AcquireSubmemory(
            dx_vec_dims, offset, reorder_src_memory_p);

        auto reorder_dst_memory_p = reorder_handler.AcquireDstMemory(
229 230 231 232
            dx[i],
            dx_vec_dims,
            platform::GetPlainMKLDNNFormat(dx_vec_dims.size()),
            ctx.GetPlace());
233 234 235 236 237 238 239
        auto reorder_p =
            reorder_handler.AcquireReorder(reorder_dst_memory_p, slice_mem_p);

        reorder_p->execute(astream, *slice_mem_p, *reorder_dst_memory_p);

        offset[axis] += dx[i]->dims()[axis];

240
        dx[i]->set_mem_desc(reorder_dst_memory_p->get_desc());
241 242 243 244 245 246
      }
    }
    astream.wait();
  }
};

M
Michal Gallus 已提交
247 248 249 250 251
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

252 253 254
REGISTER_OP_KERNEL(concat,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
255
                   ops::ConcatMKLDNNOpKernel<float>,
256
                   ops::ConcatMKLDNNOpKernel<paddle::platform::bfloat16>,
257 258
                   ops::ConcatMKLDNNOpKernel<int8_t>,
                   ops::ConcatMKLDNNOpKernel<uint8_t>);
259

260 261 262
REGISTER_OP_KERNEL(concat_grad,
                   MKLDNN,
                   ::paddle::platform::CPUPlace,
263 264
                   ops::ConcatGradMKLDNNOpKernel<float>,
                   ops::ConcatGradMKLDNNOpKernel<paddle::platform::bfloat16>);