π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): use tuples in container isinstance checks for torch 2.5.1 compile (#5361)
Abhilash Reddy2f99a9b37401
diff --git a/changelog.d/5361.fixed.md b/changelog.d/5361.fixed.mdnew file mode 100644index 000000000..96d7a4594--- /dev/null+++ b/changelog.d/5361.fixed.md@@ -0,0 +1 @@+`ImageSequential` and `AugmentationSequential` with image and mask data keys compile with `torch.compile(..., fullgraph=True)` on torch 2.5.1: their `isinstance` checks use tuples of classes instead of `X | Y` unions, which that version of Dynamo cannot trace.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 273d8d336..6d1601592 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -467,7 +467,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):outputs = self.transform_op.inverse( # type: ignore*outputs, module=module, param=param, extra_args=self.extra_args)- if not isinstance(outputs, list | tuple):+ if not isinstance(outputs, (list, tuple)):# Make sure we are unpacking a list whilst post-procoutputs = [outputs]@@ -563,7 +563,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS:_out_k = self._postproc_keypoint(in_arg, cast(Keypoints, out_arg), dcate)- if is_autocast_enabled() and isinstance(in_arg, torch.Tensor | Keypoints):+ if is_autocast_enabled() and isinstance(in_arg, (torch.Tensor, Keypoints)):if isinstance(_out_k, list):_out_k = [i.type(in_arg.dtype) for i in _out_k]else:@@ -572,7 +572,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):elif DataKey.get(dcate) in _BOXES_OPTIONS:_out_b = self._postproc_boxes(in_arg, cast(Boxes, out_arg), dcate)- if is_autocast_enabled() and isinstance(in_arg, torch.Tensor | Boxes):+ if is_autocast_enabled() and isinstance(in_arg, (torch.Tensor, Boxes)):if isinstance(_out_b, list):_out_b = [i.type(in_arg.dtype) for i in _out_b]else:@@ -655,7 +655,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):for param in params:module = self.get_submodule(param.name)outputs = self.transform_op.transform(*outputs, module=module, param=param, extra_args=self.extra_args)- if not isinstance(outputs, list | tuple):+ if not isinstance(outputs, (list, tuple)):# Make sure we are unpacking a list whilst post-procoutputs = [outputs]self._update_transform_matrix_by_module(module)@@ -785,7 +785,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):idx = data_keys.index(DataKey.INPUT)if isinstance(output, dict):return output[original_keys[idx]]- if len(data_keys) > 1 and isinstance(output, list | tuple):+ if len(data_keys) > 1 and isinstance(output, (list, tuple)):return output[idx]return outputdiff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex ba82e5670..f7213137a 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -292,7 +292,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):params: List[ParamItem] = []mod_param: Union[Dict[str, torch.Tensor], List[ParamItem]]for name, module in named_modules:- if isinstance(module, (_AugmentationBase | K.MixAugmentationBaseV2 | ImageSequentialBase)):+ if isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2, ImageSequentialBase)):mod_param = module.forward_parameters(batch_shape)param = ParamItem(name, mod_param)else:diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pyindex 3876ec3cd..9b9148425 100644--- a/kornia/core/mixin/image_module.py+++ b/kornia/core/mixin/image_module.py@@ -347,7 +347,7 @@ class ImageModuleMixIn:) -> Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]:if isinstance(output_image, torch.Tensor):return output_image.detach()- if isinstance(output_image, list | tuple):+ if isinstance(output_image, (list, tuple)):return type(output_image)([self._detach_tensor(out) for out in output_image]) # type: ignoreraise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`")diff --git a/tests/augmentation/test_augmentation_compile.py b/tests/augmentation/test_augmentation_compile.pyindex 6b279dce3..ffc19c102 100644--- a/tests/augmentation/test_augmentation_compile.py+++ b/tests/augmentation/test_augmentation_compile.py@@ -26,7 +26,7 @@ from torch._dynamo.testing import CompileCounter, CompileCounterWithBackendimport kornia.augmentation as K-from testing.base import BaseTester+from testing.base import BaseTester, dynamo_is_availableclass TestAugmentationCompile(BaseTester):@@ -416,3 +416,36 @@ class TestRandomCropCompile(BaseTester):[[[0, 0], [size - 1, 0], [size - 1, size - 1], [0, size - 1]]], device=device, dtype=dtype)self.assert_close(torch_optimizer(aug, fullgraph=True)(input, params=params), input, atol=0, rtol=0)+++class TestContainerCompile(BaseTester):+ # Named without "compile" or "dynamo" so the ordinary jobs collect it: the CompileCounter backend needs no+ # optimizer, and those jobs are the only ones that run torch 2.5.1 with Dynamo (Python 3.11 and 3.12).+ @pytest.mark.skipif(not dynamo_is_available(), reason="no Dynamo on this torch/python pair")+ @pytest.mark.parametrize("disable_features", [True, False])+ @pytest.mark.parametrize(+ "container,data_keys",+ [+ (K.ImageSequential, None),+ (K.AugmentationSequential, ["input"]),+ (K.AugmentationSequential, ["input", "mask"]),+ ],+ )+ def test_eager_backend_traces_container_in_one_graph(self, device, dtype, container, data_keys, disable_features):+ # Dynamo on torch 2.5.1 cannot trace isinstance() against a PEP 604 union (#5223).+ torch._dynamo.reset()+ kwargs = {} if data_keys is None else {"data_keys": data_keys}+ aug = container(K.RandomHorizontalFlip(p=1.0), **kwargs)+ aug.disable_features = disable_features+ input = torch.rand(1, 3, 4, 6, device=device, dtype=dtype)+ args = (input,) * len(data_keys or ["input"])+ counter = CompileCounter()+ fn = torch.compile(aug, backend=counter, fullgraph=True)+ actual, expected = fn(*args), aug(*args)+ if len(args) == 1:+ actual, expected = [actual], [expected]+ assert len(actual) == len(args)+ for out, ref in zip(actual, expected, strict=True):+ self.assert_close(out, ref)+ self.assert_close(out, input.flip(-1))+ assert counter.frame_count == 1