未验证 提交 b94d7ff3 编写于 作者: Z zhulei 提交者: GitHub

[NPU] Add log_loss op (#35010)

* [NPU] Add log_loss op

* [NPU] Add log_loss op

* [NPU] Add log_loss op
上级 e864667b
/* 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 Licnse. */
#include "paddle/fluid/operators/log_loss_op.h"
#include <cmath>
#include "paddle/fluid/operators/npu_op_runner.h"
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
template <typename T>
void LogLossAdds(const platform::Place& place, const aclrtStream& stream,
const Tensor* x, float scale, Tensor* y) {
// Calculate y = x + scale
y->mutable_data<T>(x->dims(), place);
const auto& runner = NpuOpRunner("Adds", {*x}, {*y}, {{"value", scale}});
runner.Run(stream);
}
template <typename T>
void LogLossMuls(const platform::Place& place, const aclrtStream& stream,
const Tensor* x, float scale, Tensor* y) {
// Calculate y = x + scale
y->mutable_data<T>(x->dims(), place);
const auto& runner = NpuOpRunner("Muls", {*x}, {*y}, {{"value", scale}});
runner.Run(stream);
}
template <typename T>
void LogLossBCE(const platform::Place& place, const aclrtStream& stream,
const Tensor* x, const Tensor* y, Tensor* z) {
z->mutable_data<T>(x->dims(), place);
const auto& runner =
NpuOpRunner("BinaryCrossEntropy", {*x, *y}, {*z},
{{"reduction", static_cast<std::string>("none")}});
runner.Run(stream);
}
template <typename T>
void LogLossBCEGrad(const platform::Place& place, const aclrtStream& stream,
const Tensor* x, const Tensor* y, const Tensor* dout,
Tensor* dx) {
dx->mutable_data<T>(x->dims(), place);
const auto& runner =
NpuOpRunner("BinaryCrossEntropyGrad", {*x, *y, *dout}, {*dx},
{{"reduction", static_cast<std::string>("none")}});
runner.Run(stream);
}
template <typename T, typename AttrType = T>
class LogLossNPUKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* y = ctx.Output<Tensor>("Loss");
auto* pred = ctx.Input<Tensor>("Predicted");
auto* label = ctx.Input<Tensor>("Labels");
auto epsilon = static_cast<T>(ctx.Attr<AttrType>("epsilon"));
auto place = ctx.GetPlace();
auto stream =
ctx.template device_context<paddle::platform::NPUDeviceContext>()
.stream();
float factor = 1 / (1 + 2 * epsilon);
float coef = std::log(factor);
LogLossAdds<T>(place, stream, pred, epsilon, y);
LogLossMuls<T>(place, stream, y, factor, y);
LogLossBCE<T>(place, stream, y, label, y);
LogLossAdds<T>(place, stream, y, coef, y);
}
};
template <typename T, typename AttrType = T>
class LogLossGradNPUKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* pred = ctx.Input<Tensor>("Predicted");
auto* label = ctx.Input<Tensor>("Labels");
auto* dloss = ctx.Input<Tensor>(framework::GradVarName("Loss"));
auto* dpred = ctx.Output<Tensor>(framework::GradVarName("Predicted"));
auto epsilon = static_cast<T>(ctx.Attr<AttrType>("epsilon"));
auto place = ctx.GetPlace();
auto stream =
ctx.template device_context<paddle::platform::NPUDeviceContext>()
.stream();
if (dpred) {
LogLossBCEGrad<T>(place, stream, pred, label, dloss, dpred);
LogLossMuls<T>(place, stream, dpred, 1 / (1 + 2 * epsilon), dpred);
}
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP_NPU_KERNEL(log_loss, ops::LogLossNPUKernel<float>);
REGISTER_OP_NPU_KERNEL(log_loss_grad, ops::LogLossGradNPUKernel<float>);
# 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.
from __future__ import print_function
import numpy as np
import unittest
import sys
sys.path.append("..")
from op_test import OpTest
import paddle
import paddle.fluid as fluid
paddle.enable_static()
def sigmoid_array(x):
return 1 / (1 + np.exp(-x))
@unittest.skipIf(not paddle.is_compiled_with_npu(),
"core is not compiled with NPU")
class TestLogLossOp(OpTest):
def setUp(self):
self.set_npu()
self.op_type = 'log_loss'
self.place = paddle.NPUPlace(0)
self.init_dtype()
self.set_inputs()
self.set_attrs()
self.set_outputs()
def set_inputs(self):
samples_num = 100
x = np.random.random((samples_num, 1)).astype(self.dtype)
predicted = sigmoid_array(x)
labels = np.random.randint(0, 2, (samples_num, 1)).astype(self.dtype)
self.inputs = {'Predicted': predicted, 'Labels': labels}
def set_attrs(self):
epsilon = 1e-7
self.attrs = {'epsilon': epsilon}
def set_outputs(self):
epsilon = self.attrs['epsilon']
labels = self.inputs['Labels']
predicted = self.inputs['Predicted']
loss = -labels * np.log(predicted + epsilon) - (
1 - labels) * np.log(1 - predicted + epsilon)
self.outputs = {'Loss': loss}
def set_npu(self):
self.__class__.use_npu = True
def init_dtype(self):
self.dtype = np.float32
def test_check_output(self):
self.check_output_with_place(self.place)
def test_check_grad(self):
self.check_grad_with_place(self.place, ['Predicted'], 'Loss')
@unittest.skipIf(not paddle.is_compiled_with_npu(),
"core is not compiled with NPU")
class TestLogLossOpError(unittest.TestCase):
def test_errors(self):
with fluid.program_guard(fluid.Program()):
def test_x_type():
input_data = np.random.random(100, 1).astype("float32")
fluid.layers.log_loss(input_data)
self.assertRaises(TypeError, test_x_type)
def test_x_dtype():
x2 = fluid.layers.data(name='x2', shape=[100, 1], dtype='int32')
fluid.layers.log_loss(x2)
self.assertRaises(TypeError, test_x_dtype)
def test_label_type():
input_data = np.random.random(100, 1).astype("float32")
fluid.layers.log_loss(input_data)
self.assertRaises(TypeError, test_label_type)
def test_label_dtype():
x2 = fluid.layers.data(name='x2', shape=[100, 1], dtype='int32')
fluid.layers.log_loss(x2)
self.assertRaises(TypeError, test_label_dtype)
if __name__ == '__main__':
unittest.main()
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册