Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【PIR API adaptor No.1、20、103、104、120】 Migrate L1Loss/BCELoss/HSigmoidLoss/SmoothL1Loss/KLDivLoss into pir #58708

Merged
merged 19 commits into from
Dec 26, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions python/paddle/nn/functional/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# TODO: define loss functions of neural network
import paddle
from paddle import _C_ops, base, in_dynamic_mode
from paddle.framework import core
from paddle.framework import core, in_dynamic_or_pir_mode
from paddle.static.nn.control_flow import Assert
from paddle.utils import deprecated

Expand Down Expand Up @@ -654,7 +654,7 @@ def binary_cross_entropy(
% reduction
)

if in_dynamic_mode():
if in_dynamic_or_pir_mode():
out = _C_ops.bce_loss(input, label)
if weight is not None:
out = _C_ops.multiply(out, weight, 'axis', -1)
Expand Down Expand Up @@ -979,7 +979,7 @@ def hsigmoid_loss(
if num_classes < 2:
raise ValueError(f'Expected num_classes >= 2 (got {num_classes})')

if in_dynamic_mode():
if in_dynamic_or_pir_mode():
out, _, _ = _C_ops.hsigmoid_loss(
input,
label,
Expand Down Expand Up @@ -1098,7 +1098,7 @@ def smooth_l1_loss(input, label, reduction='mean', delta=1.0, name=None):

"""

if in_dynamic_mode():
if in_dynamic_or_pir_mode():
out = _C_ops.huber_loss(input, label, delta)
else:
check_variable_and_dtype(
Expand Down Expand Up @@ -1324,7 +1324,7 @@ def l1_loss(input, label, reduction='mean', name=None):
"received %s, which is not allowed." % reduction
)

if in_dynamic_mode():
if in_dynamic_or_pir_mode():
unreduced = _C_ops.abs(_C_ops.subtract(input, label))

if reduction == 'mean':
Expand Down Expand Up @@ -1683,7 +1683,7 @@ def kl_div(input, label, reduction='mean', name=None):
):
label = paddle.cast(label, 'float64')

if in_dynamic_mode():
if in_dynamic_or_pir_mode():
out = _C_ops.kldiv_loss(input, label, 'none')
if reduction == 'mean':
out = paddle.mean(out)
Expand Down
13 changes: 9 additions & 4 deletions test/legacy_test/test_bce_loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import paddle
from paddle import base
from paddle.base import core
from paddle.pir_utils import test_with_pir_api


def test_static_layer(
Expand Down Expand Up @@ -55,6 +56,7 @@ def test_static_layer(
return static_result


@test_with_pir_api
DrRyanHuang marked this conversation as resolved.
Show resolved Hide resolved
def test_static_functional(
place, input_np, label_np, reduction='mean', weight_np=None
):
Expand Down Expand Up @@ -152,6 +154,7 @@ def calc_bceloss(input_np, label_np, reduction='mean', weight_np=None):


class TestBCELoss(unittest.TestCase):
@test_with_pir_api
def test_BCELoss(self):
input_np = np.random.uniform(0.1, 0.8, size=(20, 30)).astype(np.float64)
label_np = np.random.randint(0, 2, size=(20, 30)).astype(np.float64)
Expand Down Expand Up @@ -185,6 +188,7 @@ def test_BCELoss(self):
)
np.testing.assert_allclose(dy_functional, expected, rtol=1e-05)

@test_with_pir_api
def test_BCELoss_weight(self):
input_np = np.random.uniform(0.1, 0.8, size=(2, 3, 4, 10)).astype(
np.float64
Expand Down Expand Up @@ -262,10 +266,10 @@ def setUp(self):
self.outputs = {'Out': output_np}

def test_check_output(self):
self.check_output()
self.check_output(check_pir=True)

def test_check_grad(self):
self.check_grad(['X'], 'Out')
self.check_grad(['X'], 'Out', check_pir=True)

def init_test_case(self):
self.shape = [10, 10]
Expand All @@ -286,16 +290,17 @@ def init_test_cast(self):

class TestBceLossOpFP16(TestBceLossOp):
def test_check_output(self):
self.check_output()
self.check_output(check_pir=True)

def test_check_grad(self):
self.check_grad(['X'], 'Out')
self.check_grad(['X'], 'Out', check_pir=True)

def init_test_dtype(self):
self.dtype = np.float16


class TestBceLossOpStaticFP16(unittest.TestCase):
@test_with_pir_api
def test_fp16(self):
DrRyanHuang marked this conversation as resolved.
Show resolved Hide resolved
paddle.enable_static()
shape = [2, 3, 20]
Expand Down
36 changes: 20 additions & 16 deletions test/legacy_test/test_hsigmoid_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import paddle
import paddle.nn.functional as F
from paddle import base
from paddle.pir_utils import test_with_pir_api

paddle.enable_static()
np.random.seed(100)
Expand Down Expand Up @@ -218,13 +219,14 @@ def setUp(self):
self.user_grads = hsigmoid_grad(x, w, label, bias, num_classes)

def test_check_output(self):
self.check_output()
self.check_output(check_pir=True)

def test_check_grad(self):
self.check_grad(
['X', 'W', 'Bias'],
['Out'],
user_defined_grads=self.user_grads,
check_pir=True,
)


Expand Down Expand Up @@ -278,7 +280,7 @@ def setUp(self):
self.outputs = {'PreOut': pre_output, 'Out': out}

def test_check_output(self):
self.check_output()
self.check_output(check_pir=True)


class TestHSigmoidOpWithSparseGrad(unittest.TestCase):
Expand Down Expand Up @@ -338,7 +340,7 @@ def training_test(self, is_sparse):
main_program = base.default_main_program()
place = base.CPUPlace()
feeder = base.DataFeeder(feed_list=data_list, place=place)
exe = base.Executor(place)
exe = paddle.static.Executor(place)

exe.run(start_up)
result = []
Expand All @@ -358,6 +360,7 @@ def training_test(self, is_sparse):
result.append(loss_val)
return result

@test_with_pir_api
DrRyanHuang marked this conversation as resolved.
Show resolved Hide resolved
def test_hs_grad_with_sparse(self):
dense_result = self.training_test(is_sparse=False)
sparse_result = self.training_test(is_sparse=True)
Expand Down Expand Up @@ -414,13 +417,14 @@ def setUp(self):
self.outputs = {'PreOut': pre_output, 'Out': out}

def test_check_output(self):
self.check_output()
self.check_output(check_pir=True)

def test_check_grad(self):
self.check_grad(
['Bias', 'X', 'W'],
['Out'],
no_grad_set=set('Label'),
check_pir=True,
)


Expand Down Expand Up @@ -479,10 +483,12 @@ def setUp(self):
self.outputs = {'PreOut': pre_output, 'Out': out}

def test_check_output(self):
self.check_output()
self.check_output(check_pir=True)

def test_check_grad(self):
self.check_grad(['X', 'W'], ['Out'], no_grad_set=set('Label'))
self.check_grad(
['X', 'W'], ['Out'], no_grad_set=set('Label'), check_pir=True
)


class TestHSigmoidLossAPI(unittest.TestCase):
Expand Down Expand Up @@ -564,6 +570,7 @@ def test_dygraph_api(self):
np.testing.assert_allclose(self.out_np, out.numpy(), rtol=1e-05)
paddle.enable_static()

@test_with_pir_api
def test_static_api(self):
train_program = paddle.static.Program()
startup_program = paddle.static.Program()
Expand Down Expand Up @@ -602,7 +609,6 @@ def test_static_api(self):
out2 = m(x, labels, path_table, path_code)

exe = paddle.static.Executor(self.place)
exe.run(startup_program)
feed_dict = {
'x': self.x_np,
'labels': self.labels_np,
Expand All @@ -612,17 +618,16 @@ def test_static_api(self):
if self.is_custom:
feed_dict["path_code"] = self.path_code_np
feed_dict["path_table"] = self.path_table_np
ret1, ret2 = exe.run(
train_program, feed=feed_dict, fetch_list=[out1, out2]
)
ret1, ret2 = exe.run(feed=feed_dict, fetch_list=[out1, out2])
DrRyanHuang marked this conversation as resolved.
Show resolved Hide resolved

for ret in [ret1, ret2]:
np.testing.assert_allclose(self.out_np, ret, rtol=1e-05)

@test_with_pir_api
def test_base_api(self):
train_program = base.Program()
startup_program = base.Program()
with base.program_guard(train_program, startup_program):
train_program = paddle.static.Program()
startup_program = paddle.static.Program()
with paddle.static.program_guard(train_program, startup_program):
x = paddle.static.data('x', [-1, self.feature_size])
labels = paddle.static.data('labels', [-1, 1], 'int64')
path_table = None
Expand All @@ -647,13 +652,12 @@ def test_base_api(self):
path_code=path_code,
)

exe = base.Executor(self.place)
exe.run(startup_program)
exe = paddle.static.Executor(self.place)
feed_dict = {'x': self.x_np, 'labels': self.labels_np}
if self.is_custom:
feed_dict["path_code"] = self.path_code_np
feed_dict["path_table"] = self.path_table_np
(ret,) = exe.run(train_program, feed=feed_dict, fetch_list=[out])
(ret,) = exe.run(feed=feed_dict, fetch_list=[out])

np.testing.assert_allclose(ret, self.out_np, rtol=1e-05)

Expand Down
4 changes: 2 additions & 2 deletions test/legacy_test/test_kldiv_loss_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ def setUp(self):
self.outputs = {'Loss': loss.astype('float64')}

def test_check_output(self):
self.check_output()
self.check_output(check_pir=True)

def test_check_grad(self):
self.check_grad(['X'], 'Loss', no_grad_set={"Target"})
self.check_grad(['X'], 'Loss', no_grad_set={"Target"}, check_pir=True)

def initTestCase(self):
self.x_shape = (4, 5, 5)
Expand Down
Loading