π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): dispatch mix annotation keys in AugmentationSequential (#4493) (#4505)
yi1117e4504688bc7
diff --git a/changelog.d/4505.fixed.md b/changelog.d/4505.fixed.mdnew file mode 100644index 000000000..75619e92a--- /dev/null+++ b/changelog.d/4505.fixed.md@@ -0,0 +1,3 @@+`AugmentationSequential` dispatches ``mask``, box and ``keypoints`` keys through a mix child's own handlers+instead of silently returning them unchanged next to a mixed image. Unsupported keys raise+``NotImplementedError`` as a direct call does; ``RandomMosaic`` boxes are transformed. (#4493)diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 38fa6b0e6..96fc00e60 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -185,10 +185,11 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):Tracked in `#4420 <https://github.com/kornia/kornia/issues/4420>`_... note::- Inside this container a mix child (e.g. RandomMixUpV2, RandomCutMixV2, RandomMosaic) mixes the image only.- A ``class``/``label`` key raises ``NotImplementedError``, and ``mask``, box and ``keypoints`` keys are- returned unchanged, silently desynchronized from the mixed image, even where the class transforms that- key when called directly (``RandomMosaic`` boxes). Tracked in+ Inside this container a mix child (e.g. RandomMixUpV2, RandomCutMixV2, RandomMosaic) dispatches+ ``mask``, box and ``keypoints`` keys to the child's own handlers, using the same parameters as the+ mixed image. Keys the child does not implement raise ``NotImplementedError``, matching a direct call+ (for example ``RandomMosaic`` transforms boxes and refuses masks/keypoints). A ``class``/``label`` key+ still raises ``NotImplementedError`` from the container. Fixed in`#4493 <https://github.com/kornia/kornia/issues/4493>`_... note::diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.pyindex 950b4749c..e27abbd83 100644--- a/kornia/augmentation/container/ops.py+++ b/kornia/augmentation/container/ops.py@@ -427,6 +427,12 @@ 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)+ elif isinstance(module, K.MixAugmentationBaseV2):+ # Dispatch to the mix child's own mask handler. Unsupported children+ # raise NotImplementedError from apply_transform_mask (matching a+ # direct call) instead of silently returning the mask unchanged.+ input = module.transform_mask(input, cls.get_instance_module_param(param), module.flags)+elif isinstance(module, (_AugmentationBase)):input = module.transform_masks(input, params=cls.get_instance_module_param(param), flags=module.flags, **extra_args@@ -587,6 +593,12 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):"The support for 3d box operations are not yet supported. You are welcome to file a PR in our repo.")+ elif isinstance(module, K.MixAugmentationBaseV2):+ # Dispatch to the mix child's own box handler (e.g. RandomMosaic).+ # Unsupported children raise NotImplementedError from+ # apply_transform_boxes, matching a direct call.+ _input = module.transform_boxes(_input, cls.get_instance_module_param(param), module.flags)+elif isinstance(module, K.ImageSequential) and not module.is_intensity_only():_input = module.transform_boxes(_input, params=cls.get_sequential_module_param(param), extra_args=extra_args@@ -685,6 +697,13 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):"You are welcome to file a PR in our repo.")+ elif isinstance(module, K.MixAugmentationBaseV2):+ # Dispatch to the mix child's own keypoint handler. Unsupported+ # children raise NotImplementedError from apply_transform_keypoint+ # (matching a direct call) instead of silently returning keypoints.+ out = module.transform_keypoint(_input.data, cls.get_instance_module_param(param), module.flags)+ _input = Keypoints(out, raise_if_not_floating_point=False)+elif isinstance(module, K.ImageSequential) and not module.is_intensity_only():_input = module.transform_keypoints(_input, params=cls.get_sequential_module_param(param), extra_args=extra_argsdiff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 5154e9eeb..7de55de11 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -734,31 +734,46 @@ class TestConventionAugmentationSequential(BaseTester):self.assert_close(out_masks[1], output[:1])assert not torch.equal(out_masks[1], output[1:])- def test_wart_mix_children_pass_annotations_through_4493(self, device, dtype):- # Wart pin (#4493): the container's mask, box and keypoint handlers have no branch for a mix child, so- # those keys come back unchanged next to a mixed image. Called directly, RandomMosaic transforms boxes- # and RandomMixUpV2 raises NotImplementedError on a mask; the container hides both. A class key still- # raises. Seed 0 on a 16x16 batch: every listed mix applies (a 6x8 fixture can draw an empty cut box).+ def test_mix_children_dispatch_annotation_keys_4493(self, device, dtype):+ # Regression (#4493): mix children used to fall through Mask/Box/KeypointSequentialOps to a silent+ # passthrough, so annotations desynchronized from the mixed image. The container now dispatches to+ # the child's own handlers: RandomMosaic transforms boxes (container xyxy_plus path), and unsupported+ # keys raise NotImplementedError as a direct call does. A class key still raises from the container.if dtype == torch.bfloat16:pytest.skip("Tracked in #4467: the mix forward path has no bfloat16 DType")+ from kornia.geometry.boxes import Boxes+image = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)boxes = torch.tensor([[[0.0, 0.0, 2.0, 2.0]], [[1.0, 1.0, 3.0, 3.0]]], device=device, dtype=dtype)mask = torch.arange(2, device=device, dtype=dtype).reshape(2, 1, 1, 1).expand(2, 1, 16, 16).clone()keypoints = torch.tensor([[[1.0, 1.0]], [[2.0, 2.0]]], device=device, dtype=dtype)++ # RandomMosaic boxes are transformed inside the container (no longer passthrough).+ seq = K.AugmentationSequential(K.RandomMosaic(p=1.0), data_keys=["input", "bbox_xyxy"])torch.manual_seed(0)- container = K.AugmentationSequential(- K.RandomMosaic(p=1.0), data_keys=["input", "bbox_xyxy", "mask", "keypoints"]+ out_image, out_boxes = seq(image, boxes)+ assert not torch.equal(out_image, image)+ assert not torch.equal(out_boxes, boxes)+ params = seq._params[0].data+ mosaic = K.RandomMosaic(p=1.0)+ expected = mosaic.transform_boxes(Boxes.from_tensor(boxes, mode="xyxy_plus"), params, mosaic.flags).to_tensor(+ mode="xyxy_plus")- out_image, out_boxes, out_mask, out_keypoints = container(image, boxes, mask, keypoints)- assert not torch.equal(out_image, image) # the image was mixed- self.assert_close(out_boxes, boxes, rtol=0, atol=0)- self.assert_close(out_mask, mask, rtol=0, atol=0)- self.assert_close(out_keypoints, keypoints, rtol=0, atol=0)- torch.manual_seed(0)- direct_boxes = K.RandomMosaic(p=1.0, data_keys=["input", "bbox_xyxy"])(image, boxes)[1]- assert not torch.equal(direct_boxes, boxes) # the same draw moves the boxes when called directly- with pytest.raises(NotImplementedError):- K.RandomMixUpV2(p=1.0)(image, mask, data_keys=["input", "mask"])+ self.assert_close(out_boxes, expected, rtol=0, atol=0)++ # Unsupported annotation keys raise, matching a direct call (no silent passthrough).+ for factory, key, payload in (+ (lambda: K.RandomMixUpV2(p=1.0), "mask", mask),+ (lambda: K.RandomMixUpV2(p=1.0), "bbox_xyxy", boxes),+ (lambda: K.RandomMixUpV2(p=1.0), "keypoints", keypoints),+ (lambda: K.RandomMosaic(p=1.0), "mask", mask),+ (lambda: K.RandomMosaic(p=1.0), "keypoints", keypoints),+ (lambda: K.RandomCutMixV2(p=1.0), "mask", mask),+ (lambda: K.RandomJigsaw(p=1.0), "mask", mask),+ ):+ with pytest.raises(NotImplementedError):+ K.AugmentationSequential(factory(), data_keys=["input", key])(image, payload)+with pytest.raises(NotImplementedError, match="class labels"):K.AugmentationSequential(K.RandomMixUpV2(p=1.0), data_keys=["input", "class"])(image, torch.tensor([0, 1], device=device)