Skip to content

Commit d33e678

Browse files
林旻佑林旻佑
authored andcommitted
Fix #8366: Add strict shape validation to sliding_window_inference
Signed-off-by: 林旻佑 <[email protected]>
1 parent e267705 commit d33e678

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

monai/inferers/utils.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
import itertools
1515
from collections.abc import Callable, Iterable, Mapping, Sequence
16+
from numbers import Integral
1617
from typing import Any
1718

1819
import numpy as np
@@ -131,11 +132,27 @@ def sliding_window_inference(
131132
kwargs: optional keyword args to be passed to ``predictor``.
132133
133134
Note:
134-
- input must be channel-first and have a batch dim, supports N-D sliding window.
135+
- Inputs must be channel-first and have a batch dim (NCHW / NCDHW).
136+
- If your data is NHWC/NDHWC, please apply `EnsureChannelFirst` / `EnsureChannelFirstd` upstream.
135137
136138
"""
137-
buffered = buffer_steps is not None and buffer_steps > 0
138139
num_spatial_dims = len(inputs.shape) - 2
140+
141+
# Only perform strict shape validation if roi_size is a sequence (explicit dimensions).
142+
# If roi_size is an integer, it is broadcast to all dimensions, so we cannot
143+
# infer the expected dimensionality to enforce a strict check here.
144+
if not isinstance(roi_size, Integral):
145+
roi_dims = len(roi_size)
146+
if num_spatial_dims != roi_dims:
147+
raise ValueError(
148+
f"inputs must have {roi_dims + 2} dimensions for {roi_dims}D roi_size "
149+
f"(Batch, Channel, {', '.join(['Spatial'] * roi_dims)}), "
150+
f"but got inputs shape {inputs.shape}.\n"
151+
"If you have channel-last data (e.g. B, D, H, W, C), please use "
152+
"monai.transforms.EnsureChannelFirst or EnsureChannelFirstd upstream."
153+
)
154+
# -----------------------------------------------------------------
155+
buffered = buffer_steps is not None and buffer_steps > 0
139156
if buffered:
140157
if buffer_dim < -num_spatial_dims or buffer_dim > num_spatial_dims:
141158
raise ValueError(f"buffer_dim must be in [{-num_spatial_dims}, {num_spatial_dims}], got {buffer_dim}.")

tests/inferers/test_sliding_window_inference.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,26 @@ def compute_dict(data):
372372
for rr, _ in zip(result_dict, expected_dict):
373373
np.testing.assert_allclose(result_dict[rr].cpu().numpy(), expected_dict[rr], rtol=1e-4)
374374

375+
def test_strict_shape_validation(self):
376+
"""Test strict shape validation to ensure inputs match roi_size dimensions."""
377+
device = "cpu"
378+
roi_size = (16, 16, 16)
379+
sw_batch_size = 4
380+
381+
def predictor(data):
382+
return data
383+
384+
# Case 1: Input has fewer dimensions than expected (e.g., missing Batch or Channel)
385+
# 3D roi_size requires 5D input (B, C, D, H, W), giving 4D here.
386+
inputs_4d = torch.randn((1, 16, 16, 16), device=device)
387+
with self.assertRaisesRegex(ValueError, "inputs must have 5 dimensions"):
388+
sliding_window_inference(inputs_4d, roi_size, sw_batch_size, predictor)
389+
390+
# Case 2: Input is 3D (missing Batch AND Channel)
391+
inputs_3d = torch.randn((16, 16, 16), device=device)
392+
with self.assertRaisesRegex(ValueError, "inputs must have 5 dimensions"):
393+
sliding_window_inference(inputs_3d, roi_size, sw_batch_size, predictor)
394+
375395

376396
class TestSlidingWindowInferenceCond(unittest.TestCase):
377397
@parameterized.expand(TEST_CASES)

0 commit comments

Comments
 (0)