Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): invert a list-valued mask in AugmentationSequential (#4739)

Dipak Chaudhari012997ceb469
diff --git a/changelog.d/4739.fixed.md b/changelog.d/4739.fixed.md
new file mode 100644
index 000000000..446fe601b
--- /dev/null
+++ b/changelog.d/4739.fixed.md
@@ -0,0 +1 @@
+`AugmentationSequential.inverse` now inverts a list-valued `mask` element by element, reusing each entry's forward gate, instead of raising `AttributeError: 'list' object has no attribute 'dtype'`.
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 33f75d200..d018326ca 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -131,7 +131,10 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
children. Per-sample list tensors are unsupported by warp operations, and full-batch tensors in that
list can become desynchronized from the image when the gate differs across samples. A list longer
than the batch raises ``IndexError``. Use separate ``mask`` data keys for separate full-batch masks.
- Tracked in `#4477 <https://github.com/kornia/kornia/issues/4477>`_.
+ ``.inverse()`` takes the list the forward pass returned and inverts it element by element with the
+ same per-entry gate. A flip round-trips each entry, subject to the working-dtype rounding above; other
+ warps lose the pixels they move out of the frame and, when they resample, restore the rest only
+ approximately. Tracked in `#4477 <https://github.com/kornia/kornia/issues/4477>`_.
- supported geometric data-key handlers share the recorded transform, subject to the mask limitations
above. Custom rigid subclasses are not dispatched solely because they supply a matrix
(`#4481 <https://github.com/kornia/kornia/issues/4481>`_). A non-rigid warp child has no matrix, so
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 5dea048b6..cb5549f04 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -239,7 +239,11 @@ class AugmentationSequentialOps:
for inp, dcate in zip(arg, _data_keys):
op = self._get_op(dcate)
extra_arg = extra_args[dcate] if dcate in extra_args else {}
- outputs.append(op.inverse(inp, module, param=param, extra_args=extra_arg))
+ if dcate.name == "MASK" and isinstance(inp, list):
+ # Mirror ``transform``: a list of masks is inverted element by element.
+ outputs.append(MaskSequentialOps.inverse_list(inp, module, param=param, extra_args=extra_arg))
+ else:
+ outputs.append(op.inverse(inp, module, param=param, extra_args=extra_arg))
if len(outputs) == 1 and isinstance(outputs, (list, tuple)):
return outputs[0]
return outputs
@@ -570,6 +574,54 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
return input
+ @classmethod
+ def inverse_list(
+ cls, input: List[torch.Tensor], module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> List[torch.Tensor]:
+ """Inverse a transformation on a list of masks, undoing :meth:`transform_list` element by element.
+
+ Args:
+ input: list of input tensors.
+ module: any torch nn.Module but only kornia augmentation modules will count
+ to apply transformations.
+ param: the corresponding parameters to the module.
+ extra_args: Optional dictionary of extra arguments with specific options for different input types.
+ """
+ if extra_args is None:
+ extra_args = {}
+
+ if isinstance(module, (K.GeometricAugmentationBase2D,)):
+ if module.transform_matrix is None:
+ raise ValueError(f"No valid transformation matrix found in {module.__class__}.")
+ transform = module.compute_inverse_transformation(module.transform_matrix)
+ params = cls.get_instance_module_param(param)
+ params_i = copy.deepcopy(params)
+ inv_input = []
+ for i, inp in enumerate(input):
+ # The same per-element ``batch_prob`` that ``transform_list`` gave this element.
+ params_i["batch_prob"] = params["batch_prob"][i]
+ inv_input.append(
+ module.inverse_masks(inp, params=params_i, flags=module.flags, transform=transform, **extra_args)
+ )
+ input = inv_input
+
+ elif isinstance(module, (K.GeometricAugmentationBase3D,)):
+ raise NotImplementedError(
+ "The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo."
+ )
+
+ elif isinstance(module, K.container.ImageSequentialBase):
+ seq_params = cls.get_sequential_module_param(param)
+ input = [module.inverse_masks(inp, params=seq_params, extra_args=extra_args) for inp in input]
+
+ elif isinstance(module, (K.auto.operations.OperationBase,)):
+ raise NotImplementedError(
+ "The support for list of masks under auto operations are not yet supported. You are welcome to file a"
+ " PR in our repo."
+ )
+
+ return input
+
class BoxSequentialOps(SequentialOpsInterface[Boxes]):
"""Apply and inverse transformations for bounding box tensors.
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 3bb4a5f87..a12d6c39d 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -900,6 +900,66 @@ class TestConventionAugmentationSequential(BaseTester):
assert torch.equal(out_entry, entry.flip(-1))
assert seq.mask_dtype == mask_dtypes[0] # the attribute records the first element of the last list mask
+ def test_list_mask_inverse_undoes_the_forward_pass_4716(self, device, dtype):
+ # kornia#4716: forward accepted a list mask and returned one, but inverse raised
+ # "'list' object has no attribute 'dtype'". It now inverts element by element, and each
+ # entry comes back in its own dtype, as in the forward pass (#4478).
+ image = torch.arange(48, device=device, dtype=dtype).reshape(2, 1, 4, 6)
+ labels = torch.arange(24, device=device).reshape(1, 1, 4, 6).expand(2, 1, -1, -1) % 5
+ masks = [labels.clone(), (labels > 2)]
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ out_image, out_masks = seq(image, masks)
+ restored_image, restored = seq.inverse(out_image, out_masks)
+ self.assert_close(restored_image, image)
+ assert isinstance(restored, list) and len(restored) == 2
+ assert [m.dtype for m in restored] == [torch.int64, torch.bool]
+ for entry, original in zip(restored, masks):
+ assert torch.equal(entry, original)
+
+ def test_list_mask_inverse_uses_each_entrys_forward_gate_4716(self, device, dtype):
+ # The forward pass gives list entry i the gate of sample i (the #4477 wart). The inverse has to
+ # reuse that same gate, or a mixed-probability batch would come back half re-flipped.
+ image = torch.arange(24, device=device, dtype=dtype).reshape(2, 1, 3, 4)
+ masks = [image.clone(), image.expand(-1, 2, -1, -1).clone()]
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.5), data_keys=["input", "mask"])
+ params = [
+ ParamItem(
+ "RandomHorizontalFlip_0",
+ {"batch_prob": torch.tensor([1.0, 0.0]), "forward_input_shape": torch.tensor(image.shape)},
+ )
+ ]
+ out_image, out_masks = seq(image, masks, params=params)
+ _, restored = seq.inverse(out_image, out_masks, params=params)
+ self.assert_close(restored[0], masks[0])
+ self.assert_close(restored[1], masks[1])
+
+ def test_list_mask_inverse_through_a_nested_sequential_4716(self, device, dtype):
+ image = torch.arange(24, device=device, dtype=dtype).reshape(1, 1, 4, 6)
+ masks = [image.clone(), image.clone() * 2]
+ seq = K.AugmentationSequential(
+ K.ImageSequential(K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0)),
+ data_keys=["input", "mask"],
+ )
+ out_image, out_masks = seq(image, masks)
+ self.assert_close(out_masks[0], image.flip(-1).flip(-2))
+ _, restored = seq.inverse(out_image, out_masks)
+ for entry, original in zip(restored, masks):
+ self.assert_close(entry, original)
+
+ def test_list_mask_inverse_applies_the_inverse_matrix_4716(self, device, dtype):
+ # A flip is its own inverse, so a flip round trip cannot tell the inverse matrix from the forward one.
+ # A quarter turn can: applying the forward matrix again gives a half turn instead of the identity.
+ image = torch.rand(2, 1, 8, 8, device=device, dtype=dtype)
+ labels = torch.arange(64, device=device).reshape(1, 1, 8, 8).expand(2, 1, -1, -1) % 7
+ masks = [labels.clone(), labels > 3]
+ seq = K.AugmentationSequential(K.RandomRotation(degrees=(90.0, 90.0), p=1.0), data_keys=["input", "mask"])
+ out_image, out_masks = seq(image, masks)
+ assert not torch.equal(out_masks[0], labels)
+ _, restored = seq.inverse(out_image, out_masks)
+ assert [m.dtype for m in restored] == [torch.int64, torch.bool]
+ for entry, original in zip(restored, masks):
+ assert torch.equal(entry, original)
+
@pytest.mark.parametrize("key", ["bbox_xyxy", "bbox_xywh"])
@pytest.mark.parametrize("suffix", ["", "_2", "-a"])
def test_dictionary_coordinate_box_keys_4483(self, key, suffix, device, dtype):