π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): infer Affine defaults from shear (#5715)
peng xiangf942e56804fa
diff --git a/changelog.d/5715.breaking.md b/changelog.d/5715.breaking.mdnew file mode 100644index 000000000..965c8d0f9--- /dev/null+++ b/changelog.d/5715.breaking.md@@ -0,0 +1,10 @@+`Affine` now uses `shear` like `angle`, `translation` and `scale_factor` when it creates the parameters it was not+given and when it checks that its parameters share one device and dtype. An `Affine` given only `shear` now creates its+default rotation, translation and scale on the shear's device and in its dtype, so it works on float64, float16 and+bfloat16 inputs and on accelerators. Before, those defaults were float32 tensors on the default device, and the forward+raised `ValueError` on any other input. A `shear` on another device or of another dtype than the other parameters now+raises `DeviceError` or `TypeCheckError` when the module is built, as a mismatch among `angle`, `translation` and+`scale_factor` already did. Before, such a module was built and its forward raised, except for a `shear` of lower+precision than parameters matching the input (a float32 `shear` with a float64 `angle` on a float64 image), which+worked. An integer `shear` given alone now gets integer defaults, and its forward raises `ValueError`, as it already+did for an integer `angle`, `translation` or `scale_factor` given alone; before, it was combined with float32 defaults.diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex c80dd7915..eb1d1ec5e 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -915,6 +915,9 @@ class Affine(nn.Module):Raises:RuntimeError: If not one of ``angle``, ``translation``, ``scale_factor``, or ``shear`` is set.+ DeviceError: If ``angle``, ``translation``, ``scale_factor`` and ``shear`` are not all on one device.+ TypeCheckError: If they are on one device but do not all have one dtype. The ones not given are+ created on that device and in that dtype.Returns:The transformed tensor with same shape as input.@@ -954,7 +957,7 @@ class Affine(nn.Module):self._batch_size = batch_sizesuper().__init__()- device, dtype = _extract_device_dtype([angle, translation, scale_factor])+ device, dtype = _extract_device_dtype([angle, translation, scale_factor, shear])if angle is None:angle = torch.zeros(batch_size, device=device, dtype=dtype)diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.pyindex 31bde55ef..f9e26727c 100644--- a/tests/geometry/transform/test_affine.py+++ b/tests/geometry/transform/test_affine.py@@ -21,6 +21,7 @@ import pytestimport torchimport kornia+from kornia.core.exceptions import DeviceError, TypeCheckErrorfrom testing.base import BaseTester@@ -752,6 +753,29 @@ class TestAffine2d(BaseTester):expected = kornia.geometry.transform.scale(input, scale_factor)self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)+ @pytest.mark.parametrize("batch_size", [1, 3])+ def test_affine_shear_only_5662(self, device, dtype, batch_size):+ shear = torch.tensor([[0.1, -0.2]], device=device, dtype=dtype).repeat(batch_size, 1)+ image = torch.arange(batch_size * 30, device=device, dtype=dtype).reshape(batch_size, 1, 5, 6) / 30+ # Explicit identity components define the same shear without relying on constructor defaults.+ expected = kornia.geometry.transform.Affine(+ angle=torch.zeros(batch_size, device=device, dtype=dtype),+ translation=torch.zeros(batch_size, 2, device=device, dtype=dtype),+ scale_factor=torch.ones(batch_size, 2, device=device, dtype=dtype),+ shear=shear,+ )(image)+ actual = kornia.geometry.transform.Affine(shear=shear)(image)+ self.assert_close(actual, expected)++ def test_affine_shear_checked_with_other_parameters_5662(self, device, dtype):+ # shear takes part in the constructor's device and dtype check, as angle, translation and scale_factor do.+ shear = torch.tensor([[0.1, -0.2]], device=device, dtype=dtype)+ other = torch.float16 if dtype != torch.float16 else torch.float32 # float64 is unavailable on MPS+ with pytest.raises(TypeCheckError):+ kornia.geometry.transform.Affine(angle=torch.zeros(1, device=device, dtype=other), shear=shear)+ with pytest.raises(DeviceError):+ kornia.geometry.transform.Affine(angle=torch.zeros(1, device="meta", dtype=dtype), shear=shear)+@pytest.mark.parametrize("as_module", [False, True])def test_convention_shear_raw_factors_5661(self, device, dtype, as_module):# Both off-diagonal factors act on the original coordinates, about pixel (0, 0).@@ -792,9 +816,8 @@ class TestAffine2d(BaseTester):expected = torch.zeros_like(image)row, col = (6, 2) if custom_center else (8, 3)expected[0, 0, row, col] = 1- # Explicit typed zero rotation avoids the separate shear-only dtype/device inference bug (#5662).transform = kornia.geometry.transform.Affine(- angle=angle, shear=shear, center=center if custom_center else None, mode="nearest", align_corners=True+ shear=shear, center=center if custom_center else None, mode="nearest", align_corners=True)self.assert_close(transform(image), expected)@@ -805,9 +828,7 @@ class TestAffine2d(BaseTester):image = torch.zeros(1, 1, 9, 9, device=device, dtype=dtype)image[0, 0, 8, 4] = 1sheared = kornia.geometry.transform.shear(image, shear, mode="nearest", align_corners=True)- # a typed zero angle, as above (#5662)- angle = torch.zeros(1, device=device, dtype=dtype)- affine = kornia.geometry.transform.Affine(angle=angle, shear=shear, mode="nearest", align_corners=True)+ affine = kornia.geometry.transform.Affine(shear=shear, mode="nearest", align_corners=True)assert sheared[0, 0, 8].argmax().item() == 8assert affine(image)[0, 0, 8].argmax().item() == 2@@ -1032,6 +1053,7 @@ class TestTransformModuleBuffers(BaseTester):("Rotate", "angle", [17.0]),("Scale", "scale_factor", [[0.8, 1.2]]),("Affine", "angle", [17.0]),+ ("Affine", "shear", [[0.1, -0.05]]),("Translate", "translation", [[0.4, -0.2]]),("Shear", "shear", [[0.1, -0.05]]),],