π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core): harden image module output cache (#5504)
Karnajeet Gosavid0913b33653c
diff --git a/changelog.d/5504.fixed.md b/changelog.d/5504.fixed.mdnew file mode 100644index 000000000..bba080087--- /dev/null+++ b/changelog.d/5504.fixed.md@@ -0,0 +1 @@+`ImageModule` and `ImageSequential` (core and augmentation) `show()` and `save()` raise the documented `ValueError` before the first call instead of an `AttributeError`, and again after `disable_features = True`, which now clears the cached output instead of leaving the last image to be shown. An output that is not 3-D or 4-D gets one clear `ValueError` from both instead of an empty `ValueError` from `show()` and an `UnboundLocalError` from `save()`. `show()` keeps a unit height or width: a `(3, 1, 5)` image renders as a 5 x 1 RGB picture instead of a 3 x 5 grayscale one. `output_type="numpy"` turns a `bfloat16` output into a `float32` array instead of raising `TypeError`, and the cached output is no longer pickled with the module, so `torch.save(module)` no longer grows by the size of the last output (#5211).diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 6185b85bd..7a684afb1 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -44,6 +44,8 @@ class ImageModuleForSequentialMixIn(ImageModuleMixIn):@disable_features.setterdef disable_features(self, value: bool = True) -> None:self._disable_features = value+ if value:+ self._output_image = Nonedef disable_item_features(self, *args: nn.Module) -> None:for arg in args:@@ -95,6 +97,10 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.Those transformations in ``kornia.geometry`` will not be taken into account.+ Note:+ The output cache retains a detached reference to the last tensor output and is omitted when pickled.+ Setting ``disable_features = True`` clears it.+Examples:>>> _ = torch.manual_seed(77)>>> import kornia@@ -163,6 +169,12 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):)self.random_apply_weights = torch.as_tensor(random_apply_weights or torch.ones((len(self),)))self.if_unsupported_ops = if_unsupported_ops+ self._output_image = None++ def __getstate__(self) -> dict[str, Any]:+ state = super().__getstate__()+ state.pop("_output_image", None)+ return statedef _read_random_apply(self, random_apply: Union[int, bool, Tuple[int, int]], max_length: intdiff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pyindex 55e022706..f17dea880 100644--- a/kornia/core/mixin/image_module.py+++ b/kornia/core/mixin/image_module.py@@ -312,7 +312,8 @@ class ImageModuleMixIn:converts 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 tochannels-last too; modules with several outputs are tracked in- `#5210 <https://github.com/kornia/kornia/issues/5210>`_.+ `#5210 <https://github.com/kornia/kornia/issues/5210>`_. A ``bfloat16`` tensor becomes a ``float32`` array,+ since NumPy has no ``bfloat16``.Args:x: The input to convert.@@ -323,6 +324,8 @@ class ImageModuleMixIn:"""if isinstance(x, torch.Tensor):x = x.detach().cpu()+ if x.dtype == torch.bfloat16:+ x = x.float()if x.dim() == 3:x = x.permute(1, 2, 0)elif x.dim() == 4:@@ -393,6 +396,15 @@ class ImageModuleMixIn:returnself._output_image = self._detach_tensor(output_image) if output_type == "pt" else output_image+ def _get_output_image(self) -> torch.Tensor:+ output_image = getattr(self, "_output_image", None)+ 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):+ shape = tuple(output_image.shape) if isinstance(output_image, torch.Tensor) else type(output_image).__name__+ raise ValueError(f"Expected a 3D or 4D image tensor, got {shape}.")+ return output_image+def show(self, n_row: Optional[int] = None, backend: str = "pil", display: bool = True) -> Optional[Any]:"""Return PIL images.@@ -402,28 +414,22 @@ class ImageModuleMixIn:display: Whether or not to show the image."""- if self._output_image is None:- raise ValueError("No pre-computed images found. Needs to execute first.")- output_image = self._output_image- if isinstance(output_image, torch.Tensor):- output_image = output_image.detach().cpu()+ output_image = self._get_output_image().detach().cpu()if len(output_image.shape) == 3:out_image = output_image- elif len(output_image.shape) == 4:+ else:from kornia.image.utils import make_grid # pylint: disable=C0415if n_row is None:n_row = math.ceil(output_image.shape[0] ** 0.5)out_image = make_grid(output_image, n_row, padding=2)- else:- raise ValueErrorif backend == "pil" and display:- Image.fromarray(_to_uint8_image(out_image).permute(1, 2, 0).squeeze().numpy()).show() # type: ignore+ self.to_pil(out_image).show()return Noneif backend == "pil":- return Image.fromarray(_to_uint8_image(out_image).permute(1, 2, 0).squeeze().numpy()) # type: ignore+ return self.to_pil(out_image)raise ValueError(f"Unsupported backend `{backend}`.")def save(self, name: Optional[str] = None, n_row: Optional[int] = None) -> None:@@ -434,21 +440,18 @@ class ImageModuleMixIn:n_row: Number of images displayed in each row of the grid."""- from kornia.image.utils import make_grid # pylint: disable=C0415- from kornia.io import write_image # pylint: disable=C0415-- if self._output_image is None:- raise ValueError("No pre-computed images found. Needs to execute first.")- output_image = self._output_image- if isinstance(output_image, torch.Tensor):- output_image = output_image.detach().cpu()+ output_image = self._get_output_image().detach().cpu()if name is None:name = f"Kornia-{datetime.datetime.now(tz=datetime.UTC).strftime('%Y%m%d%H%M%S')!s}.jpg"if len(output_image.shape) == 3:out_image = output_image- if len(output_image.shape) == 4:+ else:+ from kornia.image.utils import make_grid # pylint: disable=C0415+if n_row is None:n_row = math.ceil(output_image.shape[0] ** 0.5)out_image = make_grid(output_image, n_row, padding=2)+ from kornia.io import write_image # pylint: disable=C0415+write_image(name, _to_uint8_image(out_image))diff --git a/kornia/core/module.py b/kornia/core/module.pyindex a6fc8dede..d3a388253 100644--- a/kornia/core/module.py+++ b/kornia/core/module.py@@ -33,14 +33,21 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):return one image tensor only.Note:- The additional add-on features increase the use of memories. To restore the- original behaviour, you may set `disable_features = True`.+ The output cache retains a detached reference to the last tensor output, so it can keep that storage alive and+ reflects later in-place edits. Setting ``disable_features = True`` clears the cache and bypasses the extra+ behavior. The cache is omitted when the module is pickled."""def __init__(self, *args: Any, **kwargs: Any) -> None:super().__init__(*args, **kwargs)self._disable_features: bool = False+ self._output_image = None++ def __getstate__(self) -> dict[str, Any]:+ state = super().__getstate__()+ state.pop("_output_image", None)+ return state@propertydef disable_features(self) -> bool:@@ -67,6 +74,8 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):- ``False``: keep helper features active."""self._disable_features = value+ if value:+ self._output_image = Nonedef __call__(self,@@ -111,14 +120,21 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):return one image tensor only.Note:- The additional add-on features increase the use of memories. To restore the- original behaviour, you may set `disable_features = True`.+ The output cache retains a detached reference to the last tensor output, so it can keep that storage alive and+ reflects later in-place edits. Setting ``disable_features = True`` clears the cache and bypasses the extra+ behavior. The cache is omitted when the module is pickled."""def __init__(self, *args: Any, **kwargs: Any) -> None:super().__init__(*args, **kwargs)self._disable_features: bool = False+ self._output_image = None++ def __getstate__(self) -> dict[str, Any]:+ state = super().__getstate__()+ state.pop("_output_image", None)+ return state@propertydef disable_features(self) -> bool:@@ -145,6 +161,8 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):- ``False``: keep helper features active."""self._disable_features = value+ if value:+ self._output_image = Nonedef __call__(self,diff --git a/tests/core/test_module.py b/tests/core/test_module.pyindex 6fa7f3d99..84de9e1d0 100644--- a/tests/core/test_module.py+++ b/tests/core/test_module.py@@ -15,6 +15,7 @@# limitations under the License.#+import ioimport osimport sysfrom unittest.mock import MagicMock@@ -239,7 +240,6 @@ class TestImageModuleMixIn:img_module.show(backend="matplotlib", display=False)def test_save_without_output_image_raises(self, img_module, tmpdir):- img_module._output_image = Nonewith pytest.raises(ValueError, match="No pre-computed images found"):img_module.save(name=tmpdir.join("test_image.jpg"))@@ -366,16 +366,97 @@ class TestLazyOutputCache(BaseTester):assert module._output_image is cachedassert cached.device == image.device+ def test_fresh_module_show_and_save_raise(self, module, tmp_path):+ assert module._output_image is None+ with pytest.raises(ValueError, match="No pre-computed images found"):+ module.show(display=False)+ with pytest.raises(ValueError, match="No pre-computed images found"):+ module.save(name=str(tmp_path / "empty.png"))++ def test_disabling_features_clears_output_cache(self, module, device, dtype, tmp_path):+ image = torch.rand(1, 3, 6, 8, device=device, dtype=dtype)+ module(image)+ assert module._output_image is not None+ module.disable_features = False+ assert module._output_image is not None++ module.disable_features = True+ assert module._output_image is None+ module(image)+ assert module._output_image is None+ with pytest.raises(ValueError, match="No pre-computed images found"):+ module.show(display=False)+ with pytest.raises(ValueError, match="No pre-computed images found"):+ module.save(name=str(tmp_path / "disabled.png"))++ @pytest.mark.parametrize("container", ["module", "core_sequential", "augmentation_sequential"])+ def test_output_cache_is_not_serialized(self, container):+ if container == "module":+ module = _Identity()+ elif container == "core_sequential":+ module = ImageSequential(torch.nn.Identity())+ else:+ module = AugmentationImageSequential(torch.nn.Identity())++ def serialized_size():+ buffer = io.BytesIO()+ torch.save(module, buffer)+ return buffer.tell()++ before = serialized_size()+ output = module(torch.rand(4, 3, 64, 64))+ assert "_output_image" not in module.__getstate__()+ assert serialized_size() - before < output.numel() * output.element_size()+ buffer = io.BytesIO()+ torch.save(module, buffer)+ buffer.seek(0)+ restored = torch.load(buffer, weights_only=False)+ assert not hasattr(restored, "_output_image")++ @pytest.mark.parametrize("shape,expected_size", [((3, 1, 5), (5, 1)), ((3, 5, 1), (1, 5))])+ def test_show_and_save_preserve_unit_spatial_dimensions(self, shape, expected_size, tmp_path):+ module = _Identity()+ module(torch.rand(shape))+ image = module.show(display=False)+ assert image.mode == "RGB"+ assert image.size == expected_size+ path = tmp_path / "single-row-or-column.png"+ module.save(name=str(path))+ with PILImage.open(path) as saved:+ assert saved.mode == "RGB"+ assert saved.size == expected_size++ def test_two_dimensional_output_has_clear_show_and_save_error(self, tmp_path):+ module = ImageModuleMixIn()+ module._output_image = torch.rand(4, 5)+ with pytest.raises(ValueError, match="Expected a 3D or 4D image tensor"):+ module.show(display=False)+ with pytest.raises(ValueError, match="Expected a 3D or 4D image tensor"):+ module.save(name=str(tmp_path / "2d.png"))+ module._output_image = [torch.rand(3, 4, 5), torch.rand(3, 4, 5)]+ with pytest.raises(ValueError, match="got list"):+ module.show(display=False)++ def test_bfloat16_output_can_be_shown_and_converted_to_numpy(self):+ module = _Identity()+ image = torch.rand(3, 4, 6, dtype=torch.bfloat16)+ output = module(image, output_type="numpy")+ assert output.dtype == np.float32+ np.testing.assert_array_equal(output, image.float().permute(1, 2, 0).numpy())+ rendered = module.show(display=False)+ assert rendered.mode == "RGB"+ assert rendered.size == (6, 4)+@pytest.mark.parametrize("output_type", ["numpy", "pil"])def test_requested_output_conversion_4957(self, module, output_type, device, dtype):- if dtype == torch.bfloat16 and output_type == "numpy":- pytest.skip("NumPy does not support bfloat16")image = torch.rand(1, 3, 6, 8, device=device, dtype=dtype, requires_grad=True)output = module(image, output_type=output_type)expected = image.sigmoid().detach().cpu()if output_type == "numpy":assert isinstance(output, np.ndarray)- np.testing.assert_array_equal(output, expected.permute(0, 2, 3, 1).numpy())+ # NumPy has no bfloat16: to_numpy upcasts it to float32, which holds every bfloat16 value exactly+ numpy_dtype = torch.float32 if dtype == torch.bfloat16 else dtype+ np.testing.assert_array_equal(output, expected.to(numpy_dtype).permute(0, 2, 3, 1).numpy())else:assert isinstance(output, list)assert len(output) == 1@@ -386,8 +467,6 @@ class TestLazyOutputCache(BaseTester):@pytest.mark.parametrize("output_type", ["numpy", "pil"])def test_converted_output_can_be_shown_and_saved_4964(self, module, output_type, device, dtype, tmp_path):- if dtype == torch.bfloat16 and output_type == "numpy":- pytest.skip("NumPy does not support bfloat16")image = torch.rand(1, 3, 6, 8, device=device, dtype=dtype, requires_grad=True)module(image, output_type=output_type)cached = module._output_image@@ -669,9 +748,6 @@ class TestTupleOutputCache(BaseTester):@pytest.mark.parametrize("count", [1, 2])@pytest.mark.parametrize("output_type", ["pt", "numpy", "pil"])def test_tuple_conversion_and_cache(self, container, count, output_type, device, dtype):- if dtype == torch.bfloat16 and output_type == "numpy":- pytest.skip("NumPy does not support bfloat16")-class TupleModule(container):def forward(self, x):return tuple(x.sigmoid() for _ in range(count))@@ -696,7 +772,8 @@ class TestTupleOutputCache(BaseTester):assert output.requires_gradself.assert_close(output, expected)elif output_type == "numpy":- np.testing.assert_array_equal(output, expected.cpu().permute(1, 2, 0).numpy())+ numpy_dtype = torch.float32 if dtype == torch.bfloat16 else dtype+ np.testing.assert_array_equal(output, expected.cpu().to(numpy_dtype).permute(1, 2, 0).numpy())else:assert isinstance(output, PILImage.Image)working = expected.cpu().to(torch.promote_types(dtype, torch.float32))