top_k_op_npu.cc 3.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* 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 <memory>
#include <string>

#include "paddle/fluid/operators/top_k_op.h"
16
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
17 18 19 20

namespace paddle {
namespace operators {

21 22
void gen_assist_seq(framework::Tensor* assit_tensor,
                    int64_t dim,
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
                    const framework::ExecutionContext& ctx) {
  const int64_t dimx2 = dim;
  std::vector<paddle::platform::float16> assit;
  assit.resize(2 * dimx2);
  for (int64_t i = 0; i < dimx2; i++) {
    // for i in range [0, dim]
    assit[i] = static_cast<paddle::platform::float16>(i);

    // for i in range [dim, dimx2]
    int64_t idx =
        static_cast<int64_t>(static_cast<paddle::platform::float16>(i));
    int64_t gap = i - idx;
    assit[i + dim] = static_cast<paddle::platform::float16>(gap);
  }
  framework::TensorFromVector(assit, ctx.device_context(), assit_tensor);
}

template <typename DeviceContext, typename T>
class TopkNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    // read input
    auto* input = ctx.Input<framework::LoDTensor>("X");
    auto* output = ctx.Output<framework::LoDTensor>("Out");
    auto* indices = ctx.Output<framework::LoDTensor>("Indices");

    size_t k = static_cast<int>(ctx.Attr<int>("k"));

    output->mutable_data<T>(ctx.GetPlace());
52
    indices->mutable_data<int64_t>(ctx.GetPlace());
53 54

    // prepare assit
P
pangyoki 已提交
55 56 57
    auto size = input->dims().size();
    // dim is the last dimension of input
    auto dim = input->dims()[size - 1];
58 59 60 61 62 63 64 65 66 67
    framework::Tensor assist_seq_tensor;
    assist_seq_tensor.Resize({2 * dim});
    assist_seq_tensor.mutable_data<T>(ctx.GetPlace());
    gen_assist_seq(&assist_seq_tensor, dim, ctx);

    framework::NPUAttributeMap attr_input = {{"sorted", "true"},
                                             {"k", static_cast<int>(k)},
                                             {"dim", -1},
                                             {"largest", true}};

68
    Tensor tmp_indices(experimental::DataType::INT32);
69 70 71
    tmp_indices.Resize(indices->dims());
    tmp_indices.mutable_data<int>(ctx.GetPlace());

72
    // run ascend
73 74 75 76
    const auto& runner = NpuOpRunner("TopKD",
                                     {*input, assist_seq_tensor},
                                     {*output, tmp_indices},
                                     attr_input);
77 78 79 80
    auto stream =
        ctx.template device_context<paddle::platform::NPUDeviceContext>()
            .stream();
    runner.Run(stream);
81 82

    // cast indices from INT32 to INT64
83 84
    auto dst_dtype =
        ConvertToNpuDtype(framework::TransToProtoVarType(indices->dtype()));
L
Leo Chen 已提交
85
    const auto& runner_cast_indices =
86 87 88
        NpuOpRunner("Cast",
                    {tmp_indices},
                    {*indices},
89 90
                    {{"dst_type", static_cast<int>(dst_dtype)}});
    runner_cast_indices.Run(stream);
91 92 93 94 95 96 97 98 99 100 101 102
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

// Ascend Op TopKD only support input float 16 dtype
REGISTER_OP_NPU_KERNEL(top_k,
                       ops::TopkNPUKernel<paddle::platform::NPUDeviceContext,
                                          paddle::platform::float16>);