accuracy_op_npu.cc 5.6 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 24 25
/* 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"
#include "paddle/fluid/operators/npu_op_runner.h"

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

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

    // cast equal
81 82
    Tensor tmp_equal_cast(framework::proto::VarType::FP32);
    tmp_equal_cast.Resize(inference->dims());
83
    tmp_equal_cast.mutable_data<float>(ctx.GetPlace());
L
Leo Chen 已提交
84
    const auto& runner_cast_equal = NpuOpRunner(
85 86 87
        "Cast", {tmp_equal}, {tmp_equal_cast},
        {{"dst_type",
          static_cast<int>(ConvertToNpuDtype(tmp_equal_cast.type()))}});
88 89
    runner_cast_equal.Run(stream);

90 91 92 93 94
    // [correct]
    // reduce_max
    Tensor tmp_correct_max(framework::proto::VarType::FP32);
    tmp_correct_max.Resize(framework::make_ddim({num_samples}));
    tmp_correct_max.mutable_data<float>(ctx.GetPlace());
L
Leo Chen 已提交
95
    const auto& runner_reduce_max =
96 97 98 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
    Tensor tmp_correct(framework::proto::VarType::FP32);
    tmp_correct.Resize(correct->dims());
    tmp_correct.mutable_data<float>(ctx.GetPlace());
L
Leo Chen 已提交
104
    const auto& runner_reduce_sum =
105 106 107 108 109 110
        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 已提交
111
    const auto& runner_cast_correct = NpuOpRunner(
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        "Cast", {tmp_correct}, {*correct},
        {{"dst_type", static_cast<int>(ConvertToNpuDtype(correct->type()))}});
    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
    Tensor tmp_total(framework::proto::VarType::FP32);
    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 已提交
129
    const auto& runner_accuracy =
130 131
        NpuOpRunner("Div", {tmp_correct, tmp_total}, {*accuracy}, {});
    runner_accuracy.Run(stream);
132 133 134 135 136 137 138 139 140 141 142 143 144 145
  }
};

}  // 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>);