Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): keep RandomMotionBlur3D kernel_size inside its range (#4674)

Charan184595f66fa712e2
diff --git a/changelog.d/4674.fixed.md b/changelog.d/4674.fixed.md
new file mode 100644
index 000000000..b2f1da779
--- /dev/null
+++ b/changelog.d/4674.fixed.md
@@ -0,0 +1,7 @@
+`RandomMotionBlur3D` keeps a tuple `kernel_size` inside the range it was given. An even upper bound used to
+admit the odd size above it -- the `+ 1` was taken off `kernel_size[1] // 2` rather than off the largest odd
+size in the range -- so `(3, 4)` drew `5` and `(3, 20)` drew `21`. The upper bound is now the largest odd size
+not above `kernel_size[1]`. A `float32` draw landing on the sampler's open upper end is clamped back onto the
+range, where `(3, 5)` could otherwise draw `7`. A reversed range such as `(20, 3)` now raises a `ValueError` at
+construction; it used to be accepted and drew a constant `9`, outside both of its own bounds. A range holding
+no odd size still rounds up out of the range, so `(4, 4)` draws `5` as before, matching the 2D generator. (#4674)
diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.py
index 2bea1cf62..ff19fc4b4 100644
--- a/kornia/augmentation/_3d/intensity/motion_blur.py
+++ b/kornia/augmentation/_3d/intensity/motion_blur.py
@@ -61,6 +61,11 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):
Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
applied transformation will be merged int to the input transformation torch.Tensor and returned.
+ A tuple ``kernel_size`` is drawn once per call and shared across the batch, and each odd size inside
+ the range is equally likely, bounds included, so ``(3, 5)`` draws ``3`` and ``5`` and ``(3, 20)`` draws
+ ``3, 5, ..., 19``. A range holding no odd size is rounded **up** out of the requested range instead, so
+ ``(4, 4)`` draws ``5``; a reversed pair such as ``(20, 3)`` raises a ``ValueError`` at construction.
+
Examples:
>>> import torch
>>> rng = torch.manual_seed(0)
diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.py
index 51f50b7ad..d1d8c296c 100644
--- a/kornia/augmentation/random_generator/_3d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py
@@ -82,13 +82,24 @@ class MotionBlurGenerator3D(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)
+ self._ksize_half_max = self.kernel_size // 2
elif isinstance(self.kernel_size, tuple):
# kernel_size is fixed across the batch
if 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 + 1, validate_args=False
- )
+ # 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. hi is the largest odd size not above the upper bound --
+ # taking `+ 1` off `ks[1] // 2` instead admitted the size `ks[1] + 1` for an even `ks[1]`, so
+ # (3, 4) drew 5. `max(half_lo, ...)` keeps a range holding no odd size, such as (4, 4),
+ # rounding up to 5 as before, matching the 2D generator after #4610.
+ 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_hi
else:
raise TypeError(f"Unsupported type: {type(self.kernel_size)}")
@@ -111,10 +122,13 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
if isinstance(self.kernel_size, tuple):
# A ranged kernel size is sampled once per call and shared across the batch.
- ksize_factor = _adapted_rsampling((1,), self.ksize_sampler, same_on_batch).int() * 2 + 1
+ ksize_half = _adapted_rsampling((1,), self.ksize_sampler, 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 + 1
ksize_factor = ksize_factor.expand(batch_size)
else:
- ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1
+ ksize_half = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).floor()
+ ksize_factor = ksize_half.clamp_max(self._ksize_half_max).int() * 2 + 1
return {
"ksize_factor": ksize_factor.to(device=_device, dtype=torch.int32),
diff --git a/tests/augmentation/test_random_generator_3d.py b/tests/augmentation/test_random_generator_3d.py
index 20d05ffbc..2e066dc0b 100644
--- a/tests/augmentation/test_random_generator_3d.py
+++ b/tests/augmentation/test_random_generator_3d.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+from unittest.mock import patch
+
import pytest
import torch
@@ -724,8 +726,11 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
assert seen == {3, 5, 7}
+ # Issue #4672: an even upper bound used to admit the odd size above it -- `ks[1] // 2 + 1` took the
+ # `+ 1` off `ks[1] // 2` rather than off the largest odd size in the range -- so (3, 20) drew 21 and
+ # (3, 4) drew 5. The bound is now the largest odd size not above `ks[1]`, as in 2D after #4610.
@pytest.mark.device_agnostic
- def test_ranged_kernel_size_even_upper_bound_rounds_up(self, device, dtype):
+ def test_ranged_kernel_size_even_upper_bound_caps_at_largest_odd(self, device, dtype):
param_gen = MotionBlurGenerator3D(
kernel_size=(3, 20),
angle=torch.tensor([(0.0, 0.0)] * 3, device=device, dtype=dtype),
@@ -738,4 +743,55 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
res = param_gen(batch_shape=torch.Size((1,)), same_on_batch=False)
seen.add(int(res["ksize_factor"][0]))
- assert seen == {3, 5, 7, 9, 11, 13, 15, 17, 19, 21}
+ assert seen == {3, 5, 7, 9, 11, 13, 15, 17, 19}
+
+ # A range holding no odd size keeps rounding up out of the range, which 2D documents as well: the
+ # half-size floor is taken from the lower bound, so (4, 4) draws 5 and (2, 2) draws 3.
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(("kernel_size", "expected"), [((4, 4), 5), ((2, 2), 3)])
+ def test_ranged_kernel_size_without_an_odd_size_rounds_up(self, kernel_size, expected, device, dtype):
+ param_gen = MotionBlurGenerator3D(
+ kernel_size=kernel_size,
+ angle=torch.tensor([(0.0, 0.0)] * 3, device=device, dtype=dtype),
+ direction=torch.tensor([0.0, 0.0], device=device, dtype=dtype),
+ )
+
+ seen = set()
+ for seed in range(200):
+ torch.manual_seed(seed)
+ res = param_gen(batch_shape=torch.Size((1,)), same_on_batch=False)
+ seen.add(int(res["ksize_factor"][0]))
+
+ assert seen == {expected}
+
+ # The sampler is half-open on [lo, hi + 1), so a float32 draw can round up onto `hi + 1` itself and
+ # leave the range. Forcing the largest float below 1 through the sampler used to draw 7 for (3, 5).
+ @pytest.mark.device_agnostic
+ def test_ranged_kernel_size_top_draw_stays_in_range(self, device, dtype):
+ param_gen = MotionBlurGenerator3D(
+ kernel_size=(3, 5),
+ angle=torch.tensor([(0.0, 0.0)] * 3, device=device, dtype=dtype),
+ direction=torch.tensor([0.0, 0.0], device=device, dtype=dtype),
+ )
+ param_gen.make_samplers(device, dtype)
+
+ def _top_draw(*args, **kwargs):
+ shape = args[0] if args else kwargs["size"]
+ forwarded = {k: v for k, v in kwargs.items() if k in ("dtype", "device")}
+ return torch.full(shape, 1 - 2**-24, **forwarded)
+
+ with patch("torch.rand", _top_draw):
+ res = param_gen(batch_shape=torch.Size((4,)), same_on_batch=False)
+
+ assert int(res["ksize_factor"].max()) == 5
+
+ # A reversed pair used to be accepted and drew a constant above *both* bounds: (20, 3) drew 9.
+ @pytest.mark.device_agnostic
+ def test_reversed_kernel_size_raises(self, device, dtype):
+ # `make_samplers` runs from `__post_init__`, so the pair is refused as the generator is built.
+ with pytest.raises(ValueError, match="should be smaller than or equal to"):
+ MotionBlurGenerator3D(
+ kernel_size=(20, 3),
+ angle=torch.tensor([(0.0, 0.0)] * 3, device=device, dtype=dtype),
+ direction=torch.tensor([0.0, 0.0], device=device, dtype=dtype),
+ )