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

CuPy to Tensor #2919

Merged
merged 2 commits into from
Sep 10, 2021
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
2 changes: 2 additions & 0 deletions monai/utils/type_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ def convert_to_tensor(data, wrap_sequence: bool = False):
# numpy array with 0 dims is also sequence iterable,
# `ascontiguousarray` will add 1 dim if img has no dim, so we only apply on data with dims
return torch.as_tensor(data if data.ndim == 0 else np.ascontiguousarray(data))
elif has_cp and isinstance(data, cp_ndarray):
return torch.as_tensor(data)
elif isinstance(data, (float, int, bool)):
return torch.as_tensor(data)
elif isinstance(data, Sequence) and wrap_sequence:
Expand Down
15 changes: 14 additions & 1 deletion tests/test_to_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@
import unittest

from parameterized import parameterized
from torch import Tensor

from monai.transforms import ToTensor
from tests.utils import TEST_NDARRAYS, assert_allclose
from tests.utils import TEST_NDARRAYS, assert_allclose, optional_import

cp, has_cp = optional_import("cupy")

im = [[1, 2], [3, 4]]

Expand All @@ -33,15 +36,25 @@ class TestToTensor(unittest.TestCase):
@parameterized.expand(TESTS)
def test_array_input(self, test_data, expected_shape):
result = ToTensor()(test_data)
self.assertTrue(isinstance(result, Tensor))
assert_allclose(result, test_data)
self.assertTupleEqual(result.shape, expected_shape)

@parameterized.expand(TESTS_SINGLE)
def test_single_input(self, test_data):
result = ToTensor()(test_data)
self.assertTrue(isinstance(result, Tensor))
assert_allclose(result, test_data)
self.assertEqual(result.ndim, 0)

@unittest.skipUnless(has_cp, "CuPy is required.")
def test_cupy(self):
test_data = [[1, 2], [3, 4]]
cupy_array = cp.ascontiguousarray(cp.asarray(test_data))
result = ToTensor()(cupy_array)
self.assertTrue(isinstance(result, Tensor))
assert_allclose(result, test_data)


if __name__ == "__main__":
unittest.main()