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

Fix AttributeError when using torch.min and max #8041

Merged
merged 4 commits into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions monai/transforms/utils_pytorch_numpy_unification.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,8 @@ def max(x: NdarrayTensor, dim: int | tuple | None = None, **kwargs) -> NdarrayTe
else:
ret = torch.max(x, int(dim), **kwargs) # type: ignore

if isinstance(ret, tuple):
return ret.values
return ret


Expand Down Expand Up @@ -546,6 +548,8 @@ def min(x: NdarrayTensor, dim: int | tuple | None = None, **kwargs) -> NdarrayTe
else:
ret = torch.min(x, int(dim), **kwargs) # type: ignore

if isinstance(ret, tuple):
return ret.values
return ret


Expand Down
14 changes: 13 additions & 1 deletion tests/test_utils_pytorch_numpy_unification.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import torch
from parameterized import parameterized

from monai.transforms.utils_pytorch_numpy_unification import mode, percentile
from monai.transforms.utils_pytorch_numpy_unification import min, max, mode, percentile
from monai.utils import set_determinism
from tests.utils import TEST_NDARRAYS, assert_allclose, skip_if_quick

Expand All @@ -27,6 +27,13 @@
TEST_MODE.append([p(np.array([3.1, 4.1, 4.1, 5.1])), p(4.1), False])
TEST_MODE.append([p(np.array([3.1, 4.1, 4.1, 5.1])), p(4), True])

TEST_MIN_MAX = []
for p in TEST_NDARRAYS:
TEST_MIN_MAX.append([p(np.array([1, 2, 3, 4, 4, 5])), {}, min, p(1)])
mingxin-zheng marked this conversation as resolved.
Show resolved Hide resolved
TEST_MIN_MAX.append([p(np.array([[3.1, 4.1, 4.1, 5.1], [3, 5, 4.1, 5]])), {"dim": 1}, min, p([3.1, 3])])
TEST_MIN_MAX.append([p(np.array([1, 2, 3, 4, 4, 5])), {}, max, p(5)])
TEST_MIN_MAX.append([p(np.array([[3.1, 4.1, 4.1, 5.1], [3, 5, 4.1, 5]])), {"dim": 1}, max, p([5.1, 5])])


class TestPytorchNumpyUnification(unittest.TestCase):

Expand Down Expand Up @@ -74,6 +81,11 @@ def test_mode(self, array, expected, to_long):
res = mode(array, to_long=to_long)
assert_allclose(res, expected)

@parameterized.expand(TEST_MIN_MAX)
def test_min_max(self, array, input_params, func, expected):
res = func(array, **input_params)
assert_allclose(res, expected, type_test=False)


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