set_value_op_npu.cc 6.9 KB
Newer Older
X
xiongkun 已提交
1
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Q
Qi Li 已提交
2

X
xiongkun 已提交
3 4 5
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
Q
Qi Li 已提交
6

X
xiongkun 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Q
Qi Li 已提交
8

X
xiongkun 已提交
9 10 11 12 13 14 15
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 "paddle/fluid/operators/set_value_op.h"
16
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
X
xiongkun 已提交
17

H
hong 已提交
18 19
#include "paddle/phi/kernels/funcs/slice_utils.h"

X
xiongkun 已提交
20 21 22
namespace paddle {
namespace operators {

Q
Qi Li 已提交
23
using NPUDeviceContext = platform::NPUDeviceContext;
X
xiongkun 已提交
24

Q
Qi Li 已提交
25 26 27 28 29 30 31
template <typename T>
class SetValueNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const {
    auto* in = ctx.Input<Tensor>("Input");
    auto* value_tensor = ctx.Input<Tensor>("ValueTensor");
    auto* out = ctx.Output<Tensor>("Out");
X
xiongkun 已提交
32

Q
Qi Li 已提交
33 34 35
    auto starts_tensor_list = ctx.MultiInput<Tensor>("StartsTensorList");
    auto ends_tensor_list = ctx.MultiInput<Tensor>("EndsTensorList");
    auto steps_tensor_list = ctx.MultiInput<Tensor>("StepsTensorList");
X
xiongkun 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

    auto axes = ctx.Attr<std::vector<int64_t>>("axes");
    auto starts = ctx.Attr<std::vector<int64_t>>("starts");
    auto ends = ctx.Attr<std::vector<int64_t>>("ends");
    auto steps = ctx.Attr<std::vector<int64_t>>("steps");
    auto shape = ctx.Attr<std::vector<int64_t>>("shape");
    auto decrease_axes = ctx.Attr<std::vector<int64_t>>("decrease_axes");
    auto none_axes = ctx.Attr<std::vector<int64_t>>("none_axes");

    if (!starts_tensor_list.empty()) {
      starts = GetDataFromTensorList<int64_t>(starts_tensor_list);
    }
    if (!ends_tensor_list.empty()) {
      ends = GetDataFromTensorList<int64_t>(ends_tensor_list);
    }
    if (!steps_tensor_list.empty()) {
      steps = GetDataFromTensorList<int64_t>(steps_tensor_list);
    }

    auto in_dims = in->dims();
H
hong 已提交
56 57 58 59 60
    phi::funcs::CheckAndUpdateSliceAttrs(in_dims, axes, &starts, &ends, &steps);
    auto slice_dims =
        phi::funcs::GetSliceDims(in_dims, axes, starts, ends, &steps);
    auto decrease_slice_dims =
        phi::funcs::GetDecreasedDims(slice_dims, decrease_axes);
Q
Qi Li 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

    auto slice_dims_for_assign = decrease_slice_dims;
    if (!none_axes.empty()) {
      std::vector<int64_t> slice_dims_with_none;

      size_t none_axes_cur = 0, decrease_axes_cur = 0;
      for (int i = 0; i < slice_dims.size(); ++i) {
        while (none_axes_cur < none_axes.size() &&
               none_axes[none_axes_cur] <= i) {
          slice_dims_with_none.push_back(1);
          none_axes_cur++;
        }
        if (decrease_axes_cur < decrease_axes.size() &&
            decrease_axes[decrease_axes_cur] == i) {
          decrease_axes_cur++;
        } else {
          slice_dims_with_none.push_back(slice_dims[i]);
        }
      }
      while (none_axes_cur < none_axes.size()) {
        slice_dims_with_none.push_back(1);
        none_axes_cur++;
      }
X
xiongkun 已提交
84

85
      slice_dims_for_assign = phi::make_ddim(slice_dims_with_none);
Q
Qi Li 已提交
86 87
    }

88
    paddle::framework::TensorCopy(*in, ctx.GetPlace(), out);
Q
Qi Li 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

    auto starts_indices = std::vector<int64_t>(in_dims.size(), 0);
    auto ends_indices = std::vector<int64_t>(in_dims.size(), 0);
    auto strides_indices = std::vector<int64_t>(in_dims.size(), 0);

