slice_op_mlu.cc 8.2 KB
Newer Older
F
fwenguang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2022 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. */

Z
zyfncg 已提交
15
#include "paddle/fluid/framework/op_registry.h"
F
fwenguang 已提交
16
#include "paddle/fluid/operators/mlu/mlu_baseop.h"
Z
zyfncg 已提交
17
#include "paddle/fluid/operators/utils.h"
18
#include "paddle/phi/core/tensor_utils.h"
F
fwenguang 已提交
19 20 21 22 23 24 25 26 27
#include "paddle/phi/kernels/funcs/slice_utils.h"

namespace paddle {
namespace operators {

template <typename T>
class SliceMLUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
28 29
    auto* input = ctx.Input<phi::DenseTensor>("Input");
    auto* out = ctx.Output<phi::DenseTensor>("Out");
F
fwenguang 已提交
30 31 32 33 34 35 36 37 38

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

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

    // Get the accurate attribute value of starts and ends
39 40
    auto starts_tensor_list =
        ctx.MultiInput<phi::DenseTensor>("StartsTensorList");
F
fwenguang 已提交
41
    if (ctx.HasInput("StartsTensor")) {
42 43
      starts = phi::GetVectorFromTensor<int>(
          ctx.Input<phi::DenseTensor>("StartsTensor"));
F
fwenguang 已提交
44 45 46 47
    } else if (starts_tensor_list.size() > 0) {
      starts = GetDataFromTensorList<int>(starts_tensor_list);
    }

48
    auto ends_tensor_list = ctx.MultiInput<phi::DenseTensor>("EndsTensorList");
F
fwenguang 已提交
49
    if (ctx.HasInput("EndsTensor")) {
50 51
      ends = phi::GetVectorFromTensor<int>(
          ctx.Input<phi::DenseTensor>("EndsTensor"));
F
fwenguang 已提交
52 53 54 55 56
    } else if (ends_tensor_list.size() > 0) {
      ends = GetDataFromTensorList<int>(ends_tensor_list);
    }

    PADDLE_ENFORCE_EQ(
57 58
        starts.size(),
        axes.size(),
F
fwenguang 已提交
59 60 61
        platform::errors::InvalidArgument(
            "The size of starts must be equal to the size of axes."));
    PADDLE_ENFORCE_EQ(
62 63
        ends.size(),
        axes.size(),
F
fwenguang 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        platform::errors::InvalidArgument(
            "The size of ends must be equal to the size of axes."));

    const auto& in_dims = input->dims();
    auto slice_dims = out->dims();
    bool reset_slice_dims = false;
    if (ctx.HasInput("StartsTensor") || ctx.HasInput("EndsTensor") ||
        starts_tensor_list.size() > 0 || ends_tensor_list.size() > 0) {
      // Infer output dims
      for (size_t i = 0; i < axes.size(); ++i) {
        // when start == -1 && end == start+1
        if (starts[i] == -1 && ends[i] == 0 && infer_flags[i] == -1) {
          auto ret =
              std::find(decrease_axis.begin(), decrease_axis.end(), axes[i]);
          if (ret != decrease_axis.end()) {
            ends[i] = in_dims[axes[i]];
          }
        }
      }

      phi::funcs::CheckAndUpdateSliceAttrs(in_dims, axes, &starts, &ends);
85 86
      slice_dims = phi::funcs::GetSliceDims<int>(
          in_dims, axes, starts, ends, nullptr, nullptr);
F
fwenguang 已提交
87 88 89 90 91 92 93
      reset_slice_dims = true;
      auto out_dims = phi::funcs::GetDecreasedDims(slice_dims, decrease_axis);

      out->Resize(out_dims);
    }
    if (slice_dims.size() != in_dims.size() && !reset_slice_dims) {
      phi::funcs::CheckAndUpdateSliceAttrs(in_dims, axes, &starts, &ends);
94 95
      slice_dims = phi::funcs::GetSliceDims<int>(
          in_dims, axes, starts, ends, nullptr, nullptr);
F
fwenguang 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    }

    int in_dim_size = input->dims().size();
    if (static_cast<int>(axes.size()) != in_dim_size) {
      std::vector<int> tmp_starts(in_dim_size, 0);
      const auto& in_dims_vec = phi::vectorize(input->dims());
      std::vector<int> tmp_ends(in_dims_vec.begin(), in_dims_vec.end());
      for (size_t i = 0; i < axes.size(); ++i) {
        tmp_starts[axes[i]] = starts[i];
        tmp_ends[axes[i]] = ends[i];
      }
      starts.swap(tmp_starts);
      ends.swap(tmp_ends);
    }
    std::vector<int> strides(in_dim_size, 1);

    out->mutable_data<T>(ctx.GetPlace());

