Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): validate RandomMosaic padding_mode at construction (#5917)

Anand Bd8f7589cc128
diff --git a/changelog.d/5917.breaking.md b/changelog.d/5917.breaking.md
new file mode 100644
index 000000000..58e3fefc8
--- /dev/null
+++ b/changelog.d/5917.breaking.md
@@ -0,0 +1 @@
+`RandomMosaic` now checks `padding_mode` at construction, in both cropping modes, and raises a `ValueError` that names the value and lists `constant`, `reflect` and `replicate` for anything else. Previously the constructor accepted any value: `cropping_mode="slice"` ignored it, and `cropping_mode="resample"` passed any other string to `grid_sample`, so `grid_sample`'s own names `zeros`, `border` and `reflection` worked (as `constant`, `replicate` and `reflect`) while any other value failed inside `forward` with torch's `grid_sample` error.
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 177e71180..84b74a9ca 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -59,7 +59,8 @@ class RandomMosaic(MixAugmentationBaseV2):
p: probability of applying the transformation to each sample.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
- padding_mode: Type of padding. Should be: constant, reflect, replicate.
+ padding_mode: Type of padding, used only with ``cropping_mode="resample"``.
+ Should be: constant, reflect, replicate.
resample: the interpolation mode.
align_corners: interpolation flag.
cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the torch.Tensor based
@@ -127,6 +128,10 @@ class RandomMosaic(MixAugmentationBaseV2):
align_corners: bool = True,
cropping_mode: str = "slice",
) -> None:
+ if padding_mode not in ("constant", "reflect", "replicate"):
+ raise ValueError(
+ f"{padding_mode!r} is not a valid padding_mode. Expected one of 'constant', 'reflect', 'replicate'."
+ )
super().__init__(p=p, p_batch=1.0, same_on_batch=False, keepdim=keepdim, data_keys=data_keys)
self.start_ratio_range = start_ratio_range
self._param_generator = rg.MosaicGenerator(output_size, mosaic_grid, start_ratio_range)
diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.py
index 5616010d5..9cbb96b76 100644
--- a/tests/augmentation/test_augmentation_mix.py
+++ b/tests/augmentation/test_augmentation_mix.py
@@ -838,6 +838,32 @@ class TestRandomMosaic(BaseTester):
assert region.numel() > 0, (n, (x1, y1, x2, y2))
assert bool((region > 0).all()), (n, (x1, y1, x2, y2), out_image[n, 0])
+ @pytest.mark.parametrize("cropping_mode", ["slice", "resample"])
+ def test_unknown_padding_mode_rejected_at_construction_5914(self, cropping_mode):
+ with pytest.raises(
+ ValueError,
+ match=r"'bogus' is not a valid padding_mode\. Expected one of 'constant', 'reflect', 'replicate'\.",
+ ):
+ RandomMosaic(padding_mode="bogus", cropping_mode=cropping_mode)
+
+ @pytest.mark.parametrize("padding_mode", ["zeros", "border", "reflection", "Constant"])
+ def test_grid_sample_padding_names_rejected_5914(self, padding_mode):
+ # `cropping_mode="resample"` used to pass grid_sample's own names through; names are matched as given.
+ with pytest.raises(ValueError, match=f"'{padding_mode}' is not a valid padding_mode"):
+ RandomMosaic(padding_mode=padding_mode, cropping_mode="resample")
+
+ @pytest.mark.parametrize("cropping_mode", ["slice", "resample"])
+ @pytest.mark.parametrize("padding_mode", ["constant", "reflect", "replicate"])
+ def test_valid_padding_mode_forward_5914(self, cropping_mode, padding_mode, device, dtype):
+ image = torch.rand(2, 3, 32, 48, device=device, dtype=dtype)
+ output = RandomMosaic(
+ output_size=(32, 48),
+ p=1.0,
+ padding_mode=padding_mode,
+ cropping_mode=cropping_mode,
+ )(image)
+ assert output.shape == (2, 3, 32, 48)
+
def test_smoke(self):
f = RandomMosaic(data_keys=["input", "class"])
repr = (