π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): cache a detached CPU image for AugmentationSequential.show() (#4918)
stanleys126d5da2e33273
diff --git a/changelog.d/4918.fixed.md b/changelog.d/4918.fixed.mdnew file mode 100644index 000000000..83c98e1d5--- /dev/null+++ b/changelog.d/4918.fixed.md@@ -0,0 +1,8 @@+`AugmentationSequential.show()` and `.save()` now work after a forward call that returns tensors (the default+`output_type="pt"`). The container cached the raw forward output, so `.show()` raised `RuntimeError: Can't call+numpy() on Tensor that requires grad` for an input that requires gradients, a `TypeError` for a CUDA or MPS one,+and `AttributeError: 'list' object has no attribute 'shape'` for a call with several data keys. It now caches a+detached view of the augmented image alone, which no longer holds the autograd graph, and `.show()` / `.save()` move+it to the CPU when they render it, so the forward pass still makes no device-to-host copy. A call whose data keys+carry no image caches nothing, and `ImageModule.save()` reports an empty cache with the same `ValueError` as+`.show()` instead of `AttributeError: 'NoneType' object has no attribute 'shape'`. Closes #4835.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 0f5d8713c..e7115f46c 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -632,29 +632,35 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):_output_image = decorated_forward(*inputs, **kwargs)in_data_keys: Optional[List[DataKey]]+ original_keys: Optional[Tuple[str, ...]] = Noneif len(inputs) == 1 and isinstance(inputs[0], dict):original_keys, in_data_keys, inputs, _invalid_data = self._preproc_dict_data(inputs[0])else:in_data_keys = kwargs.get("data_keys", self.data_keys)data_keys = self.transform_op.preproc_datakeys(in_data_keys)+ # 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 syncif not is_exporting():- if len(data_keys) > 1 and DataKey.INPUT in data_keys:- idx = data_keys.index(DataKey.INPUT)- if output_type == "pt":- # ``self._output_image`` already holds ``_output_image`` here, so the old- # per-key rebind was a no-op; just store the whole output.- self._output_image = _output_image- elif isinstance(_output_image, dict):- self._output_image[original_keys[idx]] = _output_image[original_keys[idx]]- else:- self._output_image[idx] = _output_image[idx]- else:- self._output_image = _output_image+ image = self._select_output_image(_output_image, data_keys, original_keys)+ self._output_image = image.detach() if isinstance(image, torch.Tensor) else imageelse:_output_image = super(ImageSequential, self).__call__(*inputs, **kwargs)return _output_image+ def _select_output_image(+ self, output: Any, data_keys: List[DataKey], original_keys: Optional[Tuple[str, ...]]+ ) -> Any:+ # ``forward`` returns the image itself, a list ordered like ``data_keys``, or a dict keyed like the input+ if DataKey.INPUT not in data_keys:+ return None+ 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):+ return output[idx]+ return output+def _preproc_dict_data(self, data: Dict[str, DataType]) -> Tuple[Tuple[str, ...], List[DataKey], Tuple[DataType, ...], Optional[Dict[str, Any]]]:diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pyindex 92828a4b5..2dcf53b21 100644--- a/kornia/core/mixin/image_module.py+++ b/kornia/core/mixin/image_module.py@@ -220,15 +220,18 @@ class ImageModuleMixIn:"""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()- if len(self._output_image.shape) == 3:- out_image = self._output_image- elif len(self._output_image.shape) == 4:+ if len(output_image.shape) == 3:+ out_image = output_image+ elif len(output_image.shape) == 4:from kornia.image.utils import make_grid # pylint: disable=C0415if n_row is None:- n_row = math.ceil(self._output_image.shape[0] ** 0.5)- out_image = make_grid(self._output_image, n_row, padding=2)+ n_row = math.ceil(output_image.shape[0] ** 0.5)+ out_image = make_grid(output_image, n_row, padding=2)else:raise ValueError@@ -250,12 +253,18 @@ class ImageModuleMixIn:from kornia.image.utils import make_grid # pylint: disable=C0415from 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()+if name is None:name = f"Kornia-{datetime.datetime.now(tz=datetime.UTC).strftime('%Y%m%d%H%M%S')!s}.jpg"- if len(self._output_image.shape) == 3:- out_image = self._output_image- if len(self._output_image.shape) == 4:+ if len(output_image.shape) == 3:+ out_image = output_image+ if len(output_image.shape) == 4:if n_row is None:- n_row = math.ceil(self._output_image.shape[0] ** 0.5)- out_image = make_grid(self._output_image, n_row, padding=2)+ n_row = math.ceil(output_image.shape[0] ** 0.5)+ out_image = make_grid(output_image, n_row, padding=2)write_image(name, out_image.mul(255.0).byte())diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 512553ea2..86c355c04 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -1440,3 +1440,61 @@ class TestConventionAugmentationSequential(BaseTester):):with pytest.raises(NotImplementedError):K.AugmentationSequential(factory(), data_keys=["input", "mask"])(img, mask)++ @pytest.mark.parametrize("data_style", ["image", "list", "dict", "dict_mask_first"])+ def test_show_and_save_render_a_detached_image_4835(self, data_style, tmp_path, device, dtype):+ # `.show()` / `.save()` render the cache through `.numpy()`, so it must hold the augmented image+ # alone and detached: the raw forward output keeps the autograd graph and, for several data keys,+ # is a list or a dict. It stays on the input device; the helpers move it to the CPU themselves.+ from PIL import Image as PILImage++ image = torch.rand(2, 3, 6, 8, device=device, dtype=dtype, requires_grad=True)+ mask = torch.rand(2, 1, 6, 8, device=device, dtype=dtype)+ if data_style == "image":+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0))+ out_image = aug(image)+ elif data_style == "list":+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])+ out_image, _ = aug(image, mask)+ elif data_style == "dict":+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)+ out_image = aug({"image": image, "mask": mask})["image"]+ else: # the image is not the first key, so the cache must pick it by its position+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)+ out_image = aug({"mask": mask, "image": image})["image"]++ assert out_image.requires_grad # the returned image still carries the graph+ cached = aug._output_image+ assert isinstance(cached, torch.Tensor)+ assert not cached.requires_grad+ assert cached.device == out_image.device # no device-to-host copy in the forward pass+ self.assert_close(cached, out_image.detach())++ if dtype != torch.bfloat16: # `.show()` renders through `Tensor.numpy()`, which has no bfloat16 support+ assert isinstance(aug.show(display=False), PILImage.Image)+ path = tmp_path / "augmented.jpg"+ aug.save(name=str(path))+ assert path.is_file()++ @pytest.mark.parametrize("no_image_style", ["dict", "data_keys"])+ def test_show_and_save_reject_a_call_that_carried_no_image_4835(self, no_image_style, tmp_path, device, dtype):+ # A call whose data keys hold no `DataKey.INPUT` augments no image, so there is nothing to+ # render: neither the mask that came out nor the raw container output may be cached. Both+ # helpers report the empty cache instead. `forward` only accepts such a call when `params`+ # are supplied, since it otherwise has no image to sample them from.+ mask = torch.rand(2, 1, 6, 8, device=device, dtype=dtype)+ if no_image_style == "dict":+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)+ params = aug.forward_parameters((2, 3, 6, 8))+ out = aug({"mask": mask}, params=params)+ assert set(out) == {"mask"}+ else:+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])+ params = aug.forward_parameters((2, 3, 6, 8))+ out = aug(mask, data_keys=["mask"], params=params)+ assert isinstance(out, torch.Tensor)++ assert aug._output_image is None+ for helper in (lambda: aug.show(display=False), lambda: aug.save(name=str(tmp_path / "none.jpg"))):+ with pytest.raises(ValueError, match="No pre-computed images found"):+ helper()diff --git a/tests/core/test_module.py b/tests/core/test_module.pyindex d37714d82..9f0acfd04 100644--- a/tests/core/test_module.py+++ b/tests/core/test_module.py@@ -154,6 +154,11 @@ class TestImageModuleMixIn:with pytest.raises(ValueError, match="Unsupported backend"):img_module.show(backend="matplotlib", display=False)+ def test_save_without_output_image_raises(self, img_module, tmpdir):+ img_module._output_image = None+ with pytest.raises(ValueError, match="No pre-computed images found"):+ img_module.save(name=tmpdir.join("test_image.jpg"))+def test_detach_tensor_to_cpu_tensor(self, img_module, sample_tensor):result = img_module._detach_tensor_to_cpu(sample_tensor)assert isinstance(result, torch.Tensor)