Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): clarify 3D crop size diagnostics (#5789)

peng xiang139fe8598cb3
diff --git a/changelog.d/5789.breaking.md b/changelog.d/5789.breaking.md
new file mode 100644
index 000000000..320755a73
--- /dev/null
+++ b/changelog.d/5789.breaking.md
@@ -0,0 +1 @@
+`CenterCrop3D` and `RandomCrop3D` now name `size` and the value passed in their size errors. A `size` of the wrong type or length, or with a float element, raises `TypeError` in the constructor: before, `CenterCrop3D((2, 2))` raised `IndexError`, `CenterCrop3D((2, 2, 2, 2))` silently cropped to `(2, 2, 2)`, `RandomCrop3D` raised `AssertionError` at the first call for an `int` or a sequence of other than three elements, and a float element raised `TypeError` from `affine_grid` at the first call in both classes. A crop larger than the input along any axis now raises `ValueError` in both classes, with the requested and input spatial sizes; before, `CenterCrop3D` raised `AssertionError`. `CenterCrop3D(n)` still works and `RandomCrop3D(n)` still does not: pass `(n, n, n)`.
diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.py
index dc5c90f7b..0cfadbac5 100644
--- a/kornia/augmentation/_3d/geometric/center_crop.py
+++ b/kornia/augmentation/_3d/geometric/center_crop.py
@@ -51,8 +51,11 @@ class CenterCrop3D(GeometricAugmentationBase3D):
- ``size`` is ``(D, H, W)``. The crop is shared across the batch; its ``p`` is the call-wide gate, so a
valid ``p=0`` request returns the un-cropped input and ``p=1`` returns the requested crop. Size validation
- still runs when the call is skipped, so an oversized crop raises even at ``p=0``. The exception types
- differ from :class:`RandomCrop3D`'s, and a two-element ``size`` fails with ``IndexError``
+ still runs when the call is skipped, so an oversized crop raises ``ValueError`` even at ``p=0``,
+ naming ``size`` and the input spatial size. A tuple with other than three elements, or with a Python or
+ NumPy float element, raises ``TypeError`` naming the supplied value; NumPy integers and 0-d integer
+ tensors are accepted.
+ An integer ``size`` is supported here but not by :class:`RandomCrop3D`
(`#4417 <https://github.com/kornia/kornia/issues/4417>`_).
- defaults are bilinear resampling and ``align_corners=True``.
@@ -96,13 +99,17 @@ class CenterCrop3D(GeometricAugmentationBase3D):
) -> None:
# same_on_batch is always True for CenterCrop
# Since PyTorch does not support ragged torch.Tensor. So cropping function happens batch-wisely.
+ """Initialize the crop and validate its three integer dimensions."""
super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim)
if isinstance(size, tuple):
+ # As in RandomCrop3D: NumPy integers and 0-d integer tensors pass, a Python or NumPy float does not.
+ if len(size) != 3 or not all(hasattr(v, "__index__") for v in size):
+ raise TypeError(f"`size` must be an int or a three-element (D, H, W) tuple of integers. Got {size!r}.")
self.size = (size[0], size[1], size[2])
elif isinstance(size, int):
self.size = (size, size, size)
else:
- raise TypeError(f"Invalid size type. Expected int or tuple[int, int, int]. Got: {type(size)}.")
+ raise TypeError(f"Invalid `size` type. Expected int or tuple[int, int, int] (D, H, W). Got {size!r}.")
self.flags = {"align_corners": align_corners, "resample": Resample.get(resample)}
def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index f2734f35b..6b52109fa 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -48,7 +48,8 @@ class RandomCrop3D(GeometricAugmentationBase3D):
p: probability of applying the transformation for the whole batch.
When skipped, the input is returned without padding or cropping.
size: Desired output size (out_d, out_h, out_w) of the crop.
- Must be Tuple[int, int, int], then out_d = size[0], out_h = size[1], out_w = size[2].
+ Must be a three-element tuple or list of integers, then
+ out_d = size[0], out_h = size[1], out_w = size[2].
padding: Optional padding on each border of the image.
Default is None, i.e no padding. If a sequence of length 6 is provided, it is passed to F.pad as
left, right, top, bottom, front, back borders respectively.
@@ -85,7 +86,11 @@ class RandomCrop3D(GeometricAugmentationBase3D):
left, top, and front translation from explicit padding and ``pad_if_needed``.
- its ``p`` is a call-wide gate. Size validation uses the padded input even when the call is skipped: a
crop larger than the padded volume along any axis, even by one voxel, raises; a crop equal to it is
- valid. The exception types differ from :class:`CenterCrop3D`'s, and an ``int`` ``size`` is rejected
+ valid. An oversized crop raises ``ValueError`` naming ``size`` and the padded input spatial size.
+ Unsupported size types, sequences with other than three elements, or Python or NumPy float elements
+ raise ``TypeError`` naming ``size`` and the required integer ``(D, H, W)`` values (NumPy integers and
+ 0-d integer tensors are accepted);
+ unlike :class:`CenterCrop3D`, an integer ``size`` remains unsupported
(`#4417 <https://github.com/kornia/kornia/issues/4417>`_).
A valid gated-off call returns the input unchanged -- unpadded, at the input shape rather than ``size`` --
with an identity ``transform_matrix``.
@@ -113,7 +118,7 @@ class RandomCrop3D(GeometricAugmentationBase3D):
def __init__(
self,
- size: Tuple[int, int, int],
+ size: Union[Tuple[int, int, int], List[int]],
padding: Optional[Union[int, Tuple[int, int, int], Tuple[int, int, int, int, int, int]]] = None,
pad_if_needed: Optional[bool] = False,
fill: Union[float, Sequence[float]] = 0,
@@ -125,7 +130,12 @@ class RandomCrop3D(GeometricAugmentationBase3D):
keepdim: bool = False,
) -> None:
# Since PyTorch does not support ragged torch.Tensor. So cropping function happens batch-wisely.
+ """Initialize the crop and validate its three integer dimensions."""
super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
+ # `__index__` admits NumPy integers and 0-d integer tensors along with `int`, and rejects a Python or NumPy
+ # float here rather than in grid sampling.
+ if not isinstance(size, (tuple, list)) or len(size) != 3 or not all(hasattr(v, "__index__") for v in size):
+ raise TypeError(f"`size` must be a three-element (D, H, W) sequence of integers. Got {size!r}.")
self.flags = {
"size": size,
"padding": padding,
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index 2ce2b92fa..4d8a4e37c 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -77,6 +77,7 @@ class CropGenerator3D(RandomGeneratorBase):
)
def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ """Generate crop boxes after checking that the requested size fits the input volume."""
batch_size, _, depth, height, width = batch_shape
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, torch.Tensor) else None])
@@ -109,7 +110,8 @@ class CropGenerator3D(RandomGeneratorBase):
# The size check reads the data, which graph capture cannot do; skip it under export.
if not is_exporting() and ((x_diff <= 0).any() or (y_diff <= 0).any() or (z_diff <= 0).any()):
raise ValueError(
- f"input_size {(depth, height, width)} cannot be smaller than crop size {size!s} in any dimension."
+ "`size` must not exceed the input spatial size in any dimension. "
+ f"Got size={self.size!r} and input_size={(depth, height, width)}."
)
if batch_size == 0:
@@ -210,7 +212,10 @@ def center_crop_generator3d(
and isinstance(width, int)
and not (depth >= size[0] and height >= size[1] and width >= size[2])
):
- raise AssertionError(f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}.")
+ raise ValueError(
+ "`size` must not exceed the input spatial size in any dimension. "
+ f"Got size={size!r} and input_size={(depth, height, width)}."
+ )
# unpack input sizes
dst_d, dst_h, dst_w = size
diff --git a/tests/augmentation/_3d/test_random_crop_3d.py b/tests/augmentation/_3d/test_random_crop_3d.py
index d6c530c79..1bdc4d98a 100644
--- a/tests/augmentation/_3d/test_random_crop_3d.py
+++ b/tests/augmentation/_3d/test_random_crop_3d.py
@@ -266,10 +266,11 @@ class TestRandomCrop3D(BaseTester):
def test_rejects_a_crop_one_voxel_larger_than_the_input(self, axis, device, dtype):
# The size guard counted valid start offsets and rejected only a negative count, so a crop exactly
# one voxel too large passed and the output gained an empty slab.
+ """Reject crops exceeding the input by even one voxel on any spatial axis."""
volume = torch.ones(1, 1, 4, 5, 6, device=device, dtype=dtype)
size = [4, 5, 6]
size[axis] += 1
- with pytest.raises(ValueError, match="cannot be smaller than crop size"):
+ with pytest.raises(ValueError, match=r"size.*must not exceed.*input"):
RandomCrop3D(tuple(size), p=1.0)(volume)
# The whole volume is still a valid crop.
assert RandomCrop3D((4, 5, 6), p=1.0)(volume).shape == (1, 1, 4, 5, 6)
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
index b2a7b7bfe..3eb734df4 100644
--- a/tests/augmentation/test_conventions_3d.py
+++ b/tests/augmentation/test_conventions_3d.py
@@ -20,6 +20,7 @@ from __future__ import annotations
import math
import warnings
+import numpy as np
import pytest
import torch
@@ -471,31 +472,115 @@ class Test3DAugmentationConventions(BaseTester):
@pytest.mark.device_agnostic
def test_convention_crop3d_validates_size_before_a_disabled_gate(self):
- # The exception types are split between the two classes (#4417); this pin is about the order only.
+ # #4417: validation still precedes the probability gate and sees the padded spatial size.
+ """Validate an oversized crop even when the probability gate disables the transform."""
volume = torch.rand(1, 1, 4, 5, 6)
- with pytest.raises((AssertionError, ValueError)):
+ with pytest.raises(ValueError, match="size"):
K.CenterCrop3D((5, 6, 7), p=0.0)(volume)
- with pytest.raises((AssertionError, ValueError)):
+ with pytest.raises(ValueError, match="size"):
K.RandomCrop3D((9, 9, 9), padding=1, p=0.0)(volume)
# (6, 5, 6) fits the padded (6, 7, 8) volume but not the (4, 5, 6) input: validation sees the padded one.
self.assert_close(K.RandomCrop3D((6, 5, 6), padding=1, p=0.0)(volume), volume, rtol=0, atol=0)
- with pytest.raises((AssertionError, ValueError)):
+ with pytest.raises(ValueError, match="size"):
K.RandomCrop3D((6, 5, 6), p=0.0)(volume)
@pytest.mark.device_agnostic
- def test_wart_crop3d_siblings_disagree_on_size_errors_4417(self):
- # #4417: flips when the two classes validate `size` the same way; which assertion fails depends on the
- # direction of the fix.
+ @pytest.mark.parametrize(
+ "augmentation,size",
+ [
+ (K.CenterCrop3D, ()),
+ (K.CenterCrop3D, (2,)),
+ (K.CenterCrop3D, (2, 2)),
+ (K.CenterCrop3D, (2, 2, 2, 2)),
+ (K.CenterCrop3D, 2.0),
+ (K.CenterCrop3D, None),
+ (K.RandomCrop3D, 2),
+ (K.RandomCrop3D, 2.0),
+ (K.RandomCrop3D, None),
+ (K.RandomCrop3D, "234"),
+ (K.RandomCrop3D, {2, 3, 4}),
+ (K.RandomCrop3D, ()),
+ (K.RandomCrop3D, (2,)),
+ (K.RandomCrop3D, (2, 2)),
+ (K.RandomCrop3D, (2, 2, 2, 2)),
+ ],
+ )
+ def test_crop3d_size_format_errors_4417(self, augmentation, size):
+ """Report malformed crop sizes consistently across 3D crop entry points."""
+ with pytest.raises(TypeError, match=r"size.*\(D, H, W\)") as exc_info:
+ augmentation(size)
+ assert repr(size) in str(exc_info.value)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("container", [tuple, list])
+ @pytest.mark.parametrize("axis", [0, 1, 2])
+ @pytest.mark.parametrize("value", [2.0, 2.5, "2", None])
+ def test_random_crop3d_size_elements_must_be_integers_4417(self, container, axis, value):
+ """Reject non-integer crop dimensions before generating random boxes."""
+ size = [2, 2, 2]
+ size[axis] = value
+ size = container(size)
+ with pytest.raises(TypeError, match=r"size.*\(D, H, W\).*integers") as exc_info:
+ K.RandomCrop3D(size)
+ assert repr(size) in str(exc_info.value)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("axis", [0, 1, 2])
+ @pytest.mark.parametrize("value", [2.0, 2.5, "2", None])
+ def test_center_crop3d_size_elements_must_be_integers_4417(self, axis, value):
+ """Reject non-integer dimensions on each axis before storing a center-crop size."""
+ size = [2, 2, 2]
+ size[axis] = value
+ size = tuple(size)
+ with pytest.raises(TypeError, match=r"size.*\(D, H, W\).*integers") as exc_info:
+ K.CenterCrop3D(size)
+ assert repr(size) in str(exc_info.value)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("augmentation", [K.CenterCrop3D, K.RandomCrop3D])
+ def test_crop3d_integer_like_size_elements_4417(self, augmentation):
+ # NumPy integers and 0-d integer tensors index like ints, so the element checks keep them working.
+ volume = torch.arange(240.0).reshape(2, 1, 4, 5, 6)
+ torch.manual_seed(0)
+ expected = augmentation((2, 3, 4))(volume)
+ for size in ((np.int64(2), np.int32(3), np.int64(4)), (torch.tensor(2), 3, 4)):
+ torch.manual_seed(0)
+ self.assert_close(augmentation(size)(volume), expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("augmentation", [K.CenterCrop3D, K.RandomCrop3D])
+ @pytest.mark.parametrize("size", [(5, 5, 6), (4, 6, 6), (4, 5, 7)])
+ @pytest.mark.parametrize("p", [0.0, 1.0])
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ def test_crop3d_oversized_errors_4417(self, augmentation, size, p, batch_size, device, dtype):
+ """Include the input and requested sizes when a crop exceeds the volume."""
+ volume = torch.zeros(batch_size, 1, 4, 5, 6, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match=r"size.*must not exceed.*input") as exc_info:
+ augmentation(size, p=p)(volume)
+ message = str(exc_info.value)
+ assert f"size={size}" in message
+ assert "input_size=(4, 5, 6)" in message
+ assert "tensor(" not in message
+
+ @pytest.mark.device_agnostic
+ def test_crop3d_integer_size_support_4417(self):
+ # Accepting an int in RandomCrop3D is still the separate compatibility-window decision.
+ """Keep scalar integer sizes supported by center crops and unsupported by random crops."""
volume = torch.rand(1, 1, 4, 5, 6)
- with pytest.raises(AssertionError):
- K.CenterCrop3D((5, 5, 6), p=1.0)(volume)
- with pytest.raises(ValueError, match=r"cannot be smaller than crop size"):
- K.RandomCrop3D((5, 5, 6), p=1.0)(volume)
assert K.CenterCrop3D(2, p=1.0)(volume).shape == (1, 1, 2, 2, 2)
- with pytest.raises(AssertionError):
+ with pytest.raises(TypeError, match="size"):
K.RandomCrop3D(2, p=1.0)(volume)
- with pytest.raises(IndexError):
- K.CenterCrop3D((2, 2), p=1.0)(volume)
+
+ @pytest.mark.parametrize(
+ "augmentation,size",
+ [(K.CenterCrop3D, (4, 5, 6)), (K.RandomCrop3D, (4, 5, 6)), (K.RandomCrop3D, [4, 5, 6])],
+ )
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ def test_crop3d_equal_size_is_valid_4417(self, augmentation, batch_size, size, device, dtype):
+ """Allow a crop matching all three input dimensions."""
+ if not supports_nearest_3d_grid_sample(device, dtype):
+ pytest.skip("3D nearest grid_sample is unavailable for this device/dtype")
+ volume = torch.arange(120, device=device, dtype=dtype).reshape(1, 1, 4, 5, 6).repeat(batch_size, 1, 1, 1, 1)
+ self.assert_close(augmentation(size, p=1.0, resample="nearest")(volume), volume, atol=0, rtol=0)
@pytest.mark.parametrize(
"padding,size,marker",