π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core): keep the forward output container and pass non-tensors through (#5695)
niukanen13e4d3f5c70de
diff --git a/changelog.d/5695.breaking.md b/changelog.d/5695.breaking.mdnew file mode 100644index 000000000..d1b6da871--- /dev/null+++ b/changelog.d/5695.breaking.md@@ -0,0 +1,6 @@+A tuple `forward` output of `ImageModule`, `ImageSequential` and the augmentation containers used+to come back as a list, and a one-element tuple as its bare element. It now keeps the tuple type+and its length. A caller that used the bare element of a one-element tuple output must index it:+`out = module(x)[0]`. A caller that relied on the list type of a multi-element tuple output+(`isinstance(out, list)`, `out.append`) must convert with `list(out)`; one that indexed it+(`out[0]`) needs no change.diff --git a/changelog.d/5695.fixed.md b/changelog.d/5695.fixed.mdnew file mode 100644index 000000000..343a7bb90--- /dev/null+++ b/changelog.d/5695.fixed.md@@ -0,0 +1,16 @@+`ImageModule`, `ImageSequential` and the augmentation containers keep the container type of a+multi-output `forward`: a tuple stays a tuple and a one-element tuple stays a one-element tuple+with the helper features enabled, the same as with `disable_features = True`. A `forward` that+returns a dict, `None` or a Python scalar passes that output through, with the tensors of a dict+cached detached, instead of raising `RuntimeError: Unexpected object ...` after the work has+already run, and a list output converts its elements for `output_type="numpy"` / `"pil"` like a+tuple does instead of raising `TypeError: Input type not supported`.++`AugmentationSequential` with `output_type="numpy"` or `"pil"` used to raise+`TypeError: Input type not supported` for more than one data key or a dict input. It now converts+the images and masks, positional or in a dict, and leaves a dict value under an unrecognized key+as it is. A mask converts like the image: a `(B, 1, H, W)` mask becomes a `(B, H, W, 1)` array,+the layout a NumPy mask input is read in, or one PIL image per sample; a `(B, H, W)` mask returned+under `keepdim=True` gets its channel axis back first, and a per-sample list of masks converts+element by element. Boxes, keypoints and labels are not images: with any of them in the data keys+such a call raises `ValueError` before `forward` runs.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 3355dfc14..d81017c70 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -30,6 +30,7 @@ from kornia.constants import DataKey, Resamplefrom kornia.core._compat import torch_version_ltfrom kornia.core.external import PILImage as Imagefrom kornia.core.external import numpy as np+from kornia.core.mixin.image_module import _rebuild_containerfrom kornia.core.ops import eye_likefrom kornia.core.utils import _normalize_to_float32_or_float64, is_autocast_enabled, is_exportingfrom kornia.geometry.boxes import Boxes, VideoBoxes@@ -806,6 +807,14 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):# TODO: Some more behaviour for AugmentationSequential needs to be revisited later# e.g. We convert only images, etc.self._check_output_type(output_type)+ non_images = [key.name for key in data_keys if key not in _IMG_OPTIONS and key not in _MSK_OPTIONS]+ if output_type != "pt" and non_images:+ # a box or keypoint tensor converted like an image (moved to channels-last, or made a PIL image) is+ # not a box any more, so only images and masks take the conversion+ raise ValueError(+ f"output_type={output_type!r} converts images and masks only, and data_keys also hold "+ f"{non_images}. Call with output_type='pt'."+ )# 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(@@ -827,14 +836,72 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):# cache a detached view of the augmented image for ``.show()`` / ``.save()``, which move it to the# CPU themselves, so the forward pass pays no device-to-host copy or sync+ image = self._select_output_image(tensor_output, data_keys, original_keys)if not is_exporting():- image = self._select_output_image(tensor_output, data_keys, original_keys)self._output_image = image.detach() if isinstance(image, torch.Tensor) else image- _output_image = self._convert_output(tensor_output, output_type)+ _output_image = (+ self._convert_dict_output(tensor_output, output_type, image)+ if isinstance(tensor_output, dict)+ else self._convert_positional_output(tensor_output, output_type, data_keys, image)+ )else:_output_image = super(ImageSequential, self).__call__(*inputs, **kwargs)return _output_image+ def _convert_positional_output(+ self, tensor_output: Any, output_type: str, data_keys: List[DataKey], image: Any+ ) -> Any:+ """Convert a positional forward output for ``output_type``, one value per data key.++ The outputs align with ``data_keys`` positionally; see :meth:`_convert_output_for_data_key`.+ """+ if isinstance(tensor_output, (list, tuple)) and len(tensor_output) == len(data_keys):+ converted = [+ self._convert_output_for_data_key(output, output_type, data_key, image)+ for output, data_key in zip(tensor_output, data_keys)+ ]+ return _rebuild_container(tensor_output, converted)+ return self._convert_output(tensor_output, output_type)++ def _convert_dict_output(self, tensor_output: Dict[str, Any], output_type: str, image: Any) -> Dict[str, Any]:+ """Convert a dict forward output for ``output_type``, keyed by its data keys.++ Only the values under recognized image or mask keys take the conversion: an unrecognized key holds a+ pass-through value the caller supplied, and moving it to channels-last (or making it a PIL image) is+ not what they passed in. See :meth:`_convert_output_for_data_key`.+ """+ valid_data_keys, invalid_keys = self._read_datakeys_from_dict(tuple(tensor_output.keys()))+ key_data_keys = dict(zip([k for k in tensor_output if k not in (invalid_keys or [])], valid_data_keys))+ return {+ key: self._convert_output_for_data_key(value, output_type, key_data_keys.get(key), image)+ for key, value in tensor_output.items()+ }++ def _convert_output_for_data_key(+ self, value: Any, output_type: str, data_key: Optional[DataKey], image: Any+ ) -> Any:+ """Convert one output value for ``output_type``.++ A mask converts like the image, to the NumPy layout the mask input reads back (:meth:`to_numpy`), or to+ one PIL image per sample. A 3D mask next to a batched image is read the way the input reads it: as+ ``(B, H, W)`` when its leading size is the image batch (a mask returned under ``keepdim=True``), so it gets+ its channel axis back and stays batch-first; any other 3D mask is one ``(C, H, W)`` mask.+ """+ if data_key is None:+ # An unrecognized key holds a pass-through value: there is no data key to convert it by.+ return value+ if (+ data_key in _MSK_OPTIONS+ and output_type != "pt"+ and isinstance(value, torch.Tensor)+ and value.dim() == 3+ and isinstance(image, torch.Tensor)+ and image.dim() == 4+ and value.shape[0] == image.shape[0]+ ):+ value = value.unsqueeze(1)+ return self._convert_output(value, output_type)+def _convert_non_image(self, arg: Any, data_key: DataKey) -> Any:if data_key in _IMG_OPTIONS:return argdiff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pyindex f17dea880..06a5bdd4d 100644--- a/kornia/core/mixin/image_module.py+++ b/kornia/core/mixin/image_module.py@@ -62,6 +62,18 @@ def _array_to_float_image(array: Any) -> torch.Tensor:_PIL_ONE_CHANNEL_DTYPES = (torch.bool, torch.int8, torch.int16, torch.uint16, torch.int32, torch.uint32)+def _rebuild_container(source: Any, items: List[Any]) -> Any:+ """Rebuild a tuple or list output from converted elements.++ A namedtuple takes its elements as separate arguments, so a plain ``type(source)(items)``+ call would raise a ``TypeError`` for want of one argument per field: it is rebuilt with its+ field-aware ``_make``. A plain tuple or list takes an iterable.+ """+ if hasattr(type(source), "_make"):+ return type(source)._make(items) # type: ignore[attr-defined]+ return type(source)(items)++def _to_uint8_image(image: torch.Tensor) -> torch.Tensor:"""Convert a floating image in ``[0, 1]`` to ``uint8`` for display or an 8-bit file.@@ -198,29 +210,37 @@ class ImageModuleMixIn:def _convert_output(self, tensor_outputs: Any, output_type: str) -> Any:"""Convert a forward output to ``output_type`` the way :meth:`convert_input_output` does.+ A tuple or a list is converted element by element and keeps its container type, so a+ one-element tuple stays a tuple. An output that is not a tensor, a tuple or a list (a dict,+ ``None``, a Python scalar) is returned as is: the mixin's contract covers a single image+ tensor, so there is nothing to convert (#5210).+Args:- tensor_outputs: The forward output: a tensor, or a tuple whose elements are converted one by one.+ tensor_outputs: The forward output: a tensor, or a tuple or list whose elements are+ converted one by one.output_type: Desired output type ('pt', 'numpy', or 'pil').Returns:- The converted output, or a list of converted outputs for a tuple of several.+ The converted output, or a container of converted outputs of the same type."""- if not isinstance(tensor_outputs, tuple):- tensor_outputs = (tensor_outputs,)-- outputs = []- for output in tensor_outputs:- if output_type == "pt":- outputs.append(output)- elif output_type == "numpy":- outputs.append(self.to_numpy(output))- elif output_type == "pil":- outputs.append(self.to_pil(output))- else:- raise ValueError("Output type not supported. Choose from 'pt', 'numpy', or 'pil'.")-- return outputs if len(outputs) > 1 else outputs[0]+ if not isinstance(tensor_outputs, (list, tuple)):+ return self._convert_single_output(tensor_outputs, output_type)++ converted = [self._convert_single_output(output, output_type) for output in tensor_outputs]+ return _rebuild_container(tensor_outputs, converted)++ def _convert_single_output(self, output: Any, output_type: str) -> Any:+ """Convert one forward output, passing containers and non-tensors through unchanged."""+ if not isinstance(output, torch.Tensor):+ return output+ if output_type == "pt":+ return output+ if output_type == "numpy":+ return self.to_numpy(output)+ if output_type == "pil":+ return self.to_pil(output)+ raise ValueError("Output type not supported. Choose from 'pt', 'numpy', or 'pil'.")def _is_valid_arg(self, arg: Any) -> bool:"""Check if the argument is a valid type for conversion.@@ -311,9 +331,9 @@ class ImageModuleMixIn::math:`(B, H, W, C)` array with the same values, the layout :meth:`to_tensor` accepts, so a floating arrayconverts back to the same tensor. A tensor of any other rank keeps its shape. Every 3-D or 4-D tensor is takento be an image, so a non-image element of a tuple output, such as a :math:`(B, N, 4)` box tensor, is moved to- channels-last too; modules with several outputs are tracked in- `#5210 <https://github.com/kornia/kornia/issues/5210>`_. A ``bfloat16`` tensor becomes a ``float32`` array,- since NumPy has no ``bfloat16``.+ channels-last too. :class:`~kornia.augmentation.container.AugmentationSequential` knows its outputs: it+ converts its images and masks only, and rejects ``output_type="numpy"`` / ``"pil"`` when its data keys hold+ boxes, keypoints or labels. A ``bfloat16`` tensor becomes a ``float32`` array, since NumPy has no ``bfloat16``.Args:x: The input to convert.@@ -378,13 +398,16 @@ class ImageModuleMixIn:return Image.fromarray(image.permute(1, 2, 0).numpy()) # type: ignoredef _detach_tensor(- self, output_image: Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]- ) -> Union[torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor]]:+ self, output_image: Union[torch.Tensor, List[Any], Tuple[Any, ...]]+ ) -> Union[torch.Tensor, List[Any], Tuple[Any, ...]]:if isinstance(output_image, torch.Tensor):return output_image.detach()if isinstance(output_image, (list, tuple)):- return type(output_image)([self._detach_tensor(out) for out in output_image]) # type: ignore- raise RuntimeError(f"Unexpected object {output_image} with a type of `{type(output_image)}`")+ return _rebuild_container(output_image, [self._detach_tensor(out) for out in output_image])+ if isinstance(output_image, dict):+ return {key: self._detach_tensor(value) for key, value in output_image.items()}+ # ``None`` or a Python scalar: nothing to detach+ return output_imagedef _store_output_image(self, output_image: Any, output_type: str) -> None:"""Cache detached outputs on their device; ``.show()`` / ``.save()`` move them to CPU on use.@@ -397,7 +420,11 @@ class ImageModuleMixIn:self._output_image = self._detach_tensor(output_image) if output_type == "pt" else output_imagedef _get_output_image(self) -> torch.Tensor:- output_image = getattr(self, "_output_image", None)+ output_image: Any = getattr(self, "_output_image", None)+ if isinstance(output_image, tuple) and len(output_image) == 1 and isinstance(output_image[0], torch.Tensor):+ # a one-element tuple output keeps its container (#5210): ``show()`` / ``save()`` render+ # its sole tensor, the same image the call returned before the container was preserved+ output_image = output_image[0]if output_image is None:raise ValueError("No pre-computed images found. Needs to execute first.")if not isinstance(output_image, torch.Tensor) or output_image.ndim not in (3, 4):diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 01f49bc7e..a275b88a2 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -280,6 +280,88 @@ class TestAugmentationSequential:assert out["mask"].shape == (2, 8, 8)+ def test_dict_output_leaves_unrecognized_keys_alone_5695(self, device, dtype):+ # A dictionary key that is not a data key holds a pass-through value: converting it like an+ # image would move a (B, C, H, W) tensor to channels-last, which is not what the caller passed in.+ image = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)+ aux = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.0), data_keys=None)++ out = aug({"image": image, "aux": aux}, output_type="numpy")++ assert out["aux"].shape == (1, 3, 8, 8)++ def test_dict_output_keeps_a_three_dimensional_mask_batch_first_5695(self, device, dtype):+ # A (B, H, W) mask returned under keepdim=True is batch-first, like the image: it gets its channel axis+ # back instead of being read as (C, H, W) and permuted to (H, W, B).+ image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ mask = torch.rand(2, 8, 8, device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.0), data_keys=None, keepdim=True)++ out = aug({"image": image, "mask": mask}, output_type="numpy")++ assert out["mask"].shape == (2, 8, 8, 1)+ numpy_dtype = torch.float32 if dtype == torch.bfloat16 else dtype+ np.testing.assert_array_equal(out["mask"][..., 0], mask.cpu().to(numpy_dtype).numpy())++ def test_positional_output_converts_each_tensor_of_a_mask_list_5695(self, device, dtype):+ # A mask given as a per-sample list of tensors comes back as a list of arrays for+ # output_type != "pt", each converted like the image.+ image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ masks = [+ torch.rand(1, 1, 8, 8, device=device, dtype=dtype),+ torch.rand(1, 1, 8, 8, device=device, dtype=dtype),+ ]+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.0), data_keys=["input", "mask"])++ _, out_masks = aug(image, masks, output_type="numpy")++ assert [type(m) for m in out_masks] == [np.ndarray, np.ndarray]+ assert out_masks[0].shape == (1, 8, 8, 1)+ assert out_masks[1].shape == (1, 8, 8, 1)++ @pytest.mark.parametrize("batch", [1, 2, 3])+ def test_mask_output_converts_per_sample_like_the_image_5695(self, batch, device, dtype):+ # Every sample's mask is its own PIL image, as every sample's image is, and the NumPy mask has the layout+ # the mask input reads, so feeding it back in gives the same mask.+ image = torch.rand(batch, 3, 6, 8, device=device, dtype=dtype)+ mask = (torch.rand(batch, 1, 6, 8, device=device, dtype=dtype) > 0.5).to(dtype)+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])++ pil_image, pil_mask = aug(image, mask, output_type="pil")++ assert len(pil_image) == len(pil_mask) == batch+ for sample, flipped in zip(pil_mask, mask.flip(-1)):+ assert sample.mode == "L"+ np.testing.assert_array_equal(np.asarray(sample), (flipped[0] * 255).to(torch.uint8).cpu().numpy())++ _, np_mask = aug(image, mask, output_type="numpy")++ assert np_mask.shape == (batch, 6, 8, 1)+ _, fed_back = aug(image.cpu(), np_mask)+ assert_close(fed_back.to(device=device, dtype=dtype), mask)++ @pytest.mark.parametrize(+ "image_shape, mask_shape, expected",+ [+ ((2, 3, 6, 8), (2, 6, 8), (2, 6, 8, 1)), # (B, H, W): the leading size is the image batch+ ((1, 3, 6, 8), (2, 6, 8), (6, 8, 2)), # one (C, H, W) mask next to a batch of one+ ((3, 6, 8), (3, 6, 8), (6, 8, 3)), # one (C, H, W) mask next to an unbatched image+ ],+ )+ def test_keepdim_three_dimensional_mask_reads_like_the_input_5695(+ self, image_shape, mask_shape, expected, device, dtype+ ):+ # A 3D mask is (B, H, W) when its leading size is the batch of a batched image, as on the way in;+ # otherwise it is one (C, H, W) mask and converts like an unbatched image.+ image = torch.rand(*image_shape, device=device, dtype=dtype)+ mask = torch.rand(*mask_shape, device=device, dtype=dtype)+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.0), data_keys=["input", "mask"], keepdim=True)++ _, out = aug(image, mask, output_type="numpy")++ assert out.shape == expected+def test_single_mask_with_an_unbatched_image_stays_single(self):aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])diff --git a/tests/core/test_module.py b/tests/core/test_module.pyindex 84de9e1d0..83b2467c1 100644--- a/tests/core/test_module.py+++ b/tests/core/test_module.py@@ -18,6 +18,7 @@import ioimport osimport sys+from typing import NamedTuplefrom unittest.mock import MagicMockimport numpy as np@@ -109,15 +110,17 @@ class TestImageModuleMixIn:assert decorated.__doc__ == dummy_func.__doc__assert decorated.__wrapped__ is dummy_func- def test_convert_input_output_caches_single_output_tuple_as_tensor(self, img_module, sample_tensor):- # A one-element tuple is returned as its element; the cache must hold the same tensor for ``show()``.+ def test_convert_input_output_caches_single_output_tuple_as_tuple(self, img_module, sample_tensor):+ # A one-element tuple keeps its type on the way out; the cache holds the detached tensor for ``show()``+ # (#5210: with features on, a module returns the same container type as with features off)decorated = img_module.convert_input_output(cache_output=True)(lambda tensor: (tensor,))output = decorated(sample_tensor)- assert isinstance(output, torch.Tensor)- assert isinstance(img_module._output_image, torch.Tensor)- assert torch.equal(img_module._output_image, sample_tensor)+ assert isinstance(output, tuple)+ assert len(output) == 1+ assert isinstance(img_module._output_image, tuple)+ assert torch.equal(img_module._output_image[0], sample_tensor)def test_show(self, img_module, sample_tensor):img_module._output_image = sample_tensor@@ -756,11 +759,9 @@ class TestTupleOutputCache(BaseTester):image = torch.rand(3, 6, 8, device=device, dtype=dtype, requires_grad=True)result = module(image, output_type=output_type)cached = module._output_image- if count == 1:- result, cached = [result], [cached]- else:- assert isinstance(result, list)- assert isinstance(cached, list)+ # a tuple stays a tuple, whatever its length (#5210)+ assert isinstance(result, tuple)+ assert isinstance(cached, tuple)assert len(result) == len(cached) == countexpected = image.sigmoid().detach()for output, tensor in zip(result, cached):@@ -781,6 +782,149 @@ class TestTupleOutputCache(BaseTester):np.testing.assert_array_equal(np.asarray(output), rendered)+class TestNonTensorOutputPassthrough(BaseTester):+ """#5210: outputs outside the one-tensor contract pass through, and the container type is kept."""++ @pytest.mark.parametrize("container", [ImageModule, ImageSequential])+ @pytest.mark.parametrize("output_type", ["pt", "numpy", "pil"])+ def test_non_tensor_outputs_pass_through_with_features_on(self, container, output_type, device, dtype):+ class PassthroughModule(container):+ def forward(self, x):+ return {"image": x, "count": float(x.mean())}++ module = PassthroughModule()+ image = torch.rand(3, 6, 8, device=device, dtype=dtype)+ result = module(image, output_type=output_type)++ # a dict is outside the one-tensor contract: ImageModule / ImageSequential pass it through+ # untouched, whatever the output_type+ assert isinstance(result, dict)+ assert set(result) == {"image", "count"}+ assert isinstance(result["count"], float)+ self.assert_close(result["image"], image)++ @pytest.mark.parametrize("container", [ImageModule, ImageSequential])+ @pytest.mark.parametrize("forward_output", [None, 0.5, {"image": 1}])+ def test_non_container_outputs_match_features_disabled(self, container, forward_output, device, dtype):+ class FixedModule(container):+ def forward(self, x):+ return forward_output++ image = torch.rand(3, 6, 8, device=device, dtype=dtype)+ enabled, disabled = FixedModule(), FixedModule()+ disabled.disable_features = True++ assert enabled(image) == disabled(image)++ @pytest.mark.parametrize("container", [ImageModule, ImageSequential])+ def test_features_flag_does_not_change_container_type(self, container, device, dtype):+ class TupleModule(container):+ def forward(self, x):+ return (x, x[:1])++ image = torch.rand(3, 6, 8, device=device, dtype=dtype)+ enabled, disabled = TupleModule(), TupleModule()+ disabled.disable_features = True++ assert type(enabled(image)) is type(disabled(image))+ assert isinstance(enabled(image), tuple)+ assert len(enabled(image)) == 2++ class OneTupleModule(container):+ def forward(self, x):+ return (x,)++ one_enabled, one_disabled = OneTupleModule(), OneTupleModule()+ one_disabled.disable_features = True++ assert isinstance(one_enabled(image), tuple)+ assert len(one_enabled(image)) == 1++ @pytest.mark.parametrize("container", [ImageModule, ImageSequential])+ def test_list_output_converts_elements_for_numpy(self, container, device, dtype):+ class ListModule(container):+ def forward(self, x):+ return [x, x[:1]]++ module = ListModule()+ image = torch.rand(3, 6, 8, device=device, dtype=dtype)++ result = module(image, output_type="numpy")++ assert isinstance(result, list)+ assert len(result) == 2+ numpy_dtype = torch.float32 if dtype == torch.bfloat16 else dtype+ np.testing.assert_array_equal(result[0], image.cpu().to(numpy_dtype).permute(1, 2, 0).numpy())+ np.testing.assert_array_equal(result[1], image[:1].cpu().to(numpy_dtype).permute(1, 2, 0).numpy())++ @pytest.mark.parametrize("container", [ImageModule, ImageSequential])+ def test_mixed_tuple_output_converts_tensors_only(self, container, device, dtype):+ class MixedModule(container):+ def forward(self, x):+ return (x, "label")++ module = MixedModule()+ image = torch.rand(3, 6, 8, device=device, dtype=dtype)++ result = module(image, output_type="numpy")++ assert isinstance(result, tuple)+ numpy_dtype = torch.float32 if dtype == torch.bfloat16 else dtype+ np.testing.assert_array_equal(result[0], image.cpu().to(numpy_dtype).permute(1, 2, 0).numpy())+ assert result[1] == "label"+++class TestNamedtupleAndSingletonTupleOutput(BaseTester):+ """A namedtuple output keeps its fields, and a one-element tuple stays renderable (#5210)."""++ @pytest.mark.parametrize("container", [ImageModule, ImageSequential])+ @pytest.mark.parametrize("output_type", ["pt", "numpy"])+ def test_namedtuple_output_keeps_its_fields(self, container, output_type, device, dtype):+ class Pair(NamedTuple):+ image: torch.Tensor+ mask: torch.Tensor++ class NamedModule(container):+ def forward(self, x):+ return Pair(x, x[:1])++ module = NamedModule()+ image = torch.rand(3, 6, 8, device=device, dtype=dtype)++ result = module(image, output_type=output_type)++ assert isinstance(result, Pair)+ if output_type == "pt":+ self.assert_close(result.image, image)+ self.assert_close(result.mask, image[:1])+ else:+ numpy_dtype = torch.float32 if dtype == torch.bfloat16 else dtype+ np.testing.assert_array_equal(result.image, image.cpu().to(numpy_dtype).permute(1, 2, 0).numpy())+ np.testing.assert_array_equal(result.mask, image[:1].cpu().to(numpy_dtype).permute(1, 2, 0).numpy())+ cached = module._output_image+ assert isinstance(cached, Pair)+ assert isinstance(cached.image, torch.Tensor)+ assert not cached.image.requires_grad++ @pytest.mark.parametrize("container", [ImageModule, ImageSequential])+ def test_one_element_tuple_stays_renderable(self, container, device, dtype, tmp_path):+ class OneTupleModule(container):+ def forward(self, x):+ return (x,)++ module = OneTupleModule()+ image = torch.rand(3, 6, 8, device=device, dtype=dtype)+ result = module(image)+ assert isinstance(result, tuple)++ saved = str(tmp_path / "one.png")+ module.save(saved)+ loaded = PILImage.open(saved)+ working = image.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(loaded), rendered)++class TestNamedInputConversion(BaseTester):@pytest.mark.parametrize("keyword", [False, True])def test_module_forward_names_5206(self, keyword):@@ -897,3 +1041,57 @@ class TestNamedInputConversion(BaseTester):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))+++def _cached_tensors(cache):+ if isinstance(cache, torch.Tensor):+ return [cache]+ if isinstance(cache, (list, tuple)):+ return [t for item in cache for t in _cached_tensors(item)]+ if isinstance(cache, dict):+ return [t for item in cache.values() for t in _cached_tensors(item)]+ return []+++class TestKeyedAndNestedOutputs(BaseTester):+ @pytest.mark.parametrize(+ "make",+ [+ lambda x: ((x * 2, x * 3), x * 4),+ lambda x: [[x * 2], x * 3],+ lambda x: {"image": x * 2},+ lambda x: ({"a": x * 2}, x),+ ],+ )+ def test_cache_holds_no_autograd_graph(self, make, device, dtype):+ # the cache keeps a detached copy of every tensor, also inside a nested container or a dict+ class Make(ImageModule):+ def forward(self, x):+ return make(x)++ module = Make()+ module(torch.rand(3, 6, 8, device=device, dtype=dtype, requires_grad=True))+ cached = _cached_tensors(module._output_image)+ assert cached+ assert all(t.grad_fn is None and not t.requires_grad for t in cached)++ @pytest.mark.parametrize("output_type", ["numpy", "pil"])+ @pytest.mark.parametrize("key", ["bbox_xyxy", "keypoints"])+ def test_augmentation_sequential_rejects_converting_non_images(self, key, output_type, device, dtype):+ # a box or keypoint tensor converted like an image is not a box any more+ image = torch.rand(2, 3, 16, 20, device=device, dtype=dtype)+ other = torch.tensor([[[1.0, 2.0, 8.0, 9.0]], [[3.0, 3.0, 10.0, 12.0]]], device=device, dtype=dtype)+ other = other if key == "bbox_xyxy" else other[..., :2]+ aug = AugmentationSequential(RandomHorizontalFlip(p=1.0), data_keys=["input", key])+ with pytest.raises(ValueError, match="images and masks only"):+ aug(image, other, output_type=output_type)+ assert isinstance(aug(image, other)[1], torch.Tensor)++ def test_augmentation_sequential_converts_dict_values(self, device, dtype):+ image = torch.rand(2, 3, 16, 20, device=device, dtype=dtype)+ mask = torch.rand(2, 1, 16, 20, device=device, dtype=dtype)+ aug = AugmentationSequential(RandomHorizontalFlip(p=1.0), data_keys=None)+ out = aug({"input": image, "mask": mask}, output_type="numpy")+ assert set(out) == {"input", "mask"}+ assert out["input"].shape == (2, 16, 20, 3)+ assert out["mask"].shape == (2, 16, 20, 1)