Skip to content

Commit

Permalink
[Zero-Dim]Paddle.t support 0d tensor (#49880)
Browse files Browse the repository at this point in the history
* support paddle.t 0d tensor

* fix paddle.t test case

* merge from develop
  • Loading branch information
heliqi authored Jan 18, 2023
1 parent 7242f40 commit 5ffc22d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
26 changes: 26 additions & 0 deletions python/paddle/fluid/tests/unittests/test_zero_dim_tensor.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -1345,6 +1345,17 @@ def test_maseked_select(self):
self.assertEqual(x.grad.shape, [])
self.assertEqual(x.grad.numpy(), 1)

def test_t(self):
x = paddle.full([], 2.0)
x.stop_gradient = False
x.retain_grads()
out = paddle.t(x)
out.retain_grads()
out.backward()
self.assertEqual(out.shape, [])
self.assertEqual(out.grad.shape, [])
self.assertEqual(x.grad.shape, [])


class TestSundryAPIStatic(unittest.TestCase):
def setUp(self):
Expand Down Expand Up @@ -2080,6 +2091,21 @@ def test_maseked_select(self):
self.assertEqual(res[3].shape, ())
self.assertEqual(res[3], 1)

@prog_scope()
def test_t(self):
x = paddle.full([], 2.0)
x.stop_gradient = False
out = paddle.t(x)
paddle.static.append_backward(out.sum())
prog = paddle.static.default_main_program()
res = self.exe.run(
prog, feed={}, fetch_list=[out, out.grad_name, x.grad_name]
)

self.assertEqual(res[0].shape, ())
self.assertEqual(res[1].shape, ())
self.assertEqual(res[2].shape, ())


# Use to test API whose zero-dim input tensors don't have grad and not need to test backward in OpTest.
class TestNoBackwardAPI(unittest.TestCase):
Expand Down
4 changes: 2 additions & 2 deletions python/paddle/tensor/linalg.py
Original file line number Diff line number Diff line change
Expand Up @@ -1296,7 +1296,7 @@ def t(input, name=None):
"tensor.transpose() instead." % len(input.shape)
)
if in_dygraph_mode():
if len(input.shape) == 1:
if len(input.shape) <= 1:
return input
# 2-D tensor
perm = [1, 0]
Expand All @@ -1313,7 +1313,7 @@ def t(input, name=None):
helper = LayerHelper('t', **locals())
out = helper.create_variable_for_type_inference(input.dtype)
input_shape = helper.create_variable_for_type_inference(input.dtype)
if len(input.shape) == 1:
if len(input.shape) <= 1:
out = input
else:
helper.append_op(
Expand Down

0 comments on commit 5ffc22d

Please sign in to comment.