Skip to content

Commit

Permalink
add unique support zero dim (#49260)
Browse files Browse the repository at this point in the history
  • Loading branch information
sprouteer authored Jan 20, 2023
1 parent 073f7ce commit ee4e532
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 6 deletions.
21 changes: 15 additions & 6 deletions paddle/phi/infermeta/unary.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4596,17 +4596,26 @@ void UniqueRawInferMeta(const MetaTensor& x,
MetaTensor* index,
MetaTensor* counts) {
if (!is_sorted) {
PADDLE_ENFORCE_EQ(
x.dims().size(),
1,
phi::errors::InvalidArgument("The Input(X) should be 1-D Tensor, "
"But now the dims of Input(X) is %d.",
x.dims().size()));
PADDLE_ENFORCE_EQ(x.dims().size() == 1 || x.dims().size() == 0,
true,
phi::errors::InvalidArgument(
"The Input(X) should be 0-D or 1-D Tensor, "
"But now the dims of Input(X) is %d.",
x.dims().size()));
out->set_dims(phi::make_ddim({-1}));
index->set_dims(x.dims());
return;
}

if (x.dims().size() == 0) {
PADDLE_ENFORCE_EQ(axis.empty(),
true,
phi::errors::InvalidArgument(
"The Input(X) with 0-D Tensor, axis must be None"
"But now the axis is %d.",
axis[0]));
}

if (axis.empty()) {
out->set_dims(phi::make_ddim({-1}));
if (return_inverse) {
Expand Down
40 changes: 40 additions & 0 deletions python/paddle/fluid/tests/unittests/test_zero_dim_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2445,6 +2445,29 @@ def test_one_hot_label(self):
self.assertEqual(one_hot_label.shape, [4])
self.assertEqual(one_hot_label.numpy()[2], 1)

def test_unique(self):
places = ['cpu']
if paddle.is_compiled_with_cuda():
places.append('gpu')
for place in places:
paddle.set_device(place)
x = paddle.rand([])
y, index, inverse, counts = paddle.unique(
x,
return_index=True,
return_inverse=True,
return_counts=True,
)

self.assertEqual(y, x)
self.assertEqual(index, 0)
self.assertEqual(inverse, 0)
self.assertEqual(counts, 1)
self.assertEqual(y.shape, [1])
self.assertEqual(index.shape, [1])
self.assertEqual(inverse.shape, [1])
self.assertEqual(counts.shape, [1])


class TestNoBackwardAPIStatic(unittest.TestCase):
def setUp(self):
Expand Down Expand Up @@ -2647,6 +2670,23 @@ def test_one_hot_label(self):
self.assertEqual(res[0].shape, (4,))
self.assertEqual(res[0][2], 1)

def test_unique(self):
x = paddle.rand([])
y, index, inverse, counts = paddle.unique(
x, return_index=True, return_inverse=True, return_counts=True
)

prog = paddle.static.default_main_program()
res = self.exe.run(prog, fetch_list=[y, index, inverse, counts])
self.assertEqual(y, x)
self.assertEqual(index, 0)
self.assertEqual(inverse, 0)
self.assertEqual(counts, 1)
self.assertEqual(res[0].shape, (1,))
self.assertEqual(res[1].shape, (1,))
self.assertEqual(res[2].shape, (1,))
self.assertEqual(res[3].shape, (1,))


unary_apis_with_complex_input = [
paddle.real,
Expand Down

0 comments on commit ee4e532

Please sign in to comment.