π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): honour an explicit mask resample on the 2D geometric forward path (#4509)
Dipak Chaudhari2c349f2354a2
diff --git a/changelog.d/4509.fixed.md b/changelog.d/4509.fixed.mdnew file mode 100644index 000000000..33e3a4b62--- /dev/null+++ b/changelog.d/4509.fixed.md@@ -0,0 +1,5 @@+A `resample` entry in `AugmentationSequential(extra_args={DataKey.MASK: {...}})` now reaches the mask sampler on+2D geometric augmentations that use the base mask path (`RandomAffine`, `RandomRotation`, `RandomPerspective`,+`Resize`, the crops and the rest). It used to be merged and then overwritten with nearest on the forward path,+though `inverse` already honoured it. Masks still default to nearest when no `resample` is given, including+when a user dict leaves it out. (#4419)diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.pyindex 5049a8a53..87524a220 100644--- a/kornia/augmentation/_2d/geometric/base.py+++ b/kornia/augmentation/_2d/geometric/base.py@@ -52,10 +52,11 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):- a subclass supplies its own :meth:`inverse_transform` -- the base raises ``NotImplementedError`` --while :meth:`compute_inverse_transformation` defaults to inverting the sampled matrix.- .. warning::- The ``resample`` half of an ``extra_args[DataKey.MASK]`` override is discarded here -- masks are- always nearest -- while the ``align_corners`` half does reach the sampler. Tracked in- `#4419 <https://github.com/kornia/kornia/issues/4419>`_.+ Note:+ Masks are resampled with nearest neighbour whatever ``resample`` the augmentation uses for images,+ unless ``resample`` is passed explicitly to :meth:`transform_masks` or :meth:`inverse_masks` --+ which is what ``extra_args[DataKey.MASK]`` does in a container. An explicit value is honoured in+ both directions."""@@ -103,6 +104,19 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):"""Process masks corresponding to the inputs that are no transformation applied."""return input+ def transform_masks(+ self,+ input: torch.Tensor,+ params: Dict[str, torch.Tensor],+ flags: Dict[str, Any],+ transform: Optional[torch.Tensor] = None,+ **kwargs: Any,+ ) -> torch.Tensor:+ # Nearest is the mask default, but an explicit ``resample`` wins, matching ``inverse_masks``.+ if "resample" not in kwargs and "resample" in (self.flags if flags is None else flags):+ kwargs["resample"] = Resample.get("nearest")+ return super().transform_masks(input, params, flags, transform=transform, **kwargs)+def apply_transform_mask(self,input: torch.Tensor,@@ -113,18 +127,14 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):"""Process masks corresponding to the inputs that are transformed.Note:- Convert "resample" arguments to "nearest" by default.+ Uses ``flags["resample"]`` as given; :meth:`transform_masks` supplies "nearest" when the caller+ did not choose one.Normalize "align_corners" from None to False to match PyTorch's default behavior."""- resample_method: Optional[Resample] = Nonealign_corners_was_none: bool = Falseoriginal_align_corners: Optional[bool] = None- if "resample" in flags:- resample_method = flags["resample"]- flags["resample"] = Resample.get("nearest")-# When align_corners=None is in flags (from extra_args), use the module's default# This ensures masks use the same align_corners value as inputs for consistency# However, for 'slice' cropping_mode with 'nearest' mode, align_corners must be None@@ -146,9 +156,6 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):output = self.apply_transform(input, params, flags, transform)- if resample_method is not None:- flags["resample"] = resample_method-# Restore align_corners if it was modifiedif align_corners_was_none:flags["align_corners"] = original_align_cornersdiff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 652536a39..38fa6b0e6 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -91,9 +91,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):merging into it, so an override that omits a key drops that key's default. An empty dictis falsy and restores the default. ``DataKey.IMAGE`` honours both entries and``DataKey.KEYPOINTS`` honours neither. For ``DataKey.MASK`` on a 2D geometric augmentation- that uses the base mask path the ``resample`` entry is discarded -- masks are resampled- with nearest neighbour whatever it says. ``align_corners`` is handler-dependent: some warps- honor it, but resize mask paths replace it as well (see #4419).+ that uses the base mask path the ``resample`` entry is honoured in both directions, and a+ dict without one resamples masks with nearest neighbour. ``align_corners`` is+ handler-dependent: some warps honor it, but resize mask paths replace it.With :class:`~kornia.augmentation.RandomResizedCrop`,boolean ``align_corners`` overrides raise ``ValueError`` in the default ``cropping_mode='slice'``mask path; ``cropping_mode='resample'`` accepts them. ``None`` works in both modes.@@ -176,11 +176,6 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):inspect nested children. ``skip`` leaves``.transform_matrix`` at ``None`` whatever the chain.- .. warning::- The base 2D geometric mask path discards the ``resample`` half of an ``extra_args[DataKey.MASK]``- override. Custom mask paths, including ``RandomElasticTransform``, may honor it instead. Tracked in- `#4419 <https://github.com/kornia/kornia/issues/4419>`_.-.. warning::A non-rigid child silently desynchronizes the coordinate data keys::class:`~kornia.augmentation.RandomElasticTransform` warps the image **and** a ``mask`` key with it,diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 599f53ce5..5154e9eeb 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -1014,15 +1014,14 @@ class TestConventionAugmentationSequential(BaseTester):assert shape(False, True) == (1, 3, 6, 8)assert shape(True, False) == (3, 6, 8)- def test_wart_extra_args_mask_resample_override_is_discarded_4419(self, device, dtype):- # Wart pin (#4419): `extra_args[DataKey.MASK]` is documented as the way to control how masks are- # handled, but on every class whose mask path is `RigidAffineAugmentationBase2D.apply_transform_mask`- # the `resample` half is overwritten with NEAREST after the override was merged, so asking for- # bilinear changes nothing. The `align_corners` half of the same dict IS honoured and reaches the- # sampler, and `RandomElasticTransform`, which has its own mask path, honours both halves.+ def test_extra_args_mask_override_reaches_the_sampler_4419(self, device, dtype):+ # #4419: `extra_args[DataKey.MASK]` is the documented way to control how masks are handled, and both+ # halves of it reach the sampler. The base 2D geometric mask path used to overwrite `resample` with+ # NEAREST after merging the override, so asking for bilinear changed nothing on `RandomAffine`, while+ # the `align_corners` half of the same dict was honoured. `RandomElasticTransform`, which has its own+ # mask path, honours both halves.# Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu), seed 0, a- # (1, 1, 6, 8) mask with a 1-block: RandomAffine resample override max|delta| 0.0, RandomPerspective- # align_corners override 1.0.+ # (1, 1, 6, 8) mask with a 1-block: RandomPerspective align_corners override 1.0.# The elastic half uses its own fixture, reusing the #4420 pin's style below: `RandomElasticTransform# (alpha=(5.0, 5.0), sigma=(4.0, 4.0), p=1.0)` on a checkerboard mask, same (1, 1, 6, 8), H != W frame,# instead of the default alpha/sigma with a solid block. #4382 ("fix: respect align_corners in elastic@@ -1038,7 +1037,6 @@ class TestConventionAugmentationSequential(BaseTester):# skip that used to guard this pin is dropped: affine and perspective are exact on float16/bfloat16# (0.0 and 1.0, matching float32/float64) and the elastic delta stays far above the threshold there# too.- # The fix lands in the repair window and flips the first assertion; do not "correct" it here.def mask_of(aug_factory, extra):torch.manual_seed(0)@@ -1052,7 +1050,7 @@ class TestConventionAugmentationSequential(BaseTester):align = {DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": True}}affine = lambda: K.RandomAffine(degrees=(45.0, 45.0), p=1.0) # noqa: E731- assert (mask_of(affine, bilinear) - mask_of(affine, None)).abs().max().item() == 0.0+ assert (mask_of(affine, bilinear) - mask_of(affine, None)).abs().max().item() > 0.0perspective = lambda: K.RandomPerspective(0.5, p=1.0) # noqa: E731assert (mask_of(perspective, align) - mask_of(perspective, None)).abs().max().item() == 1.0@@ -1079,25 +1077,56 @@ class TestConventionAugmentationSequential(BaseTester):).extra_argsassert replaced == {DataKey.MASK: {"align_corners": True}}- @pytest.mark.xfail(strict=True, raises=AssertionError, reason="Tracked in #4419")- def test_convention_extra_args_mask_resample_override_is_honoured(self, device, dtype):- # Strict xfail (#4419): the intended reading is the one `AugmentationSequential`'s own docstring- # states - `extra_args[DataKey.MASK]` controls how masks are handled, so asking for a bilinear- # `resample` must reach the sampler and change the mask, exactly as it already does on- # `RandomElasticTransform`. Today the 2D geometric mask path overwrites `resample` with NEAREST after- # merging the override, so this XFAILs; it turns XPASS when the repair lands, which is the signal to- # delete the wart pin above. The affine override currently has no effect.- def mask_of(factory, extra):+ @pytest.mark.parametrize(+ "factory",+ [+ lambda: K.RandomAffine(degrees=(45.0, 45.0), p=1.0),+ lambda: K.RandomRotation(degrees=(45.0, 45.0), p=1.0),+ lambda: K.RandomPerspective(0.5, p=1.0),+ lambda: K.RandomShear((20.0, 20.0), p=1.0),+ lambda: K.Resize((9, 13)),+ lambda: K.RandomResizedCrop((9, 13), p=1.0),+ ],+ ids=["RandomAffine", "RandomRotation", "RandomPerspective", "RandomShear", "Resize", "RandomResizedCrop"],+ )+ def test_extra_args_mask_resample_is_honoured_and_nearest_stays_the_default_4419(self, factory, device, dtype):+ # #4419: a bilinear `resample` under `extra_args[DataKey.MASK]` reaches the sampler on the base 2D+ # geometric mask path, as it already did on `inverse` and on `RandomElasticTransform`. Without one --+ # the container's default dict, or a user dict that leaves `resample` out -- masks stay nearest, so a+ # binary mask stays binary even though these classes resample images bilinearly. A checkerboard mask,+ # so that any bilinear resample produces in-between values wherever the crop or warp lands.+ def mask_of(extra):torch.manual_seed(0)aug = K.AugmentationSequential(factory(), data_keys=["input", "mask"], extra_args=extra)img = torch.rand(1, 3, 6, 8, device=device, dtype=dtype)- mask = torch.zeros(1, 1, 6, 8, device=device, dtype=dtype)- mask[:, :, 1:4, 2:6] = 1.0+ yy, xx = torch.meshgrid(torch.arange(6, device=device), torch.arange(8, device=device), indexing="ij")+ mask = ((yy + xx) % 2).to(dtype).expand(1, 1, 6, 8).clone()return aug(img, mask)[1]- bilinear = {DataKey.MASK: {"resample": Resample.BILINEAR, "align_corners": None}}- affine = lambda: K.RandomAffine(degrees=(45.0, 45.0), p=1.0) # noqa: E731- assert (mask_of(affine, bilinear) - mask_of(affine, None)).abs().max().item() > 0.0+ def is_binary(t):+ return bool(((t == 0) | (t == 1)).all())++ default = mask_of(None)+ assert is_binary(default)+ assert is_binary(mask_of({DataKey.MASK: {"align_corners": None}}))++ bilinear = mask_of({DataKey.MASK: {"resample": Resample.BILINEAR, "align_corners": None}})+ assert not is_binary(bilinear)+ assert (bilinear - default).abs().max().item() > 0.0++ def test_direct_transform_masks_call_without_resample_stays_nearest_4419(self, device, dtype):+ # The module's own `resample` is for images. A direct call that does not choose one must not pick it+ # up for the mask.+ torch.manual_seed(0)+ aug = K.RandomAffine(degrees=(45.0, 45.0), p=1.0)+ assert aug.flags["resample"] == Resample.BILINEAR+ img = torch.rand(1, 3, 6, 8, device=device, dtype=dtype)+ mask = torch.zeros(1, 1, 6, 8, device=device, dtype=dtype)+ mask[:, :, 1:4, 2:6] = 1.0+ aug(img)+ out = aug.transform_masks(mask, params=aug._params, flags=aug.flags, transform=aug.transform_matrix)+ assert bool(((out == 0) | (out == 1)).all())+ assert aug.flags["resample"] == Resample.BILINEARdef test_wart_non_rigid_augmentation_desynchronizes_the_data_keys_4420(self, device, dtype):# Wart pin (#4420): the container promises that one call applies the same sampled transform to every