Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(metrics): avoid half-precision box IoU overflow (#5392)

A Aswanth Raj7cb3d0c6b72a
diff --git a/changelog.d/5392.fixed.md b/changelog.d/5392.fixed.md
new file mode 100644
index 000000000..b771c0338
--- /dev/null
+++ b/changelog.d/5392.fixed.md
@@ -0,0 +1 @@
+`mean_iou_bbox` now computes float16 and bfloat16 boxes in float32 and returns the IoU in the box dtype. In float16 the IoU came out 0 or NaN once the two areas together overflowed: a 181 x 181 box against itself gave 0 and a 256 x 256 box NaN, so `mean_average_precision` scored a perfect float16 detection of a 512 x 512 box as 0 instead of 1. bfloat16 rounded the areas before the ratio (0.9766 instead of 0.9805 for a 200 x 200 and a 200 x 204 box). float32, float64 and integer boxes are unchanged.
diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.py
index b9891d41c..5bce258d7 100644
--- a/kornia/metrics/mean_iou.py
+++ b/kornia/metrics/mean_iou.py
@@ -146,6 +146,13 @@ def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor, box_format: str
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 export.
if not is_exporting():
@@ -173,4 +180,5 @@ def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor, box_format: str
# Find the union
union = areas_set_1.unsqueeze(1) + areas_set_2.unsqueeze(0) - intersection # (n1, n2)
- return intersection / union # (n1, n2)
+ iou = intersection / union # (n1, n2)
+ return iou.to(output_dtype) if output_dtype in (torch.float16, torch.bfloat16) else iou
diff --git a/tests/metrics/test_map.py b/tests/metrics/test_map.py
index a7ee58b44..d83aa9d3b 100644
--- a/tests/metrics/test_map.py
+++ b/tests/metrics/test_map.py
@@ -24,12 +24,13 @@ from testing.base import BaseTester
class TestMeanAveragePrecision(BaseTester):
- def test_smoke(self, device, dtype):
- boxes = torch.tensor([[100, 50, 150, 100.0]], device=device, dtype=dtype)
+ @pytest.mark.parametrize("coordinates", [[[100, 50, 150, 100.0]], [[0, 0, 512, 512]]])
+ def test_smoke(self, coordinates, device, dtype):
+ boxes = torch.tensor(coordinates, device=device, dtype=dtype)
labels = torch.tensor([1], device=device, dtype=torch.long)
scores = torch.tensor([0.7], device=device, dtype=dtype)
- gt_boxes = torch.tensor([[100, 50, 150, 100.0]], device=device, dtype=dtype)
+ gt_boxes = torch.tensor(coordinates, device=device, dtype=dtype)
gt_labels = torch.tensor([1], device=device, dtype=torch.long)
mean_ap = kornia.metrics.mean_average_precision([boxes], [labels], [scores], [gt_boxes], [gt_labels], 2)
diff --git a/tests/metrics/test_mean_iou.py b/tests/metrics/test_mean_iou.py
index 53f890cbc..d0758f738 100644
--- a/tests/metrics/test_mean_iou.py
+++ b/tests/metrics/test_mean_iou.py
@@ -113,6 +113,67 @@ class TestMeanIoU(BaseTester):
class TestMeanIoUBBox(BaseTester):
"""Tests for mean_iou_bbox with different box formats."""
+ @pytest.mark.parametrize(
+ "box_format,coordinates",
+ [
+ ("xyxy", [[0, 0, 512, 512], [256, 0, 768, 512]]),
+ ("xywh", [[0, 0, 512, 512], [256, 0, 512, 512]]),
+ ("cxcywh", [[256, 256, 512, 512], [512, 256, 512, 512]]),
+ ],
+ )
+ def test_image_sized_boxes(self, box_format, coordinates, device, dtype):
+ boxes = torch.tensor(coordinates, device=device, dtype=dtype)
+ original = boxes.clone()
+ actual = kornia.metrics.mean_iou_bbox(boxes, boxes, box_format)
+ # Each box has area 512**2; their intersection is 256*512 and their union is 768*512.
+ expected = torch.tensor([[1.0, 1.0 / 3.0], [1.0 / 3.0, 1.0]], device=device, dtype=dtype)
+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)
+ self.assert_close(boxes, original, atol=0.0, rtol=0.0)
+ assert actual.dtype == dtype
+ assert actual.device == device
+
+ @pytest.mark.parametrize("empty_shape", [(0, 4), (2, 4)])
+ def test_empty_box_set(self, empty_shape, device, dtype):
+ empty = torch.empty(0, 4, device=device, dtype=dtype)
+ boxes = torch.tensor([[0, 0, 512, 512], [256, 0, 768, 512]], device=device, dtype=dtype)
+ other = empty if empty_shape[0] == 0 else boxes
+ actual = kornia.metrics.mean_iou_bbox(empty, other)
+ assert actual.shape == (0, empty_shape[0])
+ assert actual.dtype == dtype
+
+ def test_image_sized_boxes_backward(self, device, dtype):
+ first_coordinates = [[0, 0, 512, 512]]
+ second_coordinates = [[256, 128, 768, 640]]
+ first = torch.tensor(first_coordinates, device=device, dtype=dtype, requires_grad=True)
+ second = torch.tensor(second_coordinates, device=device, dtype=dtype)
+ actual = kornia.metrics.mean_iou_bbox(first, second)
+ reference_input = torch.tensor(first_coordinates, dtype=torch.float64, requires_grad=True)
+ reference = kornia.metrics.mean_iou_bbox(reference_input, torch.tensor(second_coordinates, dtype=torch.float64))
+ actual.sum().backward()
+ reference.sum().backward()
+ assert first.grad is not None
+ assert reference_input.grad is not None
+ self.assert_close(first.grad, reference_input.grad.to(dtype=dtype).to(device=device), atol=1e-6, rtol=1e-3)
+
+ @pytest.mark.parametrize("swap", [False, True])
+ def test_areas_are_not_rounded_to_the_box_dtype(self, swap, device, dtype):
+ # In float16 the areas 40000 and 40800 sum past the maximum, which gave an IoU of 0. Computed in bfloat16 the
+ # IoU was 0.9765625, and rounding only the taller box's area gives 0.984375, instead of 0.98046875. Every
+ # coordinate is exact in both dtypes.
+ square = torch.tensor([[0, 0, 200, 200]], device=device, dtype=dtype)
+ taller = torch.tensor([[0, 0, 200, 204]], device=device, dtype=dtype)
+ boxes_1, boxes_2 = (taller, square) if swap else (square, taller)
+ actual = kornia.metrics.mean_iou_bbox(boxes_1, boxes_2)
+ expected = torch.tensor([[40000 / 40800]], device=device, dtype=dtype)
+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)
+
+ def test_integer_boxes_return_float32(self, device):
+ boxes = torch.tensor([[0, 0, 512, 512], [256, 0, 768, 512]], device=device)
+ actual = kornia.metrics.mean_iou_bbox(boxes, boxes)
+ assert actual.dtype == torch.float32
+ expected = torch.tensor([[1.0, 1.0 / 3.0], [1.0 / 3.0, 1.0]], device=device)
+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)
+
def test_bbox_xyxy_format(self, device, dtype):
"""Test XYXY format (original behavior)."""
boxes_1 = torch.tensor([[40, 40, 60, 60], [30, 40, 50, 60]], device=device, dtype=dtype)