π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): draw the upper kernel_size bound in RandomMotionBlur (#4610)
Dipak Chaudharif49828523fd6
diff --git a/changelog.d/4610.breaking.md b/changelog.d/4610.breaking.mdnew file mode 100644index 000000000..14858b363--- /dev/null+++ b/changelog.d/4610.breaking.md@@ -0,0 +1 @@+`RandomMotionBlur` and `MotionBlurGenerator` now raise `ValueError` at construction for a reversed `kernel_size` range such as `(20, 3)`. Previously a reversed range was silently sampled as if it were ordered: `(20, 3)` drew the odd sizes `3` to `19`.diff --git a/changelog.d/4610.fixed.md b/changelog.d/4610.fixed.mdnew file mode 100644index 000000000..55d5c2459--- /dev/null+++ b/changelog.d/4610.fixed.md@@ -0,0 +1 @@+`RandomMotionBlur` now draws every odd size in a `kernel_size` range with equal probability, the upper bound included. Previously the upper bound was practically never drawn (only when a float32 draw rounded onto it), so `kernel_size=(3, 5)` practically always blurred with `3` and `(3, 7)` drew practically only `3` and `5`. An even upper bound caps at the largest odd size below it, and a range holding no odd size still rounds up, so `(4, 4)` draws `5` as before. Because the larger sizes are now drawn, `kernel_size=(3, 5)` with `border_type="reflect"` on a `2 x 2` image raises for roughly half the draws, where the constant `3` always fit. A two-element list such as `kernel_size=[3, 9]` is now accepted as a range, like a tuple, instead of raising `TypeError`.diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.pyindex dc01c11b4..6f079b24a 100644--- a/kornia/augmentation/_2d/intensity/base.py+++ b/kornia/augmentation/_2d/intensity/base.py@@ -88,11 +88,15 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):admits and :func:`kornia.filters.gaussian_blur2d` rejects;:class:`RandomMedianBlur`'s even ``kernel_size``, which raises a raw torch error the same way;:class:`RandomRain`'s drop-size bounds; a tuple ``kernel_size`` for :class:`RandomMotionBlur` whose- drawn odd size is below ``3`` -- an even bound is rounded up to the next odd size rather than- rejected, and that rounding can leave the requested range, so ``(4, 4)`` draws ``5`` and ``(2, 2)``- draws ``3``, while ``(0, 2)`` raises because the odd size it rounds to is ``1``. That same- truncation means the range's upper bound is practically never drawn -- ``kernel_size=(3, 5)`` is a- constant ``3`` (`#4599 <https://github.com/kornia/kornia/issues/4599>`_);+ drawn odd size is below ``3`` -- a range that holds no odd size is rounded up to the next odd size+ rather than rejected, which leaves the requested range, so ``(4, 4)`` draws ``5`` and ``(2, 2)``+ draws ``3``, while ``(0, 2)`` raises because the only odd size it holds is ``1``. Since every+ odd size in the range is now drawn rather than the smallest one almost always, a range that+ straddles ``3`` raises only on the draws below it: ``(0, 3)`` and ``(1, 3)`` raise on about half+ the seeds instead of all of them, and the same applies to the image-size rule above -- the larger+ sizes are live against it for the first time, so ``kernel_size=(3, 5)`` with+ ``border_type="reflect"`` on a ``2 x 2`` image raises for roughly half the draws where the+ constant ``3`` always fit. A reversed pair such as ``(5, 3)`` raises at construction;and :class:`RandomChannelDropout`'s ``num_drop_channels`` against the input's channel count.:class:`RandomPlanckianJitter`'s ``select_from`` rejects an index past the table at constructionbut accepts a negative one, as Python indexing does. A scalar magnitude ``x`` means ``center Β± x``:diff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.pyindex 6ac09ccb6..0f0f17a12 100644--- a/kornia/augmentation/_2d/intensity/motion_blur.py+++ b/kornia/augmentation/_2d/intensity/motion_blur.py@@ -36,7 +36,8 @@ 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 one value from the range for the whole batch.+ If Tuple[int, int] or a two-element list, it will randomly generate one odd value from the closed+ 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.@@ -69,11 +70,13 @@ class RandomMotionBlur(IntensityAugmentationBase2D):with shape ``(B,)``. All samples use that size, even with ``same_on_batch=False``; angle anddirection are sampled per image unless ``same_on_batch=True``. Previously saved parameterswith 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 when- the ``float32`` draw rounds onto it, about once in ``2**24`` -- and ``kernel_size=(3, 5)`` is a- constant ``3`` while ``(3, 7)`` draws only ``3`` and ``5``. An even bound is separately rounded- **up** out of the requested range, so ``(4, 4)`` draws ``5``. Tracked in- `#4599 <https://github.com/kornia/kornia/issues/4599>`_.+ A tuple range draws each odd size inside it with equal probability, bounds included, so+ ``kernel_size=(3, 5)`` draws ``3`` and ``5`` and ``(3, 20)`` draws ``3, 5, ..., 19``. A range that+ holds no odd size is rounded **up** out of the requested range instead, so ``(4, 4)`` draws ``5``;+ a reversed one such as ``(20, 3)`` raises at construction. Because the whole range is drawn, and+ not just its lowest odd size, every size in it is live against the image-size rule below: with+ ``border_type="reflect"`` a ``kernel_size=(3, 5)`` on a ``2 x 2`` image raises on the draws of+ ``5`` -- about half of them -- where a constant ``3`` always fit.- the output is not clamped. At the default ``border_type="constant"`` the padding is zeros, so aborder pixel is blended with ``0`` and pulled toward it: below the input's own minimum for apositive image, and above its maximum for a negative one. With@@ -119,7 +122,7 @@ class RandomMotionBlur(IntensityAugmentationBase2D):def __init__(self,- kernel_size: Union[int, Tuple[int, int]],+ kernel_size: Union[int, Tuple[int, int], List[int]],angle: Union[torch.Tensor, float, Tuple[float, float]],direction: Union[torch.Tensor, float, Tuple[float, float]],border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.pyindex d5aadb4e5..497d4be38 100644--- a/kornia/augmentation/random_generator/_2d/motion_blur.py+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py@@ -15,7 +15,7 @@# limitations under the License.#-from typing import Dict, Tuple, Union+from typing import Dict, List, Tuple, Unionimport torch@@ -32,7 +32,8 @@ 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 one value from the range for the whole batch.+ If Tuple[int, int] or a two-element list, it will randomly generate one odd value from the closed+ 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.@@ -57,7 +58,7 @@ class MotionBlurGenerator(RandomGeneratorBase):def __init__(self,- kernel_size: Union[int, Tuple[int, int]],+ kernel_size: Union[int, Tuple[int, int], List[int]],angle: Union[torch.Tensor, float, Tuple[float, float]],direction: Union[torch.Tensor, float, Tuple[float, float]],) -> None:@@ -76,13 +77,26 @@ class MotionBlurGenerator(RandomGeneratorBase):if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {self.kernel_size}.")self.ksize_sampler = UniformDistribution(self.kernel_size // 2, self.kernel_size // 2, validate_args=False)- elif isinstance(self.kernel_size, tuple):+ self._ksize_half_max = self.kernel_size // 2+ elif isinstance(self.kernel_size, (tuple, list)):# kernel_size is fixed across the batchif len(self.kernel_size) != 2:- raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple. Got {self.kernel_size}.")- self.ksize_sampler = UniformDistribution(- self.kernel_size[0] // 2, self.kernel_size[1] // 2, validate_args=False- )+ raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple or list. Got {self.kernel_size}.")+ # Draw the half-size h of the odd kernel 2h + 1 on [lo, hi + 1) and floor it, so every h in the+ # closed [lo, hi] is equally likely; truncating a draw on [lo, hi) never reached hi.+ # hi is the largest odd size not above the upper bound, and never below lo, which keeps an+ # even-only range such as (4, 4) drawing 5 as before.+ # A reversed pair is refused: the old sampler silently drew it as if ordered (`(20, 3)` drew+ # 3..19), and the `max(half_lo, ...)` below would turn it into a draw above *both* bounds.+ # #4568 set the precedent for RandomRain's closed integer ranges.+ if self.kernel_size[0] > self.kernel_size[1]:+ raise ValueError(+ f"`kernel_size`[0] should be smaller than or equal to `kernel_size`[1]. Got {self.kernel_size}."+ )+ half_lo = self.kernel_size[0] // 2+ half_hi = max(half_lo, (self.kernel_size[1] - 1) // 2)+ self.ksize_sampler = UniformDistribution(half_lo, half_hi + 1, validate_args=False)+ self._ksize_half_max = half_hielse:raise TypeError(f"Unsupported type: {type(self.kernel_size)}")@@ -97,8 +111,10 @@ class MotionBlurGenerator(RandomGeneratorBase):angle_factor = _adapted_rsampling((batch_size,), self.angle_sampler, same_on_batch)direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)# 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 + 1+ ksize_same_on_batch = same_on_batch or isinstance(self.kernel_size, (tuple, list))+ ksize_half = _adapted_rsampling((batch_size,), self.ksize_sampler, ksize_same_on_batch).floor()+ # A float32 draw can round up onto the open upper end, hi + 1; keep it inside the closed range.+ ksize_factor = ksize_half.clamp_max(self._ksize_half_max).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 6b5406a23..6d54cb29a 100644--- a/tests/augmentation/test_conventions_intensity_ops.py+++ b/tests/augmentation/test_conventions_intensity_ops.py@@ -376,20 +376,43 @@ class TestBlurConventions(BaseTester):assert aug.flags["border_type"] == BorderType.CONSTANTassert aug.flags["resample"] == Resample.NEAREST- # 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.+ # Issue #4599: the half-size is drawn on `[lo, hi + 1)` and floored, so every odd size in the requested+ # range is drawn, bounds included, in near-equal shares; the draw used to truncate a float on `[lo, hi)`,+ # which made `(3, 5)` a constant 3. This is the same remedy RandomRain took for #4567. An even upper+ # bound caps at the largest odd size below it, and a range holding no odd size still rounds up (`(4, 4)`+ # draws 5). The kernel size is shared within each batch (#4671), so the pin samples independent calls.+ # Snippet used to generate expected:+ # import collections+ # for ks in ((3, 5), (3, 7), (5, 11), (3, 20), (4, 7), (4, 4)):+ # torch.manual_seed(0)+ # aug = K.RandomMotionBlur(ks, (0., 0.), (0., 0.), p=1.)+ # v = torch.cat([aug.forward_parameters((1, 1, 8, 8))["ksize_factor"] for _ in range(20000)])+ # print(ks, dict(sorted(collections.Counter(v.tolist()).items())))+ # executed 2026-09-21 (torch 2.14.0, cpu) -> `{3: 9984, 5: 10016}`, `{3: 6656, 5: 6675, 7: 6669}`,+ # `{5: 4975, 7: 5009, 9: 5025, 11: 4991}`, `{3: 2189, ..., 19: 2224}` (nine sizes), `{5: 9984, 7: 10016}`,+ # `{5: 20000}`.@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):+ @pytest.mark.parametrize(+ ("kernel_size", "drawn"),+ [+ ((3, 5), [3, 5]),+ ((3, 7), [3, 5, 7]),+ ((5, 11), [5, 7, 9, 11]),+ ((3, 20), [3, 5, 7, 9, 11, 13, 15, 17, 19]),+ ((4, 7), [5, 7]),+ ((4, 4), [5]),+ ],+ )+ def test_convention_random_motion_blur_draws_every_odd_size_in_the_range_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 = 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 drawn- assert int((factors == kernel_size[1]).sum()) < 5+ counts = torch.stack([(factors == k).sum() for k in drawn])+ assert sorted(set(factors.tolist())) == drawn+ # Near-equal shares: each size within 10% of 20000 / len(drawn), where the old truncation left the+ # upper bound at a rounding handful.+ expected = 20000 / len(drawn)+ assert bool(((counts - expected).abs() < 0.1 * expected).all()), counts.tolist()# 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):diff --git a/tests/augmentation/test_motionblur.py b/tests/augmentation/test_motionblur.pyindex cde019d78..f85db7a5a 100644--- a/tests/augmentation/test_motionblur.py+++ b/tests/augmentation/test_motionblur.py@@ -65,7 +65,8 @@ class TestRandomMotionBlur(BaseTester):expected = motion_blur(input,- f._params["ksize_factor"].unique().item(),+ # The whole batch is blurred with the kernel size at `idx`; the per-sample draws can differ.+ int(f._params["ksize_factor"][f._params["idx"][0]]),f._params["angle_factor"],f._params["direction_factor"],f.flags["border_type"].name.lower(),diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.pyindex 992726dfe..9ff711a64 100644--- a/tests/augmentation/test_random_generator.py+++ b/tests/augmentation/test_random_generator.py@@ -15,11 +15,14 @@# limitations under the License.#+from typing import Any+from unittest.mock import patch+import pytestimport torchfrom torch import Tensor-from kornia.augmentation import RandomGaussianBlur+from kornia.augmentation import RandomGaussianBlur, RandomMotionBlurfrom kornia.augmentation.random_generator import (AffineGenerator,ColorJiggleGenerator,@@ -1437,6 +1440,59 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):assert_close(res["angle_factor"], expected["angle_factor"], rtol=1e-4, atol=1e-4)assert_close(res["direction_factor"], expected["direction_factor"], rtol=1e-4, atol=1e-4)+ @pytest.mark.parametrize("kernel_size, expected", [((3, 5), 5), ((5, 11), 11), ((11, 41), 41)])+ def test_kernel_size_draw_rounded_onto_the_open_end_stays_in_range_4599(self, kernel_size, expected, device, dtype):+ # The half-size sampler is uniform on [lo, hi + 1); the top float32 draw is+ # lo + (1 - 2**-24) * (hi + 1 - lo), which for these ranges lands exactly on hi + 1 and would+ # floor one odd size above the cap. Drive the real sampler to that draw rather than swapping+ # in one production cannot build, so the pin records that the escape exists as well as that+ # the clamp catches it. It is reachable from the default sampler about once in 2**24 draws.+ gen = MotionBlurGenerator(+ kernel_size=kernel_size, angle=torch.tensor([0.0, 0.0]), direction=torch.tensor([0.0, 0.0])+ )+ gen.set_rng_device_and_dtype(device, dtype)+ top = torch.nextafter(torch.ones(1, dtype=torch.float32), torch.zeros(1, dtype=torch.float32)).item()+ real_rand = torch.rand++ def _top_draw(*args: Any, **kwargs: Any) -> torch.Tensor:+ return torch.full_like(real_rand(*args, **kwargs), top)++ with patch("torch.rand", _top_draw):+ drawn = gen(torch.Size([4]))["ksize_factor"]+ assert drawn.tolist() == [expected] * 4++ def test_a_list_kernel_size_range_is_drawn_like_a_tuple_4599(self, device, dtype):+ # A two-element list is a range exactly as a tuple is: one kernel size shared by the batch, and+ # every odd size in the closed range drawn, the upper bound included. A list used to raise+ # TypeError, and the shared-draw condition checked `tuple` only.+ torch.manual_seed(0)+ gen = MotionBlurGenerator(+ kernel_size=[3, 9], angle=torch.tensor([0.0, 0.0]), direction=torch.tensor([0.0, 0.0])+ )+ gen.set_rng_device_and_dtype(device, dtype)+ seen = set()+ for _ in range(200):+ drawn = gen(torch.Size([8]))["ksize_factor"]+ assert drawn.unique().numel() == 1, drawn.tolist()+ seen.add(int(drawn[0]))+ assert seen == {3, 5, 7, 9}+ with pytest.raises(ValueError, match=r"`kernel_size`\[0\] should be smaller than or equal to"):+ MotionBlurGenerator(kernel_size=[9, 3], angle=torch.tensor([0.0, 0.0]), direction=torch.tensor([0.0, 0.0]))++ def test_a_reversed_kernel_size_range_is_refused_4599(self, device, dtype):+ # A reversed pair used to be drawn silently as if ordered -- `(20, 3)` drew 3..19 -- and+ # `half_hi = max(half_lo, ...)` would turn it into a draw above BOTH bounds, so the ordering is+ # refused, as #4568 refuses it for RandomRain's closed integer ranges.+ # the generator builds its samplers in __post_init__, so this is a construction-time raise+ with pytest.raises(ValueError, match=r"`kernel_size`\[0\] should be smaller than or equal to"):+ MotionBlurGenerator(kernel_size=(20, 3), angle=torch.tensor([0.0, 0.0]), direction=torch.tensor([0.0, 0.0]))+ with pytest.raises(ValueError, match=r"`kernel_size`\[0\] should be smaller than or equal to"):+ RandomMotionBlur((20, 3), (0.0, 0.0), (0.0, 0.0), p=1.0)+ # the degenerate equal pair is not reversed and still draws+ ok = MotionBlurGenerator(kernel_size=(5, 5), angle=torch.tensor([0.0, 0.0]), direction=torch.tensor([0.0, 0.0]))+ ok.set_rng_device_and_dtype(device, dtype)+ assert ok(torch.Size([4]))["ksize_factor"].tolist() == [5, 5, 5, 5]+class TestRandomPosterizeGen(RandomGeneratorBaseTests):@pytest.mark.parametrize("batch_size", [0, 1, 8])