Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): draw independent CutMix mixes with same_on_batch (#6203)

Karnajeet Gosavi618db408fb6f
diff --git a/changelog.d/6203.fixed.md b/changelog.d/6203.fixed.md
new file mode 100644
index 000000000..df1ed2b42
--- /dev/null
+++ b/changelog.d/6203.fixed.md
@@ -0,0 +1 @@
+`RandomCutMixV2` with `same_on_batch=True` and `num_mix > 1` repeated the first mix's pairing and cut in every mix, while the class output credited that donor once per mix; each mix now draws its own pairing and cut, shared by every row of the batch. Calls with `num_mix=1` or `same_on_batch=False` draw exactly as before; with `same_on_batch=True` and `num_mix > 1`, a seeded pipeline now draws differently after this augmentation.
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index 0d139108c..d44bf6a66 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -84,10 +84,9 @@ class RandomCutMixV2(MixAugmentationBaseV2):
(`#4425 <https://github.com/kornia/kornia/issues/4425>`_): ``_params["batch_prob"]`` is all ones or all zeros,
and every row and mix of a selected batch receives a cut, though self-pairing or a zero-sized cut can
leave a row unchanged. With ``same_on_batch=False`` each row and mix draws its own cut size and placement;
- ``same_on_batch=True`` shares one geometry, and with ``num_mix > 1`` one pairing too, so every mix
- repeats the first cut while the labels credit the donor once per mix
- (`#4805 <https://github.com/kornia/kornia/issues/4805>`_). At ``p=0`` the image is unchanged and each
- class row contains the original label twice with lambda zero.
+ ``same_on_batch=True`` shares each mix's cut size and placement across rows; each mix still draws its own
+ pairing and geometry. At ``p=0`` the image is unchanged and each class row contains the original label twice
+ with lambda zero.
Note:
This implementation would randomly cutmix images in a batch. Ideally, the larger batch size would be preferred.
diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.py
index 009225dc7..6469ef928 100644
--- a/kornia/augmentation/random_generator/_2d/cutmix.py
+++ b/kornia/augmentation/random_generator/_2d/cutmix.py
@@ -134,12 +134,15 @@ class CutmixGenerator(RandomGeneratorBase):
(batch_size * self.num_mix,), self.prob_sampler, same_on_batch
)
mix_pairs: torch.Tensor = (
- _adapted_sampling((self.num_mix, batch_size), self.pair_sampler, same_on_batch)
+ _adapted_sampling((self.num_mix, batch_size), self.pair_sampler, False)
.to(device=_device, dtype=_dtype)
.argsort(dim=1)
)
- cutmix_betas: torch.Tensor = _adapted_rsampling((batch_size * self.num_mix,), self.beta_sampler, same_on_batch)
+ if same_on_batch:
+ cutmix_betas = _adapted_rsampling((self.num_mix,), self.beta_sampler, False).repeat_interleave(batch_size)
+ else:
+ cutmix_betas = _adapted_rsampling((batch_size * self.num_mix,), self.beta_sampler, False)
# Note: torch.clamp does not accept torch.Tensor, cutmix_betas.clamp(cut_size[0], cut_size[1]) throws:
# Argument 1 to "clamp" of "_TensorBase" has incompatible type "torch.Tensor"; expected "float"
@@ -149,19 +152,17 @@ 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)
- if same_on_batch:
- 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.
+ # One size and start per row when independent; one per mix, repeated over rows when same_on_batch.
# Legal starts run 0 .. side - cut_side inclusive; the clamp only guards a u -> 1 float round-up.
_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
- )
- y_start = _adapted_rsampling(_gen_shape, self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype) * (
- height - cut_height + 1
- )
+ if same_on_batch:
+ x_start = _adapted_rsampling((self.num_mix,), self.rand_sampler, False).repeat_interleave(batch_size)
+ y_start = _adapted_rsampling((self.num_mix,), self.rand_sampler, False).repeat_interleave(batch_size)
+ else:
+ x_start = _adapted_rsampling(_gen_shape, self.rand_sampler, False)
+ y_start = _adapted_rsampling(_gen_shape, self.rand_sampler, False)
+ x_start = x_start.to(device=_device, dtype=_dtype) * (width - cut_width + 1)
+ y_start = y_start.to(device=_device, dtype=_dtype) * (height - cut_height + 1)
x_start = torch.minimum(x_start.floor(), width - cut_width)
y_start = torch.minimum(y_start.floor(), height - cut_height)
diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.py
index 1c8ce932c..a0f10251e 100644
--- a/tests/augmentation/test_conventions_mix.py
+++ b/tests/augmentation/test_conventions_mix.py
@@ -540,26 +540,52 @@ class TestMixConventions(BaseTester):
torch.manual_seed(seed)
shared = K.RandomCutMixV2(p=1.0, num_mix=2, same_on_batch=True, use_correct_lambda=True)
crop_src = shared.forward_parameters(shape)["crop_src"]
- self.assert_close(crop_src, crop_src[0, 0].expand_as(crop_src), rtol=0, atol=0)
+ for crop in crop_src:
+ self.assert_close(crop, crop[0].expand_as(crop), rtol=0, atol=0)
independent = K.RandomCutMixV2(p=1.0, num_mix=2, same_on_batch=False, use_correct_lambda=True)
heights, widths = infer_bbox_shape(independent.forward_parameters(shape)["crop_src"].flatten(0, 1))
assert heights.unique().numel() > 1
assert widths.unique().numel() > 1
@pytest.mark.device_agnostic
- def test_wart_cutmix_same_on_batch_repeats_one_cut_per_mix_4805(self):
- # #4805: with same_on_batch=True every mix repeats the first cut from the same donor, yet each mix is
- # labelled. Flips when the mixes differ or collapse to one, i.e. when the labels match the pixels.
+ def test_convention_cutmix_same_on_batch_draws_each_mix_independently_4805(self):
+ from kornia.geometry.bbox import bbox_to_mask, infer_bbox_shape
+
+ # #4805: same_on_batch shares each mix's geometry across rows, not across mixes.
torch.manual_seed(0)
image = torch.arange(4.0).view(4, 1, 1, 1).expand(4, 1, 8, 8).clone() # row i is filled with i
+ labels = torch.tensor([0, 1, 2, 3])
aug = K.RandomCutMixV2(
num_mix=2, same_on_batch=True, p=1.0, use_correct_lambda=True, data_keys=["input", "class"]
)
- output, mixed = aug(image, torch.tensor([0, 1, 2, 3]))
- assert mixed.shape[0] == 2
- assert torch.equal(mixed[0], mixed[1])
- replaced = (output[:, 0] != image[:, 0]).float().mean((-2, -1))
- self.assert_close(replaced, 1 - mixed[0, :, 2]) # one cut's area, while two mixes credit the donor
+ output, mixed = aug(image, labels)
+ pairs, crops = aug._params["mix_pairs"], aug._params["crop_src"]
+ assert not torch.equal(pairs[0], pairs[1])
+ assert not torch.equal(crops[0, 0], crops[1, 0])
+ expected_image = image.clone()
+ for mix in range(2):
+ assert torch.equal(crops[mix], crops[mix, 0].expand_as(crops[mix]))
+ self.assert_close(mixed[mix, :, 1], labels.index_select(0, pairs[mix]).float())
+ height, width = infer_bbox_shape(crops[mix, 0].unsqueeze(0))
+ expected_lambda = 1 - width * height / 64
+ self.assert_close(mixed[mix, :, 2], expected_lambda.expand(4))
+ # each mix pastes its own cut from the original image, a later mix over an earlier one
+ cut = bbox_to_mask(crops[mix], 8, 8).bool().unsqueeze(1)
+ expected_image = torch.where(cut, image[pairs[mix]], expected_image)
+ self.assert_close(output, expected_image, rtol=0, atol=0)
+
+ # Each mix draws its own size and its own x and y start: over a few seeds, each of them differs between the
+ # two mixes at least once (a fixed cut_size isolates the starts from the sizes).
+ differs = torch.zeros(3, dtype=torch.bool)
+ shape = torch.Size([4, 1, 64, 48])
+ for seed in range(10):
+ torch.manual_seed(seed)
+ free = K.RandomCutMixV2(num_mix=2, same_on_batch=True, p=1.0, use_correct_lambda=True)
+ heights, widths = infer_bbox_shape(free.forward_parameters(shape)["crop_src"][:, 0])
+ fixed = K.RandomCutMixV2(num_mix=2, same_on_batch=True, p=1.0, cut_size=(0.5, 0.5), use_correct_lambda=True)
+ start = fixed.forward_parameters(shape)["crop_src"][:, 0, 0] # (num_mix, 2) top-left of row 0
+ differs |= torch.stack([(heights[0] != heights[1]) | (widths[0] != widths[1]), *(start[0] != start[1])])
+ assert differs.all()
@pytest.mark.device_agnostic
def test_convention_cutmix_placement_is_drawn_per_cut_4712(self):