π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(image): compare ImageLayout sizes as numbers with KORNIA_CHECK_SIZES (#6265)
Prateekshit Jaiswal48a5bbe7d819
diff --git a/changelog.d/6265.fixed.md b/changelog.d/6265.fixed.mdnew file mode 100644index 000000000..2e054e70f--- /dev/null+++ b/changelog.d/6265.fixed.md@@ -0,0 +1,3 @@+`kornia.image.Image` now raises `ShapeError` when an int, float or one-element tensor size in its `ImageLayout` does not match the data. In 0.9.0 the layout check compared the sizes as strings and skipped any that were not all digits, so a tensor, float or negative size was never checked (`CameraModel.scale` returns tensor and float sizes), and `height` and `width` then reported the layout's size instead of the data's. A multi-element tensor size now raises `RuntimeError` when the `Image` is built. The `ShapeError` message, also for data with the wrong number of dimensions, now reads like `Shape mismatch: expected (3, 9, 9), got [3, 4, 5].`++Building an `Image` from `x.shape`, and `depth_from_disparity` with a `(B,)` `baseline` or `focal`, now compile under `torch.compile(fullgraph=True)` with dynamic shapes, including the automatic recompile at a second image or batch size; in 0.9.0 both raised `Unsupported` there. A `(B,)` parameter that does not match the batch now reports `Shape mismatch: expected (2,), got [3].`diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex c03300c1a..d9e353c62 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -25,7 +25,7 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, KORNIA_CHECK_SIZESfrom kornia.core.exceptions import ShapeErrorfrom kornia.core.utils import _autocast_disabled, _torch_grid_samplefrom kornia.filters.sobel import spatial_gradient@@ -791,7 +791,8 @@ def _per_sample_camera_parameter(parameter: float | torch.Tensor, disparity: torif not isinstance(parameter, torch.Tensor) or parameter.ndim == 0 or parameter.shape == (1,):return parameterif parameter.ndim == 1 and disparity.ndim >= 3:- KORNIA_CHECK_SHAPE(parameter, [str(disparity.shape[0])])+ # Compared as a number: a string would turn a symbolic batch size into a graph break under torch.compile.+ KORNIA_CHECK_SIZES(parameter, [disparity.shape[0]])return parameter.reshape(disparity.shape[0], *([1] * (disparity.ndim - 1)))KORNIA_CHECK_SHAPE(parameter, ["1"])return parameterdiff --git a/kornia/image/base.py b/kornia/image/base.pyindex 48e74ecdc..c030090e5 100644--- a/kornia/image/base.py+++ b/kornia/image/base.py@@ -22,7 +22,7 @@ from enum import Enumimport torch-from kornia.core.check import KORNIA_CHECK_SHAPE, CheckMessage+from kornia.core.check import KORNIA_CHECK_SIZES, CheckMessage@dataclass(frozen=True)@@ -139,6 +139,9 @@ def KORNIA_CHECK_IMAGE_LAYOUT() -> bool:"""Check tensor shape matches the expected ImageLayout.+ The sizes are compared as numbers, so an int, float or one-element tensor size is checked the same way, and a+ symbolic size under ``torch.compile`` is related to the tensor's size without being turned into a string.+Args:x: tensor to validate.layout: expected image layout.@@ -149,16 +152,19 @@ def KORNIA_CHECK_IMAGE_LAYOUT(True if shape matches, False otherwise (when raises=False)."""+ # Not KORNIA_CHECK_SHAPE: it takes strings and skips every entry that is not all digits, a rule meant for names+ # such as "H", so a tensor or float size would never be compared, and str() of a symbolic size under+ # torch.compile cannot be traced.if layout.channels_order == ChannelsOrder.CHANNELS_FIRST:- shape = [str(layout.channels), str(layout.image_size.height), str(layout.image_size.width)]+ sizes = [layout.channels, layout.image_size.height, layout.image_size.width]elif layout.channels_order == ChannelsOrder.CHANNELS_LAST:- shape = [str(layout.image_size.height), str(layout.image_size.width), str(layout.channels)]+ sizes = [layout.image_size.height, layout.image_size.width, layout.channels]else:if raises:raise NotImplementedError(f"Layout {layout.channels_order} not implemented.")return False- return KORNIA_CHECK_SHAPE(x, shape, msg, raises)+ return KORNIA_CHECK_SIZES(x, sizes, msg, raises)# TODO: define CompressedImagediff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.pyindex f04a6f2c1..1dffad364 100644--- a/tests/geometry/test_depth.py+++ b/tests/geometry/test_depth.py@@ -1387,9 +1387,9 @@ class TestDepthFromDisparity(BaseTester):# the width instead. The size-1 and scalar forms are unaffected, and an empty batch stays empty.disparity = torch.ones(2, 1, 2, 3, device=device, dtype=dtype)three = torch.ones(3, device=device, dtype=dtype)- with pytest.raises(ShapeError, match="expected 2, got 3"):+ with pytest.raises(ShapeError, match=r"expected \(2,\), got \[3\]"):depth_from_disparity(disparity, three, 100.0)- with pytest.raises(ShapeError, match="expected 2, got 3"):+ with pytest.raises(ShapeError, match=r"expected \(2,\), got \[3\]"):depth_from_disparity(disparity, 0.5, three)with pytest.raises(ShapeError, match="expected 1, got 3"):depth_from_disparity(torch.ones(2, 3, device=device, dtype=dtype), three, 100.0)@@ -1405,6 +1405,19 @@ class TestDepthFromDisparity(BaseTester):nothing = torch.ones(0, device=device, dtype=dtype)assert depth_from_disparity(empty, nothing, nothing).shape == (0, 1, 2, 3)+ def test_dynamo_per_batch_check_is_dynamic_6244(self, device, dtype, torch_optimizer):+ # The (B,) parameter check compares the batch as a number: as a string, the symbolic batch size could not be+ # traced, and fullgraph=True with dynamic shapes raised torch._dynamo.exc.Unsupported (tp_repr_impl).+ from torch._dynamo.testing import CompileCounter++ counter = CompileCounter()+ compiled = torch_optimizer(depth_from_disparity, backend=counter, fullgraph=True, dynamic=True)+ for batch in (2, 3):+ disparity = torch.rand(batch, 1, 5, 7, device=device, dtype=dtype) + 0.5+ baseline = torch.rand(batch, device=device, dtype=dtype) + 0.1+ self.assert_close(compiled(disparity, baseline, 100.0), depth_from_disparity(disparity, baseline, 100.0))+ assert counter.frame_count == 1+class TestDepthFromPlaneEquation(BaseTester):def test_smoke(self, device, dtype):diff --git a/tests/image/test_image.py b/tests/image/test_image.pyindex 56677f543..2ab13ec7c 100644--- a/tests/image/test_image.py+++ b/tests/image/test_image.py@@ -387,18 +387,64 @@ class TestCheckImageLayout(BaseTester):layout = ImageLayout(ImageSize(10, 10), 3, ChannelsOrder.CHANNELS_FIRST)assert not KORNIA_CHECK_IMAGE_LAYOUT(data, layout, raises=False)+ # The sizes are compared as numbers. A tensor or float size whose str() is not all digits used to be skipped+ # like a dimension name, so a 4 x 5 image was accepted against any such height and width (#6244).+ @pytest.mark.parametrize(+ "size",+ [ImageSize(torch.tensor(9), torch.tensor(9)), ImageSize(9.0, 9.0), ImageSize(4.5, 5.0)],+ ids=["tensor", "float", "fractional"],+ )+ @pytest.mark.parametrize("order", [ChannelsOrder.CHANNELS_FIRST, ChannelsOrder.CHANNELS_LAST])+ def test_mismatched_tensor_or_float_size_raises_6244(self, size, order, device):+ data = torch.rand((3, 4, 5) if order == ChannelsOrder.CHANNELS_FIRST else (4, 5, 3), device=device)+ layout = ImageLayout(size, 3, order)+ with pytest.raises(ShapeError):+ Image(data, PixelFormat(ColorSpace.RGB, 32), layout)+ assert not KORNIA_CHECK_IMAGE_LAYOUT(data, layout, raises=False)++ @pytest.mark.parametrize(+ "size",+ [+ ImageSize(4, 5),+ ImageSize(4.0, 5.0),+ ImageSize(torch.tensor(4), torch.tensor(5)),+ ImageSize(torch.tensor(4.0), torch.tensor(5.0)),+ ],+ ids=["int", "float", "int_tensor", "float_tensor"],+ )+ def test_matching_size_of_any_type_is_accepted_6244(self, size, device):+ data = torch.rand(3, 4, 5, device=device)+ image = Image(data, PixelFormat(ColorSpace.RGB, 32), ImageLayout(size, 3, ChannelsOrder.CHANNELS_FIRST))+ assert (image.height, image.width) == (4, 5)++ def test_dynamo_layout_check_does_not_stringify_sizes_6244(self, device, torch_optimizer):+ # Turning a symbolic size into a string cannot be traced: under fullgraph=True with dynamic shapes, building+ # an Image raised torch._dynamo.exc.Unsupported (tp_repr_impl) instead of compiling one graph.+ from torch._dynamo.testing import CompileCounter++ def op(x):+ layout = ImageLayout(ImageSize(x.shape[1], x.shape[2]), 3, ChannelsOrder.CHANNELS_FIRST)+ return Image(x, PixelFormat(ColorSpace.RGB, 32), layout).to_gray().data++ counter = CompileCounter()+ compiled = torch_optimizer(op, backend=counter, fullgraph=True, dynamic=True)+ for height, width in ((4, 5), (6, 7)):+ data = torch.rand(3, height, width, device=device)+ self.assert_close(compiled(data), op(data))+ assert counter.frame_count == 1+class TestConventionsImage(BaseTester):"""Pins for the unbatched layout, same-space conversions and NumPy aliasing of ``Image``."""def test_convention_image_is_unbatched(self):# Image holds one (H, W, C) or (C, H, W) image; a batched 4-D tensor is rejected by its dimension count.- # Image.from_numpy of a 4-D array raises the same ShapeError.+ # Image.from_numpy of a 4-D array raises ShapeError too.batched = torch.zeros(2, 4, 5, 3, dtype=torch.uint8)layout = ImageLayout(ImageSize(4, 5), 3, ChannelsOrder.CHANNELS_LAST)- with pytest.raises(ShapeError, match="expected 3 dimensions, got 4"):+ with pytest.raises(ShapeError, match=r"expected \(4, 5, 3\), got \[2, 4, 5, 3\]"):Image(batched, PixelFormat(ColorSpace.RGB, 8), layout)- with pytest.raises(ShapeError, match="expected 3 dimensions, got 4"):+ with pytest.raises(ShapeError, match=r"got \[2, 4, 5, 3\]"):Image.from_numpy(np.zeros((2, 4, 5, 3), np.uint8))@pytest.mark.parametrize(