Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
21 changes: 16 additions & 5 deletions python/paddle/tensor/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -2869,15 +2869,26 @@ def inner(x: Tensor, y: Tensor, name: str | None = None) -> Tensor:


"""
xshape = x.shape
yshape = y.shape
if in_dynamic_mode() and (x.size == 1 or y.size == 1):
return multiply(x, y)
else:
xshape = x.shape
yshape = y.shape
dstshape = list(xshape[:-1]) + list(yshape[:-1])

nx = x.reshape((-1, xshape[-1]))
ny = y.reshape((-1, yshape[-1]))
if xshape[-1] == 0: # If the last dimension is 0
if len(xshape) == 1: # shape is [0]
nx = x.reshape((1, 0))
else:
nx = x.reshape((math.prod(xshape[:-1]), 0))
else:
nx = x.reshape((-1, xshape[-1]))
if yshape[-1] == 0: # If the last dimension is 0
if len(yshape) == 1: # shape is [0]
ny = y.reshape((1, 0))
else:
ny = y.reshape((math.prod(yshape[:-1]), 0))
else:
ny = y.reshape((-1, yshape[-1]))

def __check_input(x, y):
var_names = {'x': x, 'y': y}
Expand Down
26 changes: 26 additions & 0 deletions test/legacy_test/test_inner.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,32 @@ def test_errors_dynamic_case4(self):
self.assertRaises(Exception, paddle.inner, x_data, y_data)


class TestMultiplyApi_ZeroSize(unittest.TestCase):
def _test_case(self, x_shape, y_shape):
paddle.disable_static()
x_data = np.random.rand(*x_shape).astype(np.float64)
y_data = np.random.rand(*y_shape).astype(np.float64)
x = paddle.to_tensor(x_data)
y = paddle.to_tensor(y_data)
x.stop_gradient = False
y.stop_gradient = False
res = paddle.inner(x, y)
np.testing.assert_allclose(
res.numpy(), np.inner(x_data, y_data), rtol=1e-05
)
loss = paddle.sum(res)
loss.backward()
np.testing.assert_allclose(x.grad.shape, x.shape)

def test_case(self):
self._test_case([5, 10, 0], [2, 0])
self._test_case([0], [0])
self._test_case([0, 0], [1, 0])
self._test_case([0, 0], [0, 0])
self._test_case([0], [1, 0])
self._test_case([5, 1, 1], [1, 0, 1])


if __name__ == '__main__':
paddle.enable_static()
unittest.main()
Loading