Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): apply batch_prob to mix class labels (#4775) (#6189)

Ali Tharwat63a8b2011767
diff --git a/changelog.d/6189.fixed.md b/changelog.d/6189.fixed.md
new file mode 100644
index 000000000..59f70ea26
--- /dev/null
+++ b/changelog.d/6189.fixed.md
@@ -0,0 +1 @@
+`RandomMixUpV2` and `RandomCutMixV2` now apply `batch_prob` to the class labels. A `params` dictionary whose `batch_prob` selects only some rows, such as a draw replayed on a subset or hand-built parameters, used to label the unselected rows as mixed with their drawn partner and weight although their images came back unchanged; those rows now get their own class twice with lambda 0, matching the image.
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 154702dbf..ad45dcb7a 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -73,11 +73,8 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
- ``batch_prob`` gates the result: a selected image is mixed and an unselected image keeps its input
values, except where a concrete class changes the output size (see
:class:`~kornia.augmentation.RandomMosaic`); the transplantation classes read ``acceptor_indices``
- instead. The box handlers use the same gate. The class-label
- handlers of :class:`~kornia.augmentation.RandomMixUpV2` and :class:`~kornia.augmentation.RandomCutMixV2`
- ignore ``batch_prob``; their sampled gate is batch-wide, but a ``params`` whose ``batch_prob`` selects
- only some rows labels the unselected, unchanged rows as mixed
- (`#4775 <https://github.com/kornia/kornia/issues/4775>`_).
+ instead. The box and class-label handlers use the same gate: an unselected row's label describes an
+ unmixed image (its own class twice, with lambda 0).
"""
@@ -220,12 +217,22 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
self._validate_data_key(DataKey.CLASS)
batch_prob = params["batch_prob"]
to_apply = torch.atleast_1d(batch_prob > 0.5)
- output = input
- if sum(to_apply) != len(to_apply):
- output = self.apply_non_transform_class(input, params, flags)
- if sum(to_apply) != 0:
- output = self.apply_transform_class(input, params, flags)
- return output
+ if sum(to_apply) == len(to_apply):
+ return self.apply_transform_class(input, params, flags)
+ if sum(to_apply) == 0:
+ return self.apply_non_transform_class(input, params, flags)
+
+ applied = self.apply_transform_class(input, params, flags)
+ non_applied = self.apply_non_transform_class(input, params, flags)
+ if applied.dim() < 2 or applied.shape != non_applied.shape:
+ # Not one row per sample in both handlers (e.g. a subclass returning one label per sample): keep the
+ # transformed labels, as ``transform_input`` keeps the transformed images when it cannot blend.
+ return applied
+
+ # The batch axis is -2 for both RandomMixUpV2 (B, 3) and RandomCutMixV2 (num_mix, B, 3).
+ view_shape = [1] * (applied.dim() - 2) + [-1, 1]
+ mask = _to_device_nonblocking(to_apply.view(*view_shape), applied.device)
+ return torch.where(mask, applied, non_applied)
def apply_non_transform_mask(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.py
index f709835c8..1c8ce932c 100644
--- a/tests/augmentation/test_conventions_mix.py
+++ b/tests/augmentation/test_conventions_mix.py
@@ -422,19 +422,21 @@ class TestMixConventions(BaseTester):
with pytest.raises(RuntimeError, match="must be divisible by grid"):
K.RandomJigsaw(grid=grid, p=p)(image)
- @pytest.mark.device_agnostic
- def test_wart_mix_class_handlers_ignore_a_replayed_partial_gate_4775(self):
- # #4775: flips when the class handler honours batch_prob, i.e. row 1 is labelled [20, 20, 0].
- image = torch.arange(3.0).view(3, 1, 1, 1).expand(3, 1, 4, 4).clone()
- labels = torch.tensor([10, 20, 30])
+ def test_convention_mix_class_handlers_honour_a_replayed_partial_gate_4775(self, device):
+ # #4775: class handler honours batch_prob, i.e. an unselected row is labelled
+ # with its own class twice and lambda 0. The recorded params stay on the CPU, as a replay passes them.
+ image = torch.arange(3.0, device=device).view(3, 1, 1, 1).expand(3, 1, 4, 4).clone()
+ labels = torch.tensor([10, 20, 30], device=device)
aug = K.RandomMixUpV2(p=1.0, lambda_val=(0.25, 0.25), data_keys=["input", "class"])
aug(image, labels)
params = dict(aug._params)
params["mixup_pairs"] = torch.tensor([1, 2, 0])
params["batch_prob"] = torch.tensor([1.0, 0.0, 1.0])
output, mixed = aug(image, labels, params=params)
- self.assert_close(output[:, 0, 0, 0], torch.tensor([0.25, 1.0, 1.5])) # row 1 keeps its image
- self.assert_close(mixed, torch.tensor([[10.0, 20.0, 0.25], [20.0, 30.0, 0.25], [30.0, 10.0, 0.25]]))
+ self.assert_close(output[:, 0, 0, 0], torch.tensor([0.25, 1.0, 1.5], device=device)) # row 1 keeps its image
+ self.assert_close(
+ mixed, torch.tensor([[10.0, 20.0, 0.25], [20.0, 20.0, 0.0], [30.0, 10.0, 0.25]], device=device)
+ )
# RandomCutMixV2 has the same handler split: a 2 x 2 cut, and row 1 is gated off.
aug = K.RandomCutMixV2(p=1.0, use_correct_lambda=True, data_keys=["input", "class"])
aug(image, labels)
@@ -444,7 +446,52 @@ class TestMixConventions(BaseTester):
params["batch_prob"] = torch.tensor([1.0, 0.0, 1.0])
output, mixed = aug(image, labels, params=params)
self.assert_close(output[1], image[1])
- self.assert_close(mixed[0], torch.tensor([[10.0, 20.0, 0.75], [20.0, 30.0, 0.75], [30.0, 10.0, 0.75]]))
+ self.assert_close(
+ mixed[0], torch.tensor([[10.0, 20.0, 0.75], [20.0, 20.0, 0.0], [30.0, 10.0, 0.75]], device=device)
+ )
+
+ # Multi-mix CutMix (num_mix=2) with interleaved selected and unselected rows:
+ aug_multi = K.RandomCutMixV2(num_mix=2, p=1.0, use_correct_lambda=True, data_keys=["input", "class"])
+ aug_multi(image, labels)
+ params_multi = dict(aug_multi._params)
+ params_multi["mix_pairs"] = torch.tensor([[1, 2, 0], [2, 0, 1]])
+ params_multi["crop_src"] = (
+ torch.tensor([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]).expand(2, 3, 4, 2).clone()
+ )
+ params_multi["batch_prob"] = torch.tensor([0.0, 1.0, 0.0])
+ output_multi, mixed_multi = aug_multi(image, labels, params=params_multi)
+ self.assert_close(output_multi[0], image[0])
+ self.assert_close(output_multi[2], image[2])
+ # Row 0 and 2 are unselected: own label twice with lambda 0 across all mixes
+ expected_mix0 = torch.tensor([[10.0, 10.0, 0.0], [20.0, 30.0, 0.75], [30.0, 30.0, 0.0]], device=device)
+ expected_mix1 = torch.tensor([[10.0, 10.0, 0.0], [20.0, 10.0, 0.75], [30.0, 30.0, 0.0]], device=device)
+ self.assert_close(mixed_multi[0], expected_mix0)
+ self.assert_close(mixed_multi[1], expected_mix1)
+
+ @pytest.mark.device_agnostic
+ def test_convention_mix_partial_gate_keeps_class_labels_it_cannot_blend_4775(self):
+ # A subclass whose class handlers do not both return one row per sample keeps its transformed labels
+ # under a partial gate: one label per sample that applies the gate itself, or a table next to the
+ # default pass-through. Three rows, so a (3, 1) gate would broadcast against either without raising.
+ class OneLabelPerSample(K.RandomMixUpV2):
+ def apply_transform_class(self, input, params, flags):
+ return torch.where(params["batch_prob"] > 0.5, input.flip(0), input)
+
+ def apply_non_transform_class(self, input, params, flags):
+ return input
+
+ class TableNextToPassThrough(K.RandomMixUpV2):
+ def apply_non_transform_class(self, input, params, flags):
+ return input
+
+ image = torch.rand(3, 1, 4, 4)
+ labels = torch.tensor([10, 20, 30])
+ for cls in (OneLabelPerSample, TableNextToPassThrough):
+ aug = cls(p=1.0, data_keys=["input", "class"])
+ aug(image, labels)
+ params = {**aug._params, "batch_prob": torch.tensor([1.0, 0.0, 1.0])}
+ _, out = aug(image, labels, params=params)
+ assert torch.equal(out, aug.apply_transform_class(labels, aug._params, aug.flags))
@pytest.mark.device_agnostic
def test_convention_cutmix_compatibility_lambda_warns(self):