index_select_op_npu.cc 5.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* 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. */

#include "paddle/fluid/operators/index_select_op.h"
#include "paddle/fluid/operators/npu_op_runner.h"

namespace paddle {
namespace operators {

template <typename DeviceContext, typename T>
class IndexSelectNPUKernel : public framework::OpKernel<T> {
 public:
24 25 26
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* x = ctx.Input<Tensor>("X");
    auto* index = ctx.Input<Tensor>("Index");
27 28
    auto dim = ctx.Attr<int>("dim");

29
    auto* out = ctx.Output<Tensor>("Out");
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    out->mutable_data<T>(ctx.GetPlace());

    auto stream =
        ctx.template device_context<paddle::platform::NPUDeviceContext>()
            .stream();

    NpuOpRunner runner;
    runner.SetType("GatherV2")
        .AddInput(*x)
        .AddInput(*index)
        .AddInput(std::vector<int32_t>{dim})
        .AddOutput(*out);
    runner.Run(stream);
  }
};

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
template <typename DeviceContext, typename T>
class IndexSelectGradNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* x_grad = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
    auto* index = ctx.Input<Tensor>("Index");
    auto* out_grad =
        ctx.Input<framework::Tensor>(framework::GradVarName("Out"));

    auto stream =
        ctx.template device_context<paddle::platform::NPUDeviceContext>()
            .stream();

    auto x_dims = x_grad->dims();
    auto out_dims = out_grad->dims();

    int dim = ctx.Attr<int>("dim");
    if (dim < 0) {
      dim += out_dims.size();
    }

    Tensor casted_index;
    if (index->type() != framework::proto::VarType::INT32) {
      casted_index.mutable_data<int32_t>(index->dims(), ctx.GetPlace());
      const auto& cast_runner = NpuOpRunner("Cast", {*index}, {casted_index},
                                            {{"dst_type", ACL_INT32}});
      cast_runner.Run(stream);
    } else {
      casted_index.ShareDataWith(*index);
    }

    if (dim == 0) {
      x_grad->mutable_data<T>(ctx.GetPlace());
      const auto& zeros_runner = NpuOpRunner("ZerosLike", {*x_grad}, {*x_grad});
      zeros_runner.Run(stream);

      NpuOpRunner runner;
      runner.SetType("UnsortedSegmentSum")
          .AddInput(*out_grad)
          .AddInput(casted_index)
          .AddInput(std::vector<int64_t>{x_dims[dim]})
          .AddOutput(*x_grad);
      runner.Run(stream);
    } else {
      Tensor transed_out_grad;
      std::vector<int> in_trans_perm;
      in_trans_perm.push_back(dim);
      for (int i = 0; i < out_dims.size(); ++i) {
        if (i == dim) continue;
        in_trans_perm.push_back(i);
      }
      framework::DDim transed_out_dims(out_dims);
      for (size_t i = 0; i < in_trans_perm.size(); ++i) {
        transed_out_dims[i] = out_dims[in_trans_perm[i]];
      }
      transed_out_grad.mutable_data<T>(transed_out_dims, ctx.GetPlace());
102 103 104 105 106
      NpuOpRunner in_trans_runner;
      in_trans_runner.SetType("Transpose")
          .AddInput(*out_grad)
          .AddInput(std::move(in_trans_perm))
          .AddOutput(transed_out_grad);
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
      in_trans_runner.Run(stream);

      Tensor sum_out;
      framework::DDim sum_dims(x_dims);
      sum_dims[0] = x_dims[dim];
      auto idx = 1;
      for (int i = 0; i < x_dims.size(); ++i) {
        if (i == dim) continue;
        sum_dims[idx++] = x_dims[i];
      }
      sum_out.mutable_data<T>(sum_dims, ctx.GetPlace());
      const auto& zeros_runner = NpuOpRunner("ZerosLike", {sum_out}, {sum_out});
      zeros_runner.Run(stream);

      NpuOpRunner runner;
      runner.SetType("UnsortedSegmentSum")
          .AddInput(transed_out_grad)
          .AddInput(casted_index)
          .AddInput(std::vector<int64_t>{x_dims[dim]})
          .AddOutput(sum_out);
      runner.Run(stream);

      std::vector<int> out_trans_perm;
      for (int i = 1; i < 1 + dim; ++i) {
        out_trans_perm.push_back(i);
      }
      out_trans_perm.push_back(0);
      for (int i = 1 + dim; i < x_dims.size(); ++i) {
        out_trans_perm.push_back(i);
      }
      x_grad->mutable_data<T>(ctx.GetPlace());
138 139 140 141 142
      NpuOpRunner out_trans_runner;
      out_trans_runner.SetType("Transpose")
          .AddInput(sum_out)
          .AddInput(std::move(out_trans_perm))
          .AddOutput(*x_grad);
143 144 145 146
      out_trans_runner.Run(stream);
    }
  }
};
147 148 149 150 151 152 153 154 155 156

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP_NPU_KERNEL(
    index_select,
    ops::IndexSelectNPUKernel<paddle::platform::NPUDeviceContext, float>,
    ops::IndexSelectNPUKernel<paddle::platform::NPUDeviceContext, int>,
    ops::IndexSelectNPUKernel<paddle::platform::NPUDeviceContext, int64_t>);
157 158 159 160 161
REGISTER_OP_NPU_KERNEL(
    index_select_grad,
    ops::IndexSelectGradNPUKernel<paddle::platform::NPUDeviceContext, float>,
    ops::IndexSelectGradNPUKernel<paddle::platform::NPUDeviceContext, int>,
    ops::IndexSelectGradNPUKernel<paddle::platform::NPUDeviceContext, int64_t>);