π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): validate empty RandomCrop3D sizes (#6156)
peng xiangf5c7c5f32c7b
diff --git a/changelog.d/6156.fixed.md b/changelog.d/6156.fixed.mdnew file mode 100644index 000000000..bcef115ec--- /dev/null+++ b/changelog.d/6156.fixed.md@@ -0,0 +1 @@+`RandomCrop3D` and `CropGenerator3D` now reject a fixed crop size larger than the input volume for empty batches, consistently with non-empty batches. Crops that fit after padding remain valid. A fixed size is now checked without reading tensor data, so on torch 2.14 `torch.compile(..., fullgraph=True)` of `CropGenerator3D`, and of `RandomCrop3D` with `p=1.0`, no longer fails with a data-dependent branch.diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.pyindex 081c699e7..06379ba9d 100644--- a/kornia/augmentation/random_generator/_3d/crop.py+++ b/kornia/augmentation/random_generator/_3d/crop.py@@ -108,12 +108,21 @@ class CropGenerator3D(RandomGeneratorBase):# ``*_diff`` is the number of valid start offsets, so it is 1 when the crop covers the whole# axis and 0 when the crop is one voxel too large. The guard has to reject that zero as well.- # 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(- "`size` must not exceed the input spatial size in any dimension. "- f"Got size={self.size!r} and input_size={(depth, height, width)}."- )+ # A tensor ``size`` is checked on its data, which graph capture cannot read; skip the check under export.+ if not is_exporting():+ # A fixed size is checked on its Python values: an empty batch has no rows to reduce over, and the+ # comparison adds no data-dependent branch under torch.compile.+ if not isinstance(self.size, torch.Tensor):+ size_exceeds_input = any(+ input_dim - crop_dim + 1 <= 0 for crop_dim, input_dim in zip(self.size, (depth, height, width))+ )+ else:+ size_exceeds_input = (x_diff <= 0).any() or (y_diff <= 0).any() or (z_diff <= 0).any()+ if size_exceeds_input:+ raise ValueError(+ "`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:return {diff --git a/tests/augmentation/_3d/test_random_crop_3d.py b/tests/augmentation/_3d/test_random_crop_3d.pyindex 1bdc4d98a..5689a8384 100644--- a/tests/augmentation/_3d/test_random_crop_3d.py+++ b/tests/augmentation/_3d/test_random_crop_3d.py@@ -19,7 +19,7 @@ import pytestimport torchimport kornia-from kornia.augmentation import RandomCrop, RandomCrop3D+from kornia.augmentation import AugmentationSequential, RandomCrop, RandomCrop3Dfrom testing.base import BaseTester@@ -303,6 +303,47 @@ class TestRandomCrop3D(BaseTester):)+class TestRandomCrop3DEmptyValidation(BaseTester):+ @pytest.mark.parametrize("batch_size", [0, 2])+ @pytest.mark.parametrize("size", [(5, 5, 6), (4, 6, 6), (4, 5, 7)])+ @pytest.mark.parametrize("probability", [0.0, 1.0])+ @pytest.mark.parametrize("in_sequence", [False, True])+ def test_oversized_crop_raises_4429(self, batch_size, size, probability, in_sequence, device, dtype):+ """Empty and skipped batches obey the same crop-size contract as applied batches."""+ volume = torch.empty(batch_size, 1, 4, 5, 6, device=device, dtype=dtype)+ crop = RandomCrop3D(size, p=probability)+ augmentation = AugmentationSequential(crop) if in_sequence else crop++ with pytest.raises(ValueError, match=r"size.*must not exceed.*input_size=\(4, 5, 6\)"):+ augmentation(volume)++ @pytest.mark.parametrize(+ "size,padding,pad_if_needed",+ [+ ((3, 4, 5), None, False),+ ((4, 5, 6), None, False),+ ((5, 6, 7), 1, False),+ ((5, 6, 7), None, True),+ ],+ )+ @pytest.mark.parametrize("probability", [0.0, 1.0])+ @pytest.mark.parametrize("in_sequence", [False, True])+ def test_legal_empty_crop_keeps_shape_4429(+ self, size, padding, pad_if_needed, probability, in_sequence, device, dtype+ ):+ """Empty crops validate against the padded canvas and preserve the skip shape."""+ volume = torch.empty(0, 1, 4, 5, 6, device=device, dtype=dtype)+ crop = RandomCrop3D(size, padding=padding, pad_if_needed=pad_if_needed, p=probability)+ augmentation = AugmentationSequential(crop) if in_sequence else crop++ output = augmentation(volume)++ expected_size = size if probability == 1.0 else (4, 5, 6)+ assert output.shape == (0, 1, *expected_size)+ assert output.device == volume.device+ assert output.dtype == volume.dtype++class TestRandomCrop3DPaddingMatrix(BaseTester):@pytest.mark.parametrize("same_on_batch", [False, True])@pytest.mark.parametrize(diff --git a/tests/augmentation/test_parameter_constants.py b/tests/augmentation/test_parameter_constants.pyindex 7d7dcef05..9ecfa0d2b 100644--- a/tests/augmentation/test_parameter_constants.py+++ b/tests/augmentation/test_parameter_constants.py@@ -131,8 +131,7 @@ class TestAugmentationConstantTransfer(BaseTester):params = aug.forward_parameters(input.shape)return aug(input, params=params), params- # Crop3D validates crop sizes and still has a separate graph break.- compiled = torch_optimizer(apply, fullgraph=not isinstance(aug, K.RandomCrop3D))+ compiled = torch_optimizer(apply, fullgraph=True)for _ in range(2):actual, params = compiled(input)if device.type == "cuda":diff --git a/tests/augmentation/test_random_generator_3d.py b/tests/augmentation/test_random_generator_3d.pyindex 5ccf530f1..21460069d 100644--- a/tests/augmentation/test_random_generator_3d.py+++ b/tests/augmentation/test_random_generator_3d.py@@ -439,6 +439,34 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):class TestRandomCropGen3D(RandomGeneratorBaseTests):+ @pytest.mark.parametrize("batch_size", [0, 2])+ @pytest.mark.parametrize("size", [(5, 5, 6), (4, 6, 6), (4, 5, 7)])+ @pytest.mark.parametrize("resize_to", [None, (2, 2, 2)])+ @pytest.mark.parametrize("same_on_batch", [False, True])+ def test_oversized_crop_is_rejected_for_empty_batches_4429(+ self, batch_size, size, resize_to, same_on_batch, device, dtype+ ):+ """A fixed crop must fit the source volume even when no rows are sampled."""+ generator = CropGenerator3D(size, resize_to)+ generator.set_rng_device_and_dtype(device, dtype)++ with pytest.raises(ValueError, match=r"size.*must not exceed.*input_size=\(4, 5, 6\)"):+ generator((batch_size, 1, 4, 5, 6), same_on_batch=same_on_batch)++ @pytest.mark.parametrize("batch_size", [0, 2])+ def test_dynamo_fixed_crop_parameters_4429(self, batch_size, device, dtype, torch_optimizer):+ """Fullgraph compilation captures a legal fixed-size crop for empty and non-empty batches."""+ generator = CropGenerator3D((3, 4, 5))+ generator.set_rng_device_and_dtype(device, dtype)+ optimized = torch_optimizer(generator, fullgraph=True)++ params = optimized((batch_size, 1, 4, 5, 6))++ assert params["src"].shape == (batch_size, 8, 3)+ assert params["dst"].shape == (batch_size, 8, 3)+ assert params["output_size"].tolist() == [[3, 4, 5]] * batch_size+ assert params["output_size"].dtype == torch.long+@pytest.mark.parametrize("batch_size", [0, 2])@pytest.mark.parametrize("input_size", [(200, 200, 200)])@pytest.mark.parametrize("size", [(100, 100, 100), torch.tensor([50, 60, 70])])