π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): keep the shape for an empty RandomJPEG batch (#5972)
XXXXXQ.f35ba02c64a1
diff --git a/changelog.d/5972.fixed.md b/changelog.d/5972.fixed.mdnew file mode 100644index 000000000..756ccf0e8--- /dev/null+++ b/changelog.d/5972.fixed.md@@ -0,0 +1,3 @@+`RandomJPEG` accepts an empty batch and returns it unchanged. It raised+`ValueError: Invalid input tensor, it is empty.` before the codec ran, because the differentiable JPEG codec rejects+an empty input.diff --git a/kornia/augmentation/_2d/intensity/jpeg.py b/kornia/augmentation/_2d/intensity/jpeg.pyindex 3ccb6a227..432cacdc4 100644--- a/kornia/augmentation/_2d/intensity/jpeg.py+++ b/kornia/augmentation/_2d/intensity/jpeg.py@@ -81,5 +81,14 @@ class RandomJPEG(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:+ if (+ params["jpeg_quality"].numel() == 0+ and input.shape[0] == 0+ and input.shape[1] == 3+ and input.shape[-2] > 0+ and input.shape[-1] > 0+ ):+ # An empty batch draws no quality and has no pixels to code; JPEG coding keeps the shape (#4429).+ return input.clone()jpeg_output: torch.Tensor = jpeg_codec_differentiable(input, params["jpeg_quality"])return jpeg_outputdiff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex e91c9c084..5377a89f7 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -6405,6 +6405,42 @@ class TestRandomJPEG(BaseTester):self.assert_close(img.grad.mean().view(-1), img_jpeg_mean_grad_ref, rtol=0.01, atol=0.01)+class TestRandomJPEGEmptyBatch(BaseTester):+ # Not marked slow like TestRandomJPEG: an empty batch never reaches the codec, so these run on every CI leg.++ @pytest.mark.parametrize("p", [1.0, 0.5])+ @pytest.mark.parametrize("same_on_batch", [False, True])+ def test_empty_batch(self, p, same_on_batch, device, dtype):+ # #4429: the differentiable JPEG codec rejects an empty batch, so the augmentation short-circuits it and+ # keeps the shape like the other classes in the empty-batch convention.+ image = torch.rand(0, 3, 8, 10, device=device, dtype=dtype, requires_grad=True)+ output = RandomJPEG(p=p, same_on_batch=same_on_batch)(image)+ assert output.shape == image.shape+ assert output.dtype == dtype+ output.sum().backward()+ assert image.grad is not None+ assert image.grad.shape == image.shape++ @pytest.mark.parametrize(+ ("params_batch", "batch", "error", "match"),+ [(0, 2, RuntimeError, r"amin\(\)"), (2, 0, ValueError, r"Invalid input tensor, it is empty\.")],+ )+ def test_empty_batch_shortcut_needs_an_empty_batch(self, params_batch, batch, error, match, device, dtype):+ # Replaying parameters drawn for another batch size raises as it did before the empty-batch shortcut; a+ # non-empty batch with no drawn quality must not come back uncoded.+ aug = RandomJPEG(p=1.0)+ params = aug.forward_parameters(torch.Size((params_batch, 3, 8, 10)))+ with pytest.raises(error, match=match):+ aug(torch.rand(batch, 3, 8, 10, device=device, dtype=dtype), params=params)++ @pytest.mark.parametrize("shape", [(0, 1, 8, 10), (0, 3, 0, 10), (0, 3, 8, 0)])+ def test_empty_batch_keeps_the_input_checks(self, shape, device, dtype):+ # The codec needs three channels and a non-empty image at every batch size, so these empty batches still+ # raise as they did before the empty-batch shortcut.+ with pytest.raises(ValueError, match=r"it is empty|expected 3"):+ RandomJPEG(p=1.0)(torch.rand(*shape, device=device, dtype=dtype))++@pytest.mark.slowclass TestRandomDissolving(BaseTester):torch.manual_seed(0) # for random reproductibilitydiff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.pyindex d6136ff1b..ad39b2fd6 100644--- a/tests/augmentation/test_base.py+++ b/tests/augmentation/test_base.py@@ -1244,6 +1244,7 @@ class TestConventionAugmentationBase2D(BaseTester):id="RandomGaussianBlur",),pytest.param(lambda: K.RandomMotionBlur(3, 35.0, 0.5, p=1.0), (0, 3, 6, 8), id="RandomMotionBlur"),+ pytest.param(lambda: K.RandomJPEG(p=1.0), (0, 3, 6, 8), id="RandomJPEG"),],)def test_convention_zero_batch_is_empty_in_empty_out(self, augmentation, shape, device, dtype):