π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): bound the 3D angle ranges like the 2D ones (#4644)
Dipak Chaudhari2f89c4e2f993
diff --git a/changelog.d/4644.breaking.md b/changelog.d/4644.breaking.mdnew file mode 100644index 000000000..9aaf69ec5--- /dev/null+++ b/changelog.d/4644.breaking.md@@ -0,0 +1 @@+The 3D augmentations now reject an angle range wider than one turn at construction, as the 2D ones do: `RandomRotation3D`, `RandomAffine3D` (`degrees` and `shears`) and `RandomMotionBlur3D` raise `ValueError` for a scalar or explicit range past `Β±360`, where they used to sample from it.diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.pyindex 9b2d4ea59..0b8deb4f6 100644--- a/kornia/augmentation/random_generator/_3d/affine.py+++ b/kornia/augmentation/random_generator/_3d/affine.py@@ -122,10 +122,10 @@ class AffineGenerator3D(RandomGeneratorBase):return reprdef make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:- degrees = _tuple_range_reader(self.degrees, 3, device, dtype)+ degrees = _tuple_range_reader(self.degrees, 3, device, dtype, "degrees", (-360, 360))shear: Optional[torch.Tensor] = Noneif self.shears is not None:- shear = _tuple_range_reader(self.shears, 6, device, dtype)+ shear = _tuple_range_reader(self.shears, 6, device, dtype, "shears", (-360, 360))self.sxy_sampler = UniformDistribution(shear[0, 0], shear[0, 1], validate_args=False)self.sxz_sampler = UniformDistribution(shear[1, 0], shear[1, 1], validate_args=False)self.syx_sampler = UniformDistribution(shear[2, 0], shear[2, 1], validate_args=False)diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.pyindex 50e8d3be9..3a5930876 100644--- a/kornia/augmentation/random_generator/_3d/motion_blur.py+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py@@ -74,7 +74,9 @@ class MotionBlurGenerator3D(RandomGeneratorBase):return reprdef make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:- angle: torch.Tensor = _tuple_range_reader(self.angle, 3, device=device, dtype=dtype)+ angle: torch.Tensor = _tuple_range_reader(+ self.angle, 3, device=device, dtype=dtype, name="angle", bounds=(-360, 360)+ )direction = _range_bound(self.direction, "direction", center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)if isinstance(self.kernel_size, int):if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.pyindex fba2d0037..bc028f726 100644--- a/kornia/augmentation/random_generator/_3d/rotation.py+++ b/kornia/augmentation/random_generator/_3d/rotation.py@@ -67,7 +67,7 @@ class RotationGenerator3D(RandomGeneratorBase):return reprdef make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:- degrees = _tuple_range_reader(self.degrees, 3, device, dtype)+ degrees = _tuple_range_reader(self.degrees, 3, device, dtype, "degrees", (-360, 360))self.yaw_sampler = UniformDistribution(degrees[0][0], degrees[0][1], validate_args=False)self.pitch_sampler = UniformDistribution(degrees[1][0], degrees[1][1], validate_args=False)self.roll_sampler = UniformDistribution(degrees[2][0], degrees[2][1], validate_args=False)diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.pyindex 408bc2425..3d6616925 100644--- a/kornia/augmentation/utils/param_validation.py+++ b/kornia/augmentation/utils/param_validation.py@@ -189,11 +189,17 @@ def _tuple_range_reader(target_size: int,device: Optional[torch.device] = None,dtype: Optional[torch.dtype] = None,+ name: str = "input_range",+ bounds: Optional[Tuple[float, float]] = None,) -> torch.Tensor:"""Given target_size, it will generate the corresponding (target_size, 2) range torch.Tensor.This is for element-wise params.+ Every read range is checked against ``bounds``, when given, the way :func:`_range_bound` checks+ the 2D scalar and explicit forms, so a 3D angle past one turn raises at construction instead of+ being sampled (#4617). ``name`` only names the parameter in that error.+Example:>>> degree = torch.tensor([0.2, 0.3])>>> _tuple_range_reader(degree, 3) # read degree for yaw, pitch and roll.@@ -264,4 +270,8 @@ def _tuple_range_reader(f"{target_size} floats or {target_size} (float, float) for independent operation. Got {input_range}.")+ if bounds is not None:+ for row in input_range_tmp:+ _joint_range_check(row, name, bounds)+return input_range_tmpdiff --git a/tests/augmentation/test_param_validation.py b/tests/augmentation/test_param_validation.pyindex c1d32577f..5c2a0c177 100644--- a/tests/augmentation/test_param_validation.py+++ b/tests/augmentation/test_param_validation.py@@ -210,3 +210,45 @@ class TestParamValidation:"""A scalar that overshoots a geometric parameter's bound is rejected at construction."""with pytest.raises(ValueError, match=match_msg):ctor()++ # The 3D readers took a scalar or an explicit range without any bound, so an angle past one+ # turn was sampled instead of rejected (#4617). Executed 2026-09-17 (torch 2.5.0, cpu).+ @pytest.mark.parametrize(+ "ctor, match_msg",+ [+ (lambda: K.RandomRotation3D(400.0), r"degrees out of bounds\. .*got tensor\(\[-400\., 400\.\]\)"),+ (+ lambda: K.RandomRotation3D((-400.0, 400.0)),+ r"degrees out of bounds\. .*got tensor\(\[-400\., 400\.\]\)",+ ),+ (lambda: K.RandomAffine3D(400.0), r"degrees out of bounds\. .*got tensor\(\[-400\., 400\.\]\)"),+ (+ lambda: K.RandomAffine3D(30.0, shears=400.0),+ r"shears out of bounds\. .*got tensor\(\[-400\., 400\.\]\)",+ ),+ (+ lambda: K.RandomMotionBlur3D(3, 400.0, 0.5),+ r"angle out of bounds\. .*got tensor\(\[-400\., 400\.\]\)",+ ),+ ],+ ids=["rotation3d-scalar", "rotation3d-range", "affine3d-degrees", "affine3d-shears", "motion-blur3d-angle"],+ )+ def test_3d_angle_past_one_turn_raises(self, ctor, match_msg):+ """A 3D angle range wider than one turn is rejected, as the 2D one is."""+ with pytest.raises(ValueError, match=match_msg):+ ctor()++ @pytest.mark.parametrize(+ "ctor",+ [+ lambda: K.RandomRotation3D(360.0),+ lambda: K.RandomRotation3D((-360.0, 360.0)),+ lambda: K.RandomRotation3D((10.0, 20.0, 30.0)),+ lambda: K.RandomAffine3D(30.0, shears=(10.0, 20.0, 30.0, 40.0, 50.0, 60.0)),+ lambda: K.RandomMotionBlur3D(3, 360.0, 0.5),+ ],+ ids=["at-the-bound", "explicit-at-the-bound", "per-axis", "per-axis-shears", "motion-blur-at-the-bound"],+ )+ def test_3d_angles_inside_the_bound_still_construct(self, ctor):+ """The bound is inclusive, and the per-axis forms are unaffected."""+ assert ctor() is not None