π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix integer coordinate dtype promotion in keypoints and boxes (#6323)
Muhammad Talha23dc233244f0
diff --git a/changelog.d/6323.fixed.md b/changelog.d/6323.fixed.mdnew file mode 100644index 000000000..85d9d2ffc--- /dev/null+++ b/changelog.d/6323.fixed.md@@ -0,0 +1 @@+When `raise_if_not_floating_point=False`, the `Keypoints`, `Keypoints3D`, `Boxes`, `Boxes3D` and `VideoBoxes` constructors cast integer tensor coordinates to `float32`, or to `float64` when that is the default dtype; they still reject integer tensors by default. `Boxes.from_tensor`, `Boxes3D.from_tensor` and `VideoBoxes.from_tensor` accept integer input and use the same dtype promotion. `Boxes` used to cast integers to the default dtype, which under a `float16` or `bfloat16` default moved coordinates above 2048 or 256; `Keypoints` used to cast to `float32` even under a `float64` default.diff --git a/kornia/geometry/_coordinate.py b/kornia/geometry/_coordinate.pynew file mode 100644index 000000000..a9ea7f506--- /dev/null+++ b/kornia/geometry/_coordinate.py@@ -0,0 +1,27 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++import torch+++def _cast_to_floating_point(coordinates: torch.Tensor) -> torch.Tensor:+ """Preserve floating inputs; cast integer coordinates to at least float32."""+ if coordinates.is_floating_point():+ return coordinates+ return coordinates.to(torch.promote_types(torch.get_default_dtype(), torch.float32))diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex 3a6f91016..183306e10 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -25,6 +25,7 @@ from torch import Sizefrom kornia.core.check import _check_asyncfrom kornia.core.ops import eye_likefrom kornia.core.utils import is_compiling, is_exporting+from kornia.geometry._coordinate import _cast_to_floating_pointfrom kornia.geometry.linalg import transform_points__all__ = ["Boxes", "Boxes3D", "VideoBoxes"]@@ -60,7 +61,7 @@ def _transform_boxes(boxes: torch.Tensor, M: torch.Tensor) -> torch.Tensor::math:`(B, 4, 4)` for 3D hexahedron."""- M = M if M.is_floating_point() else M.to(torch.get_default_dtype())+ M = _cast_to_floating_point(M)# Work with batch as kornia.transform_points only supports a batch of points.boxes_per_batch, n_points_per_box, coordinates_dimension = boxes.shape[-3:]@@ -128,7 +129,7 @@ def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_belse:raise ValueError(f"Unknown mode {mode}")- boxes = boxes if boxes.is_floating_point() else boxes.to(torch.get_default_dtype())+ boxes = _cast_to_floating_point(boxes)boxes = boxes if batched else boxes.unsqueeze(0)# Value validation reads the data, which graph capture cannot do; skip it under export. The vertex modes check@@ -212,7 +213,8 @@ class Boxes:See below for more details.raise_if_not_floating_point: flag to control floating point casting behaviour when `boxes` is not afloating point tensor. True to raise an error when `boxes` isn't a floating point tensor, False- to cast to float.+ to cast to ``float32``, or ``float64`` when that is the default dtype.+ Floating-point input keeps its dtype.mode: Representation label reused as the default output mode by :meth:`to_tensor`. The constructor does notconvert ``boxes``; use :meth:`from_tensor` to import another representation.@@ -236,7 +238,8 @@ class Boxes:``fullgraph``-compilable, and take no extent or shape check, so the arbitrary quadrilaterals of:meth:`transform_boxes` import unchanged.- The constructor rejects an integer tensor unless ``raise_if_not_floating_point=False`` (a list is- checked by its first element's dtype); :meth:`from_tensor` casts integer input to the default dtype.+ checked by its first element's dtype); :meth:`from_tensor` casts integer input to ``float32``,+ or ``float64`` when that is the default dtype.- :meth:`merge` and :meth:`index_put` are non-mutating by default... warning::@@ -276,7 +279,7 @@ class Boxes:if raise_if_not_floating_point:raise ValueError(f"Coordinates must be in floating point. Got {boxes.dtype}")- boxes = boxes.to(torch.get_default_dtype())+ boxes = _cast_to_floating_point(boxes)if len(boxes.shape) == 0:boxes = boxes.reshape((-1, 4))@@ -671,7 +674,8 @@ class Boxes:Args:boxes: 2D boxes, shape of :math:`(N, 4)`, :math:`(B, N, 4)`, :math:`(N, 4, 2)` or:math:`(B, N, 4, 2)`, a nested numeric list with one of those shapes, or a list of- :math:`(N, 4)` or :math:`(N, 4, 2)` tensors matching ``mode``.+ :math:`(N, 4)` or :math:`(N, 4, 2)` tensors matching ``mode``. Integer input is cast to ``float32``,+ or ``float64`` when that is the default dtype. Floating-point input keeps its dtype.mode: The format in which the boxes are provided:* 'xyxy': ``xmin, ymin, xmax, ymax`` with exclusive extent. With shape :math:`(N, 4)`,@@ -1074,8 +1078,9 @@ class VideoBoxes(Boxes):Convention:- :meth:`from_tensor` stores :math:`(B, T, N, 4, 2)` input unchanged as :math:`(B \cdot T, N, 4, 2)`- ``'vertices_plus'`` data, with no mode or conversion; integer input is cast to the default dtype, and- another shape or a list raises ``ValueError``. ``validate_boxes=True`` rejects a non-finite coordinate as+ ``'vertices_plus'`` data, with no mode or conversion; integer input is cast to ``float32``,+ or ``float64`` when that is the default dtype. Another shape or a list raises ``ValueError``.+ ``validate_boxes=True`` rejects a non-finite coordinate as:meth:`Boxes.from_tensor` does for ``'vertices_plus'``.- :meth:`to_tensor` accepts every :class:`Boxes` mode and restores the temporal axis(``to_tensor('xyxy')`` is :math:`(B, T, N, 4)`).@@ -1103,7 +1108,8 @@ class VideoBoxes(Boxes):boxes: Box corners with shape :math:`(B, T, N, 4, 2)` in``vertices_plus`` order (top-left, top-right, bottom-right,bottom-left), stored unchanged; integer input is cast to- ``torch.get_default_dtype()``. Lists of tensors are not supported yet.+ ``float32``, or ``float64`` when that is the default dtype. Floating-point input keeps its dtype.+ Lists of tensors are not supported yet.validate_boxes: Reject a non-finite coordinate with ``RuntimeError``(``torch._assert_async``). There is no extent or shapecheck, as for ``'vertices_plus'`` in@@ -1207,7 +1213,8 @@ class Boxes3D:Args:boxes: 3D boxes, shape of :math:`(N,8,3)` or :math:`(B,N,8,3)`. See below for more details.raise_if_not_floating_point: flag to control floating point casting behaviour when `boxes` is not a floating- point tensor. True to raise an error when `boxes` isn't a floating point tensor, False to cast to float.+ point tensor. True to raise an error when `boxes` isn't a floating point tensor, False to cast to+ ``float32``, or ``float64`` when that is the default dtype. Floating-point input keeps its dtype.mode: Representation label reported by :attr:`mode`. The constructor does not convert ``boxes`` and:meth:`to_tensor` does not consult the label; use :meth:`from_tensor` to import another representation.@@ -1226,7 +1233,8 @@ class Boxes3D:- With ``validate_boxes=True``, :meth:`from_tensor` rejects a non-finite coordinate and extents that arenot positive in the given mode (``xmax == xmin`` fails in ``'xyzxyz'``, passes in ``'xyzxyz_plus'``).- The constructor rejects an integer tensor unless ``raise_if_not_floating_point=False``;- :meth:`from_tensor` casts integer input to the default dtype.+ :meth:`from_tensor` casts integer input to ``float32``,+ or ``float64`` when that is the default dtype.- :meth:`transform_boxes` returns a new object labelled ``'xyzxyz_plus'``; :meth:`transform_boxes_`rebinds the internal tensor of ``self`` and keeps the label.@@ -1250,7 +1258,7 @@ class Boxes3D:if raise_if_not_floating_point:raise ValueError(f"Coordinates must be in floating point. Got {boxes.dtype}.")- boxes = boxes.to(torch.get_default_dtype())+ boxes = _cast_to_floating_point(boxes)if len(boxes.shape) == 0:boxes = boxes.reshape((-1, 6))@@ -1313,7 +1321,7 @@ class Boxes3D:Args:boxes: 3D boxes, shape of :math:`(N,6)` or :math:`(B,N,6)`. Integer input is cast to- ``torch.get_default_dtype()``.+ ``float32``, or ``float64`` when that is the default dtype. Floating-point input keeps its dtype.mode: The format in which the 3D boxes are provided, matched case-insensitively.* 'xyzxyz': boxes are assumed to be in the format ``xmin, ymin, zmin, xmax, ymax, zmax`` where@@ -1359,7 +1367,7 @@ class Boxes3D:batched = boxes.ndim == 3boxes = boxes if batched else boxes.unsqueeze(0)- boxes = boxes if boxes.is_floating_point() else boxes.to(torch.get_default_dtype())+ boxes = _cast_to_floating_point(boxes)xmin, ymin, zmin = boxes[..., 0], boxes[..., 1], boxes[..., 2]mode = mode.lower()diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.pyindex e9889287b..bcaa1602a 100644--- a/kornia/geometry/keypoints.py+++ b/kornia/geometry/keypoints.py@@ -22,6 +22,7 @@ from torch import Sizefrom kornia.core._compat import _emit_deprecation_warningfrom kornia.geometry import transform_points+from kornia.geometry._coordinate import _cast_to_floating_point__all__ = ["Keypoints", "Keypoints3D"]@@ -40,7 +41,7 @@ class Keypoints:keypoints: tensor of :math:`(N, 2)` or :math:`(B, N, 2)` coordinates. A list of tensors is not implemented(see Known defects).raise_if_not_floating_point: ``True`` raises ``ValueError`` for a non-floating-point tensor, ``False`` casts- it to ``float32``.+ it to ``float32``, or ``float64`` when that is the default dtype. Floating-point input keeps its dtype.Convention:- A point is ``(x, y)`` in pixel coordinates (:ref:`Coordinates and sizes <coordinate-conventions>`), the@@ -70,7 +71,7 @@ class Keypoints:if raise_if_not_floating_point:raise ValueError(f"Coordinates must be in floating point. Got {keypoints.dtype}")- keypoints = keypoints.float()+ keypoints = _cast_to_floating_point(keypoints)if len(keypoints.shape) == 0:# Use reshape, so we don't end up creating a new tensor that does not depend on@@ -344,7 +345,7 @@ class Keypoints3D:keypoints: tensor of :math:`(N, 3)` or :math:`(B, N, 3)` coordinates. A list of tensors is not implemented(see Known defects).raise_if_not_floating_point: ``True`` raises ``ValueError`` for a non-floating-point tensor, ``False`` casts- it to ``float32``.+ it to ``float32``, or ``float64`` when that is the default dtype. Floating-point input keeps its dtype.Convention:- Known defects: list input and ``to_tensor(as_padded_sequence=True)`` raise ``NotImplementedError``;@@ -366,7 +367,7 @@ class Keypoints3D:if raise_if_not_floating_point:raise ValueError(f"Coordinates must be in floating point. Got {keypoints.dtype}")- keypoints = keypoints.float()+ keypoints = _cast_to_floating_point(keypoints)if len(keypoints.shape) == 0:# Use reshape, so we don't end up creating a new tensor that does not depend ondiff --git a/tests/geometry/test_coordinate_dtypes.py b/tests/geometry/test_coordinate_dtypes.pynew file mode 100644index 000000000..de14697f2--- /dev/null+++ b/tests/geometry/test_coordinate_dtypes.py@@ -0,0 +1,105 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from functools import partial++import pytest+import torch++from kornia.geometry.boxes import Boxes, Boxes3D, VideoBoxes+from kornia.geometry.keypoints import Keypoints, Keypoints3D++from testing.base import BaseTester++_BOX = [[[2049, 2051], [2051, 2051], [2051, 2053], [2049, 2053]]]+_CUBE = [+ [+ [2049, 2051, 257],+ [2051, 2051, 257],+ [2051, 2053, 257],+ [2049, 2053, 257],+ [2049, 2051, 259],+ [2051, 2051, 259],+ [2051, 2053, 259],+ [2049, 2053, 259],+ ]+]++[email protected]("default_dtype", [torch.float32, torch.float64, torch.float16, torch.bfloat16])+class TestCoordinateDtypes(BaseTester):+ @pytest.mark.parametrize(+ "constructor, coordinates",+ [+ pytest.param(partial(Keypoints, raise_if_not_floating_point=False), [[2049, 2051]], id="keypoints"),+ pytest.param(+ partial(Keypoints3D, raise_if_not_floating_point=False), [[2049, 2051, 257]], id="keypoints3d"+ ),+ pytest.param(partial(Boxes, raise_if_not_floating_point=False), _BOX, id="boxes"),+ pytest.param(partial(Boxes.from_tensor, mode="vertices_plus"), _BOX, id="boxes-from-tensor"),+ pytest.param(partial(Boxes3D, raise_if_not_floating_point=False), _CUBE, id="boxes3d"),+ pytest.param(+ partial(Boxes3D.from_tensor, mode="xyzxyz_plus"),+ [[2049, 2051, 257, 2051, 2053, 259]],+ id="boxes3d-from-tensor",+ ),+ pytest.param(partial(VideoBoxes, raise_if_not_floating_point=False), [_BOX], id="video-boxes"),+ pytest.param(VideoBoxes.from_tensor, [[_BOX]], id="video-boxes-from-tensor"),+ ],+ )+ @pytest.mark.parametrize("input_dtype", [torch.int64, torch.float16, torch.bfloat16, torch.float32, torch.float64])+ def test_coordinate_dtype(self, device, default_dtype, input_dtype, constructor, coordinates):+ expected_dtype = (+ (torch.float64 if default_dtype == torch.float64 else torch.float32)+ if input_dtype == torch.int64+ else input_dtype+ )+ if device.type == "mps" and torch.float64 in (input_dtype, expected_dtype):+ pytest.skip("MPS does not support float64")+ source = torch.tensor(coordinates, device=device, dtype=input_dtype)+ original_default = torch.get_default_dtype()+ try:+ torch.set_default_dtype(default_dtype)+ result = constructor(source)+ assert result.data.dtype == expected_dtype+ assert result.data.device == device+ # Check exact coordinates, including values not representable in half precision.+ if isinstance(result, Boxes3D) and source.shape[-1] == 6:+ actual = result.to_tensor(mode="xyzxyz_plus")+ else:+ actual = result.data.reshape(source.shape)+ self.assert_close(actual, source.to(expected_dtype), atol=0, rtol=0)+ finally:+ torch.set_default_dtype(original_default)++ @pytest.mark.parametrize("box_class, dimensions", [(Boxes, 2), (Boxes3D, 3)])+ def test_integer_transform_dtype(self, device, default_dtype, box_class, dimensions):+ expected_dtype = torch.float64 if default_dtype == torch.float64 else torch.float32+ if device.type == "mps" and expected_dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ vertices = torch.zeros((1, 2**dimensions, dimensions), device=device, dtype=expected_dtype)+ transform = torch.eye(dimensions + 1, device=device, dtype=torch.int64)+ translation = torch.tensor([2049, 2051, 257][:dimensions], device=device, dtype=torch.int64)+ transform[:-1, -1] = translation+ original_default = torch.get_default_dtype()+ try:+ torch.set_default_dtype(default_dtype)+ result = box_class(vertices).transform_boxes(transform)+ assert result.data.dtype == expected_dtype+ self.assert_close(result.data, vertices + translation.to(expected_dtype), atol=0, rtol=0)+ finally:+ torch.set_default_dtype(original_default)