Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): normalize transplant mask rank (#5592)

Karnajeet Gosavi4044322caf4b
diff --git a/changelog.d/5592.breaking.md b/changelog.d/5592.breaking.md
new file mode 100644
index 000000000..cac1ff145
--- /dev/null
+++ b/changelog.d/5592.breaking.md
@@ -0,0 +1 @@
+`RandomTransplantation` inside `AugmentationSequential` now returns a batched `(B, H, W)` mask as `(B, 1, H, W)`, like every other child without `keepdim=True`. Previously it returned the mask as given, so a pipeline whose only child is the transplant, or whose transplant runs after a child with `keepdim=True`, returned `(B, H, W)`. With the container's `keepdim=True` the mask stays `(B, H, W)`. A mask of the wrong rank is now refused with "Every segmentation mask must have one fewer dimension ... than the image" instead of "Every image input must have one additional dimension ...".
diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.py
index 1b4ba951f..5b0b9de29 100644
--- a/kornia/augmentation/_2d/mix/transplantation.py
+++ b/kornia/augmentation/_2d/mix/transplantation.py
@@ -87,7 +87,9 @@ class RandomTransplantation(MixAugmentationBaseV2):
Convention:
- the transplant is driven by the first ``"mask"`` input. An image is ``(B, C, *spatial)`` and a mask
``(B, *spatial)`` for any number of spatial dimensions, including none (a ``(B,)`` mask moves whole
- images). There is no unbatched form, and the inherited ``keepdim`` is inert.
+ images). There is no unbatched form, and the inherited ``keepdim`` is inert on a direct call. In
+ :class:`~kornia.augmentation.container.AugmentationSequential` a 2D ``(B, H, W)`` mask comes back as
+ ``(B, 1, H, W)``, like from any other child, unless the container sets ``keepdim=True``.
- ``p`` gates samples and ``p_batch`` the whole call. The donor of acceptor ``i`` is image ``(i - 1) mod B``
of the full batch, with its original content, whether or not it is an acceptor itself; at ``B = 1`` the
call is an identity.
@@ -299,8 +301,8 @@ class RandomTransplantation(MixAugmentationBaseV2):
if key == DataKey.INPUT:
KORNIA_CHECK(
_input.ndim == mask.ndim + 1,
- "Every image input must have one additional dimension (channel dimension) than the segmentation "
- f"mask, but got {_input.ndim} for the input image and {mask.ndim} for the segmentation mask.",
+ "Every segmentation mask must have one fewer dimension (no channel dimension) than the image, "
+ f"but got {mask.ndim} for the segmentation mask and {_input.ndim} for the input image.",
)
KORNIA_CHECK(
mask.size() == torch.Size([s for i, s in enumerate(_input.size()) if i != self._channel_dim]),
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 3da4d11a2..41667b49b 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -486,7 +486,9 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
)
elif isinstance(module, K.RandomTransplantation):
- input = module(input, params=cls.get_instance_module_param(param), data_keys=[DataKey.MASK], **extra_args)
+ output = module(input, params=cls.get_instance_module_param(param), data_keys=[DataKey.MASK], **extra_args)
+ # A (B, H, W) mask leaves the transplant as (B, 1, H, W), like any other child without keepdim.
+ input = output.unsqueeze(1) if output.ndim == 3 and not module.keepdim else output
elif isinstance(module, K.MixAugmentationBaseV2):
# Dispatch to the mix child's own mask handler. Unsupported children
diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.py
index c25262fdb..11fb22f84 100644
--- a/tests/augmentation/test_augmentation_mix.py
+++ b/tests/augmentation/test_augmentation_mix.py
@@ -1164,7 +1164,11 @@ class TestRandomTransplantation(BaseTester):
image_out2, mask_out2 = AugmentationSequential(f)(image, mask, data_keys=["image", "mask"])
self.assert_close(image_out, image_out2)
- self.assert_close(mask_out, mask_out2)
+ if n_spatial == 2:
+ assert mask_out2.shape == (mask.shape[0], 1, *mask.shape[1:])
+ self.assert_close(mask_out, mask_out2[:, 0])
+ else:
+ self.assert_close(mask_out, mask_out2)
@pytest.mark.parametrize(
"input_shape_image, input_shape_mask, target_shape_image",
@@ -1221,7 +1225,7 @@ class TestRandomTransplantation(BaseTester):
with pytest.raises(Exception, match="There cannot be more selected labels"):
f(image, mask, params=params_copy)
- with pytest.raises(Exception, match="Every image input must have one additional dimension"):
+ with pytest.raises(Exception, match="Every segmentation mask must have one fewer dimension"):
f(image.unsqueeze(dim=-1), mask)
image = torch.rand(1, 3, 2, 5, device=device, dtype=torch.float64)
diff --git a/tests/augmentation/test_conventions_transplantation.py b/tests/augmentation/test_conventions_transplantation.py
index f4ba49e85..3b6a1cb71 100644
--- a/tests/augmentation/test_conventions_transplantation.py
+++ b/tests/augmentation/test_conventions_transplantation.py
@@ -100,7 +100,7 @@ class TestTransplantationConventions(BaseTester):
cls(p=1.0)(torch.rand(2, 4, 5), torch.randint(0, 3, (4, 5)))
mask = torch.randint(0, 3, (3, 4, 5))
for image in (torch.rand(3, 4, 5), torch.rand(3, 2, 4, 5, 6)):
- with pytest.raises(BaseError, match="one additional dimension"):
+ with pytest.raises(BaseError, match="one fewer dimension"):
cls(p=1.0)(image, mask)
@pytest.mark.device_agnostic
@@ -484,6 +484,43 @@ class TestTransplantationConventions(BaseTester):
assert torch.equal(out_mask[:, 0], direct_mask)
assert not torch.equal(direct_mask, mask) # something really moved
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("keepdim", [None, False, True])
+ @pytest.mark.parametrize("has_following_step", [False, True])
+ def test_convention_container_transplant_mask_rank_is_consistent_4750(self, keepdim, has_following_step):
+ image, mask = _labelled_batch(batch=3)
+ modules = [K.RandomTransplantation(p=1.0)]
+ if has_following_step:
+ modules.append(K.RandomHorizontalFlip(p=0.0))
+ aug = K.AugmentationSequential(*modules, data_keys=["image", "mask"], keepdim=keepdim)
+
+ _, out_mask = aug(image, mask)
+
+ expected_shape = mask.shape if keepdim else (mask.shape[0], 1, *mask.shape[1:])
+ assert out_mask.shape == expected_shape
+ actual_mask = out_mask if keepdim else out_mask[:, 0]
+ assert torch.equal(actual_mask, mask.roll(1, dims=0))
+
+ @pytest.mark.device_agnostic
+ def test_convention_invalid_mask_rank_error_names_mask_4750(self):
+ image = torch.rand(3, 2, 4, 6)
+ mask = torch.randint(0, 3, (3, 2, 4, 6))
+
+ with pytest.raises(BaseError, match="Every segmentation mask must have one fewer dimension"):
+ K.RandomTransplantation(p=1.0)(image, mask)
+
+ @pytest.mark.device_agnostic
+ def test_convention_container_child_keepdim_keeps_the_mask_rank_4750(self):
+ # The promotion belongs to the transplant: a child with keepdim=True under the container's keepdim=None
+ # still returns the caller's rank, for a batched mask and for per-sample masks in a list.
+ image, mask = _labelled_batch(batch=3)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0, keepdim=True), data_keys=["image", "mask"])
+ _, out_mask = aug(image, mask)
+ assert out_mask.shape == mask.shape
+ masks = [mask[:1], torch.cat([mask[1:2], mask[1:2]]), mask[2:]]
+ _, out_masks = aug(image, masks)
+ assert [m.shape for m in out_masks] == [m.shape for m in masks]
+
@pytest.mark.device_agnostic
@pytest.mark.parametrize(
"cls, spatial", [(K.RandomTransplantation, (4, 6)), (K.RandomTransplantation3D, (3, 4, 6))], ids=["2d", "3d"]