Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): prevent NMS area overflow on image-sized boxes (#6083)

A Aswanth Raj832f11685f55
diff --git a/changelog.d/6083.fixed.md b/changelog.d/6083.fixed.md
new file mode 100644
index 000000000..1cc2d517f
--- /dev/null
+++ b/changelog.d/6083.fixed.md
@@ -0,0 +1 @@
+`geometry.bbox.nms` computes half-precision and narrow-integer box areas in a wider dtype, preventing duplicate boxes from surviving or distinct boxes from being suppressed because areas or unions overflow on image-sized coordinates, and bfloat16 rounding from moving an IoU across the threshold.
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index df9bb4fa5..3f57f9bcb 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -705,6 +705,12 @@ def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torc
Returns:
Indices of the boxes kept from the input set, ordered by descending score.
+ Note:
+ Coordinates in ``float16`` or ``bfloat16`` are computed in ``float32``, and ``uint8``, ``int8``, ``int16``
+ or ``int32`` coordinates in ``int64``. In their own dtype the sum of two areas overflows: two 181-pixel
+ squares exceed the ``float16`` maximum of 65504, and two 32768-pixel squares exceed ``int32``.
+ ``bfloat16`` does not overflow, but its rounding can move an IoU across ``iou_threshold``.
+
.. warning::
This differs from the inclusive coordinate arithmetic used by several other
:mod:`kornia.geometry.bbox` operations and is documented in
@@ -730,6 +736,11 @@ def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torc
if boxes.shape[0] != scores.shape[0]:
raise ValueError(f"boxes and scores mus have same shape. Got: {boxes.shape, scores.shape}.")
+ if boxes.dtype in (torch.float16, torch.bfloat16):
+ boxes = boxes.float()
+ elif boxes.dtype in (torch.uint8, torch.int8, torch.int16, torch.int32):
+ boxes = boxes.to(torch.int64)
+
x1, y1, x2, y2 = boxes.unbind(-1)
areas = (x2 - x1) * (y2 - y1)
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index f2afb7c7c..28a672e00 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -838,6 +838,55 @@ class TestBbox3D(BaseTester):
class TestNMS(BaseTester):
+ @pytest.mark.parametrize(
+ ("side", "offset", "expected"),
+ [(200, 0, [0, 2]), (512, 128, [0, 1, 2])],
+ )
+ def test_image_sized_boxes(self, device, dtype, side, offset, expected):
+ # Identical boxes have IoU 1; offset 512-pixel boxes have IoU 9/23.
+ boxes = torch.tensor(
+ [[0, 0, side, side], [offset, offset, side + offset, side + offset], [600, 0, 640, 40]],
+ device=device,
+ dtype=dtype,
+ )
+ scores = torch.tensor([0.875, 0.75, 0.5], device=device, dtype=dtype)
+ original = boxes.clone()
+ expected = torch.tensor(expected, device=device, dtype=torch.long)
+
+ for _ in range(2):
+ self.assert_close(nms(boxes, scores, 0.5), expected, atol=0, rtol=0)
+ self.assert_close(boxes, original, atol=0, rtol=0)
+
+ @pytest.mark.parametrize(
+ ("box_dtype", "side", "origin"),
+ [
+ (torch.uint8, 100, 0),
+ (torch.int8, 100, -100),
+ (torch.int16, 200, 0),
+ (torch.int32, 200, 2**24),
+ (torch.int32, 50_000, 0), # each area exceeds 2**31 - 1
+ (torch.int64, 200, 2**40),
+ ],
+ )
+ def test_integer_boxes(self, device, box_dtype, side, origin):
+ boxes = torch.tensor(
+ [[origin, origin, origin + side, origin + side]] * 2
+ + [[origin + side - 20, origin + side - 20, origin + side - 10, origin + side - 10]],
+ device=device,
+ dtype=box_dtype,
+ )
+ scores = torch.tensor([0.875, 0.75, 0.5], device=device)
+ expected = torch.tensor([0, 2], device=device, dtype=torch.long)
+ self.assert_close(nms(boxes, scores, 0.5), expected, atol=0, rtol=0)
+
+ def test_iou_just_above_threshold(self, device, dtype):
+ # The exact IoU is 8479 / 16793 = 0.5049, so 0.5 suppresses the second box. Computed in bfloat16, the areas,
+ # intersection and union round to an IoU of exactly 0.5, which kept it. The coordinates are exact in any dtype.
+ boxes = torch.tensor([[0, 0, 153, 162], [14, 40, 173, 202]], device=device, dtype=dtype)
+ scores = torch.tensor([0.875, 0.75], device=device, dtype=dtype)
+ expected = torch.tensor([0], device=device, dtype=torch.long)
+ self.assert_close(nms(boxes, scores, 0.5), expected, atol=0, rtol=0)
+
def test_convention_nms_uses_exclusive_xyxy_iou_4008(self, device, dtype):
# The boxes overlap by 1 / 4 under exclusive xyxy arithmetic. At 0.3, NMS
# keeps both; inclusive corner arithmetic would compute 4 / 9 and suppress