slice_mkldnn_op.cc 8.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2021 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. */

15
#include "paddle/fluid/operators/utils.h"
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include "paddle/fluid/platform/mkldnn_reuse.h"

namespace paddle {
namespace operators {

using paddle::framework::Tensor;

template <typename T>
class SliceMKLDNNKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    this->RunKernel(ctx);
  }

  void RunKernel(const framework::ExecutionContext& ctx) const {
    const auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
    const auto& onednn_engine = dev_ctx.GetEngine();

    auto* x = ctx.Input<Tensor>("Input");
    auto* out = ctx.Output<Tensor>("Out");

38
    auto x_vec_dims = phi::vectorize(x->dims());
39 40 41 42 43 44 45 46 47 48 49 50

    auto axes_int = ctx.Attr<std::vector<int>>("axes");
    auto starts_int = ctx.Attr<std::vector<int>>("starts");
    auto ends_int = ctx.Attr<std::vector<int>>("ends");

    std::vector<int64_t> axes(ctx.Attr<std::vector<int>>("axes").begin(),
                              ctx.Attr<std::vector<int>>("axes").end());
    std::vector<int64_t> starts(ctx.Attr<std::vector<int>>("starts").begin(),
                                ctx.Attr<std::vector<int>>("starts").end());
    std::vector<int64_t> ends(ctx.Attr<std::vector<int>>("ends").begin(),
                              ctx.Attr<std::vector<int>>("ends").end());

51 52 53 54 55 56 57
    auto starts_tensor_list = ctx.MultiInput<Tensor>("StartsTensorList");
    if (ctx.HasInput("StartsTensor")) {
      starts = GetDataFromTensor<int64_t>(ctx.Input<Tensor>("StartsTensor"));
    } else if (starts_tensor_list.size() > 0) {
      starts = GetDataFromTensorList<int64_t>(starts_tensor_list);
    }

58 59
    auto decrease_axis = ctx.Attr<std::vector<int>>("decrease_axis");

60 61 62 63 64 65 66
    auto ends_tensor_list = ctx.MultiInput<Tensor>("EndsTensorList");
    if (ctx.HasInput("EndsTensor")) {
      ends = GetDataFromTensor<int64_t>(ctx.Input<Tensor>("EndsTensor"));
    } else if (ends_tensor_list.size() > 0) {
      ends = GetDataFromTensorList<int64_t>(ends_tensor_list);
    }

67 68 69 70 71 72 73 74
    std::vector<int64_t> offsets(x_vec_dims.size(), 0);
    std::vector<int64_t> slice_dims(x_vec_dims);

    for (size_t i = 0; i < axes.size(); ++i) {
      starts[i] = starts[i] < 0 ? x_vec_dims[axes[i]] + starts[i] : starts[i];
      ends[i] = ends[i] < 0 ? x_vec_dims[axes[i]] + ends[i]
                            : std::min(ends[i], x_vec_dims[axes[i]]);
      offsets[axes[i]] = starts[i];
75 76
      slice_dims[axes[i]] =
          std::max(static_cast<int64_t>(0), ends[i] - starts[i]);
77 78
    }

79
    out->Resize(phi::make_ddim(slice_dims));
80

81 82 83 84 85 86 87
    // Note(0x45f): To support slice Tensors with shapes like [0, 0, 0].
    if (!x->initialized()) {
      out->mutable_data(x->place(), x->dtype());
      out->set_layout(experimental::DataLayout::kMKLDNN);
      return;
    }

88 89
    dnnl::memory::data_type x_type =
        framework::ToMKLDNNDataType(framework::TransToProtoVarType(x->dtype()));
90

91
    platform::ReorderMKLDNNHandler reorder_handler(
92 93 94
        x_vec_dims,
        framework::TransToProtoVarType(x->dtype()),
        x_type,
95
        onednn_engine);
96 97

    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
98
        x->mem_desc(), platform::to_void_cast(x->data<T>()));
99 100
    auto slice_mem_p = reorder_handler.AcquireSubmemory(
        slice_dims, offsets, reorder_src_memory_p);
101
    auto reorder_dst_memory_p = reorder_handler.AcquireDstMemory(
102 103 104
        out,
        slice_dims,
        platform::GetPlainMKLDNNFormat(x_vec_dims.size()),
105
        ctx.GetPlace());
106 107 108 109 110 111

    auto reorder_p =
        reorder_handler.AcquireReorder(reorder_dst_memory_p, slice_mem_p);
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
    reorder_p->execute(astream, *slice_mem_p, *reorder_dst_memory_p);

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    std::vector<int64_t> new_out_dims(slice_dims.size() - decrease_axis.size());

    if (new_out_dims.size() == 0) {
      new_out_dims.emplace_back(1);
    } else {
      for (const auto& axis : decrease_axis) {
        slice_dims[axis] = 0;
      }

      int i = 0;
      for (const auto& slice_dim : slice_dims) {
        if (slice_dim != 0) new_out_dims[i++] = slice_dim;
      }
    }