    MLUCnnlTensorDesc input_desc(*input);
    MLUCnnlTensorDesc out_desc(slice_dims.size(),
                               phi::vectorize(slice_dims).data(),
                               ToCnnlDataType<T>());
118 119 120 121 122 123 124
    MLUCnnl::StridedSlice(ctx,
                          starts.data(),
                          ends.data(),
                          strides.data(),
                          input_desc.get(),
                          GetBasePtr(input),
                          out_desc.get(),
F
fwenguang 已提交
125 126 127 128 129 130 131 132
                          GetBasePtr(out));
  }
};

template <typename T>
class SliceGradMLUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
133 134 135 136
    auto* input = ctx.Input<phi::DenseTensor>("Input");
    auto* dout = ctx.Input<phi::DenseTensor>(framework::GradVarName("Out"));
    auto* dinput =
        ctx.Output<phi::DenseTensor>(framework::GradVarName("Input"));
F
fwenguang 已提交
137 138 139 140 141 142

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

    // Get the accurate attribute value of starts and ends
143 144
    auto starts_tensor_list =
        ctx.MultiInput<phi::DenseTensor>("StartsTensorList");
F
fwenguang 已提交
145
    if (ctx.HasInput("StartsTensor")) {
146 147
      starts = phi::GetVectorFromTensor<int>(
          ctx.Input<phi::DenseTensor>("StartsTensor"));
F
fwenguang 已提交
148 149 150 151
    } else if (starts_tensor_list.size() > 0) {
      starts = GetDataFromTensorList<int>(starts_tensor_list);
    }

152
    auto ends_tensor_list = ctx.MultiInput<phi::DenseTensor>("EndsTensorList");
F
fwenguang 已提交
153
    if (ctx.HasInput("EndsTensor")) {
154 155
      ends = phi::GetVectorFromTensor<int>(
          ctx.Input<phi::DenseTensor>("EndsTensor"));
F
fwenguang 已提交
156 157 158 159 160 161 162 163
    } else if (ends_tensor_list.size() > 0) {
      ends = GetDataFromTensorList<int>(ends_tensor_list);
    }

    const auto& in_dims = input->dims();
    auto slice_dims = dout->dims();
    if (slice_dims.size() != in_dims.size()) {
      phi::funcs::CheckAndUpdateSliceAttrs(in_dims, axes, &starts, &ends);
164 165
      slice_dims = phi::funcs::GetSliceDims<int>(
          in_dims, axes, starts, ends, nullptr, nullptr);
F
fwenguang 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    }

    int in_dim_size = input->dims().size();
    if (static_cast<int>(axes.size()) != in_dim_size) {
      std::vector<int> tmp_starts(in_dim_size, 0);
      const auto& in_dims_vec = phi::vectorize(input->dims());
      std::vector<int> tmp_ends(in_dims_vec.begin(), in_dims_vec.end());
      for (size_t i = 0; i < axes.size(); ++i) {
        tmp_starts[axes[i]] = starts[i];
        tmp_ends[axes[i]] = ends[i];
      }
      starts.swap(tmp_starts);
      ends.swap(tmp_ends);
    }
    std::vector<int> strides(in_dim_size, 1);

    dinput->mutable_data<T>(ctx.GetPlace());

    MLUCnnlTensorDesc dout_desc(slice_dims.size(),
                                phi::vectorize(slice_dims).data(),
                                ToCnnlDataType<T>());
    MLUCnnlTensorDesc dinput_desc(*dinput);
188 189 190 191 192 193 194 195
    MLUCnnl::StridedSliceGrad(ctx,
                              starts.data(),
                              ends.data(),
                              strides.data(),
                              dout_desc.get(),
                              GetBasePtr(dout),
                              dinput_desc.get(),
                              GetBasePtr(dinput));
F
fwenguang 已提交
196 197 198 199 200 201 202 203
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

204 205 206 207
REGISTER_OP_MLU_KERNEL(slice,
                       ops::SliceMLUKernel<float>,
                       ops::SliceMLUKernel<int>,
                       ops::SliceMLUKernel<bool>,
F
fwenguang 已提交
208 209 210 211
                       ops::SliceMLUKernel<int64_t>,
                       ops::SliceMLUKernel<double>,
                       ops::SliceMLUKernel<paddle::platform::float16>);

212 213
REGISTER_OP_MLU_KERNEL(slice_grad,
                       ops::SliceGradMLUKernel<float>,
F
fwenguang 已提交
214 215 216 217
                       ops::SliceGradMLUKernel<int>,
                       ops::SliceGradMLUKernel<bool>,
                       ops::SliceGradMLUKernel<int64_t>,
                       ops::SliceGradMLUKernel<paddle::platform::float16>);