Skip to content

Commit ad9f60a

Browse files
committed
FIX: ensure pad_nd handles value kwarg correctly across modes
Strip value for non-constant modes for both PyTorch and NumPy backends and ensure reliable fallback behavior. Update tests to cover multiple padding modes and dtype preservation. Signed-off-by: Shubham Chandravanshi <[email protected]>
1 parent df7711d commit ad9f60a

2 files changed

Lines changed: 27 additions & 11 deletions

File tree

‎monai/transforms/croppad/functional.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,12 +99,17 @@ def pad_nd(
9999
if mode in {"constant", "reflect", "edge", "replicate", "wrap", "circular"}:
100100
# Try PyTorch pad for these modes; fallback to NumPy on error.
101101
_pad = _pt_pad
102-
return _pad(img, pad_width=to_pad, mode=mode, **kwargs)
102+
call_kwargs = dict(kwargs)
103+
if mode != "constant":
104+
call_kwargs.pop("value", None)
105+
return _pad(img, pad_width=to_pad, mode=mode, **call_kwargs)
106+
except NotImplementedError:
107+
return _np_pad(img, pad_width=to_pad, mode=mode, **call_kwargs)
103108
except (ValueError, TypeError, RuntimeError) as err:
104-
if isinstance(err, NotImplementedError) or any(
109+
if any(
105110
k in str(err) for k in ("supported", "unexpected keyword", "implemented", "value")
106111
):
107-
return _np_pad(img, pad_width=to_pad, mode=mode, **kwargs)
112+
return _np_pad(img, pad_width=to_pad, mode=mode, **call_kwargs)
108113
raise ValueError(
109114
f"{img.shape} {to_pad} {mode} {kwargs} {img.dtype} {img.device if isinstance(img, torch.Tensor) else None}"
110115
) from err

‎tests/transforms/croppad/test_pad_nd_dtypes.py‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,19 @@
88
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
99
# See the License for the specific language governing permissions and
1010
# limitations under the License.
11-
12-
11+
"""
12+
Tests for pad_nd dtype support and backend selection.
13+
Validates PyTorch padding preference and NumPy fallback behavior.
14+
"""
1315
from __future__ import annotations
14-
1516
from unittest.mock import Mock, patch
16-
1717
import pytest
1818
import torch
19-
2019
import monai.transforms.croppad.functional as F
2120
from monai.transforms.croppad.functional import pad_nd
2221

23-
2422
def test_pad_uses_pt_for_bool():
23+
"""Test that pad_nd uses PyTorch backend for bool dtype in constant mode."""
2524
img = torch.ones((1, 4, 4), dtype=torch.bool)
2625
to_pad = [(0, 0), (1, 1), (2, 2)]
2726
with patch.object(F, "_pt_pad", wraps=F._pt_pad) as mock_pt, patch.object(F, "_np_pad", wraps=F._np_pad) as mock_np:
@@ -31,8 +30,8 @@ def test_pad_uses_pt_for_bool():
3130
assert not mock_np.called
3231
assert out.dtype == img.dtype
3332

34-
3533
def test_pad_falls_back_to_np_if_pt_raises():
34+
"""Test that pad_nd falls back to NumPy when PyTorch raises NotImplementedError."""
3635
img = torch.ones((1, 4, 4), dtype=torch.bool)
3736
to_pad = [(0, 0), (1, 1), (2, 2)]
3837
with (
@@ -45,14 +44,26 @@ def test_pad_falls_back_to_np_if_pt_raises():
4544
assert mock_np.called
4645
assert out.dtype == img.dtype
4746

48-
4947
@pytest.mark.parametrize(
5048
"dtype", [torch.bool, torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.float32]
5149
)
5250
def test_pad_dtype_no_error_and_dtype_preserved(dtype):
51+
"""Test that pad_nd handles various dtypes without error and preserves dtype."""
5352
img = torch.ones((1, 4, 4), dtype=dtype)
5453
to_pad = [(0, 0), (1, 1), (2, 2)]
5554
out = pad_nd(img, to_pad, mode="constant", value=0)
5655

5756
assert out.shape == (1, 6, 8)
5857
assert out.dtype == img.dtype
58+
59+
@pytest.mark.parametrize("mode", ["constant", "reflect", "replicate"])
60+
@pytest.mark.parametrize("dtype", [torch.bool, torch.int8, torch.float32])
61+
def test_pad_multiple_modes_dtype_preserved(mode, dtype):
62+
"""Test that pad_nd preserves dtype across multiple padding modes."""
63+
img = torch.ones((1, 4, 4), dtype=dtype)
64+
to_pad = [(0, 0), (1, 1), (2, 2)]
65+
66+
out = pad_nd(img, to_pad, mode=mode, value=0)
67+
68+
assert out.shape == (1, 6, 8)
69+
assert out.dtype == img.dtype

0 commit comments

Comments
 (0)