π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): draw each CutMix cut's placement per row and mix (#4721)
abhijeet sharmafb6f98876f37
diff --git a/changelog.d/4721.fixed.md b/changelog.d/4721.fixed.mdnew file mode 100644index 000000000..c70034258--- /dev/null+++ b/changelog.d/4721.fixed.md@@ -0,0 +1 @@+`RandomCutMixV2` now draws the cut placement per row and mix when `same_on_batch=False`; one uniform draw per axis used to place every cut of the batch, so all cuts sat at the same relative position. The random stream for a fixed seed changes when `B * num_mix > 1`.diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.pyindex 0780d7d12..412cd054a 100644--- a/kornia/augmentation/_2d/mix/cutmix.py+++ b/kornia/augmentation/_2d/mix/cutmix.py@@ -80,11 +80,9 @@ class RandomCutMixV2(MixAugmentationBaseV2):the compatibility default returns ``cut_area / image_area`` and emits a deprecation warning.- ``p`` is a batch-wide gate and is applied once: one draw per call selects the whole batch with probability``p``, so ``_params["batch_prob"]`` is all ones or all zeros. Every row and mix of a selected batch receives- a cut and none is dropped again. With ``same_on_batch=False`` each row and mix draws its own cut size, but- the placement comes from one uniform draw per axis that all of them share- (`#4712 <https://github.com/kornia/kornia/issues/4712>`_); ``same_on_batch=True`` shares the size as well,- so all rows and mixes receive one geometry. A cut can still leave the image unchanged through self-pairing- or a zero-sized cut.+ a cut and none is dropped again. With ``same_on_batch=False`` each row and mix draws its own cut size and+ its own placement; ``same_on_batch=True`` shares both, so all rows and mixes receive one geometry. A cut+ can still leave the image unchanged through self-pairing or a zero-sized cut.At ``p=0`` the image is unchanged and each class row contains the originallabel twice with lambda zero. The current ``cut_size`` interpretation and its rejection of a minimum of``1`` are described in its argument above; this is the repaired behavior fromdiff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.pyindex 56a774574..8d916944d 100644--- a/kornia/augmentation/random_generator/_2d/cutmix.py+++ b/kornia/augmentation/random_generator/_2d/cutmix.py@@ -148,14 +148,14 @@ class CutmixGenerator(RandomGeneratorBase):cut_height = (cutmix_rate * height).floor().to(device=_device, dtype=_dtype)cut_width = (cutmix_rate * width).floor().to(device=_device, dtype=_dtype)- _gen_shape = (1,)if same_on_batch:- _gen_shape = (cut_height.size(0),)cut_height = cut_height[0]cut_width = cut_width[0]+ # One start position per cut, like the sizes above; with same_on_batch the helper repeats a single draw.# Reserve at least 1 pixel for cropping.+ _gen_shape = (batch_size * self.num_mix,)x_start = _adapted_rsampling(_gen_shape, self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype) * (width - cut_width - 1)diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.pyindex 3cd107725..504f5bebe 100644--- a/tests/augmentation/test_conventions_mix.py+++ b/tests/augmentation/test_conventions_mix.py@@ -447,14 +447,28 @@ class TestMixConventions(BaseTester):assert heights.unique().numel() > 1 and widths.unique().numel() > 1@pytest.mark.device_agnostic- def test_wart_cutmix_placement_is_one_shared_draw_4712(self):- # #4712: with the size fixed, only the placement could differ, and it never does with same_on_batch=False.+ def test_convention_cutmix_placement_is_drawn_per_cut_4712(self):+ from kornia.geometry.bbox import infer_bbox_shape++ # #4712: one uniform draw per axis used to place every cut of the batch. With the size fixed, only the+ # placement can differ, so equal boxes here would mean the placement is shared again.shape = torch.Size([8, 1, 64, 48])for seed in range(10):torch.manual_seed(seed)aug = K.RandomCutMixV2(p=1.0, cut_size=(0.5, 0.5), num_mix=2, same_on_batch=False, use_correct_lambda=True)- crop_src = aug.forward_parameters(shape)["crop_src"]- self.assert_close(crop_src, crop_src[0, 0].expand_as(crop_src), rtol=0, atol=0)+ crop_src = aug.forward_parameters(shape)["crop_src"] # (num_mix, B, 4, 2)+ heights, widths = infer_bbox_shape(crop_src.flatten(0, 1))+ assert heights.unique().numel() == 1 and widths.unique().numel() == 1 # the sizes are pinned...+ top_left = crop_src[:, :, 0, :]+ assert top_left[0].unique(dim=0).shape[0] > 1 # ...and rows of one mix land in different places,+ assert top_left[1].unique(dim=0).shape[0] > 1+ assert bool((top_left[0] != top_left[1]).any()) # as do the two mixes of one row.+ # Each axis is drawn on its own: sharing only the x or only the y draw would still vary the pairs.+ assert top_left[..., 0].unique().numel() > 1 and top_left[..., 1].unique().numel() > 1+ # Every cut fits inside the image (the far corner is inclusive).+ assert bool((crop_src >= 0).all())+ assert bool((crop_src[..., 0] <= shape[-1] - 1).all())+ assert bool((crop_src[..., 1] <= shape[-2] - 1).all())@pytest.mark.device_agnostic@pytest.mark.parametrize("p", [0.0, 1.0])diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.pyindex 9ff711a64..cf3f47920 100644--- a/tests/augmentation/test_random_generator.py+++ b/tests/augmentation/test_random_generator.py@@ -1756,14 +1756,14 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):"crop_src": torch.tensor([[- [[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],- [[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],- [[17.0, 11.0], [141.0, 11.0], [141.0, 135.0], [17.0, 135.0]],- [[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],- [[16.0, 10.0], [147.0, 10.0], [147.0, 141.0], [16.0, 141.0]],- [[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],- [[8.0, 5.0], [171.0, 5.0], [171.0, 168.0], [8.0, 168.0]],- [[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],+ [[48.0, 49.0], [47.0, 49.0], [47.0, 48.0], [48.0, 48.0]],+ [[31.0, 129.0], [30.0, 129.0], [30.0, 128.0], [31.0, 128.0]],+ [[56.0, 44.0], [180.0, 44.0], [180.0, 168.0], [56.0, 168.0]],+ [[59.0, 74.0], [58.0, 74.0], [58.0, 73.0], [59.0, 73.0]],+ [[53.0, 53.0], [184.0, 53.0], [184.0, 184.0], [53.0, 184.0]],+ [[75.0, 167.0], [74.0, 167.0], [74.0, 166.0], [75.0, 166.0]],+ [[27.0, 4.0], [190.0, 4.0], [190.0, 167.0], [27.0, 167.0]],+ [[22.0, 46.0], [21.0, 46.0], [21.0, 45.0], [22.0, 45.0]],]],device=device,@@ -1773,7 +1773,9 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):}assert res.keys() == expected.keys(), res.keys()assert_close(res["mix_pairs"], expected["mix_pairs"], rtol=1e-4, atol=1e-4)- assert_close(res["crop_src"], expected["crop_src"], rtol=1e-4, atol=1e-4)+ # bfloat16 keeps 8 significant bits, so ``floor(u * span)`` can land one pixel from the float32 literal.+ tolerance = {"rtol": 0.0, "atol": 1.0} if dtype == torch.bfloat16 else {"rtol": 1e-4, "atol": 1e-4}+ assert_close(res["crop_src"], expected["crop_src"], **tolerance)def test_same_on_batch(self, device, dtype):torch.manual_seed(42)