Skip to content

Commit

Permalink
use numpy array in unit test again
Browse files Browse the repository at this point in the history
  • Loading branch information
OccupyMars2025 committed Oct 14, 2022
1 parent a96baa6 commit 8c7f144
Showing 1 changed file with 37 additions and 6 deletions.
43 changes: 37 additions & 6 deletions python/paddle/fluid/tests/unittests/test_sparse_reshape_op.py
Expand Up @@ -33,17 +33,21 @@ def check_result(self, x_shape, new_shape, format):
Compare the output of paddle.reshape and the output of
paddle.incubate.sparse.reshape.
"""
mask = paddle.randint(0, 2, x_shape).astype("float32")
origin_x = (paddle.rand(x_shape, dtype='float32') + 1) * mask
mask = np.random.randint(0, 2, x_shape)
np_x = np.random.randint(-100, 100, x_shape) * mask

dense_x = origin_x.detach()
# check cpu kernel
dense_x = paddle.to_tensor(np_x, place=paddle.CPUPlace())
dense_x.stop_gradient = False
dense_out = paddle.reshape(dense_x, new_shape)

if format == "coo":
sp_x = origin_x.detach().to_sparse_coo(len(x_shape))
sp_x = paddle.to_tensor(np_x,
place=paddle.CPUPlace()).to_sparse_coo(
len(x_shape))
else:
sp_x = origin_x.detach().to_sparse_csr()
sp_x = paddle.to_tensor(np_x,
place=paddle.CPUPlace()).to_sparse_csr()
sp_x.stop_gradient = False
sp_out = paddle.incubate.sparse.reshape(sp_x, new_shape)

Expand All @@ -54,9 +58,36 @@ def check_result(self, x_shape, new_shape, format):
dense_out.backward()
sp_out.backward()
np.testing.assert_allclose(sp_x.grad.to_dense().numpy(),
(dense_x.grad * mask).numpy(),
dense_x.grad.numpy() *
np_x.astype('bool').astype('int'),
rtol=1e-05)

# check gpu kernel
if paddle.device.is_compiled_with_cuda():
dense_x = paddle.to_tensor(np_x, place=paddle.CUDAPlace(0))
dense_x.stop_gradient = False
dense_out = paddle.reshape(dense_x, new_shape)

if format == "coo":
sp_x = paddle.to_tensor(
np_x, place=paddle.CUDAPlace(0)).to_sparse_coo(len(x_shape))
else:
sp_x = paddle.to_tensor(
np_x, place=paddle.CUDAPlace(0)).to_sparse_csr()
sp_x.stop_gradient = False
sp_out = paddle.incubate.sparse.reshape(sp_x, new_shape)

np.testing.assert_allclose(sp_out.to_dense().numpy(),
dense_out.numpy(),
rtol=1e-05)

dense_out.backward()
sp_out.backward()
np.testing.assert_allclose(sp_x.grad.to_dense().numpy(),
dense_x.grad.numpy() *
np_x.astype('bool').astype('int'),
rtol=1e-05)

def test_reshape_2d(self):
self.check_result([2, 5], [
10,
Expand Down

0 comments on commit 8c7f144

Please sign in to comment.