π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): document RandomCutMixV2's cut_size and reject a minimum of 1 (#4491)
Dipak Chaudharica5021ebc11b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 35c58deb9..d786e5b09 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -407,6 +407,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `RandomCutMixV2` and `CutmixGenerator` document `cut_size` as what it is: the `[min, max]` clamp on the+ Beta-sampled mixing coefficient `lambda`, where the cut side is `floor(sqrt(1 - lambda) * side)`, so a larger+ `cut_size` gives a smaller cut. It was described as the "minimum and maximum cut ratio". A minimum of `1.0` is+ now rejected with a `ValueError`: it forced `lambda = 1`, built an inverted zero-size box and silently made the+ augmentation an identity. (#4439, #4491)+* Made uncompiled `RandomGaussianIllumination` instances serializable with `pickle` and `torch.save`,preserving parameter replay and the `compile()` execution path after restoring the module. (#4457)* The `Args` blocks of `ColorJitter`, `RandomBrightness` and `RandomGaussianBlur` no longer document adiff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.pyindex 298c788b5..b38741ded 100644--- a/kornia/augmentation/_2d/mix/cutmix.py+++ b/kornia/augmentation/_2d/mix/cutmix.py@@ -48,8 +48,10 @@ class RandomCutMixV2(MixAugmentationBaseV2):num_mix: cut mix times.beta: hyperparameter for generating cut size from beta distribution.Beta cannot be set to 0 after torch 1.8.0. If None, it will be set to 1.- cut_size: controlling the minimum and maximum cut ratio from [0, 1].- If None, it will be set to [0, 1], which means no restriction.+ cut_size: the ``[min, max]`` clamp, within [0, 1], applied to the Beta-sampled mixing coefficient+ ``lambda``, not the fraction of the image to cut. The cut side is ``floor(sqrt(1 - lambda) * side)``,+ so a larger ``cut_size`` gives a *smaller* cut, and a minimum of 1 is rejected because it would cut+ nothing. If None, it will be set to [0, 1], which means no restriction.same_on_batch: apply the same transformation across the batch.This flag will not maintain permutation order.keepdim: whether to keep the output shape the same as input (True) or broadcast itdiff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.pyindex fbcb96867..c17c17345 100644--- a/kornia/augmentation/random_generator/_2d/cutmix.py+++ b/kornia/augmentation/random_generator/_2d/cutmix.py@@ -42,8 +42,10 @@ class CutmixGenerator(RandomGeneratorBase):num_mix (int): number of images to mix with. Default is 1.beta (torch.Tensor, optional): hyperparameter for generating cut size from beta distribution.If None, it will be set to 1.- cut_size (torch.Tensor, optional): controlling the minimum and maximum cut ratio from [0, 1].- If None, it will be set to [0, 1], which means no restriction.+ cut_size (torch.Tensor, optional): the ``[min, max]`` clamp, within [0, 1], applied to the+ Beta-sampled mixing coefficient ``lambda``. The cut side is ``floor(sqrt(1 - lambda) * side)``,+ so a larger ``cut_size`` gives a *smaller* cut. The minimum must be below 1: at 1, ``lambda`` is+ always 1 and nothing is cut. If None, it will be set to [0, 1], which means no restriction.Returns:params Dict[str, torch.Tensor]: parameters to be passed for transformation.@@ -88,6 +90,12 @@ class CutmixGenerator(RandomGeneratorBase):self._cut_size = torch.as_tensor(self.cut_size, device=device, dtype=dtype)_joint_range_check(self._cut_size, "cut_size", bounds=(0, 1))+ if float(self._cut_size[0]) >= 1.0:+ raise ValueError(+ f"`cut_size` clamps the mixing coefficient lambda, and a minimum of 1 forces lambda = 1, which "+ f"cuts nothing (cut side = floor(sqrt(1 - lambda) * side)). A larger cut_size gives a smaller "+ f"cut, so lower the minimum. Got {self._cut_size.tolist()}."+ )self.beta_sampler = Beta(self._beta, self._beta)self.prob_sampler = Bernoulli(torch.tensor(float(self.p), device=device, dtype=dtype))diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.pyindex 3e4224cb7..583f9cc46 100644--- a/tests/augmentation/test_random_generator.py+++ b/tests/augmentation/test_random_generator.py@@ -1487,6 +1487,7 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):(200, 200, 1, torch.tensor([0.0, 1.0]), None),(200, 200, 1, None, torch.tensor([-1.0, 1.0])),(200, 200, 1, None, torch.tensor([0.0, 2.0])),+ (200, 200, 1, None, torch.tensor([1.0, 1.0])),],)@pytest.mark.parametrize("same_on_batch", [True, False])@@ -1499,6 +1500,23 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):cut_size=(cut_size.to(device=device, dtype=dtype) if isinstance(cut_size, (Tensor)) else cut_size),)(torch.Size([8, 3, height, width]), same_on_batch=same_on_batch)+ def test_a_minimum_cut_size_of_one_is_rejected_by_name_4439(self, device, dtype):+ # kornia#4439: cut_size clamps lambda, so (1.0, 1.0) forced lambda = 1 and built an inverted,+ # zero-size box that silently made the augmentation an identity.+ with pytest.raises(ValueError, match="forces lambda = 1, which cuts nothing"):+ CutmixGenerator(cut_size=torch.tensor([1.0, 1.0], device=device, dtype=dtype))++ def test_a_larger_cut_size_gives_a_smaller_cut_4439(self, device, dtype):+ side = []+ for cut_size in ((0.1, 0.1), (0.9, 0.9)):+ torch.manual_seed(0)+ params = CutmixGenerator(cut_size=torch.tensor(cut_size, device=device, dtype=dtype), p=1.0)(+ torch.Size([4, 3, 60, 80])+ )+ box = params["crop_src"][0, 0]+ side.append(float(box[:, 0].max() - box[:, 0].min()))+ assert side[0] > side[1]+def test_random_gen(self, device, dtype):torch.manual_seed(42)image_shape = torch.Size([8, 3, 200, 200])