Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: correct logic bugs in augmentation and crop validation (#3605)

Yashh5fa120811549
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 390900f85..1cb08bc85 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -89,9 +89,9 @@ class _BasicAugmentationBase(nn.Module):
self._params: Dict[str, torch.Tensor] = {}
self._p_gen: Distribution
self._p_batch_gen: Distribution
- if p != 0.0 or p != 1.0:
+ if p not in {0.0, 1.0}:
self._p_gen = Bernoulli(self.p)
- if p_batch != 0.0 or p_batch != 1.0:
+ if p_batch not in {0.0, 1.0}:
self._p_batch_gen = Bernoulli(self.p_batch)
self._param_generator: Optional[RandomGeneratorBase] = None
self.flags: Dict[str, Any] = {}
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index ad6ae4765..5d5c2a897 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -308,7 +308,7 @@ def center_crop_generator(
if device is None:
device = torch.device("cpu")
_common_param_check(batch_size)
- if not isinstance(size, (tuple, list)) and len(size) == 2:
+ if not isinstance(size, (tuple, list)) or len(size) != 2:
raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
if not (isinstance(height, int) and height > 0 and isinstance(width, int) and width > 0):
raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index 57f522224..cd6b0e394 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -184,7 +184,7 @@ def center_crop_generator3d(
"""
if device is None:
device = torch.device("cpu")
- if not isinstance(size, (tuple, list)) and len(size) == 3:
+ if not isinstance(size, (tuple, list)) or len(size) != 3:
raise ValueError(f"Input size must be a tuple/list of length 3. Got {size}")
if not (
isinstance(depth, int)
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 1fe8b4fe5..4bbac44a1 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -89,7 +89,7 @@ def crop_and_resize(
if not isinstance(boxes, torch.Tensor):
raise TypeError(f"Input boxes type is not a torch.Tensor. Got {type(boxes)}")
- if not isinstance(size, (tuple, list)) and len(size) == 2:
+ if not isinstance(size, (tuple, list)) or len(size) != 2:
raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
if len(input_tensor.shape) != 4:
@@ -150,7 +150,7 @@ def center_crop(
if not isinstance(input_tensor, torch.Tensor):
raise TypeError(f"Input torch.tensor type is not a torch.Tensor. Got {type(input_tensor)}")
- if not isinstance(size, (tuple, list)) and len(size) == 2:
+ if not isinstance(size, (tuple, list)) or len(size) != 2:
raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
if len(input_tensor.shape) != 4:
diff --git a/kornia/geometry/transform/crop3d.py b/kornia/geometry/transform/crop3d.py
index 172e48a0c..5269ef2ca 100644
--- a/kornia/geometry/transform/crop3d.py
+++ b/kornia/geometry/transform/crop3d.py
@@ -93,7 +93,7 @@ def crop_and_resize3d(
raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
if not isinstance(boxes, (torch.Tensor)):
raise TypeError(f"Input boxes type is not a torch.Tensor. Got {type(boxes)}")
- if not isinstance(size, (tuple, list)) and len(size) != 3:
+ if not isinstance(size, (tuple, list)) or len(size) != 3:
raise ValueError(f"Input size must be a tuple/list of length 3. Got {size}")
if len(tensor.shape) != 5:
raise AssertionError(f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}.")
@@ -179,7 +179,7 @@ def center_crop3d(
if len(tensor.shape) != 5:
raise AssertionError(f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}.")
- if not isinstance(size, (tuple, list)) and len(size) == 3:
+ if not isinstance(size, (tuple, list)) or len(size) != 3:
raise ValueError(f"Input size must be a tuple/list of length 3. Got {size}")
# unpack input sizes
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index 9d824b339..d70200d91 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -93,6 +93,18 @@ class TestBasicAugmentationBase(BaseTester):
assert output.shape == expected_output.shape
self.assert_close(output, expected_output)
+ @pytest.mark.parametrize("p", [0.0, 1.0])
+ def test_deterministic_p_skips_bernoulli(self, p):
+ """When p is 0 or 1 the outcome is deterministic β€” no Bernoulli sampler should be created."""
+ base = _BasicAugmentationBase(p=p, p_batch=0.5)
+ assert not isinstance(getattr(base, "_p_gen", None), torch.distributions.Bernoulli)
+
+ @pytest.mark.parametrize("p_batch", [0.0, 1.0])
+ def test_deterministic_p_batch_skips_bernoulli(self, p_batch):
+ """When p_batch is 0 or 1 the outcome is deterministic β€” no Bernoulli sampler should be created."""
+ base = _BasicAugmentationBase(p=0.5, p_batch=p_batch)
+ assert not isinstance(getattr(base, "_p_batch_gen", None), torch.distributions.Bernoulli)
+
class TestAugmentationBase2D(BaseTester):
def test_forward(self, device, dtype):
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index 3591a6941..0a27d82cd 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import pytest
import torch
import kornia
@@ -301,3 +302,27 @@ class TestCropByIndices(BaseTester):
actual = op_script(img, torch.tensor([[[0, 0], [1, 0], [1, 1], [0, 1]]]))
expected = op(img, torch.tensor([[[0, 0], [1, 0], [1, 1], [0, 1]]]))
self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
+
+
+class TestCropSizeValidation:
+ """Tests that crop functions properly reject invalid size arguments."""
+
+ def test_crop_and_resize_rejects_wrong_length(self, device, dtype):
+ inp = torch.rand(1, 1, 4, 4, device=device, dtype=dtype)
+ boxes = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="tuple/list of length 2"):
+ kornia.geometry.transform.crop_and_resize(inp, boxes, (2, 2, 2))
+
+ def test_crop_and_resize_rejects_non_tuple(self, device, dtype):
+ inp = torch.rand(1, 1, 4, 4, device=device, dtype=dtype)
+ boxes = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype)
+ # Passing an int instead of a tuple can raise either ValueError (from an
+ # explicit validation check) or TypeError (from calling len() on an int),
+ # depending on which code path runs first inside crop_and_resize.
+ with pytest.raises((ValueError, TypeError)):
+ kornia.geometry.transform.crop_and_resize(inp, boxes, 2)
+
+ def test_center_crop_rejects_wrong_length(self, device, dtype):
+ inp = torch.rand(1, 1, 4, 4, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="tuple/list of length 2"):
+ kornia.geometry.transform.center_crop(inp, (2, 2, 2))
diff --git a/tests/geometry/transform/test_crop3d.py b/tests/geometry/transform/test_crop3d.py
index 7bb2a6488..9a8698cf5 100644
--- a/tests/geometry/transform/test_crop3d.py
+++ b/tests/geometry/transform/test_crop3d.py
@@ -326,3 +326,24 @@ class TestCropByBoxes3D(BaseTester):
self.gradcheck(
kornia.geometry.transform.crop_by_boxes3d, (inp, src_box, dst_box), requires_grad=(True, False, False)
)
+
+
+class TestCrop3DSizeValidation:
+ """Tests that 3D crop functions properly reject invalid size arguments."""
+
+ def test_crop_and_resize3d_rejects_wrong_length(self, device, dtype):
+ inp = torch.rand(1, 1, 4, 4, 4, device=device, dtype=dtype)
+ boxes = torch.rand(1, 8, 3, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="tuple/list of length 3"):
+ kornia.geometry.transform.crop_and_resize3d(inp, boxes, (2, 2))
+
+ def test_crop_and_resize3d_rejects_non_tuple(self, device, dtype):
+ inp = torch.rand(1, 1, 4, 4, 4, device=device, dtype=dtype)
+ boxes = torch.rand(1, 8, 3, device=device, dtype=dtype)
+ with pytest.raises((ValueError, TypeError)):
+ kornia.geometry.transform.crop_and_resize3d(inp, boxes, 2)
+
+ def test_center_crop3d_rejects_wrong_length(self, device, dtype):
+ inp = torch.rand(1, 1, 4, 4, 4, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="tuple/list of length 3"):
+ kornia.geometry.transform.center_crop3d(inp, (2, 2))