index_sample_op_npu.cc 5.1 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. */

S
seemingwang 已提交
15
#include "paddle/fluid/framework/op_registry.h"
16 17 18 19

namespace paddle {
namespace operators {

20 21
template <typename IndexT>
void IndexSampleGather(const paddle::platform::NPUDeviceContext& dev_ctx,
22 23 24
                       const phi::DenseTensor* index,
                       const phi::DenseTensor* input,
                       phi::DenseTensor* out) {
25 26 27 28 29 30 31 32 33 34 35 36 37 38
  auto index_dims = index->dims();
  auto input_dims = input->dims();
  auto batch_size = input_dims[0];
  auto index_length = index_dims[1];

  std::vector<IndexT> gather_index_vec;
  std::vector<IndexT> index_vec;
  framework::TensorToVector(*index, dev_ctx, &index_vec);
  for (auto i = 0; i < batch_size; ++i) {
    for (auto j = 0; j < index_length; j++) {
      gather_index_vec.push_back(i);
      gather_index_vec.push_back(index_vec[i * index_length + j]);
    }
  }
39
  phi::DenseTensor gather_index;
40 41 42 43 44 45 46 47 48 49 50
  framework::TensorFromVector(gather_index_vec, dev_ctx, &gather_index);
  gather_index.Resize({batch_size, index_length, 2});

  NpuOpRunner runner;
  runner.SetType("GatherNd")
      .AddInput(*input)
      .AddInput(gather_index)
      .AddOutput(*out);
  runner.Run(dev_ctx.stream());
}

51 52 53 54 55 56
template <typename T>
class IndexSampleNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::NPUDeviceContext>();
57 58 59
    auto* input = ctx.Input<phi::DenseTensor>("X");
    auto* index = ctx.Input<phi::DenseTensor>("Index");
    auto* out = ctx.Output<phi::DenseTensor>("Out");
60 61
    out->mutable_data<T>(ctx.GetPlace());

62
    const auto& index_type = framework::TransToProtoVarType(index->dtype());
63
    if (index_type == framework::proto::VarType::INT32) {
64
      IndexSampleGather<int32_t>(dev_ctx, index, input, out);
65
    } else {
66
      IndexSampleGather<int64_t>(dev_ctx, index, input, out);
67 68 69 70 71 72
    }
  }
};

template <typename IndexT>
void IndexSampleGradScatter(const paddle::platform::NPUDeviceContext& dev_ctx,
73 74 75
                            const phi::DenseTensor* index,
                            const phi::DenseTensor* out_grad,
                            phi::DenseTensor* x_grad) {
76 77 78 79 80 81 82 83 84 85 86 87 88 89
  auto index_dims = index->dims();
  auto input_dims = x_grad->dims();
  auto batch_size = input_dims[0];
  auto index_length = index_dims[1];

  std::vector<IndexT> scatter_index_vec;
  std::vector<IndexT> index_vec;
  framework::TensorToVector(*index, dev_ctx, &index_vec);
  for (auto i = 0; i < batch_size; ++i) {
    for (auto j = 0; j < index_length; j++) {
      scatter_index_vec.push_back(i);
      scatter_index_vec.push_back(index_vec[i * index_length + j]);
    }
  }
90
  phi::DenseTensor scatter_index;
91 92 93 94 95 96 97
  framework::TensorFromVector(scatter_index_vec, dev_ctx, &scatter_index);
  scatter_index.Resize({batch_size, index_length, 2});

  NpuOpRunner runner;
  runner.SetType("ScatterNd")
      .AddInput(scatter_index)
      .AddInput(*out_grad)
98
      .AddInput(phi::vectorize<IndexT>(x_grad->dims()))
99 100 101 102 103 104 105 106 107 108
      .AddOutput(*x_grad);
  runner.Run(dev_ctx.stream());
}

template <typename T>
class IndexSampleGradNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::NPUDeviceContext>();
109 110 111
    auto* index = ctx.Input<phi::DenseTensor>("Index");
    auto* out_grad = ctx.Input<phi::DenseTensor>(framework::GradVarName("Out"));
    auto* x_grad = ctx.Output<phi::DenseTensor>(framework::GradVarName("X"));
112 113
    x_grad->mutable_data<T>(ctx.GetPlace());

114
    const auto& index_type = framework::TransToProtoVarType(index->dtype());
115 116 117 118 119 120 121 122 123 124 125 126 127 128
    if (index_type == framework::proto::VarType::INT32) {
      IndexSampleGradScatter<int32_t>(dev_ctx, index, out_grad, x_grad);
    } else {
      IndexSampleGradScatter<int64_t>(dev_ctx, index, out_grad, x_grad);
    }
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;

129 130
REGISTER_OP_NPU_KERNEL(index_sample,
                       ops::IndexSampleNPUKernel<plat::float16>,
131 132 133 134 135 136 137 138
                       ops::IndexSampleNPUKernel<float>,
                       ops::IndexSampleNPUKernel<int32_t>,
                       ops::IndexSampleNPUKernel<int64_t>);
REGISTER_OP_NPU_KERNEL(index_sample_grad,
                       ops::IndexSampleGradNPUKernel<plat::float16>,
                       ops::IndexSampleGradNPUKernel<float>,
                       ops::IndexSampleGradNPUKernel<int32_t>,
                       ops::IndexSampleGradNPUKernel<int64_t>);