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

Fix npairloss bug #51092

Merged
merged 10 commits into from
Mar 6, 2023
37 changes: 37 additions & 0 deletions python/paddle/fluid/tests/unittests/test_npair_loss_op.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -196,5 +196,42 @@ def test_labels_type():
self.assertRaises(TypeError, test_labels_type)


class TestNpairLossZeroError(unittest.TestCase):
def test_errors(self):
with paddle.fluid.dygraph.guard():

def test_anchor_0_size():
array = np.array([], dtype=np.float32)
anchor = paddle.to_tensor(
np.reshape(array, [0, 0, 0]), dtype='float32'
)
positive = paddle.to_tensor(
np.reshape(array, [0]), dtype='float32'
)
array = np.array([1, 2, 3, 4], dtype=np.float32)
labels = paddle.to_tensor(
np.reshape(array, [4]), dtype='float32'
)
paddle.nn.functional.npair_loss(anchor, positive, labels)

def test_positive_0_size():
array = np.array([1], dtype=np.float32)
array1 = np.array([], dtype=np.float32)
anchor = paddle.to_tensor(
np.reshape(array, [1, 1, 1]), dtype='float32'
)
positive = paddle.to_tensor(
np.reshape(array1, [0]), dtype='float32'
)
array = np.array([1, 2, 3, 4], dtype=np.float32)
labels = paddle.to_tensor(
np.reshape(array, [4]), dtype='float32'
)
paddle.nn.functional.npair_loss(anchor, positive, labels)

self.assertRaises(ValueError, test_anchor_0_size)
self.assertRaises(ValueError, test_positive_0_size)


if __name__ == '__main__':
unittest.main()
4 changes: 4 additions & 0 deletions python/paddle/nn/functional/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,10 @@ def npair_loss(anchor, positive, labels, l2_reg=0.002):
print(npair_loss)

"""
if anchor.size == 0:
raise ValueError("The dims of anchor should be greater than 0.")
if positive.size == 0:
raise ValueError("The dims of positive should be greater than 0.")
check_variable_and_dtype(
anchor, 'anchor', ['float32', 'float64'], 'npair_loss'
)
Expand Down