π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): keep PerspectiveGenerator3D's singleton-axis rule under torch.jit.trace (#5115)
εΊζ’η52df145f5ee5
diff --git a/changelog.d/5115.fixed.md b/changelog.d/5115.fixed.mdnew file mode 100644index 000000000..95167536c--- /dev/null+++ b/changelog.d/5115.fixed.md@@ -0,0 +1,5 @@+`RandomPerspective3D` traced with `torch.jit.trace` on a volume with a size-1 axis now matches eager mode instead of+raising a singular solve. The tracer passes the sizes as 0-d tensors, and both size-1 rules used to apply only to+Python integers: `PerspectiveGenerator3D` now gives a traced size-1 axis the unit source extent and zero corner offset+of eager mode, and `RandomPerspective3D` keeps, in the traced graph, the corner order that holds a size-1 width in+place. Eager parameters and outputs are unchanged (#5110).diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.pyindex 0fad0c1a9..5c4692d9e 100644--- a/kornia/augmentation/_3d/geometric/perspective.py+++ b/kornia/augmentation/_3d/geometric/perspective.py@@ -21,6 +21,7 @@ import torchfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.constants import Resamplefrom kornia.geometry import get_perspective_transform3d, warp_perspective3d@@ -110,10 +111,21 @@ class RandomPerspective3D(GeometricAugmentationBase3D):self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:start_points, end_points = params["start_points"], params["end_points"]- if isinstance(input.shape[-1], int) and input.shape[-1] == 1:- # The solver uses corners 0, 1, 2, 5, 7: only two lie on x=0. Swap the x/z or x/y- # corner ordering so three constrain each singleton plane to map onto itself.- order = [0, 4, 7, 3, 1, 5, 6, 2] if input.shape[-3] > 1 else [0, 3, 2, 1, 4, 7, 6, 5]+ width, depth = input.shape[-1], input.shape[-3]+ # The solver uses corners 0, 1, 2, 5, 7: only two lie on x=0. On a singleton x axis, swap the x/z+ # or x/y corner ordering so three constrain each singleton plane to map onto itself.+ if isinstance(width, torch.Tensor):+ # torch.jit.trace passes the sizes as 0-d tensors, so the order is selected in the graph (#5110).+ device = start_points.device+ singleton_order = torch.where(+ torch.as_tensor(depth, device=device) > 1,+ _constant_tensor([0, 4, 7, 3, 1, 5, 6, 2], device=device, dtype=torch.long),+ _constant_tensor([0, 3, 2, 1, 4, 7, 6, 5], device=device, dtype=torch.long),+ )+ order = torch.where(width.to(device) == 1, singleton_order, torch.arange(8, device=device))+ start_points, end_points = start_points[:, order], end_points[:, order]+ elif isinstance(width, int) and width == 1:+ order = [0, 4, 7, 3, 1, 5, 6, 2] if depth > 1 else [0, 3, 2, 1, 4, 7, 6, 5]start_points, end_points = start_points[:, order], end_points[:, order]return get_perspective_transform3d(start_points, end_points).to(input)diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.pyindex 41b598d4f..381757b47 100644--- a/kornia/augmentation/random_generator/_3d/perspective.py+++ b/kornia/augmentation/random_generator/_3d/perspective.py@@ -20,6 +20,7 @@ from typing import Dict, Tuple, Unionimport torchfrom torch.distributions import Uniform+from kornia.augmentation.random_generator._2d.perspective import _as_scalar_tensor, _source_end_and_extentfrom kornia.augmentation.random_generator.base import RandomGeneratorBasefrom kornia.augmentation.utils import _adapted_rsampling, _common_param_checkfrom kornia.augmentation.utils.helpers import _constant_tensor@@ -73,35 +74,49 @@ class PerspectiveGenerator3D(RandomGeneratorBase):_device, _dtype = _extract_device_dtype([self.distortion_scale])# Coincident source corners make the perspective solve singular. Give singleton axes a- # unit extent and no offset, as in the 2D generator.- flat_x = isinstance(width, int) and width == 1- flat_y = isinstance(height, int) and height == 1- flat_z = isinstance(depth, int) and depth == 1- x_end = 1 if flat_x else width - 1- y_end = 1 if flat_y else height - 1- z_end = 1 if flat_z else depth - 1-- start_points: torch.Tensor = _constant_tensor(- [+ # unit extent and no offset, as in the 2D generator. torch.jit.trace passes the sizes as+ # 0-d tensors, and the helper keeps the rule as tensor arithmetic there (#5110).+ x_end, x_extent = _source_end_and_extent(width)+ y_end, y_extent = _source_end_and_extent(height)+ z_end, z_extent = _source_end_and_extent(depth)++ if isinstance(x_end, torch.Tensor) or isinstance(y_end, torch.Tensor) or isinstance(z_end, torch.Tensor):+ # _constant_tensor is specified for Python scalars only, so build the corners from the traced sizes.+ x = _as_scalar_tensor(x_end, _device, _dtype)+ y = _as_scalar_tensor(y_end, _device, _dtype)+ z = _as_scalar_tensor(z_end, _device, _dtype)+ zero = torch.zeros((), device=_device, dtype=_dtype)+ start_points = torch.stack([- [0, 0, 0],- [x_end, 0, 0],- [x_end, y_end, 0],- [0, y_end, 0],- [0, 0, z_end],- [x_end, 0, z_end],- [x_end, y_end, z_end],- [0, y_end, z_end],- ]- ],- device=_device,- dtype=_dtype,- ).expand(batch_size, -1, -1)+ torch.stack([zero, x, x, zero, zero, x, x, zero]),+ torch.stack([zero, zero, y, y, zero, zero, y, y]),+ torch.stack([zero, zero, zero, zero, z, z, z, z]),+ ],+ dim=-1,+ ).unsqueeze(0)+ else:+ start_points = _constant_tensor(+ [+ [+ [0, 0, 0],+ [x_end, 0, 0],+ [x_end, y_end, 0],+ [0, y_end, 0],+ [0, 0, z_end],+ [x_end, 0, z_end],+ [x_end, y_end, z_end],+ [0, y_end, z_end],+ ]+ ],+ device=_device,+ dtype=_dtype,+ )+ start_points = start_points.expand(batch_size, -1, -1)# generate random offset not larger than half of the image- fx = self._distortion_scale * (0 if flat_x else width) / 2- fy = self._distortion_scale * (0 if flat_y else height) / 2- fz = self._distortion_scale * (0 if flat_z else depth) / 2+ fx = self._distortion_scale * x_extent / 2+ fy = self._distortion_scale * y_extent / 2+ fz = self._distortion_scale * z_extent / 2factor = torch.stack([fx, fy, fz], 0).view(-1, 1, 3).to(device=_device, dtype=_dtype)diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.pyindex f71594e56..c771a0b1b 100644--- a/tests/augmentation/test_conventions_3d.py+++ b/tests/augmentation/test_conventions_3d.py@@ -17,6 +17,8 @@from __future__ import annotations+import warnings+import pytestimport torch@@ -230,6 +232,25 @@ class Test3DAugmentationConventions(BaseTester):else:assert not torch.allclose(mapped[..., axis], points[..., axis], atol=1e-2)+ @pytest.mark.parametrize(+ "depth,height,width", [(1, 4, 5), (4, 1, 5), (4, 5, 1), (1, 1, 5), (1, 4, 1), (4, 1, 1), (1, 1, 1), (2, 3, 4)]+ )+ @pytest.mark.device_agnostic+ def test_convention_random_perspective3d_traced_singleton_matches_eager_5110(self, depth, height, width):+ # #5110: torch.jit.trace passes the sizes as 0-d tensors. The generator's unit extent and the corner order+ # that keeps a singleton x plane fixed both have to reach the traced graph; otherwise a size-1 depth or+ # height raises a singular solve and a size-1 width warps differently from eager.+ volume = torch.linspace(0, 1, 2 * depth * height * width).reshape(2, 1, depth, height, width)+ augmentation = K.RandomPerspective3D(0.5, p=1.0, align_corners=True)+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ traced = torch.jit.trace(augmentation, volume, check_trace=False)+ torch.manual_seed(0)+ output = traced(volume)+ torch.manual_seed(0)+ expected = augmentation(volume)+ self.assert_close(output, expected, rtol=1e-4, atol=1e-4)+@pytest.mark.device_agnosticdef test_wart_positive_roll_direction_splits_the_rotation_entry_points_4408(self):# An off-centre marker in a 7 x 7 slice: a counter-clockwise quarter turn sends (row 1, col 4) to (2, 1),diff --git a/tests/augmentation/test_random_generator_3d.py b/tests/augmentation/test_random_generator_3d.pyindex 7f9e3a89a..6d50d8ba3 100644--- a/tests/augmentation/test_random_generator_3d.py+++ b/tests/augmentation/test_random_generator_3d.py@@ -15,6 +15,7 @@# limitations under the License.#+import warningsfrom unittest.mock import patchimport pytest@@ -202,6 +203,50 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):assert_close(res["start_points"], expected["start_points"], atol=1e-4, rtol=1e-4)assert_close(res["end_points"], expected["end_points"], atol=1e-4, rtol=1e-4)+ @pytest.mark.parametrize("depth,height,width", [(1, 4, 4), (4, 1, 4), (4, 4, 1), (1, 1, 1), (2, 3, 5)])+ @pytest.mark.device_agnostic+ def test_traced_singleton_axis_5110(self, depth, height, width):+ # #5110: torch.jit.trace passes the sizes as 0-d tensors, so the size-1 rule of #5071 has to be tensor+ # arithmetic to reach the graph: a unit source extent and no corner offset along that axis. Every other axis+ # keeps the eager extent, so the traced parameters equal the eager ones for the same seed.+ class _Params(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.generator = PerspectiveGenerator3D(torch.tensor(1.0))++ def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ params = self.generator(x.shape)+ return params["start_points"], params["end_points"]++ volume = torch.zeros(2, 1, depth, height, width)+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ traced = torch.jit.trace(_Params(), volume, check_trace=False)+ torch.manual_seed(0)+ start, end = traced(volume)+ torch.manual_seed(0)+ eager = PerspectiveGenerator3D(torch.tensor(1.0))(volume.shape)++ x_end, y_end, z_end = max(width - 1, 1), max(height - 1, 1), max(depth - 1, 1)+ expected = torch.tensor(+ [+ [0.0, 0.0, 0.0],+ [x_end, 0.0, 0.0],+ [x_end, y_end, 0.0],+ [0.0, y_end, 0.0],+ [0.0, 0.0, z_end],+ [x_end, 0.0, z_end],+ [x_end, y_end, z_end],+ [0.0, y_end, z_end],+ ]+ ).expand(2, 8, 3)+ assert torch.equal(start, expected)+ assert torch.equal(start, eager["start_points"])+ assert torch.equal(end, eager["end_points"])+ for axis, size in ((0, width), (1, height), (2, depth)):+ if size == 1:+ assert torch.equal(end[..., axis], start[..., axis])+class TestRandomAffineGen3D(RandomGeneratorBaseTests):@pytest.mark.parametrize("batch_shape", [(0, 200, 300, 400), (1, 200, 300, 400), (8, 200, 300, 400)])