Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Promote half precision boxes before coordinate conversion (#5782)

AhmetHakanBezirc3f793324a70
diff --git a/changelog.d/5782.fixed.md b/changelog.d/5782.fixed.md
new file mode 100644
index 000000000..c0a13eda4
--- /dev/null
+++ b/changelog.d/5782.fixed.md
@@ -0,0 +1 @@
+`mean_iou_bbox` converts float16 and bfloat16 `xywh` and `cxcywh` boxes to corners in float32. The corners used to be rounded in the box dtype first: in float16, `289.5 + 22.375` became `312.0`, which moved the IoU of that pair from 0.4994 to 0.5029, and a 1 px wide box at x = 2048 collapsed to zero width and raised `AssertionError`.
diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.py
index 8d8eb6e00..bc898e588 100644
--- a/kornia/metrics/mean_iou.py
+++ b/kornia/metrics/mean_iou.py
@@ -165,17 +165,18 @@ def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor, box_format: str
boxes_1 = _promote_integer_boxes(boxes_1)
boxes_2 = _promote_integer_boxes(boxes_2)
+ output_dtype = torch.promote_types(boxes_1.dtype, boxes_2.dtype)
+ # Compute half-precision boxes in float32 from the start: the corners (x + w) round in their dtype, which can erase
+ # a small width at a large position, and image-sized areas overflow float16.
+ if boxes_1.dtype in (torch.float16, torch.bfloat16):
+ boxes_1 = boxes_1.float()
+ if boxes_2.dtype in (torch.float16, torch.bfloat16):
+ boxes_2 = boxes_2.float()
+
# Convert boxes to xyxy format
boxes_1_xyxy = _convert_boxes_to_xyxy(boxes_1, box_format)
boxes_2_xyxy = _convert_boxes_to_xyxy(boxes_2, box_format)
- output_dtype = torch.promote_types(boxes_1_xyxy.dtype, boxes_2_xyxy.dtype)
- # Ordinary image-sized areas overflow float16; compute the ratio before rounding back.
- if boxes_1_xyxy.dtype in (torch.float16, torch.bfloat16):
- boxes_1_xyxy = boxes_1_xyxy.float()
- if boxes_2_xyxy.dtype in (torch.float16, torch.bfloat16):
- boxes_2_xyxy = boxes_2_xyxy.float()
-
# Validate boxes are in proper xyxy format. The checks read the data, which graph capture cannot do;
# skip them under any capture. TorchScript cannot call is_compiling(), and a scripted call keeps the checks.
if torch.jit.is_scripting() or not is_compiling():
diff --git a/tests/metrics/test_mean_iou.py b/tests/metrics/test_mean_iou.py
index ab22e82ac..1a328d2de 100644
--- a/tests/metrics/test_mean_iou.py
+++ b/tests/metrics/test_mean_iou.py
@@ -427,3 +427,44 @@ class TestConventionsMeanIoU(BaseTester):
self.assert_close(kornia.metrics.mean_iou_bbox(to_xywh(boxes_1), to_xywh(boxes_2), "xywh"), expected)
self.assert_close(kornia.metrics.mean_iou_bbox(to_cxcywh(boxes_1), to_cxcywh(boxes_2), "cxcywh"), expected)
+
+
+class TestHalfBoxConversion(BaseTester):
+ @pytest.mark.parametrize("box_format", ["xywh", "cxcywh"])
+ def test_realistic_box_sizes(self, device, dtype, box_format):
+ # A real-input pair from #6204: widths/heights are tens of pixels, not sub-spacing boxes.
+ boxes = torch.tensor(
+ [[70.375, 289.5, 39.0625, 22.375], [55.65625, 290.5, 54.375, 30.03125]],
+ dtype=torch.float64,
+ )
+ if box_format == "cxcywh":
+ boxes[:, :2] += boxes[:, 2:] / 2
+ boxes = boxes.to(device=device, dtype=dtype)
+ # Build corners independently in double precision from the SAME quantized input boxes.
+ reference = boxes.cpu().double()
+ origin = reference[:, :2]
+ if box_format == "cxcywh":
+ origin = origin - reference[:, 2:] / 2
+ end = origin + reference[:, 2:]
+ overlap = (torch.minimum(end[0], end[1]) - torch.maximum(origin[0], origin[1])).clamp_min(0).prod()
+ area = reference[:, 2:].prod(dim=-1)
+ expected = (overlap / (area.sum() - overlap)).to(device=device, dtype=dtype).reshape(1, 1)
+
+ actual = kornia.metrics.mean_iou_bbox(boxes[:1], boxes[1:], box_format)
+ assert actual.dtype == dtype
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("box_format", ["xywh", "cxcywh"])
+ def test_small_width_at_large_position(self, device, dtype, box_format):
+ boxes_1 = torch.tensor([[2048.0, 0.0, 1.0, 2.0]], device=device, dtype=dtype, requires_grad=True)
+ boxes_2 = torch.tensor([[2048.0, 1.0, 1.0, 2.0]], device=device, dtype=dtype, requires_grad=True)
+ # Both boxes have area 2, their overlap has area 1, and the union has area 3.
+ actual = kornia.metrics.mean_iou_bbox(boxes_1, boxes_2, box_format)
+ assert actual.dtype == dtype
+ self.assert_close(actual, boxes_1.new_tensor([[1 / 3]]))
+ grad_1, grad_2 = torch.autograd.grad(actual.sum(), (boxes_1, boxes_2))
+ assert torch.isfinite(grad_1).all()
+ assert torch.isfinite(grad_2).all()
+ # Moving the first box vertically toward the second changes I / U by 4 / 9.
+ self.assert_close(grad_1[:, 1], boxes_1.new_tensor([4 / 9]))
+ self.assert_close(grad_2[:, 1], boxes_2.new_tensor([-4 / 9]))