π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): make the RandAugment and AutoAugment range guards say what they enforce (#4447)
Aditya Malkar8fb9ad1219c1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex be43283d1..8e58f2244 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -379,6 +379,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `RandAugment`'s `m` guard is exclusive at both ends, but its docstring and its error message+ both named the closed interval `[0, 30]`, so a user who asked for the maximum strength the+ message advertised got an exception saying `30` was in range. Both now read `(0, 30)`; the+ accepted values are unchanged. `n` was validated nowhere: `n=0` constructed a `RandAugment`+ that applied nothing, and `n` above the policy length was silently clamped, because the+ sampler draws without replacement. It is now checked against the policy. `AutoAugment`'s+ magnitude bin indexes two adjacent points of an 11-point scale, so `9` is the last usable+ bin; a larger one raised a raw `IndexError` naming an internal tensor, and a negative one+ wrapped silently onto a reversed range. Out-of-range bins now name the operation and the+ valid range. Operations that ignore the magnitude entirely keep accepting any bin. (#4447)+* `pixel2cam` now validates the full `Bx4x4` shape of `intrinsics_inv`, rejecting invalid matrix sizesbefore they cause unrelated transformation errors or return the wrong number of coordinate components. (#4381)* `Boxes.to_mask` leaves list-padding channels empty, including after coordinate transforms,diff --git a/kornia/augmentation/auto/autoaugment/ops.py b/kornia/augmentation/auto/autoaugment/ops.pyindex 24ee74b1b..75671b152 100644--- a/kornia/augmentation/auto/autoaugment/ops.py+++ b/kornia/augmentation/auto/autoaugment/ops.py@@ -17,6 +17,8 @@"""AutoAugment operation wrapper."""+from typing import Tuple+import torchfrom kornia.augmentation.auto.operations import (@@ -38,13 +40,38 @@ from kornia.augmentation.auto.operations import ()+def _magnitude_bin(magnitudes: torch.Tensor, magnitude: int, name: str) -> Tuple[float, float]:+ """Return the magnitude range that bin ``magnitude`` selects from ``magnitudes``.++ A bin indexes two adjacent points, so the last usable bin is two short of the end.+ Indexing directly would let a negative bin wrap silently onto a reversed range, and+ an over-large one surface an ``IndexError`` naming an internal tensor rather than the+ policy entry the caller wrote.++ Args:+ magnitudes: The op's magnitude scale.+ magnitude: Bin index into that scale.+ name: Operation name, for the error message.++ Returns:+ The ``(low, high)`` range for that bin.++ Raises:+ ValueError: If ``magnitude`` is not a usable bin index.+ """+ last_bin = magnitudes.shape[0] - 2+ if not 0 <= magnitude <= last_bin:+ raise ValueError(f"Expect magnitude bin for `{name}` in [0, {last_bin}]. Got {magnitude}.")+ return magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()++def shear_x(probability: float, magnitude: int) -> OperationBase:"""Return ShearX op."""magnitudes = torch.linspace(-0.3, 0.3, 11) * 180.0return ShearX(None,probability,- magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()),+ magnitude_range=_magnitude_bin(magnitudes, magnitude, "shear_x"),symmetric_megnitude=False,)@@ -55,7 +82,7 @@ def shear_y(probability: float, magnitude: int) -> OperationBase:return ShearY(None,probability,- magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()),+ magnitude_range=_magnitude_bin(magnitudes, magnitude, "shear_y"),symmetric_megnitude=False,)@@ -66,7 +93,7 @@ def translate_x(probability: float, magnitude: int) -> OperationBase:return TranslateX(None,probability,- magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()),+ magnitude_range=_magnitude_bin(magnitudes, magnitude, "translate_x"),symmetric_megnitude=False,)@@ -77,7 +104,7 @@ def translate_y(probability: float, magnitude: int) -> OperationBase:return TranslateY(None,probability,- magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()),+ magnitude_range=_magnitude_bin(magnitudes, magnitude, "translate_y"),symmetric_megnitude=False,)@@ -88,7 +115,7 @@ def rotate(probability: float, magnitude: int) -> OperationBase:return Rotate(None,probability,- magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()),+ magnitude_range=_magnitude_bin(magnitudes, magnitude, "rotate"),symmetric_megnitude=False,)@@ -111,40 +138,34 @@ def equalize(probability: float, _: int) -> OperationBase:def solarize(probability: float, magnitude: int) -> OperationBase:"""Return solarize op."""magnitudes = torch.linspace(0, 255, 11) / 255.0- return Solarize(None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()))+ return Solarize(None, probability, magnitude_range=_magnitude_bin(magnitudes, magnitude, "solarize"))def posterize(probability: float, magnitude: int) -> OperationBase:"""Return posterize op."""magnitudes = torch.linspace(4, 8, 11)- return Posterize(- None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item())- )+ return Posterize(None, probability, magnitude_range=_magnitude_bin(magnitudes, magnitude, "posterize"))def contrast(probability: float, magnitude: int) -> OperationBase:"""Return contrast op."""magnitudes = torch.linspace(0.1, 1.9, 11)- return Contrast(None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()))+ return Contrast(None, probability, magnitude_range=_magnitude_bin(magnitudes, magnitude, "contrast"))def brightness(probability: float, magnitude: int) -> OperationBase:"""Return brightness op."""magnitudes = torch.linspace(0.1, 1.9, 11)- return Brightness(- None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item())- )+ return Brightness(None, probability, magnitude_range=_magnitude_bin(magnitudes, magnitude, "brightness"))def sharpness(probability: float, magnitude: int) -> OperationBase:"""Return sharpness op."""magnitudes = torch.linspace(0.1, 1.9, 11)- return Sharpness(- None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item())- )+ return Sharpness(None, probability, magnitude_range=_magnitude_bin(magnitudes, magnitude, "sharpness"))def color(probability: float, magnitude: int) -> OperationBase:"""Return color op."""magnitudes = torch.linspace(0.1, 1.9, 11)- return Saturate(None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()))+ return Saturate(None, probability, magnitude_range=_magnitude_bin(magnitudes, magnitude, "color"))diff --git a/kornia/augmentation/auto/rand_augment/rand_augment.py b/kornia/augmentation/auto/rand_augment/rand_augment.pyindex 20647e48e..4f7c630d3 100644--- a/kornia/augmentation/auto/rand_augment/rand_augment.py+++ b/kornia/augmentation/auto/rand_augment/rand_augment.py@@ -51,8 +51,10 @@ class RandAugment(PolicyAugmentBase):"""Apply RandAugment :cite:`cubuk2020randaugment` augmentation strategies.Args:- n: the number of augmentations to apply sequentially.- m: magnitude for all the augmentations, ranged from [0, 30].+ n: the number of augmentations to apply sequentially. Must be at least ``1`` and at+ most the number of sub-policies in ``policy``, since they are sampled without+ replacement.+ m: magnitude for all the augmentations, ranged from (0, 30) exclusive.policy: candidate transformations. If None, a default candidate list will be used.transformation_matrix_mode: computation mode for the chained transformation matrix, via `.transform_matrix`attribute.@@ -79,13 +81,18 @@ class RandAugment(PolicyAugmentBase):transformation_matrix_mode: str = "silent",) -> None:if m <= 0 or m >= 30:- raise ValueError(f"Expect `m` in [0, 30]. Got {m}.")+ raise ValueError(f"Expect `m` in (0, 30). Got {m}.")if policy is None:_policy = default_policyelse:_policy = policy+ # `rand_selector` samples without replacement, so more operations than there are+ # sub-policies cannot be honoured, and `n <= 0` silently applies nothing at all.+ if not 1 <= n <= len(_policy):+ raise ValueError(f"Expect `n` in [1, {len(_policy)}], the number of sub-policies. Got {n}.")+super().__init__(_policy, transformation_matrix_mode=transformation_matrix_mode)self.n = nself.m = mdiff --git a/tests/augmentation/test_auto_operation.py b/tests/augmentation/test_auto_operation.pyindex 4946c9dbb..a33ff5014 100644--- a/tests/augmentation/test_auto_operation.py+++ b/tests/augmentation/test_auto_operation.py@@ -90,6 +90,25 @@ class TestAutoAugment(BaseTester):def test_sequential(augment_method, device, dtype):_test_sequential(AutoAugment(), device=device, dtype=dtype)+ @pytest.mark.parametrize("magnitude", [10, 11, -1, -2])+ def test_magnitude_bin_out_of_range_names_the_op(self, magnitude):+ """A bin indexes two adjacent points, so 9 is the last usable one.++ Over-large bins raised a raw IndexError naming an internal tensor, and negative+ ones wrapped silently onto a reversed range.+ """+ with pytest.raises(ValueError, match=r"Expect magnitude bin for `rotate` in \[0, 9\]"):+ AutoAugment(policy=[[("rotate", 1.0, magnitude)]])++ @pytest.mark.parametrize("name", ["auto_contrast", "invert", "equalize"])+ def test_ops_that_ignore_magnitude_are_not_gated(self, name):+ """These take `_: int` and never index the scale, so any bin stays legal."""+ AutoAugment(policy=[[(name, 1.0, 10)]])++ def test_magnitude_bin_endpoints_are_accepted(self):+ AutoAugment(policy=[[("rotate", 1.0, 0)]])+ AutoAugment(policy=[[("rotate", 1.0, 9)]])+class TestRandAugment(BaseTester):@pytest.mark.parametrize("policy", [None, [[("translate_y", -0.5, 0.5)]]])@@ -127,6 +146,28 @@ class TestRandAugment(BaseTester):def test_sequential(augment_method, device, dtype):_test_sequential(RandAugment(n=3, m=15), device=device, dtype=dtype)+ @pytest.mark.parametrize("m", [1, 15, 29])+ def test_m_accepts_the_interval_its_message_names(self, m):+ """The guard is exclusive at both ends, and the message says so."""+ RandAugment(n=2, m=m)++ @pytest.mark.parametrize("m", [-1, 0, 30, 31])+ def test_m_outside_the_open_interval_is_rejected(self, m):+ with pytest.raises(ValueError, match=r"Expect `m` in \(0, 30\)"):+ RandAugment(n=2, m=m)++ @pytest.mark.parametrize("n", [0, -1, len(randaug_config) + 1])+ def test_n_outside_the_policy_length_is_rejected(self, n):+ """`n=0` applied nothing and `n > len(policy)` was silently clamped."""+ with pytest.raises(ValueError, match=r"Expect `n` in \[1, 15\]"):+ RandAugment(n=n, m=10)++ def test_n_is_bounded_by_the_supplied_policy(self):+ policy = [[("translate_y", -0.5, 0.5)], [("translate_x", -0.5, 0.5)]]+ RandAugment(n=2, m=10, policy=policy)+ with pytest.raises(ValueError, match=r"Expect `n` in \[1, 2\]"):+ RandAugment(n=3, m=10, policy=policy)+class TestTrivialAugment(BaseTester):@pytest.mark.parametrize("policy", [None, [[("translate_y", -0.5, 0.5)]]])