π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix named image input conversion using forward signatures (#5448)
AhmetHakanBezirc7b3737e6073
diff --git a/changelog.d/5448.fixed.md b/changelog.d/5448.fixed.mdnew file mode 100644index 000000000..c9a475b4a--- /dev/null+++ b/changelog.d/5448.fixed.md@@ -0,0 +1 @@+Named input conversion now binds positional arguments to `forward` parameters in image modules and sequential containers, rather than to the internal PyTorch call wrapper. Selective conversion also handles bound decorated methods and variadic arguments.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 74511e9e4..273d8d336 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -731,7 +731,12 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):# run the forward pass in tensor mode and convert the output to ``output_type`` only after the image# has been cached, so ``.show()`` / ``.save()`` never receive a NumPy array or PIL imagestensor_output = self._call_converted(- super(ImageSequential, self).__call__, converted_inputs, kwargs, input_names_to_handle, "pt"+ super(ImageSequential, self).__call__,+ converted_inputs,+ kwargs,+ input_names_to_handle,+ "pt",+ signature_source=self.forward,)in_data_keys: Optional[List[DataKey]]diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 294de4c0a..ba82e5670 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -441,7 +441,9 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):self._check_output_type(output_type)# run the forward pass in tensor mode, cache that tensor for ``.show()`` / ``.save()``, and convert the# output to ``output_type`` only afterwards, so the helpers never receive a NumPy array or PIL images- tensor_output = self._call_converted(super().__call__, inputs, kwargs, input_names_to_handle, "pt")+ tensor_output = self._call_converted(+ super().__call__, inputs, kwargs, input_names_to_handle, "pt", signature_source=self.forward+ )self._store_output_image(self._convert_output(tensor_output, "pt"), "pt")_output_image = self._convert_output(tensor_output, output_type)else:diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pyindex 1bc7731a2..3876ec3cd 100644--- a/kornia/core/mixin/image_module.py+++ b/kornia/core/mixin/image_module.py@@ -16,6 +16,7 @@#import datetime+import inspectimport mathimport osimport sys@@ -103,7 +104,8 @@ class ImageModuleMixIn:"""Convert input and output types for a function.Args:- input_names_to_handle: List of input names to convert.+ input_names_to_handle: List of parameter names to convert. Module calls use the ``forward``+ signature; a variadic parameter name selects all its values.If None, convert every tensor, NumPy array and PIL image argument, and load a string as an imagepath only if it is the first positional argument.output_type: Desired output type ('pt', 'numpy', or 'pil').@@ -135,6 +137,8 @@ class ImageModuleMixIn:kwargs: dict[str, Any],input_names_to_handle: Optional[List[Any]],output_type: Literal["pt", "numpy", "pil"],+ *,+ signature_source: Optional[Callable[..., Any]] = None,) -> Union[Any, List[Any]]:if input_names_to_handle is None:args = tuple(@@ -146,13 +150,39 @@ class ImageModuleMixIn:for k, v in kwargs.items()}else:- args = list(args)- for i, (arg, name) in enumerate(zip(args, func.__code__.co_varnames)): # ty: ignore[unresolved-attribute]- if name in input_names_to_handle:- args[i] = self.to_tensor(arg) # type:ignore- for name, value in kwargs.items():- if name in input_names_to_handle:- kwargs[name] = self.to_tensor(value)+ signature = inspect.signature(func if signature_source is None else signature_source)+ try:+ bound = signature.bind(*args, **kwargs)+ except TypeError:+ # the arguments do not fit the signature: let the call raise its own error, which names the function+ return func(*args, **kwargs)+ for name, value in bound.arguments.items():+ kind = signature.parameters[name].kind+ if kind == inspect.Parameter.VAR_KEYWORD:+ bound.arguments[name] = {+ key: self.to_tensor(item)+ if name in input_names_to_handle or key in input_names_to_handle+ else item+ for key, item in value.items()+ }+ elif name in input_names_to_handle:+ if kind == inspect.Parameter.VAR_POSITIONAL:+ bound.arguments[name] = tuple(self.to_tensor(item) for item in value)+ else:+ bound.arguments[name] = self.to_tensor(value)+ # pass the converted values the way the caller did, positional or keyword, so hooks registered with+ # ``with_kwargs=True`` see the same split as without ``input_names_to_handle``+ var_keyword = next(+ (p.name for p in signature.parameters.values() if p.kind == inspect.Parameter.VAR_KEYWORD), None+ )+ named = (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)+ converted_kwargs: dict[str, Any] = {}+ for key in kwargs:+ if key in signature.parameters and signature.parameters[key].kind in named:+ converted_kwargs[key] = bound.arguments[key]+ else:+ converted_kwargs[key] = bound.arguments[var_keyword][key]+ args, kwargs = bound.args[: len(args)], converted_kwargsreturn func(*args, **kwargs)diff --git a/kornia/core/module.py b/kornia/core/module.pyindex d8ccc9cbe..a6fc8dede 100644--- a/kornia/core/module.py+++ b/kornia/core/module.py@@ -79,7 +79,8 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):Args:inputs: Inputs to operate on.- input_names_to_handle: List of input names to convert.+ input_names_to_handle: List of parameter names to convert. Module calls use the ``forward``+ signature; a variadic parameter name selects all its values.If None, convert every tensor, NumPy array and PIL image argument, and load a string as an imagepath only if it is the first positional argument.output_type: Desired output type ('pt', 'numpy', or 'pil').@@ -91,7 +92,9 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):"""# Convert inputs and outputs around the forward callif not self._disable_features:- tensor_output = self._call_converted(super().__call__, inputs, kwargs, input_names_to_handle, "pt")+ tensor_output = self._call_converted(+ super().__call__, inputs, kwargs, input_names_to_handle, "pt", signature_source=self.forward+ )self._store_output_image(self._convert_output(tensor_output, "pt"), "pt")_output_image = self._convert_output(tensor_output, output_type)@@ -154,7 +157,8 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):Args:inputs: Inputs to operate on.- input_names_to_handle: List of input names to convert.+ input_names_to_handle: List of parameter names to convert. Module calls use the ``forward``+ signature; a variadic parameter name selects all its values.If None, convert every tensor, NumPy array and PIL image argument, and load a string as an imagepath only if it is the first positional argument.output_type: Desired output type ('pt', 'numpy', or 'pil').@@ -166,7 +170,9 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):"""# Convert inputs and outputs around the forward callif not self._disable_features:- tensor_output = self._call_converted(super().__call__, inputs, kwargs, input_names_to_handle, "pt")+ tensor_output = self._call_converted(+ super().__call__, inputs, kwargs, input_names_to_handle, "pt", signature_source=self.forward+ )self._store_output_image(self._convert_output(tensor_output, "pt"), "pt")_output_image = self._convert_output(tensor_output, output_type)diff --git a/tests/core/test_module.py b/tests/core/test_module.pyindex d525bf290..ee9d01505 100644--- a/tests/core/test_module.py+++ b/tests/core/test_module.py@@ -24,6 +24,7 @@ import pytestimport torchfrom PIL import Image as PILImage+from kornia.augmentation import AugmentationSequential, RandomHorizontalFlipfrom kornia.augmentation import ImageSequential as AugmentationImageSequentialfrom kornia.core.module import ImageModule, ImageModuleMixIn, ImageSequentialfrom kornia.io import write_image@@ -685,3 +686,121 @@ class TestTupleOutputCache(BaseTester):working = expected.cpu().to(torch.promote_types(dtype, torch.float32))rendered = (working.clamp(0.0, 1.0) * 255).round().to(torch.uint8).permute(1, 2, 0).numpy()np.testing.assert_array_equal(np.asarray(output), rendered)+++class TestNamedInputConversion(BaseTester):+ @pytest.mark.parametrize("keyword", [False, True])+ def test_module_forward_names_5206(self, keyword):+ class Select(ImageModule):+ def forward(self, image, other, *, scale=1.0):+ assert isinstance(image, torch.Tensor)+ assert other is untouched+ return image * scale++ array = np.full((4, 6, 3), 255, dtype=np.uint8)+ untouched = array.copy()+ module = Select()+ calls = []+ module.register_forward_hook(lambda *args: calls.append(True))+ kwargs = {"other": untouched, "scale": 0.5, "input_names_to_handle": ["image"]}+ output = module(image=array, **kwargs) if keyword else module(array, **kwargs)+ self.assert_close(output, torch.full((3, 4, 6), 0.5))+ assert calls == [True]++ @pytest.mark.parametrize("kind", ["core", "augmentation"])+ def test_sequential_forward_name_5206(self, kind):+ factory = ImageSequential if kind == "core" else AugmentationImageSequential+ module = factory(torch.nn.Identity())+ array = np.full((4, 6, 3), 255, dtype=np.uint8)+ output = module(array, input_names_to_handle=["input"])+ assert isinstance(output, torch.Tensor)+ assert output.shape[-3:] == (3, 4, 6)+ self.assert_close(output, torch.ones_like(output))++ def test_bound_decorator_5206(self):+ class Methods:+ def select(self, image, other):+ assert other is untouched+ return image++ array = np.full((4, 6, 3), 255, dtype=np.uint8)+ untouched = array.copy()+ decorated = ImageModuleMixIn().convert_input_output(["image"])(Methods().select)+ output = decorated(array, untouched)+ assert isinstance(output, torch.Tensor)+ self.assert_close(output, torch.ones(3, 4, 6))++ def test_variadic_decorator_5206(self):+ module = ImageModuleMixIn()++ @module.convert_input_output(["images", "options"])+ def select(*images, **options):+ assert all(isinstance(x, torch.Tensor) for x in images)+ assert isinstance(options["image"], torch.Tensor)+ return images[0]++ array = np.full((4, 6, 3), 255, dtype=np.uint8)+ self.assert_close(select(array, array, image=array), torch.ones(3, 4, 6))++ def test_keyword_name_in_variadic_options_5206(self):+ @ImageModuleMixIn().convert_input_output(["image"])+ def select(**options):+ assert options["other"] is untouched+ return options["image"]++ array = np.full((4, 6, 3), 255, dtype=np.uint8)+ untouched = array.copy()+ self.assert_close(select(image=array, other=untouched), torch.ones(3, 4, 6))++ def test_positional_only_and_keyword_only_5206(self):+ @ImageModuleMixIn().convert_input_output(["image", "mask"])+ def select(image, /, *, mask):+ return image + mask++ array = np.full((4, 6, 3), 255, dtype=np.uint8)+ self.assert_close(select(array, mask=array), torch.full((3, 4, 6), 2.0))++ def test_augmentation_variadic_forward_5206(self):+ module = AugmentationSequential(RandomHorizontalFlip(p=1.0), data_keys=["input"])+ array = np.arange(4 * 6 * 3, dtype=np.uint8).reshape(4, 6, 3)+ expected = torch.from_numpy(array).permute(2, 0, 1).float().div(255).flip(-1)+ output = module(array, input_names_to_handle=["args"])+ self.assert_close(output[0], expected)++ @pytest.mark.parametrize("keyword", [False, True])+ def test_hooks_see_the_callers_argument_split_5206(self, keyword):+ class Select(ImageModule):+ def forward(self, image, other=None, **options):+ return image++ array = np.full((4, 6, 3), 255, dtype=np.uint8)+ module = Select()+ seen = []+ module.register_forward_pre_hook(+ lambda _, args, kwargs: seen.append((len(args), sorted(kwargs), type(kwargs.get("image")))),+ with_kwargs=True,+ )+ if keyword:+ module(image=array, other=1, extra=array, input_names_to_handle=["image", "extra"])+ assert seen == [(0, ["extra", "image", "other"], torch.Tensor)]+ else:+ module(array, other=1, extra=array, input_names_to_handle=["image", "extra"])+ assert seen == [(1, ["extra", "other"], type(None))]++ def test_arguments_that_do_not_bind_raise_the_calls_own_error_5206(self):+ class Select(ImageModule):+ def forward(self, image):+ return image++ array = np.full((4, 6, 3), 255, dtype=np.uint8)+ with pytest.raises(TypeError, match="forward"):+ Select()(array, array, input_names_to_handle=["image"])++ def test_keyword_named_like_a_positional_only_parameter_5206(self):+ @ImageModuleMixIn().convert_input_output(["image"])+ def select(image, /, **options):+ return image, options["image"]++ image, option = select(np.full((4, 6, 3), 255, dtype=np.uint8), image=np.zeros((4, 6, 3), dtype=np.uint8))+ self.assert_close(image, torch.ones(3, 4, 6))+ self.assert_close(option, torch.zeros(3, 4, 6))