    for (int i = 0; i < in_dims.size(); ++i) {
      starts_indices[i] = 0;
      ends_indices[i] = slice_dims[i];
      strides_indices[i] = 1;
    }
    for (size_t i = 0; i < axes.size(); i++) {
      int axis_index = axes[i];
      starts_indices[axis_index] = starts[i];
      ends_indices[axis_index] = ends[i];
      strides_indices[axis_index] = steps[i];
    }

106
    int64_t stride_step = phi::product(in_dims);
Q
Qi Li 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    std::vector<int64_t> index_indices(1, 0);
    for (size_t i = 0; i < strides_indices.size(); ++i) {
      auto index_size = index_indices.size();
      stride_step /= in_dims[i];
      for (size_t j = 0; j < index_size; ++j) {
        auto start_index = *index_indices.begin();
        if (strides_indices[i] > 0) {
          for (int64_t k = starts_indices[i]; k < ends_indices[i];
               k += strides_indices[i]) {
            index_indices.push_back(start_index + k * stride_step);
          }
        } else {
          for (int64_t k = starts_indices[i]; k > ends_indices[i];
               k += strides_indices[i]) {
            index_indices.push_back(start_index + k * stride_step);
          }
        }
        index_indices.erase(index_indices.begin());
      }
    }
X
xiongkun 已提交
127

Q
Qi Li 已提交
128 129
    PADDLE_ENFORCE_EQ(
        static_cast<int64_t>(index_indices.size()),
130
        phi::product(slice_dims_for_assign),
Q
Qi Li 已提交
131 132
        platform::errors::InvalidArgument(
            "OP(set_value) error index indices and value update not match "));
X
xiongkun 已提交
133

Q
Qi Li 已提交
134 135 136 137
    Tensor value_t(in->type());
    if (value_tensor != nullptr) {
      value_t.ShareDataWith(*value_tensor);
    } else {
138
      auto value_dims = phi::make_ddim(shape);
Q
Qi Li 已提交
139 140 141
      CheckIsDimsMatch(slice_dims_for_assign, value_dims);

      value_t.mutable_data<T>(value_dims, ctx.GetPlace());
142 143
      auto value_name =
          GetValueName(framework::TransToProtoVarType(in->dtype()));
C
Chen Weihang 已提交
144
      CopyVectorToTensor<T>(value_name.c_str(), &value_t, ctx);
X
xiongkun 已提交
145 146 147
      value_t.Resize(value_dims);
    }

Q
Qi Li 已提交
148
    auto stream = ctx.template device_context<NPUDeviceContext>().stream();
X
xiongkun 已提交
149

Q
Qi Li 已提交
150 151 152 153 154 155 156 157 158
    Tensor value_temp(in->type());
    if (slice_dims_for_assign == value_t.dims()) {
      value_temp.ShareDataWith(value_t);
    } else {
      value_temp.Resize(slice_dims_for_assign);
      value_temp.mutable_data<T>(ctx.GetPlace());
      NpuOpRunner runner_brd;
      runner_brd.SetType("BroadcastTo")
          .AddInput(value_t)
159
          .AddInput(phi::vectorize(slice_dims_for_assign))
Q
Qi Li 已提交
160 161 162
          .AddOutput(value_temp)
          .Run(stream);
    }
X
xiongkun 已提交
163

164
    int64_t input_numel = phi::product(in_dims);
Q
Qi Li 已提交
165 166 167 168 169 170
    int64_t index_numel = index_indices.size();

    Tensor in_temp, out_temp, val_temp;
    in_temp.ShareDataWith(*in);
    out_temp.ShareDataWith(*out);
    val_temp.ShareDataWith(value_temp);
171 172 173
    in_temp.Resize(phi::make_ddim({input_numel}));
    out_temp.Resize(phi::make_ddim({input_numel}));
    val_temp.Resize(phi::make_ddim({index_numel}));
Q
Qi Li 已提交
174 175 176 177 178 179 180

    NpuOpRunner runner;
    runner.SetType("ScatterUpdate")
        .AddInput(in_temp)
        .AddInput(std::move(index_indices))
        .AddInput(val_temp)
        .AddOutput(out_temp)
181
#if (CANN_VERSION_CODE >= 504000)
182 183
        .AddAttrs({{"use_locking", false}})
#endif
Q
Qi Li 已提交
184
        .Run(stream);
X
xiongkun 已提交
185 186 187 188 189 190 191
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
Q
Qi Li 已提交
192 193 194 195 196 197

REGISTER_OP_NPU_KERNEL(set_value, ops::SetValueNPUKernel<int>,
#ifdef PADDLE_WITH_ASCEND_INT64
                       ops::SetValueNPUKernel<int64_t>,
#endif
                       ops::SetValueNPUKernel<float>)