π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): keep RandomPerspective's size-1 rule in ONNX exports (#5089)
mohamed shaban30c76c9341c4
diff --git a/changelog.d/5089.fixed.md b/changelog.d/5089.fixed.mdnew file mode 100644index 000000000..fa081e6f6--- /dev/null+++ b/changelog.d/5089.fixed.md@@ -0,0 +1 @@+`RandomPerspective` exported with the legacy ONNX tracer now keeps a unit source extent on a size-1 axis, matching eager mode instead of returning zeros.diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.pyindex bf30571c1..1c4c58004 100644--- a/kornia/augmentation/random_generator/_2d/perspective.py+++ b/kornia/augmentation/random_generator/_2d/perspective.py@@ -28,6 +28,27 @@ from kornia.core.utils import _extract_device_dtype__all__ = ["PerspectiveGenerator"]+def _source_end_and_extent(+ size: Union[int, torch.Tensor],+) -> Tuple[Union[int, torch.Tensor], Union[int, torch.Tensor]]:+ """Return the last source coordinate and the corner-offset extent along one spatial axis.++ A size-1 axis would make two source corners coincide and the homography singular. It gets a+ unit extent and no offset instead, so its single row or column maps onto itself. The legacy+ ONNX tracer passes sizes as 0-d tensors; the rule then has to be tensor arithmetic, because+ a Python comparison is evaluated once at trace time and never reaches the exported graph.+ """+ if isinstance(size, torch.Tensor):+ return (size - 1).clamp(min=1), size * (size > 1)+ return (1, 0) if size == 1 else (size - 1, size)+++def _as_scalar_tensor(value: Union[int, torch.Tensor], device: torch.device, dtype: torch.dtype) -> torch.Tensor:+ if isinstance(value, torch.Tensor):+ return value.to(device=device, dtype=dtype)+ return torch.full((), value, device=device, dtype=dtype)++class PerspectiveGenerator(RandomGeneratorBase):r"""Get parameters for ``perspective`` for a random perspective transform.@@ -80,25 +101,29 @@ class PerspectiveGenerator(RandomGeneratorBase):_check_positive_int_or_traced(height, "height")_check_positive_int_or_traced(width, "width")- # A size-1 axis would make two source corners coincide and the homography singular. Give it a- # unit extent and no offset instead: the single row or column then maps onto itself.- flat_x = isinstance(width, int) and width == 1- flat_y = isinstance(height, int) and height == 1- x_end = 1 if flat_x else width - 1- y_end = 1 if flat_y else height - 1+ x_end, x_extent = _source_end_and_extent(width)+ y_end, y_extent = _source_end_and_extent(height)# Subtract before casting: bbox_generator subtracts in the tensor dtype,# which changes large half-precision image coordinates.- start_points = _constant_tensor(- [[[0, 0], [x_end, 0], [x_end, y_end], [0, y_end]]],- device=_device,- dtype=_dtype,- )+ if isinstance(x_end, torch.Tensor) or isinstance(y_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)+ zero = torch.zeros((), device=_device, dtype=_dtype)+ start_points = torch.stack([torch.stack([zero, x, x, zero]), torch.stack([zero, zero, y, y])], dim=-1)+ start_points = start_points.unsqueeze(0)+ else:+ start_points = _constant_tensor(+ [[[0, 0], [x_end, 0], [x_end, y_end], [0, y_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+ fx = self._distortion_scale * x_extent / 2+ fy = self._distortion_scale * y_extent / 2factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2).to(device=_device, dtype=_dtype)diff --git a/tests/augmentation/test_onnx_export.py b/tests/augmentation/test_onnx_export.pyindex 45ec26754..429016f3a 100644--- a/tests/augmentation/test_onnx_export.py+++ b/tests/augmentation/test_onnx_export.py@@ -329,6 +329,20 @@ def _run_onnx(module: torch.nn.Module, x: torch.Tensor) -> Any:return sess.run(["output"], {"input": x.numpy()})[0][email protected]("shape", [(1, 1, 1, 8), (1, 1, 8, 1), (1, 1, 1, 1)])[email protected]_agnostic+def test_onnx_random_perspective_singleton_axis_is_identity_5000(shape: Tuple[int, ...]) -> None:+ """A size-1 axis exported through the legacy tracer is the identity at zero distortion, as in eager."""+ # Start at 1: an all-zero 1x1 image cannot tell the identity from the zeros the broken export returned.+ image = torch.arange(1, shape[-2] * shape[-1] + 1, dtype=torch.float32).reshape(shape)+ aug = K.RandomPerspective(0.0, p=1.0).eval()+ eager = aug(image).numpy()+ onnx_out = _run_onnx(aug, image)+ assert eager.shape == onnx_out.shape+ assert float(np.abs(eager - image.numpy()).max()) < 1e-5+ assert float(np.abs(onnx_out - eager).max()) < 1e-5++@pytest.mark.parametrize("name,factory", ONNX_NUMERICAL_EQUIVALENT, ids=[n for n, _ in ONNX_NUMERICAL_EQUIVALENT])@pytest.mark.device_agnosticdef test_onnx_export_numerically_matches_eager(name: str, factory: Callable[[], torch.nn.Module]) -> None:diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.pyindex 8dc84d732..11afea1ed 100644--- a/tests/augmentation/test_random_generator.py+++ b/tests/augmentation/test_random_generator.py@@ -15,6 +15,7 @@# limitations under the License.#+import warningsfrom typing import Anyfrom unittest.mock import patch@@ -704,6 +705,39 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):assert_close(res["start_points"], expected["start_points"])assert_close(res["end_points"], expected["end_points"])+ @pytest.mark.parametrize("height,width", [(1, 8), (8, 1), (1, 1), (2, 5)])+ @pytest.mark.device_agnostic+ def test_traced_singleton_axis_5000(self, height, width):+ # #5000: torch.onnx.export(dynamo=False) traces with 0-d tensor sizes. The size-1 rule must+ # 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 = PerspectiveGenerator(torch.tensor(1.0))++ def forward(self, x: Tensor) -> tuple[Tensor, Tensor]:+ params = self.generator(x.shape)+ return params["start_points"], params["end_points"]++ image = torch.zeros(2, 1, height, width)+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ traced = torch.jit.trace(_Params(), image, check_trace=False)+ torch.manual_seed(0)+ start, end = traced(image)+ torch.manual_seed(0)+ eager = PerspectiveGenerator(torch.tensor(1.0))(image.shape)++ x_end, y_end = max(width - 1, 1), max(height - 1, 1)+ expected = torch.tensor([[0.0, 0.0], [x_end, 0.0], [x_end, y_end], [0.0, y_end]]).expand(2, 4, 2)+ 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)):+ if size == 1:+ assert torch.equal(end[..., axis], start[..., axis])+def test_sampling_method(self, device, dtype):torch.manual_seed(42)batch_size = 2