accuracy_op_npu.cc 5.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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/controlflow/compare_op.h"
#include "paddle/fluid/operators/metrics/accuracy_op.h"
17
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
18 19 20 21 22 23 24 25

namespace paddle {
namespace operators {

template <typename DeviceContext, typename T>
class AccuracyNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
26
    auto* inference = ctx.Input<Tensor>("Out");
27
    auto* label = ctx.Input<Tensor>("Label");
28
    auto* indices = ctx.Input<Tensor>("Indices");
29

30
    auto* accuracy = ctx.Output<Tensor>("Accuracy");
31 32 33 34 35 36
    auto* correct = ctx.Output<Tensor>("Correct");
    auto* total = ctx.Output<Tensor>("Total");
    auto stream =
        ctx.template device_context<paddle::platform::NPUDeviceContext>()
            .stream();

37 38 39 40
    int num_samples = inference->dims()[0];
    if (num_samples == 0) {
      return;
    }
41

42
    // cast `indices` or `label` if their type is not consistent
43 44 45
    Tensor cast_indices(experimental::DataType::INT32);
    Tensor cast_label(experimental::DataType::INT32);
    if (indices->dtype() != label->dtype()) {
46
      auto dst_dtype = ConvertToNpuDtype(framework::proto::VarType::INT32);
47 48
      if (framework::TransToProtoVarType(indices->dtype()) !=
          framework::proto::VarType::INT32) {
49 50
        cast_indices.Resize(indices->dims());
        cast_indices.mutable_data<int>(ctx.GetPlace());
L
Leo Chen 已提交
51
        const auto& runner_cast_indices =
52 53 54 55 56 57
            NpuOpRunner("Cast", {*indices}, {cast_indices},
                        {{"dst_type", static_cast<int>(dst_dtype)}});
        runner_cast_indices.Run(stream);
      } else {
        cast_indices.ShareDataWith(*indices);
      }
58 59
      if (framework::TransToProtoVarType(label->dtype()) !=
          framework::proto::VarType::INT32) {
60 61
        cast_label.Resize(label->dims());
        cast_label.mutable_data<int>(ctx.GetPlace());
L
Leo Chen 已提交
62
        const auto& runner_cast_label =
63 64 65 66 67 68 69 70 71 72 73
            NpuOpRunner("Cast", {*label}, {cast_label},
                        {{"dst_type", static_cast<int>(dst_dtype)}});
        runner_cast_label.Run(stream);
      } else {
        cast_label.ShareDataWith(*label);
      }
    } else {
      cast_indices.ShareDataWith(*indices);
      cast_label.ShareDataWith(*label);
    }

74
    // equal
75
    Tensor tmp_equal(experimental::DataType::BOOL);
76
    tmp_equal.Resize(inference->dims());
77
    tmp_equal.mutable_data<bool>(ctx.GetPlace());
L
Leo Chen 已提交
78
    const auto& runner_equal =
79
        NpuOpRunner("Equal", {cast_indices, cast_label}, {tmp_equal}, {});
80 81 82
    runner_equal.Run(stream);

    // cast equal
83
    Tensor tmp_equal_cast(experimental::DataType::FLOAT32);
84
    tmp_equal_cast.Resize(inference->dims());
85
    tmp_equal_cast.mutable_data<float>(ctx.GetPlace());
L
Leo Chen 已提交
86
    const auto& runner_cast_equal = NpuOpRunner(
87 88
        "Cast", {tmp_equal}, {tmp_equal_cast},
        {{"dst_type",
89 90
          static_cast<int>(ConvertToNpuDtype(
              framework::TransToProtoVarType(tmp_equal_cast.dtype())))}});
91 92
    runner_cast_equal.Run(stream);

93 94
    // [correct]
    // reduce_max
95
    Tensor tmp_correct_max(experimental::DataType::FLOAT32);
96
    tmp_correct_max.Resize(phi::make_ddim({num_samples}));
97
    tmp_correct_max.mutable_data<float>(ctx.GetPlace());
L
Leo Chen 已提交
98
    const auto& runner_reduce_max =
99 100 101 102 103
        NpuOpRunner("ReduceMaxD", {tmp_equal_cast}, {tmp_correct_max},
                    {{"axes", std::vector<int>{1}}, {"keep_dims", false}});
    runner_reduce_max.Run(stream);

    // reduce_sum
104
    Tensor tmp_correct(experimental::DataType::FLOAT32);
105 106
    tmp_correct.Resize(correct->dims());
    tmp_correct.mutable_data<float>(ctx.GetPlace());
L
Leo Chen 已提交
107
    const auto& runner_reduce_sum =
108 109 110 111 112 113
        NpuOpRunner("ReduceSumD", {tmp_correct_max}, {tmp_correct},
                    {{"axes", std::vector<int>{0}}, {"keep_dims", false}});
    runner_reduce_sum.Run(stream);

    // cast to int
    correct->mutable_data<int>(ctx.GetPlace());
L
Leo Chen 已提交
114
    const auto& runner_cast_correct = NpuOpRunner(
115
        "Cast", {tmp_correct}, {*correct},
116 117
        {{"dst_type", static_cast<int>(ConvertToNpuDtype(
                          framework::TransToProtoVarType(correct->dtype())))}});
118 119 120 121 122 123 124
    runner_cast_correct.Run(stream);

    // [total]
    total->mutable_data<int>(ctx.GetPlace());
    FillNpuTensorWithConstant<int>(total, static_cast<int>(num_samples));

    // use `total` of type `float32` for calculating accuracy
125
    Tensor tmp_total(experimental::DataType::FLOAT32);
126 127 128 129 130 131 132
    tmp_total.Resize(total->dims());
    tmp_total.mutable_data<float>(ctx.GetPlace());
    FillNpuTensorWithConstant<float>(&tmp_total,
                                     static_cast<float>(num_samples));

    // [accuracy]
    accuracy->mutable_data<float>(ctx.GetPlace());
L
Leo Chen 已提交
133
    const auto& runner_accuracy =
134 135
        NpuOpRunner("Div", {tmp_correct, tmp_total}, {*accuracy}, {});
    runner_accuracy.Run(stream);
136 137 138 139 140 141 142 143 144 145 146 147 148 149
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_NPU_KERNEL(
    accuracy, ops::AccuracyNPUKernel<paddle::platform::NPUDeviceContext, float>,
    ops::AccuracyNPUKernel<paddle::platform::NPUDeviceContext,
                           paddle::platform::float16>,
    ops::AccuracyNPUKernel<paddle::platform::NPUDeviceContext, int>,
    ops::AccuracyNPUKernel<paddle::platform::NPUDeviceContext, int64_t>);