From 008be79c9907e13beeca010477aa31bafa6a460e Mon Sep 17 00:00:00 2001 From: shenpengcheng Date: Fri, 28 Jan 2022 19:17:12 +0800 Subject: [PATCH] =?UTF-8?q?BinaryCrossEntropy=20=E7=AE=97=E5=AD=90?= =?UTF-8?q?=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_binary_cross_entropy.py | 92 +++++++++++++++++++ .../aten/ops/BinaryCrossEntropyKernelNpu.cpp | 73 +++++++++++++++ 2 files changed, 165 insertions(+) create mode 100644 test/test_network_ops/test_binary_cross_entropy.py create mode 100644 torch_npu/csrc/aten/ops/BinaryCrossEntropyKernelNpu.cpp diff --git a/test/test_network_ops/test_binary_cross_entropy.py b/test/test_network_ops/test_binary_cross_entropy.py new file mode 100644 index 0000000000..565d7ef3d8 --- /dev/null +++ b/test/test_network_ops/test_binary_cross_entropy.py @@ -0,0 +1,92 @@ +# Copyright (c) 2020 Huawei Technologies Co., Ltd +# Copyright (c) 2019, Facebook CORPORATION. +# All rights reserved. +# +# Licensed under the BSD 3-Clause License (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://opensource.org/licenses/BSD-3-Clause +# +# 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. +import copy +import torch +import torch_npu +import torch.nn as nn +import numpy as np + +from torch_npu.testing.common_utils import TestCase, run_tests +from torch_npu.testing.common_device_type import instantiate_device_type_tests + +LOWER = 0 +UPPER = 1 + +class TestBinaryCrossEntropy(TestCase): + + def generate_input(self, lower, upper, shape, dtype): + temp = np.random.uniform(lower, upper, shape).astype(dtype) + npu_input = torch.from_numpy(temp) + return npu_input + + def cpu_op_exec(self, predict, target, weight=None, reduction="mean"): + res = torch.nn.functional.binary_cross_entropy(predict, target, weight=weight, reduction=reduction) + return res.numpy() + + def cpu_op_exec_half(self, predict, target, weight=None, reduction="mean"): + res = torch.nn.functional.binary_cross_entropy(predict, target, weight=weight, reduction=reduction) + return res.type(torch.float16).numpy() + + def npu_op_exec(self, predict, target, weight=None, reduction="mean"): + predict = predict.to("npu") + target = target.to("npu") + if weight is not None: + weight = weight.to("npu") + res = torch.nn.functional.binary_cross_entropy(predict, target, weight=weight, reduction=reduction) + res = res.to("cpu") + return res.numpy() + + def test_binary_cross_entropy_float32(self, device): + for shape, weight_shape, reduction in [ + ((10, 64), None, "mean"), + ((10, 64), (10, 1), "mean"), + ((10, 64), None, "mean"), + ((10, 64), (10, 64), "mean"), + ((10, 64), (10, 64), "sum" ), + ((10, 64), (10, 64), "none") + ]: + predict = self.generate_input(LOWER, UPPER, shape, np.float32) + target = torch.empty(shape, dtype=torch.float32).random_(2) + weight = None + if weight_shape is not None: + weight = self.generate_input(LOWER, UPPER, weight_shape, np.float32) + cpu_output = self.cpu_op_exec(predict, target, weight=weight, reduction=reduction) + npu_output = self.npu_op_exec(predict, target, weight=weight, reduction=reduction) + self.assertRtolEqual(cpu_output, npu_output) + + def test_binary_cross_entropy_float16(self, device): + for shape, weight_shape, reduction in [ + ((10, 64), (10, 64), "sum"), + ((10, 64), (10, 64), "mean"), + ((10, 64), (10, 64), "none") + ]: + predict = self.generate_input(LOWER, UPPER, shape, np.float16) + target = torch.empty(shape, dtype=torch.float16).random_(2) + predict_32 = predict.type(torch.float32) + target_32 = target.type(torch.float32) + weight = None + weight_32 = None + if weight_shape is not None: + weight = self.generate_input(LOWER, UPPER, weight_shape, np.float16) + weight_32 = weight.type(torch.float32) + + npu_output = self.npu_op_exec(predict, target, weight=weight, reduction=reduction) + cpu_output = self.cpu_op_exec_half(predict_32, target_32, weight=weight_32, reduction=reduction) + self.assertRtolEqual(cpu_output, npu_output) + +instantiate_device_type_tests(TestBinaryCrossEntropy, globals(), except_for="cpu") +if __name__ == "__main__": + run_tests() diff --git a/torch_npu/csrc/aten/ops/BinaryCrossEntropyKernelNpu.cpp b/torch_npu/csrc/aten/ops/BinaryCrossEntropyKernelNpu.cpp new file mode 100644 index 0000000000..af1186022f --- /dev/null +++ b/torch_npu/csrc/aten/ops/BinaryCrossEntropyKernelNpu.cpp @@ -0,0 +1,73 @@ +// Copyright (c) 2020 Huawei Technologies Co., Ltd +// Copyright (c) 2019, Facebook CORPORATION. +// All rights reserved. +// +// Licensed under the BSD 3-Clause License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/BSD-3-Clause +// +// 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 "torch_npu/csrc/framework/utils/CalcuOpUtil.h" +#include "torch_npu/csrc/framework/utils/OpAdapter.h" +#include "torch_npu/csrc/aten/NPUNativeFunctions.h" + +namespace at_npu { +namespace native { + +at::Tensor& NPUNativeFunctions::binary_cross_entropy_out( + const at::Tensor& self, + const at::Tensor& target, + const c10::optional& weight_opt, + int64_t reduction, + at::Tensor& result) { + const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); + at::Tensor weightTensor = weight; + if (!weight.defined()) { + weightTensor = at::ones(self.sizes(), self.options()); + } + + string reductionStr = CalcuOpUtil::get_reduction_str(reduction); + OpCommand cmd; + cmd.Name("BinaryCrossEntropy") + .Input(self) + .Input(target) + .Input(weightTensor) + .Output(result) + .Attr("reduction", reductionStr) + .Run(); + return result; +} + +at::Tensor NPUNativeFunctions::binary_cross_entropy( + const at::Tensor& self, + const at::Tensor& target, + const c10::optional& weight_opt, + int64_t reduction) { + const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); + + at::IntArrayRef outputSize; + if (reduction == at::Reduction::None) { + outputSize = input_same_output_size(self); + } else { + outputSize = at::ArrayRef(); + } + + at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); + if (self.numel() == 0) { + result = result.to(at::kFloat).fill_(0); + result = result / 0; + return result; + } + + NPUNativeFunctions::binary_cross_entropy_out(self, target, weight, reduction, result); + return result; +} +} // namespace native +} // namespace at_npu \ No newline at end of file -- Gitee