    astream.wait();
128
    out->Resize(phi::make_ddim(new_out_dims));
129
    out->set_mem_desc(reorder_dst_memory_p->get_desc().reshape(new_out_dims));
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  }
};
template <typename T>
class SliceGradMKLDNNKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    this->RunKernel(ctx);
  }

  void RunKernel(const framework::ExecutionContext& ctx) const {
    const auto& dev_ctx =
        ctx.template device_context<platform::MKLDNNDeviceContext>();
    const auto& onednn_engine = dev_ctx.GetEngine();

    auto* dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto* dx = ctx.Output<Tensor>(framework::GradVarName("Input"));

147 148
    auto dx_vec_dims = phi::vectorize(dx->dims());
    auto dout_vec_dims = phi::vectorize(dout->dims());
149 150 151 152 153 154 155 156 157 158 159 160

    auto axes_int = ctx.Attr<std::vector<int>>("axes");
    auto starts_int = ctx.Attr<std::vector<int>>("starts");
    auto ends_int = ctx.Attr<std::vector<int>>("ends");

    std::vector<int64_t> axes(ctx.Attr<std::vector<int>>("axes").begin(),
                              ctx.Attr<std::vector<int>>("axes").end());
    std::vector<int64_t> starts(ctx.Attr<std::vector<int>>("starts").begin(),
                                ctx.Attr<std::vector<int>>("starts").end());
    std::vector<int64_t> ends(ctx.Attr<std::vector<int>>("ends").begin(),
                              ctx.Attr<std::vector<int>>("ends").end());

161 162 163 164 165 166 167 168 169 170 171 172 173 174
    auto starts_tensor_list = ctx.MultiInput<Tensor>("StartsTensorList");
    if (ctx.HasInput("StartsTensor")) {
      starts = GetDataFromTensor<int64_t>(ctx.Input<Tensor>("StartsTensor"));
    } else if (starts_tensor_list.size() > 0) {
      starts = GetDataFromTensorList<int64_t>(starts_tensor_list);
    }

    auto ends_tensor_list = ctx.MultiInput<Tensor>("EndsTensorList");
    if (ctx.HasInput("EndsTensor")) {
      ends = GetDataFromTensor<int64_t>(ctx.Input<Tensor>("EndsTensor"));
    } else if (ends_tensor_list.size() > 0) {
      ends = GetDataFromTensorList<int64_t>(ends_tensor_list);
    }

175 176 177 178 179 180 181 182 183 184 185 186 187
    auto decrease_axis = ctx.Attr<std::vector<int>>("decrease_axis");

    std::vector<int64_t> offsets(dx_vec_dims.size(), 0);
    std::vector<int64_t> slice_dims(dx_vec_dims);

    for (size_t i = 0; i < axes.size(); ++i) {
      starts[i] = starts[i] < 0 ? dx_vec_dims[axes[i]] + starts[i] : starts[i];
      ends[i] = ends[i] < 0 ? dx_vec_dims[axes[i]] + ends[i]
                            : std::min(ends[i], dx_vec_dims[axes[i]]);
      offsets[axes[i]] = starts[i];
      slice_dims[axes[i]] = ends[i] - starts[i];
    }

188 189
    dnnl::memory::data_type dout_type = framework::ToMKLDNNDataType(
        framework::TransToProtoVarType(dout->dtype()));
190

191
    platform::ReorderMKLDNNHandler reorder_handler(
192 193 194
        slice_dims,
        framework::TransToProtoVarType(dout->dtype()),
        dout_type,
195
        onednn_engine);
196 197

    auto reorder_src_memory_p = reorder_handler.AcquireSrcMemory(
198 199
        dout->mem_desc().reshape(slice_dims),
        platform::to_void_cast(dout->data<T>()));
200
    auto reorder_dst_memory_p = reorder_handler.AcquireDstMemory(
201 202 203
        dx,
        dx_vec_dims,
        platform::GetPlainMKLDNNFormat(dx_vec_dims.size()),
204
        ctx.GetPlace());
205 206
    memset(dx->data<T>(), 0, reorder_dst_memory_p->get_desc().get_size());

207 208
    auto slice_mem_p = reorder_handler.AcquireSubmemory(
        slice_dims, offsets, reorder_dst_memory_p);
209 210 211 212 213 214 215

    auto reorder_p =
        reorder_handler.AcquireReorder(slice_mem_p, reorder_src_memory_p);
    auto& astream = platform::MKLDNNDeviceContext::tls().get_stream();
    reorder_p->execute(astream, *reorder_src_memory_p, *slice_mem_p);
    astream.wait();

216
    dx->set_mem_desc(reorder_dst_memory_p->get_desc());
217 218 219 220 221 222
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
223 224 225
REGISTER_OP_KERNEL(slice,
                   MKLDNN,
                   paddle::platform::CPUPlace,
226
                   ops::SliceMKLDNNKernel<float>,
Z
Zuza 已提交
227 228
                   ops::SliceMKLDNNKernel<int8_t>,
                   ops::SliceMKLDNNKernel<uint8_t>,
229 230 231
                   ops::SliceMKLDNNKernel<paddle::platform::bfloat16>);

namespace ops = paddle::operators;
232 233 234
REGISTER_OP_KERNEL(slice_grad,
                   MKLDNN,
                   paddle::platform::CPUPlace,
235
                   ops::SliceGradMKLDNNKernel<float>,
236
                   ops::SliceGradMKLDNNKernel<paddle::platform::bfloat16>);