batched_nms adds the per-class offsets in half precision: float16 boxes round to multiples of up to 32 px and overflow to inf, so the wrong boxes are kept
🐛 Describe the bug
batched_nms runs NMS per class by shifting every box by idx * (max_coordinate + 1) and calling nms once (_batched_nms_coordinate_trick, torchvision/ops/boxes.py lines 105 to 107; it is the path taken whenever boxes.numel() is at most 100000 on CUDA, 4000 on CPU, or while tracing). The shift is computed in the dtype of boxes. For float16 boxes the shifted coordinates are far outside the range where float16 still has pixel resolution. With the 91 COCO label ids and a 1333 px wide image the offsets reach 90 * 1334 = 120060, so:
- every box of a label from about 49 up gets
infcoordinates (49 * 1334 = 65366 plus the coordinate itself; float16 ends at 65504); its IoU with anything isnan,nan > thresholdis false, and nothing of those classes is suppressed; - the lower labels keep finite coordinates rounded to multiples of 1 to 32 px (the float16 ulp between 1024 and 65504), so boxes of one class merge or separate depending on the rounding.
The CUDA nms kernel accepts float16 since #3383 and computes the IoU in float32 from the half inputs; the damage is done before, in the add. Under autocast the nms wrapper upcasts its inputs to float32, but by then boxes + offsets has already been rounded. Half precision boxes reach this function from a detector run as model.half() or from any pipeline that keeps the model's half outputs for post-processing, and batched_nms is the public entry point for that.
I do not have a GPU here. The float16 add is the same arithmetic on every device, so the script builds the shifted boxes in float16 exactly as the function does, then hands them to the float32 kernel, which is what the CUDA half kernel computes after reading them (it accumulates in float32). It compares the result on the finite classes with the per-class loop _batched_nms_vanilla on the same half boxes, the ground truth.
import torch
from torchvision.ops import nms
from torchvision.ops.boxes import _batched_nms_vanilla
torch.manual_seed(0)
num_objects, num_duplicates = 40, 25 # 1000 boxes on a 1333 x 800 image, COCO label ids 1..90
centers = torch.rand(num_objects, 2) * torch.tensor([1333.0, 800.0])
sizes = 20 + torch.rand(num_objects, 2) * 300
boxes = torch.cat((centers - sizes / 2, centers + sizes / 2), 1).repeat_interleave(num_duplicates, 0)
boxes += torch.randn_like(boxes) * sizes.repeat(1, 2).repeat_interleave(num_duplicates, 0) * 0.05
boxes = boxes.clamp(min=0).half()
scores = torch.rand(num_objects * num_duplicates).half()
idxs = torch.randint(1, 91, (num_objects,)).repeat_interleave(num_duplicates)
# the arithmetic of _batched_nms_coordinate_trick, in the dtype of the boxes
max_coordinate = boxes.max()
offsets = idxs.to(boxes) * (max_coordinate + torch.tensor(1).to(boxes))
boxes_for_nms = boxes + offsets[:, None]
finite = ~torch.isinf(boxes_for_nms).any(1)
exact = boxes.float() + offsets.float()[:, None]
print("max coordinate:", max_coordinate.item())
print("boxes with inf coordinates:", int((~finite).sum()), "of", len(boxes))
print("largest rounding of a finite shifted coordinate:", (boxes_for_nms.float() - exact).abs()[finite].max().item(), "px")
keep_trick = nms(boxes_for_nms[finite].float(), scores[finite].float(), 0.5) # what the kernel sees
keep_exact = _batched_nms_vanilla(boxes[finite].float(), scores[finite].float(), idxs[finite], 0.5)
print("finite classes: trick keeps", len(keep_trick), "boxes, per-class NMS keeps", len(keep_exact))
Output with torch 2.14.0+cpu and torchvision 0.29.0+cpu:
max coordinate: 1393.0
boxes with inf coordinates: 475 of 1000
largest rounding of a finite shifted coordinate: 16.0 px
finite classes: trick keeps 28 boxes, per-class NMS keeps 21
So 475 boxes, 19 of the 40 objects, would come back unsuppressed, and the other classes keep 28 boxes instead of 21. In float32 the trick and the per-class loop agree, which is what the existing test_batched_nms_implementations pins.
Fix: do the trick in float32 when boxes is float16 or bfloat16, boxes, scores = boxes.float(), scores.float() before the offsets. The kept indices do not depend on the dtype of the shifted boxes, so nothing else changes. bfloat16 goes with it because it has the same rounding problem (ulp 512 px at these offsets) and the nms kernels do not accept it anyway. The new test test_batched_nms_coordinate_trick_half compares the trick on float16 and bfloat16 boxes with the per-class loop on the same boxes in float32, on CPU and CUDA; on main it fails on CPU with "nms_kernel" not implemented for 'Half' (the CPU kernel has no half path, so the upcast also makes this path work there) and on CUDA it should fail with the wrong kept set from the arithmetic above. black and flake8 at line length 120 are clean, and the function still scripts.
Patch
Branch: https://github.com/Nicholas022400701/vision/tree/fix/batched-nms-half-offsets (commit 8ce3d1c)
Patch
diff --git a/test/test_ops.py b/test/test_ops.py
index ecc4378..e85df5b 100644
--- a/test/test_ops.py
+++ b/test/test_ops.py
@@ -1149,6 +1149,30 @@ class TestNMS:
empty = torch.empty((0,), dtype=torch.int64)
torch.testing.assert_close(empty, ops.batched_nms(empty, None, None, None))
+ @pytest.mark.parametrize("device", cpu_and_cuda())
+ @pytest.mark.parametrize("dtype", (torch.float16, torch.bfloat16))
+ @pytest.mark.opcheck_only_one()
+ def test_batched_nms_coordinate_trick_half(self, device, dtype):
+ """The class offsets must not be added in half precision, where they round the coordinates and overflow"""
+ torch.random.manual_seed(0)
+ # 40 objects on a 1333 x 800 image with 25 jittered duplicates each and labels up to 90 as in COCO, so the
+ # offsets reach 90 times the largest coordinate. In float16 the shifted coordinates round to multiples of up
+ # to 32 px and overflow to inf past 65504 for about half of the labels, in bfloat16 they round to multiples
+ # of up to 512 px.
+ num_objects, num_duplicates = 40, 25
+ centers = torch.rand(num_objects, 2) * torch.tensor([1333.0, 800.0])
+ sizes = 20 + torch.rand(num_objects, 2) * 300
+ boxes = torch.cat((centers - sizes / 2, centers + sizes / 2), dim=1).repeat_interleave(num_duplicates, dim=0)
+ boxes += torch.randn_like(boxes) * sizes.repeat(1, 2).repeat_interleave(num_duplicates, dim=0) * 0.05
+ boxes = boxes.clamp(min=0).to(device=device, dtype=dtype)
+ scores = torch.rand(num_objects * num_duplicates).to(device=device, dtype=dtype)
+ idxs = torch.randint(1, 91, (num_objects,)).repeat_interleave(num_duplicates).to(device)
+
+ keep = ops.boxes._batched_nms_coordinate_trick(boxes, scores, idxs, 0.5)
+ keep_ref = ops.boxes._batched_nms_vanilla(boxes.float(), scores.float(), idxs, 0.5)
+ # scores tie in half precision, so compare the kept sets rather than the score order
+ assert_equal(keep.sort().values, keep_ref.sort().values)
+
optests.generate_opcheck_tests(
testcase=TestNMS,
diff --git a/torchvision/ops/boxes.py b/torchvision/ops/boxes.py
index 73fbebd..95c1839 100644
--- a/torchvision/ops/boxes.py
+++ b/torchvision/ops/boxes.py
@@ -102,6 +102,11 @@ def _batched_nms_coordinate_trick(
# from different classes do not overlap
if boxes.numel() == 0:
return torch.empty((0,), dtype=torch.int64, device=boxes.device)
+ if boxes.dtype == torch.float16 or boxes.dtype == torch.bfloat16:
+ # The offsets reach num_classes * max_coordinate. In half precision that rounds the shifted
+ # coordinates to multiples of several pixels and overflows to inf past 65504, so do the
+ # arithmetic in float32; the kept indices do not depend on the dtype of the shifted boxes.
+ boxes, scores = boxes.float(), scores.float()
max_coordinate = boxes.max()
offsets = idxs.to(boxes) * (max_coordinate + torch.tensor(1).to(boxes))
boxes_for_nms = boxes + offsets[:, None]
AI disclosure: I used an AI coding agent to help write this patch, the test and this description. I have read the change and the test myself and I will answer review comments personally.
Versions
torch 2.14.0+cpu, torchvision 0.29.0+cpu for the script; the patch is against main at 7a7520f. Python 3.13.14, Linux x86_64, CPU only.