Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): preserve tensor cache before image output conversion (#5178)

llllgt31b09fd38e55
diff --git a/changelog.d/5178.fixed.md b/changelog.d/5178.fixed.md
new file mode 100644
index 000000000..07fdcb8d4
--- /dev/null
+++ b/changelog.d/5178.fixed.md
@@ -0,0 +1 @@
+Fix `ImageModule.show()` / `.save()` and core `ImageSequential.show()` / `.save()` after requesting NumPy or PIL output by retaining a detached tensor cache before conversion.
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index 5b2ee7562..be0a586d0 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -97,6 +97,8 @@ class ImageModuleMixIn:
self,
input_names_to_handle: Optional[List[Any]] = None,
output_type: Literal["pt", "numpy", "pil"] = "pt",
+ *,
+ cache_output: bool = False,
) -> Callable[[Any], Any]:
"""Convert input and output types for a function.
@@ -105,6 +107,7 @@ class ImageModuleMixIn:
If None, convert every tensor, NumPy array and PIL image argument, and load a string as an image
path only if it is the first positional argument.
output_type: Desired output type ('pt', 'numpy', or 'pil').
+ cache_output: Cache detached tensor outputs before converting their type, for visualization helpers.
Returns:
Callable: Decorated function with converted input and output types.
@@ -138,7 +141,10 @@ class ImageModuleMixIn:
kwargs[name] = self.to_tensor(value)
# Call the actual forward method and convert its outputs to the desired type
- return self._convert_output(func(*args, **kwargs), output_type)
+ tensor_outputs = func(*args, **kwargs)
+ if cache_output:
+ self._store_output_image(self._convert_output(tensor_outputs, "pt"), "pt")
+ return self._convert_output(tensor_outputs, output_type)
return wrapper
diff --git a/kornia/core/module.py b/kornia/core/module.py
index 72ecb4957..5398b4db9 100644
--- a/kornia/core/module.py
+++ b/kornia/core/module.py
@@ -92,10 +92,9 @@ class ImageModule(nn.Module, ImageModuleMixIn, ONNXExportMixin):
# Wrap the forward method with the decorator
if not self._disable_features:
decorated_forward = self.convert_input_output(
- input_names_to_handle=input_names_to_handle, output_type=output_type
+ input_names_to_handle=input_names_to_handle, output_type=output_type, cache_output=True
)(super().__call__)
_output_image = decorated_forward(*inputs, **kwargs)
- self._store_output_image(_output_image, output_type)
else:
_output_image = super().__call__(*inputs, **kwargs)
return _output_image
@@ -168,10 +167,9 @@ class ImageSequential(nn.Sequential, ImageModuleMixIn, ONNXExportMixin):
# Wrap the forward method with the decorator
if not self._disable_features:
decorated_forward = self.convert_input_output(
- input_names_to_handle=input_names_to_handle, output_type=output_type
+ input_names_to_handle=input_names_to_handle, output_type=output_type, cache_output=True
)(super().__call__)
_output_image = decorated_forward(*inputs, **kwargs)
- self._store_output_image(_output_image, output_type)
else:
_output_image = super().__call__(*inputs, **kwargs)
return _output_image
diff --git a/tests/core/test_module.py b/tests/core/test_module.py
index 2b298dba8..9b4151e6c 100644
--- a/tests/core/test_module.py
+++ b/tests/core/test_module.py
@@ -362,6 +362,28 @@ class TestLazyOutputCache(BaseTester):
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[0]), rendered)
+ @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
+ assert isinstance(cached, torch.Tensor)
+ assert cached.device == image.device
+ assert cached.dtype == image.dtype
+ assert cached.grad_fn is None
+ assert not cached.requires_grad
+ self.assert_close(cached, image.sigmoid().detach())
+ working = cached[0].to(torch.promote_types(dtype, torch.float32))
+ expected = (working.clamp(0.0, 1.0) * 255).round().to(torch.uint8).cpu().permute(1, 2, 0).numpy()
+ np.testing.assert_array_equal(np.asarray(module.show(display=False)), expected)
+ path = tmp_path / "converted.png"
+ module.save(name=str(path))
+ with PILImage.open(path) as saved:
+ np.testing.assert_array_equal(np.asarray(saved), expected)
+ assert module._output_image is cached
+
@pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
def test_export_preserves_cache_4957(self, device, dtype):
class CacheModule(torch.nn.Module, ImageModuleMixIn):
@@ -602,3 +624,43 @@ class TestImageModuleConversions(BaseTester):
module.save(name=str(path))
with PILImage.open(path) as saved:
np.testing.assert_array_equal(pil, np.asarray(saved))
+
+
+class TestTupleOutputCache(BaseTester):
+ @pytest.mark.parametrize("container", [ImageModule, ImageSequential])
+ @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))
+
+ module = TupleModule()
+ 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)
+ assert len(result) == len(cached) == count
+ expected = image.sigmoid().detach()
+ for output, tensor in zip(result, cached):
+ assert isinstance(tensor, torch.Tensor)
+ assert tensor.device == image.device
+ assert not tensor.requires_grad
+ self.assert_close(tensor, expected)
+ if output_type == "pt":
+ assert output.requires_grad
+ self.assert_close(output, expected)
+ elif output_type == "numpy":
+ np.testing.assert_array_equal(output, expected.cpu().permute(1, 2, 0).numpy())
+ else:
+ assert isinstance(output, PILImage.Image)
+ 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)