Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): name the missing mask in RandomTransplantation (#4983)

Mohansree Vijayakumar772fa98d4d54
diff --git a/changelog.d/4983.fixed.md b/changelog.d/4983.fixed.md
new file mode 100644
index 000000000..109e01b1d
--- /dev/null
+++ b/changelog.d/4983.fixed.md
@@ -0,0 +1 @@
+`RandomTransplantation` and `RandomTransplantation3D` now raise a kornia error naming the mask when a call has to draw the parameters without one, adding the key count when the inputs do not match `data_keys`, instead of Python's `IndexError` or `list.index` `ValueError`.
diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.py
index c3581c84b..67f75e835 100644
--- a/kornia/augmentation/_2d/mix/transplantation.py
+++ b/kornia/augmentation/_2d/mix/transplantation.py
@@ -101,9 +101,9 @@ class RandomTransplantation(MixAugmentationBaseV2):
only drawn labels), and a label list shorter than the acceptors leaves the trailing ones untouched.
- images are ``float16``, ``bfloat16``, ``float32`` or ``float64``; a mask keeps its own dtype (``bool``,
integer or floating). Only ``"input"`` / ``"image"`` and ``"mask"`` keys are implemented; any other key
- raises ``NotImplementedError``. A mask is needed only to draw the parameters, and a call without one
- fails with Python's ``IndexError`` or ``ValueError``, or a generic key-count error, rather than a kornia
- error naming the mask (`#4777 <https://github.com/kornia/kornia/issues/4777>`_). With a complete
+ raises ``NotImplementedError``. A mask is needed only to draw the parameters; a call that draws them
+ without one, or whose inputs do not match ``data_keys``, raises a kornia error that names the mask (and
+ the key count, on a mismatch) before any input is read. With a complete
``params`` any subset of the inputs is accepted, which is how
:class:`~kornia.augmentation.container.AugmentationSequential` applies the transplant, one input at a
time. Outputs come back in input order, a single one as a bare
@@ -243,6 +243,21 @@ class RandomTransplantation(MixAugmentationBaseV2):
acceptor[selection] = donor[selection]
return acceptor
+ def _check_mask_given(self, input: Sequence[torch.Tensor], data_keys: list[DataKey]) -> None:
+ # The parameters are drawn from the mask, so name it before any lookup fails on its absence.
+ names = [k.name.lower() for k in data_keys]
+ KORNIA_CHECK(
+ len(data_keys) == len(input),
+ f"Length of keys ({len(data_keys)}) does not match number of inputs ({len(input)}). "
+ f"{type(self).__name__} needs a mask to draw its parameters: pass one tensor per data_keys entry, "
+ f"the mask included, or pass complete params. Got data_keys={names}.",
+ )
+ KORNIA_CHECK(
+ DataKey.MASK in data_keys,
+ f"{type(self).__name__} needs a mask to draw its parameters: pass one and name it with a 'mask' "
+ f"entry in data_keys, or pass complete params. Got data_keys={names}.",
+ )
+
def params_from_input(
self,
*input: torch.Tensor,
@@ -267,10 +282,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
tensors separately.
"""
- KORNIA_CHECK(
- len(data_keys) == len(input),
- f"Length of keys ({len(data_keys)}) does not match number of inputs ({len(input)}).",
- )
+ self._check_mask_given(input, data_keys)
# The first mask key will be used for the transplantation
mask: torch.Tensor = input[data_keys.index(DataKey.MASK)]
@@ -383,6 +395,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
keys = [DataKey.get(inp) for inp in data_keys]
if params is None:
+ self._check_mask_given(input, keys)
mask: torch.Tensor = input[keys.index(DataKey.MASK)]
self._params = self.forward_parameters(mask.shape)
else:
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index 8848ed2ee..e9bfc4779 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -640,8 +640,8 @@ class TestConventionAugmentationBase2D(BaseTester):
],
)
def test_convention_transplantation_supports_a_mask_only_call(self, augmentation_cls, spatial_shape, device):
- # Images are optional (a missing mask is #4777). Three donors make the cyclic donor direction observable:
- # p=1 replaces every acceptor with its preceding donor.
+ # Images are optional; a missing mask raises a named error (#4777). Three donors make the cyclic donor
+ # direction observable: p=1 replaces every acceptor with its preceding donor.
mask = torch.arange(3, device=device, dtype=torch.int64).reshape(3, *((1,) * len(spatial_shape)))
mask = mask.expand(3, *spatial_shape)
augmentation = augmentation_cls(p=1.0)
diff --git a/tests/augmentation/test_conventions_transplantation.py b/tests/augmentation/test_conventions_transplantation.py
index 0cf0d5f7f..2ef4df6f9 100644
--- a/tests/augmentation/test_conventions_transplantation.py
+++ b/tests/augmentation/test_conventions_transplantation.py
@@ -24,6 +24,7 @@ import pytest
import torch
import kornia.augmentation as K
+from kornia.constants import DataKey
from kornia.core.exceptions import BaseError
from testing.base import BaseTester
@@ -366,13 +367,20 @@ class TestTransplantationConventions(BaseTester):
@pytest.mark.device_agnostic
@pytest.mark.parametrize("cls", [K.RandomTransplantation, K.RandomTransplantation3D])
- def test_wart_a_missing_mask_raises_a_python_lookup_error_4777(self, cls):
- # #4777: flips when kornia checks for the mask itself instead of failing in tuple / list lookups.
+ def test_convention_a_missing_mask_raises_a_kornia_error_naming_it_4777(self, cls):
image = torch.rand(2, 1, 4, 5)
- with pytest.raises(IndexError):
- cls(p=1.0)(image) # the default data_keys name a mask that was not passed
- with pytest.raises(ValueError, match="not in list"): # Python 3.14 reworded list.index's message
+ # the default data_keys name a mask that was not passed: the error gives the key count and names the mask
+ with pytest.raises(
+ BaseError,
+ match=rf"Length of keys \(2\) does not match number of inputs \(1\)\. {cls.__name__} needs a mask to draw "
+ r"its parameters: .* Got data_keys=\['image', 'mask'\]\.",
+ ):
+ cls(p=1.0)(image)
+ with pytest.raises(BaseError, match=rf"{cls.__name__} needs a mask to draw its parameters"):
cls(p=1.0)(image, data_keys=["input"])
+ # params_from_input, the entry AugmentationSequential uses, raises the same error
+ with pytest.raises(BaseError, match=rf"{cls.__name__} needs a mask to draw its parameters"):
+ cls(p=1.0).params_from_input(image, data_keys=[DataKey.INPUT], params={})
@pytest.mark.device_agnostic
def test_convention_a_mask_is_required_only_to_derive_the_parameters(self):