Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): replay a forward_parameters() dictionary with the class key in MixUpV2 and CutMixV2 (#4726)

Rızgar Ozane22e26f26014
diff --git a/changelog.d/4726.fixed.md b/changelog.d/4726.fixed.md
new file mode 100644
index 000000000..67f741775
--- /dev/null
+++ b/changelog.d/4726.fixed.md
@@ -0,0 +1 @@
+`RandomMixUpV2` and `RandomCutMixV2` now replay a `forward_parameters()` dictionary with the `"class"` key; the image dtype that the label handlers need is taken from the input, instead of raising `KeyError: 'dtype'`. A replayed dictionary with an unsupported image dtype still raises `TypeError`.
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 7be0ad4cc..99b97455a 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -279,6 +279,16 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
in_tensor = self.transform_tensor(in_tensor)
self._params = self.forward_parameters(in_tensor.shape)
self._params.update({"dtype": torch.full((), DType.get(in_tensor.dtype).value, dtype=torch.long)})
+ elif DataKey.INPUT in keys:
+ # The class handlers read ``"dtype"``, which a ``forward_parameters()`` dictionary does not have: take it
+ # from the input, as above, in a copy that leaves the caller's dictionary alone. A supplied ``"dtype"`` is
+ # replaced too, so a dictionary recorded on another image dtype cannot go stale. Only the dtype check of
+ # ``transform_tensor`` runs here, so that a subclass's shape checks still come after the params checks.
+ in_tensor = input[keys.index(DataKey.INPUT)]
+ _validate_input_dtype(
+ in_tensor, accepted_dtypes=[torch.bfloat16, torch.float16, torch.float32, torch.float64]
+ )
+ self._params = {**params, "dtype": torch.full((), DType.get(in_tensor.dtype).value, dtype=torch.long)}
else:
self._params = params
diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.py
index 504f5bebe..ef5dd8871 100644
--- a/tests/augmentation/test_conventions_mix.py
+++ b/tests/augmentation/test_conventions_mix.py
@@ -557,6 +557,45 @@ class TestMixConventions(BaseTester):
assert mixed[..., 0].flatten().tolist() == [257.0, 999.0]
assert mixed[..., 1].flatten().tolist() == ([999.0, 257.0] if p == 1.0 else [257.0, 999.0])
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("image_dtype", [torch.float32, torch.float16, torch.bfloat16, torch.float64])
+ @pytest.mark.parametrize("p", [0.0, 1.0])
+ def test_convention_mix_forward_parameters_replay_with_class_4706(self, image_dtype, p):
+ # A forward_parameters() dictionary has no "dtype"; forward takes it from the input, so replaying it with
+ # the "class" key matches the call that sampled the same draws, instead of raising KeyError.
+ image = torch.rand(2, 1, 4, 4, dtype=image_dtype)
+ labels = torch.tensor([1, 2])
+ for aug in (K.RandomMixUpV2(p=p), K.RandomCutMixV2(p=p, use_correct_lambda=True)):
+ torch.manual_seed(0)
+ sampled, sampled_labels = aug(image, labels, data_keys=["input", "class"])
+ torch.manual_seed(0)
+ params = aug.forward_parameters(image.shape)
+ output, mixed = aug(image, labels, params=params, data_keys=["input", "class"])
+ assert "dtype" not in params # the caller's dictionary is left as it was
+ assert torch.equal(output, sampled) and torch.equal(mixed, sampled_labels)
+ assert mixed.dtype == _label_dtype(image_dtype)
+
+ def test_convention_mix_replay_takes_dtype_from_the_input_not_the_dictionary(self):
+ # A dictionary recorded on a float32 image and replayed on a float64 one gives float64 labels, like a fresh
+ # draw on the float64 image: the recorded "dtype" is not reused.
+ image = torch.rand(2, 1, 4, 4)
+ labels = torch.tensor([1, 2])
+ for aug in (K.RandomMixUpV2(p=1.0), K.RandomCutMixV2(p=1.0, use_correct_lambda=True)):
+ aug(image, labels, data_keys=["input", "class"])
+ params = dict(aug._params)
+ _, mixed = aug(image.double(), labels, params=params, data_keys=["input", "class"])
+ assert mixed.dtype == torch.float64
+
+ @pytest.mark.parametrize("image_dtype", [torch.uint8, torch.int32, torch.bool])
+ def test_convention_mix_replay_rejects_an_unsupported_dtype_with_type_error(self, image_dtype):
+ # The replayed dictionary goes through the same dtype check as a fresh draw, so the error stays a TypeError.
+ image = torch.rand(2, 1, 4, 4)
+ for aug_cls in (K.RandomMixUpV2, K.RandomCutMixV2, K.RandomJigsaw, K.RandomMosaic):
+ aug = aug_cls(p=1.0)
+ params = aug.forward_parameters(image.shape)
+ with pytest.raises(TypeError, match="Expected input of"):
+ aug((image * 255).to(image_dtype), params=params)
+
def test_convention_jigsaw_identity_permutation_transposes_the_grid(self, device, dtype):
# The destination cell is chosen column-major by an entry's position; the entry's value indexes the
# source patch row-major. The two orders differ, so the identity permutation is not a no-op.