π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): share sampled motion blur kernel size across batch (#4687)
Puttala Jeevan Kumara7296efb668f
diff --git a/changelog.d/4687.fixed.md b/changelog.d/4687.fixed.mdnew file mode 100644index 000000000..fce537c2d--- /dev/null+++ b/changelog.d/4687.fixed.md@@ -0,0 +1 @@+`RandomMotionBlur` now draws a ranged kernel size once per call and repeats it across `ksize_factor`, so the stored sizes match the shared size applied to the batch. Previously it drew a size per sample and used only one randomly selected entry. Angle and direction still follow `same_on_batch`. Fixed integer kernel sizes and replay of previously saved parameters are unchanged; seeded ranged calls with `same_on_batch=False` can produce different sizes and advance the random generator differently.diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.pyindex dc8f2b211..dc01c11b4 100644--- a/kornia/augmentation/_2d/intensity/base.py+++ b/kornia/augmentation/_2d/intensity/base.py@@ -67,10 +67,9 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):out-of-range image even at ``p=0.0`` -- and a skipped sample's gradient can be NaN where thetransform's derivative is infinite (`#4576 <https://github.com/kornia/kornia/issues/4576>`_).- the scalar factors a concrete class draws are per sample -- one value, or one per channel- per sample where the class's own docstring says so. One class draws per sample and then- applies one draw to the whole batch: :class:`RandomMotionBlur` fills ``_params["ksize_factor"]``- with one kernel size per sample and blurs the batch with the one at ``_params["idx"]``, an index- drawn uniformly over the batch rather than the first sample's. :class:`RandomDissolving`+ per sample where the class's own docstring says so. :class:`RandomMotionBlur` instead draws+ one kernel size for the whole batch and repeats it in ``_params["ksize_factor"]`` with shape+ ``(B,)``; its angle and direction remain per sample unless ``same_on_batch=True``. :class:`RandomDissolving`hard-codes ``same_on_batch=True``. Several classes also draw a whole-image field --``gaussian_noise``, ``gradient``, ``plasma``, and :class:`RandomSaltAndPepperNoise`'s boolean``mask_salt`` and ``mask_pepper`` -- whose stored shape normally follows the original batcheddiff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.pyindex 2e7fc6e6f..6ac09ccb6 100644--- a/kornia/augmentation/_2d/intensity/motion_blur.py+++ b/kornia/augmentation/_2d/intensity/motion_blur.py@@ -36,7 +36,7 @@ class RandomMotionBlur(IntensityAugmentationBase2D):p: probability of applying the transformation.kernel_size: motion kernel size (odd and positive).If int, the kernel will have a fixed size.- If Tuple[int, int], it will randomly generate the value from the range batch-wisely.+ If Tuple[int, int], it will randomly generate one value from the range for the whole batch.angle: angle of the motion blur in degrees (anti-clockwise rotation).If float, it will generate the value from (-angle, angle).direction: forward/backward direction of the motion blur.@@ -48,6 +48,7 @@ class RandomMotionBlur(IntensityAugmentationBase2D):border_type: the padding mode to be applied before convolving.CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3.resample: the interpolation mode.+ same_on_batch: apply the same angle and direction across the batch. The kernel size is always shared.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False).@@ -64,8 +65,10 @@ class RandomMotionBlur(IntensityAugmentationBase2D):``"bilinear"`` or ``"bicubic"`` also spread weight off the line. The ends belong to the rotated line, so whichside of the image they fall on turns with ``angle`` and is not read off the image axes.- the defaults ``border_type="constant"`` and ``resample="nearest"`` are the function's own defaults.- - ``kernel_size`` is drawn once per sample into ``_params["ksize_factor"]``, and the whole batch is- then blurred with the single entry at ``_params["idx"]``, an index drawn uniformly over the batch.+ - a ranged ``kernel_size`` is drawn once per call and repeated into ``_params["ksize_factor"]``+ with shape ``(B,)``. All samples use that size, even with ``same_on_batch=False``; angle and+ direction are sampled per image unless ``same_on_batch=True``. Previously saved parameters+ with differing kernel sizes still select one entry via ``_params["idx"]`` for the whole batch.The draw truncates a float, so the range's upper bound is practically never reached -- only whenthe ``float32`` draw rounds onto it, about once in ``2**24`` -- and ``kernel_size=(3, 5)`` is aconstant ``3`` while ``(3, 7)`` draws only ``3`` and ``5``. An even bound is separately rounded@@ -149,8 +152,8 @@ class RandomMotionBlur(IntensityAugmentationBase2D):# Fixed kernel size: static value, no data-dependent indexing -> stays fullgraph.kernel_size = self._fixed_kernel_sizeelse:- # Sampled from a range. We apply the same kernel size to all samples in the batch,- # taking the previously selected random index `params["idx"][0]` to pick it.+ # Generated sizes are shared. Retain indexed selection for replay of older parameters+ # that contain differing sizes, using one selected size for the whole batch.# (`VideoSequential` flattens the first two dims and repeats that index, so all# entries are equal and taking the first is legit.) This branch is inherently# data-dependent and not fullgraph-compilable.diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.pyindex 5752f5d58..05d874727 100644--- a/kornia/augmentation/random_generator/_2d/motion_blur.py+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py@@ -32,7 +32,7 @@ class MotionBlurGenerator(RandomGeneratorBase):Args:kernel_size: motion kernel size (odd and positive).If int, the kernel will have a fixed size.- If Tuple[int, int], it will randomly generate the value from the range batch-wisely.+ If Tuple[int, int], it will randomly generate one value from the range for the whole batch.angle: angle of the motion blur in degrees (anti-clockwise rotation).If float, it will generate the value from (-angle, angle).direction: forward/backward direction of the motion blur.@@ -44,7 +44,7 @@ class MotionBlurGenerator(RandomGeneratorBase):Returns:A dict of parameters to be passed for transformation.- - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).+ - ksize_factor (torch.Tensor): one shared kernel size repeated to a shape of (B,).- angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).- direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).@@ -97,7 +97,9 @@ class MotionBlurGenerator(RandomGeneratorBase):_device, _dtype = _extract_device_dtype([self.angle, self.direction])angle_factor = _adapted_rsampling((batch_size,), self.angle_sampler, same_on_batch)direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)- ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1+ # A ranged kernel size is shared by the batch; angle and direction can still vary per sample.+ ksize_same_on_batch = same_on_batch or isinstance(self.kernel_size, tuple)+ ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, ksize_same_on_batch).int() * 2 + 1return {"ksize_factor": ksize_factor.to(device=_device, dtype=torch.int32),diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.pyindex 4823a1298..6b5406a23 100644--- a/tests/augmentation/test_conventions_intensity_ops.py+++ b/tests/augmentation/test_conventions_intensity_ops.py@@ -29,7 +29,7 @@ from torch.distributions import Distributionimport kornia.augmentation as Kfrom kornia.constants import BorderType, Resamplefrom kornia.core.exceptions import BaseError, ImageError, ShapeError-from kornia.filters import box_blur, motion_blur+from kornia.filters import box_blurfrom kornia.filters.kernels import gaussianfrom testing.base import (@@ -376,87 +376,36 @@ class TestBlurConventions(BaseTester):assert aug.flags["border_type"] == BorderType.CONSTANTassert aug.flags["resample"] == Resample.NEAREST- # Issue #4599: `kernel_size` is drawn once per SAMPLE and then one entry -- the one at a uniformly- # drawn `_params["idx"]`, not the first -- is applied to the whole batch; and because the draw is- # `UniformDistribution(ks[0] // 2, ks[1] // 2)` truncated with `.int()`, the range's upper bound is- # practically never reached. `(3, 5)` is therefore a constant 3 -- "practically": the float32 draw- # rounds onto the bound about once in 2**24 (seed 204 draws one 5 in 50000), so the pin is that the- # bound is vanishingly rare, not impossible. RandomRain had the same wart and no longer does- # (#4567): it draws over `[lo, hi + 1)`, floors, and clamps that rounding escape back onto the closed- # range -- the remedy this one still needs.- # Snippet used to generate expected:- # import collections- # for ks in ((3, 5), (3, 7), (5, 11)):- # torch.manual_seed(0)- # v = K.RandomMotionBlur(ks, (0., 0.), (0., 0.), p=1.).forward_parameters((20000, 1, 8, 8))- # print(ks, sorted(collections.Counter(v["ksize_factor"].tolist())))- # executed 2026-09-16 (torch 2.14.0, cpu) -> `[3]`, `[3, 5]`, `[5, 7, 9]`; `idx` over 400 seeds at- # B = 6 lands on every row (`{0: 67, 1: 71, 2: 66, 3: 57, 4: 83, 5: 56}`).+ # Issue #4599: truncating the half-size float draw makes the odd upper bound practically+ # unreachable (apart from float32 rounding). Sample independent calls because the kernel size+ # is shared within each batch. The range-sampling defect is separate from #4671.@pytest.mark.device_agnostic@pytest.mark.parametrize(("kernel_size", "drawn"), [((3, 5), [3]), ((3, 7), [3, 5]), ((5, 11), [5, 7, 9])])def test_wart_random_motion_blur_upper_bound_is_never_drawn_4599(self, kernel_size, drawn):torch.manual_seed(_FORWARD_SEED)aug = K.RandomMotionBlur(kernel_size, (0.0, 0.0), (0.0, 0.0), p=1.0)- factors = aug.forward_parameters((20000, 1, 8, 8))["ksize_factor"]+ factors = torch.cat([aug.forward_parameters((1, 1, 8, 8))["ksize_factor"] for _ in range(20000)])assert sorted(set(factors[factors != kernel_size[1]].tolist())) == drawn# The requested upper bound is odd and admissible, and it is practically absent: at most a rounding# handful of 20000 draws, where a uniform draw over the odd sizes would give thousands.assert kernel_size[1] % 2 == 1 and kernel_size[1] not in drawnassert int((factors == kernel_size[1]).sum()) < 5- # Issue #4599, the other half: the per-sample draw is real, and a random index selects which one- # the batch gets -- so `_params["ksize_factor"]` holds B different values while one kernel is used.- @pytest.mark.device_agnostic- def test_wart_random_motion_blur_applies_one_randomly_indexed_kernel_size_4599(self):- picked = set()- distinct = 0- for seed in range(64):- torch.manual_seed(seed)- params = K.RandomMotionBlur((3, 21), (0.0, 0.0), (0.0, 0.0), p=1.0).forward_parameters((6, 3, 8, 8))- assert params["ksize_factor"].shape == (6,)- assert params["idx"].shape == (1,)- picked.add(int(params["idx"][0]))- distinct += len(set(params["ksize_factor"].tolist())) > 1- # Every row of the batch can be the one applied, so it is not "the first sample's".- assert picked == set(range(6))- # And the draw really is per sample: a constant `ksize_factor` would make `idx` immaterial.- assert distinct > 60- # The kernel that is applied is the one at `idx`, not the first sample's: `_params` alone cannot- # see that (`kernel_size_list[0]` in apply_transform left this pin green), so compare the output- # with the functional at `ksize_factor[idx]` on seeds where that differs from `ksize_factor[0]`.- torch.manual_seed(_FIXTURE_SEED)- image = torch.rand(6, 3, 8, 8)- checked = 0+ # Issue #4671: the stored sizes describe the shared kernel actually applied to every image.+ def test_convention_random_motion_blur_stored_kernel_sizes_match_impulse_widths_4671(self, device, dtype):+ image = torch.zeros(8, 1, 17, 17, device=device, dtype=dtype)+ image[:, :, 8, 8] = 1+ aug = K.RandomMotionBlur((3, 9), (0.0, 0.0), (0.0, 0.0), p=1.0)+ drawn = set()for seed in range(8):torch.manual_seed(seed)- aug = K.RandomMotionBlur((3, 21), (-45.0, 45.0), (-1.0, 1.0), p=1.0)- out = aug(image)- params = aug._params- idx = int(params["idx"][0])- applied, first = int(params["ksize_factor"][idx]), int(params["ksize_factor"][0])- reference = motion_blur(- image,- applied,- params["angle_factor"],- params["direction_factor"],- border_type="constant",- mode="nearest",- )- assert torch.equal(out, reference)- if applied != first:- assert not torch.equal(- out,- motion_blur(- image,- first,- params["angle_factor"],- params["direction_factor"],- border_type="constant",- mode="nearest",- ),- )- checked += 1- assert checked >= 3+ output = aug(image)+ # A horizontal, uniform blur spreads an impulse across exactly kernel_size pixels.+ widths = (output[:, 0, 8] != 0).sum(-1)+ assert widths.tolist() == aug._params["ksize_factor"].tolist()+ assert widths.unique().numel() == 1+ drawn.update(widths.tolist())+ assert len(drawn) > 1# Row 6c-24, the resampling caveat: the kernel's weights are laid on a line and then rotated, so# with ``border_type="reflect"`` a "nearest" or "bilinear" rotation keeps them non-negative and thediff --git a/tests/augmentation/test_motionblur.py b/tests/augmentation/test_motionblur.pyindex 8e171ae6b..cde019d78 100644--- a/tests/augmentation/test_motionblur.py+++ b/tests/augmentation/test_motionblur.py@@ -73,6 +73,37 @@ class TestRandomMotionBlur(BaseTester):self.assert_close(output, expected, rtol=1e-4, atol=1e-4)+ @pytest.mark.parametrize("kernel_size", [5, (3, 9)])+ @pytest.mark.parametrize("same_on_batch", [False, True])+ @pytest.mark.parametrize("p", [0.0, 0.5, 1.0])+ def test_seeded_parameters_and_replay(self, kernel_size, same_on_batch, p, device, dtype):+ torch.manual_seed(42)+ image = torch.rand(8, 1, 16, 16).to(device=device, dtype=dtype)+ aug = RandomMotionBlur(kernel_size, (-45.0, 45.0), (-1.0, 1.0), same_on_batch=same_on_batch, p=p)+ torch.manual_seed(0)+ output = aug(image)+ params = {key: value.clone() for key, value in aug._params.items()}+ torch.manual_seed(0)+ self.assert_close(aug(image), output, rtol=0, atol=0)+ for key, value in params.items():+ self.assert_close(aug._params[key], value, rtol=0, atol=0)+ self.assert_close(aug(image, params=params), output, rtol=0, atol=0)+ blurred = motion_blur(+ image, int(params["ksize_factor"][params["idx"][0]]), params["angle_factor"], params["direction_factor"]+ )+ expected = torch.where(params["batch_prob"].to(device=device).view(-1, 1, 1, 1) > 0.5, blurred, image)+ self.assert_close(output, expected)++ def test_replay_legacy_per_sample_kernel_sizes(self, device, dtype):+ torch.manual_seed(0)+ image = torch.rand(3, 1, 16, 16).to(device=device, dtype=dtype)+ aug = RandomMotionBlur((3, 9), (0.0, 0.0), (0.0, 0.0), p=1.0)+ params = aug.forward_parameters(image.shape)+ params["ksize_factor"] = torch.tensor([3, 5, 7], dtype=torch.int32)+ params["idx"] = torch.tensor([1])+ expected = motion_blur(image, 5, params["angle_factor"], params["direction_factor"])+ self.assert_close(aug(image, params=params), expected)+@pytest.mark.slowdef test_gradcheck(self, device):torch.manual_seed(0) # for random reproductibilitydiff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.pyindex b6cc47724..992726dfe 100644--- a/tests/augmentation/test_random_generator.py+++ b/tests/augmentation/test_random_generator.py@@ -1349,6 +1349,26 @@ class TestCenterCropGen(RandomGeneratorBaseTests):class TestRandomMotionBlur(RandomGeneratorBaseTests):+ @pytest.mark.parametrize("same_on_batch", [False, True])+ def test_shared_kernel_size_4671(self, same_on_batch, device, dtype):+ torch.manual_seed(0)+ gen = MotionBlurGenerator(+ (3, 9),+ torch.tensor([-45.0, 45.0], device=device, dtype=dtype),+ torch.tensor([-1.0, 1.0], device=device, dtype=dtype),+ )+ params = gen(torch.Size([8]), same_on_batch=same_on_batch)+ sizes = params["ksize_factor"]+ assert sizes.shape == (8,)+ assert sizes.device == device+ assert sizes.dtype == torch.int32+ assert sizes.unique().numel() == 1+ for name in ("angle_factor", "direction_factor"):+ assert params[name].shape == (8,)+ assert params[name].device == device+ assert params[name].dtype == dtype+ assert (params[name].unique().numel() == 1) == same_on_batch+@pytest.mark.parametrize("batch_size", [0, 1, 8])@pytest.mark.parametrize("kernel_size", [3, (3, 5)])@pytest.mark.parametrize("angle", [torch.tensor([10, 30])])