π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): accept an empty batch in ranged RandomMotionBlur and RandomMotionBlur3D (#5923)
Saksham Sharmaad492524704e
diff --git a/changelog.d/5923.fixed.md b/changelog.d/5923.fixed.mdnew file mode 100644index 000000000..0e42cc974--- /dev/null+++ b/changelog.d/5923.fixed.md@@ -0,0 +1,4 @@+`RandomMotionBlur` and `RandomMotionBlur3D` with a ranged `kernel_size` accept an empty batch and return it unchanged.+They raised before the blur ran because they choose the batch's kernel size from the sampled sizes, of which an empty+batch has none: `RandomMotionBlur` with `IndexError: list index out of range` and `RandomMotionBlur3D` with+`RuntimeError: a Tensor with 0 elements cannot be converted to Scalar`.diff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.pyindex fce4bd163..1dc31954a 100644--- a/kornia/augmentation/_2d/intensity/motion_blur.py+++ b/kornia/augmentation/_2d/intensity/motion_blur.py@@ -153,6 +153,9 @@ class RandomMotionBlur(IntensityAugmentationBase2D):# entries are equal and taking the first is legit.) This branch is inherently# data-dependent and not fullgraph-compilable.kernel_size_list: List[int] = params["ksize_factor"].tolist()+ if not kernel_size_list and input.shape[0] == 0:+ # An empty batch draws no kernel size and has nothing to blur; motion blur keeps the shape (#4429).+ return input.clone()idx: int = cast(int, params["idx"][0])kernel_size = kernel_size_list[idx]border_type = flags["border_type"].name.lower()diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.pyindex 57ab846ef..df9677351 100644--- a/kornia/augmentation/_3d/intensity/motion_blur.py+++ b/kornia/augmentation/_3d/intensity/motion_blur.py@@ -153,6 +153,9 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):# Fixed kernel size: static value, no device-to-host read -> stays capturable by graph export.kernel_size = self._fixed_kernel_sizeelse:+ if params["ksize_factor"].numel() == 0 and input.shape[0] == 0:+ # An empty batch draws no kernel size and has nothing to blur; motion blur keeps the shape (#4429).+ return input.clone()kernel_size = int(params["ksize_factor"].unique().item())angle = params["angle_factor"]direction = params["direction_factor"]diff --git a/tests/augmentation/test_motionblur.py b/tests/augmentation/test_motionblur.pyindex 99f3fd40d..35475fd7c 100644--- a/tests/augmentation/test_motionblur.py+++ b/tests/augmentation/test_motionblur.py@@ -19,6 +19,7 @@ import pytestimport torchfrom kornia.augmentation import RandomMotionBlur, RandomMotionBlur3D+from kornia.core.exceptions import BaseErrorfrom kornia.filters import motion_blur, motion_blur3dfrom testing.base import BaseTester@@ -110,6 +111,31 @@ class TestRandomMotionBlur(BaseTester):expected = motion_blur(image, 5, params["angle_factor"], params["direction_factor"], border_type=border_type)self.assert_close(aug(image, params=params), expected)+ @pytest.mark.parametrize("p", [1.0, 0.5])+ @pytest.mark.parametrize("same_on_batch", [False, True])+ def test_empty_batch_ranged_kernel_size(self, p, same_on_batch, device, dtype):+ # #4429: a ranged kernel_size picks the batch's size from the sampled list, which an empty batch leaves+ # empty (IndexError). A fixed kernel_size takes the filter path instead.+ image = torch.rand(0, 3, 8, 10, device=device, dtype=dtype, requires_grad=True)+ output = RandomMotionBlur((3, 7), 35.0, 0.5, same_on_batch=same_on_batch, p=p)(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, IndexError, "list index out of range"), (2, 0, BaseError, "kernel batch must be 1 or the input batch")],+ )+ 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 kernel size must not come back unblurred.+ aug = RandomMotionBlur((3, 7), 35.0, 0.5, 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.slowdef test_gradcheck(self, device):torch.manual_seed(0) # for random reproductibility@@ -206,6 +232,30 @@ class TestRandomMotionBlur3D(BaseTester):assert output.shape == input.shape+ @pytest.mark.parametrize("resample", ["nearest", "bilinear"])+ @pytest.mark.parametrize("p", [1.0, 0.5])+ def test_empty_batch_ranged_kernel_size(self, resample, p, device, dtype):+ # #4429: a ranged kernel_size reads the batch's size with ``unique().item()``, which has no element for an+ # empty batch (RuntimeError). A fixed kernel_size takes the filter path instead.+ volume = torch.rand(0, 3, 4, 8, 10, device=device, dtype=dtype, requires_grad=True)+ output = RandomMotionBlur3D((3, 5), 35.0, 0.5, resample=resample, p=p)(volume)+ assert output.shape == volume.shape+ assert output.dtype == dtype+ output.sum().backward()+ assert volume.grad is not None+ assert volume.grad.shape == volume.shape++ @pytest.mark.parametrize(+ ("params_batch", "batch", "error", "match"),+ [(0, 2, RuntimeError, "0 elements"), (2, 0, BaseError, "kernel batch must be 1 or the input batch")],+ )+ def test_empty_batch_shortcut_needs_an_empty_batch(self, params_batch, batch, error, match, device, dtype):+ # As in the 2D class: parameters drawn for another batch size still raise.+ aug = RandomMotionBlur3D((3, 5), 35.0, 0.5, p=1.0)+ params = aug.forward_parameters(torch.Size((params_batch, 3, 4, 8, 10)))+ with pytest.raises(error, match=match):+ aug(torch.rand(batch, 3, 4, 8, 10, device=device, dtype=dtype), params=params)+# The class zero-pads by its own default, although ``motion_blur3d`` now defaults to "replicate".# Snippet used to generate expected:# import torch, kornia.augmentation as K